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

github-actions[bot]38e8ea76db1b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2958de568..6e96f565b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,125 @@
# Changelog
+## v0.4.2
+
+- chore(main): release 0.4.2
+- Scope SGLang CUDA toolkit runtime
+- Enable CUDA toolkit in SGLang worker runtime
+- perf(mineru_vl): O(L) incremental no-repeat-ngram for greedy decode
+- feat(sie_server): add MinerU2.5-Pro-2604-1.2B doc OCR adapter
+- build(deps): upgrade rust toolchain to 1.96
+- feat(models): add Marqo/marqo-fashionSigLIP (SigLIP open_clip, fashion image-text)
+- fix(ci): keep sidecar out of warm cache
+- fix(review): 0.6B ctx test 1024->4096, loader except logs, README gaps resolved
+- fix(ci): avoid nested mise in integration fixture
+- docs: align sidecar naming in active docs
+- fix(deploy): align server sidecar naming
+- fix(deploy): document worker-sidecar metrics wiring
+- fix(deploy): rename sidecar container to worker-sidecar
+- fix(deploy): align server sidecar naming and kind preload smoke
+- fix(deploy): publish server sidecar image
+- feat(model): bump Qwen3-0.6B serving context 1024→4096 for prod simple-task use
+- fix(bench): let via-SIE smoke serve a profile-variant model end-to-end
+- fix(loader): wire profile runtime.default_sampling into the adapter
+- feat(model+bench): RTX-PRO-6000 FP8 profile for Qwen3.6-27B + 6000 validation
+- refactor(glm_ocr): select patch-embed conv strictly by structure (CodeRabbit)
+- perf(glm_ocr): rebind vision Conv3d patch-embed to F.linear
+- chore(adapters,ci): remove Vidore3 throughput diagnosis instrumentation
+- fix(test): restore donut helper call contract
+- fix(ci): address analyzer findings and stale queue test
+- fix(adapters): replace Qwen3-VL vision Conv3d patch-embed with matmul
+- chore(helm): clean sidecar chart observability
+- feat(sidecar): add worker config and pool admission reconciliation
+- TEMP(colqwen3): time vision sub-modules (patch_embed/block/merger)
+- test(tilt): expand sidecar e2e coverage
+- feat(sidecar): wire generation direct dispatch
+- TEMP(colqwen3): split forward timing into vision vs text (revert before merge)
+- fix(adapters): route Qwen3-VL VLMs through flash attention (Vidore3 throughput)
+- TEMP(adapters,ci): timing instrumentation for Vidore3 throughput diag
+- chore(openapi): regenerate gateway spec for min_tokens + chat_template_kwargs
+- fix: address coderabbit + code-quality review on PR #1146
+- feat(bench+model): via-sie 4-task n=300 sweep + NEXTN smaller-draft on 27B
+- fix(worker): SGLang adapter accepts min_new_tokens kwarg + 27B via-sie validated
+- fix: slow sidecar nats consumer reconcile
+- fix: gate sidecar nats reconnect refresh
+- fix: address pr review quality issues
+- fix: harden sidecar config recovery
+- chore: clean sidecar docs and packaging
+- chore: prune sidecar compatibility paths
+- docs(sidecar): clarify worker sidecar source naming
+- fix(ci): refresh gateway openapi contract
+- fix(quality): repair adapter eval harness regressions
+- fix(worker-sidecar): harden queue carveout contracts
+- fix: scope bundle config hash cache per registry
+- chore: standardize worker sidecar packaging
+- feat: reconcile live worker config in sidecar
+- Add worker config reconciliation
+- chore: clean worker sidecar deployment surfaces
+- chore: enable rust sidecar in local tilt
+- fix: require rust sidecar for queue workers
+- docs: clarify worker config apply gap
+- chore: consolidate inference sidecar package
+- fix: preserve worker batch identity and publish image
+- chore: finish rust worker rebase integration
+- chore(helm): land S20+ rust-sidecar production tuning defaults
+- chore: scrub stale sie_candle references and dead candle metric
+- non-adapter carveout: ship sie_prep + wire passthrough end-to-end
+- non-adapter carveout: retire sie_candle, carve out sie_prep, Python passthrough
+- sie_worker_rust + sie_server: queue-depth metrics for IPC+Python loop
+- worker-rust + sie_candle: NATS health heartbeats and BERT cross-encoder
+- rust-worker: retire SIE_RUST_*_MODELS env vars, carve sie_candle out into its own crate (Stage 3 P1)
+- rust-worker: land Stage 1 (tokenise + framing) + Stage 2 (scheduler) + Stage 3 design
+- adding perf-tuning grafana dash fixes and extension
+- obs(helm): perf-tuning Grafana dashboard + ConfigMap
+- perf(rope_flash): vectorize CLS/mean pooling, eliminate per-item .item() sync
+- perf(adaptive): anchor min_batch_cost floor at max_batch_tokens // 4
+- revert: restore adaptive batching defaults to 15/50ms
+- perf(batching): tighten adaptive wait ceiling + revert gte-multilingual 32k
+- perf(gte-multilingual-base): raise max_batch_tokens 16k → 32k to stop IPC-batch shred
+- perf(server): FP16 on GPU, coalesce sized for IPC bursts, starvation self-heal
+- obs(worker+server): audit follow-ups for phase + fragmentation metrics
+- obs(worker+server): surface GPU phase latency + IPC-batch fragmentation
+- feat(worker/rust): IPC connection pool — lift the sidecar's last serialization bottleneck
+- fix(gateway+server): queue is the only mode — kill direct-mode cruft
+- fix(gateway): suppress H9 first-chunk-fallback on single-worker pools
+- worker(rust)+sie_server: post-audit P0 fixes — drain min-deadline, fallback eviction tests, dispatcher outcome binding, encoder UnsupportedModel coverage, model-label cardinality tests
+- worker(rust): finalise pre-Argo audit — native Candle, fallback breaker, full observability, Docker + Helm
+- chore(sie-server): drop dead code left over from sidecar cutover
+- fix(worker): harden payload store + error paths; surface silent success bugs
+- sie-server: commit to sidecar-only queue path; remove Python NATS
+- feat(sie_worker_rust): close parity gaps with Python pull loop + smoke test
+- feat(sie_server): UDS msgpack IPC server for Rust worker sidecar
+- feat(sie_server): carve out QueueExecutor + IPC types for Rust worker POC
+- feat(bench): 0.6B via-sie validated; harness + 27B config gains
+- fix(model): bump Qwen3.6-27B default/h100 mem_fraction_static 0.85 → 0.92
+- feat(gateway+worker): chat surface accepts min_tokens + chat_template_kwargs
+- fix: accept dense_dim in dense adapters
+- test: align structured output metric constants
+- fix(sie_server): clear CUDA cache on uncovered VLM paths + drop private sem _value access
+- chore: remove internal design doc references
+- docs: clean stale design references
+- docs: minimize design architecture docs
+- docs: update design document references
+- docs: remove internal planning references
+- docs: archive obsolete roadmap
+- fix(security): cap vite at ^6 + add Node engines to website
+- feat(gateway): strengthen generation isolation guardrails
+- feat(docling): accept image input + run on OCR-bench quality path
+- fix(security): bump sie_ts_sdk standalone pnpm transitives
+- fix(security): bump root pnpm deps + add overrides for transitives
+- fix(security): bump root Python deps to patched versions
+- fix(security): bump gateway deps to patched versions
+- chore: drop CodeQL rationale comments
+- fix(quality): batch3 of CodeQL findings + bench KIE bug
+- fix(quality): drop redundant inline imports in donut + registry
+- fix(security): use Reflect.construct for WebSocket headers shim
+- fix(quality): close CodeQL quality-tab findings
+- Fix gateway queue trace isolation
+- perf(bench,adapters): parallel VLM sub-batch dispatch + drop redundant empty_cache
+- Keep generation machinery off default queue path
+- docs(test): note `:` -> `__` replacement in test_model_yaml_filenames docstring
+- fix(models): rename ColQwen3 YAML to match sie_id casing (TomoroAI)
+
## v0.4.1
- chore(main): release 0.4.1
diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yaml
index 8ff77e553..67a43d45f 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.4.1 # x-release-please-version
-appVersion: v0.4.1 # x-release-please-version
+version: 0.4.2 # x-release-please-version
+appVersion: v0.4.2 # x-release-please-version
keywords:
- inference
- embedding
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.md
index c5af5c211..78d9bb44b 100644
--- a/deploy/helm/sie-cluster/README.md
+++ b/deploy/helm/sie-cluster/README.md
@@ -6,8 +6,6 @@ Deploy SIE (Search Inference Engine) to Kubernetes with autoscaling and observab
```bash
helm install sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster \
- --namespace sie \
- --create-namespace
--namespace sie \
--create-namespace
```
@@ -35,7 +33,7 @@ helm install sie-cluster oci://ghcr.io/superlinked/charts/sie-cluster \
When scaling from zero, expect the following latencies:
-| Phase | Duration | Notes |
+| Step | Duration | Notes |
|-------|----------|-------|
| **Node provisioning** | 2-5 min | GKE/EKS spins up GPU node (spot may be slower) |
| **Container startup** | 20-40s | Pull image, start process, health checks |
@@ -109,6 +107,24 @@ even when there are 0 workers (and thus no worker metrics).
| `sie_request_queue_depth` | Workers | Scale up on load |
| `sie_active_requests` | Workers | Scale up on concurrent requests |
+### Worker-sidecar Metrics
+
+When `workers.common.workerSidecar.enabled=true`, each worker Pod includes a
+`worker-sidecar` container. The sidecar image is
+`ghcr.io/superlinked/sie-server-sidecar`, the Rust binary is
+`sie-server-sidecar`, and Prometheus families use the `sie_worker_*` prefix
+because they describe worker-side runtime behavior.
+
+The chart wires sidecar scraping as:
+
+- `worker-sidecar` container port `metrics` on `SIE_WORKER_METRICS_PORT`
+ (default `9095`)
+- worker Service port `worker-metrics`
+- worker ServiceMonitor endpoint `worker-metrics`
+
+Alert rules that need the sidecar scrape target match
+`endpoint="worker-metrics"` rather than an old `job="sie-worker"` label.
+
## Configuration
See `values.yaml` for all options. Key settings:
@@ -154,12 +170,12 @@ ingress:
The singular `ingress.host` is the backward-compatible single-host shorthand; it is
ignored whenever `ingress.hosts` is non-empty. With neither set the chart renders a
-host-less catch-all Ingress. All hosts share the single `ingress.tls.secretName`
+host-less catch-all Ingress. All hosts share the single `ingress.tlsConfig.secretName`
(one multi-SAN certificate).
## TLS / HTTPS
-The chart supports four TLS modes for the Ingress (set via `ingress.tls.mode`):
+The chart supports four TLS modes for the Ingress (set via `ingress.tlsConfig.mode`):
- `byo` — bring your own `kubernetes.io/tls` Secret (default, backward compatible).
- `cert-manager` — chart annotates the Ingress; [cert-manager](https://cert-manager.io/) provisions and renews the certificate. Default flavour is ACME (HTTP-01 challenge to Let's Encrypt); you can also point at an existing internal Issuer/ClusterIssuer.
@@ -183,7 +199,7 @@ ingress:
enabled: true
className: nginx
host: sie.example.com
- tls:
+ tlsConfig:
enabled: true
mode: byo # default
secretName: sie-tls # default
@@ -203,6 +219,15 @@ helm install cert-manager jetstack/cert-manager \
--set crds.enabled=true -n cert-manager --create-namespace
```
+For single-tenant clusters where SIE is the only workload, the chart can also
+install cert-manager as an opt-in subchart:
+
+```yaml
+certManagerBundle:
+ certManager:
+ install: true
+```
+
Then enable cert-manager mode in your SIE values:
```yaml
@@ -210,7 +235,7 @@ ingress:
enabled: true
className: nginx
host: sie.example.com
- tls:
+ tlsConfig:
enabled: true
mode: cert-manager
certManager:
@@ -221,7 +246,7 @@ ingress:
create: true # chart renders the Issuer/ClusterIssuer
```
-The chart renders a `{kind}` named `{release-fullname}-letsencrypt-prod` (release-scoped to avoid collisions when multiple SIE releases share a cluster) and adds the appropriate `cert-manager.io/cluster-issuer` (or `/issuer`) annotation to the main Ingress. cert-manager populates `ingress.tls.secretName` (default `sie-tls`); the same Secret is referenced by the oauth2-proxy Ingress when auth is enabled.
+The chart renders a `{kind}` named `{release-fullname}-letsencrypt-prod` (release-scoped to avoid collisions when multiple SIE releases share a cluster) and adds the appropriate `cert-manager.io/cluster-issuer` (or `/issuer`) annotation to the main Ingress. cert-manager populates `ingress.tlsConfig.secretName` (default `sie-tls`); the same Secret is referenced by the oauth2-proxy Ingress when auth is enabled.
Note: Helm's standard `fullname` collapses when the release name already contains the chart name, so `helm install sie-cluster …` produces `sie-cluster-letsencrypt-prod` (not `sie-cluster-sie-cluster-letsencrypt-prod`). If you override `certManager.name`, set the full intended name explicitly rather than expecting a particular default.
@@ -234,7 +259,7 @@ Issuer kind tradeoff:
```yaml
ingress:
- tls:
+ tlsConfig:
enabled: true
mode: cert-manager
certManager:
@@ -290,7 +315,7 @@ kubectl -n sie get secret sie-root-ca-key-pair \
> **Root CA namespace constraint.** Two independent namespace-scoped lookups apply:
>
-> 1. **cert-manager** only resolves Secrets referenced by a `ClusterIssuer` inside its `--cluster-resource-namespace` (defaults to its own Deployment's namespace). The chart writes the root CA to `ingress.tls.selfSigned.rootCA.namespace` (defaults to the release namespace, which is correct for the **bundled** subchart since cert-manager also runs in the release namespace).
+> 1. **cert-manager** only resolves Secrets referenced by a `ClusterIssuer` inside its `--cluster-resource-namespace` (defaults to its own Deployment's namespace). The chart writes the root CA to `ingress.tlsConfig.selfSigned.rootCA.namespace` (defaults to the release namespace, which is correct for the **bundled** subchart since cert-manager also runs in the release namespace).
> 2. **trust-manager** only resolves source Secrets for `Bundle` resources inside its `--trust-namespace` (defaults to `cert-manager`, regardless of where trust-manager itself runs).
>
> If you also enable `certManagerBundle.trustBundle.enabled: true` with the bundled trust-manager, override the trust namespace at install time so it matches where the root CA lives:
@@ -299,7 +324,7 @@ kubectl -n sie get secret sie-root-ca-key-pair \
> helm install ... --set "trust-manager.app.trust.namespace=<release-namespace>"
> ```
>
-> Otherwise the Bundle stays `Synced=False` with `SourceNotFound`. For external cert-manager (typically in `cert-manager` namespace), set `ingress.tls.selfSigned.rootCA.namespace: cert-manager` so the CA `ClusterIssuer` can find its Secret; the default trust-namespace then already matches.
+> Otherwise the Bundle stays `Synced=False` with `SourceNotFound`. For external cert-manager (typically in `cert-manager` namespace), set `ingress.tlsConfig.selfSigned.rootCA.namespace: cert-manager` so the CA `ClusterIssuer` can find its Secret; the default trust-namespace then already matches.
**When to use this**: air-gapped / on-prem clusters where you can distribute the root CA to client machines (e.g. via MDM, internal trust store, or workload mount), and you want a single `helm install` to land a working HTTPS path.
diff --git a/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml b/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml
index 3dd425f89..97414f39e 100644
--- a/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml
+++ b/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml
@@ -1,9 +1,9 @@
groups:
# Worker health alerts
- - name: sie-worker-health
+ - name: worker-sidecar-health
rules:
- alert: SIEWorkerDown
- expr: up{job="sie-worker"} == 0
+ expr: up{namespace="__NAMESPACE__",endpoint="worker-metrics"} == 0
for: 2m
labels:
severity: critical
@@ -12,7 +12,7 @@ groups:
description: "Worker pod {{ $labels.pod }} has been unreachable for 2 minutes."
- alert: SIENoHealthyWorkers
- expr: sum(up{job="sie-worker"}) == 0
+ expr: sum(up{namespace="__NAMESPACE__",endpoint="worker-metrics"}) == 0
for: 1m
labels:
severity: critical
diff --git a/deploy/helm/sie-cluster/files/dashboards/perf-tuning.json b/deploy/helm/sie-cluster/files/dashboards/perf-tuning.json
new file mode 100644
index 000000000..566bde955
--- /dev/null
+++ b/deploy/helm/sie-cluster/files/dashboards/perf-tuning.json
@@ -0,0 +1,644 @@
+{
+ "annotations": {
+ "list": []
+ },
+ "description": "SIE perf-tuning dashboard — 4 rows mirror the four tuning surfaces documented in sie-perf-lab/docs/l4-cluster-perf-tuning.md: (1) cluster throughput + SLO, (2) worker-sidecar pull loop / IPC pool, (3) Rust scheduler adaptive controller, (4) DCGM device-level power & clocks. Each panel is annotated with the knob it answers and the failure mode its shape encodes.",
+ "editable": true,
+ "fiscalYearStartMonth": 0,
+ "graphTooltip": 1,
+ "id": null,
+ "links": [
+ {
+ "title": "Findings doc",
+ "url": "https://github.com/superlinked/sie-perf-lab/blob/main/docs/l4-cluster-perf-tuning.md",
+ "type": "link",
+ "targetBlank": true,
+ "tags": []
+ }
+ ],
+ "panels": [
+ {
+ "gridPos": { "h": 2, "w": 24, "x": 0, "y": 0 },
+ "id": 100,
+ "type": "text",
+ "options": {
+ "mode": "markdown",
+ "content": "## Cluster throughput & SLO\nTarget: **1M tok/s** cluster (= **100k tok/s per pod**). `sie_worker_backend_item_outcomes_total{disposition=\"publish_and_ack\"}` is the per-pod items/s — multiply by `tokens/item` (~433 on the NFCorpus bench) for tok/s."
+ }
+ },
+ {
+ "gridPos": { "h": 8, "w": 8, "x": 0, "y": 2 },
+ "id": 1,
+ "type": "stat",
+ "options": {
+ "reduceOptions": { "calcs": ["lastNotNull"], "fields": "", "values": false },
+ "graphMode": "area",
+ "orientation": "auto",
+ "textMode": "auto",
+ "colorMode": "value"
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": {
+ "defaults": {
+ "unit": "short",
+ "decimals": 0,
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ { "color": "red", "value": null },
+ { "color": "yellow", "value": 1500 },
+ { "color": "green", "value": 2200 }
+ ]
+ }
+ }
+ },
+ "targets": [
+ {
+ "expr": "sum(rate(sie_worker_backend_item_outcomes_total{namespace=\"$namespace\", disposition=\"publish_and_ack\"}[1m]))",
+ "legendFormat": "items/s",
+ "refId": "A"
+ }
+ ],
+ "title": "Cluster items/s (all workers)"
+ },
+ {
+ "gridPos": { "h": 8, "w": 8, "x": 8, "y": 2 },
+ "id": 2,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "mean"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "none" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "short", "custom": { "drawStyle": "line", "fillOpacity": 10 } } },
+ "targets": [
+ {
+ "expr": "sum(rate(sie_worker_backend_item_outcomes_total{namespace=\"$namespace\", disposition=\"publish_and_ack\"}[1m])) by (pod)",
+ "legendFormat": "{{pod}}",
+ "refId": "A"
+ }
+ ],
+ "title": "Per-pod items/s (target ~230/s/pod at 433 tok/item)"
+ },
+ {
+ "gridPos": { "h": 8, "w": 8, "x": 16, "y": 2 },
+ "id": 3,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "s", "custom": { "drawStyle": "line", "fillOpacity": 0 } } },
+ "targets": [
+ {
+ "expr": "histogram_quantile(0.5, sum(rate(sie_gateway_request_latency_seconds_bucket{namespace=\"$namespace\"}[1m])) by (le))",
+ "legendFormat": "p50",
+ "refId": "A"
+ },
+ {
+ "expr": "histogram_quantile(0.99, sum(rate(sie_gateway_request_latency_seconds_bucket{namespace=\"$namespace\"}[1m])) by (le))",
+ "legendFormat": "p99",
+ "refId": "B"
+ },
+ {
+ "expr": "histogram_quantile(0.99, sum(rate(sie_gateway_queue_result_wait_seconds_bucket{namespace=\"$namespace\"}[1m])) by (le))",
+ "legendFormat": "queue-wait p99",
+ "refId": "C"
+ }
+ ],
+ "title": "Gateway latency"
+ },
+ {
+ "gridPos": { "h": 2, "w": 24, "x": 0, "y": 10 },
+ "id": 101,
+ "type": "text",
+ "options": {
+ "mode": "markdown",
+ "content": "## worker-sidecar — pull loop & IPC pool\n`ipc_pool_inflight` flatlining at `SIE_IPC_POOL_SIZE` is the canonical symptom of a too-small IPC pool. Rule of thumb: keep `SIE_PULL_LOOP_INFLIGHT ≤ SIE_MAX_CONCURRENT_BATCHES ≤ SIE_IPC_POOL_SIZE`."
+ }
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 0, "y": 12 },
+ "id": 10,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "max"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "short", "custom": { "drawStyle": "line", "fillOpacity": 20 } } },
+ "targets": [
+ {
+ "expr": "avg(sie_worker_ipc_pool_inflight{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}} inflight",
+ "refId": "A"
+ },
+ {
+ "expr": "avg(sie_worker_ipc_pool_size{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}} pool size",
+ "refId": "B"
+ }
+ ],
+ "title": "IPC pool: inflight vs size (flatline at size = saturated)"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 12, "y": 12 },
+ "id": 11,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "mean"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "ms", "custom": { "drawStyle": "line", "fillOpacity": 0 } } },
+ "targets": [
+ {
+ "expr": "histogram_quantile(0.5, sum(rate(sie_pull_loop_batch_process_seconds_bucket{namespace=\"$namespace\"}[1m])) by (le, pod)) * 1000",
+ "legendFormat": "{{pod}} p50",
+ "refId": "A"
+ },
+ {
+ "expr": "histogram_quantile(0.99, sum(rate(sie_pull_loop_batch_process_seconds_bucket{namespace=\"$namespace\"}[1m])) by (le, pod)) * 1000",
+ "legendFormat": "{{pod}} p99",
+ "refId": "B"
+ }
+ ],
+ "title": "Pull-loop batch wall time (fetch → IPC → GPU → ACK)",
+ "description": "Buckets in source are [1,5,10,25,50,100,250,500,1000,2500,5000,10000] ms. p50 (~20-80ms FP16) lands in the 25-100ms range → ±33% quantile error; p99 (~100-300ms) in 100-500ms → ±50%. Use for trend, not absolute regressions < 20%."
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 0, "y": 20 },
+ "id": 12,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "mean"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "none" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "short", "custom": { "drawStyle": "line", "fillOpacity": 10 } } },
+ "targets": [
+ {
+ "expr": "sum(rate(sie_pull_loop_items_fetched_sum{namespace=\"$namespace\"}[1m])) by (pod) / sum(rate(sie_pull_loop_items_fetched_count{namespace=\"$namespace\"}[1m])) by (pod)",
+ "legendFormat": "{{pod}} items/pull (avg)",
+ "refId": "A"
+ }
+ ],
+ "title": "Avg items/pull (cap = SIE_NATS_FETCH_BUDGET, 64)"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 12, "y": 20 },
+ "id": 13,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "none" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "reqps", "custom": { "drawStyle": "line", "fillOpacity": 10 } } },
+ "targets": [
+ {
+ "expr": "sum(rate(sie_worker_ipc_requests_total{namespace=\"$namespace\"}[1m])) by (pod)",
+ "legendFormat": "{{pod}}",
+ "refId": "A"
+ }
+ ],
+ "title": "IPC requests / s (sidecar → Python)"
+ },
+ {
+ "gridPos": { "h": 2, "w": 24, "x": 0, "y": 28 },
+ "id": 102,
+ "type": "text",
+ "options": {
+ "mode": "markdown",
+ "content": "## Rust scheduler — adaptive controller\nIf `sie_worker_scheduler_batch_items` stays tiny while `sie_worker_scheduler_adaptive_fill_ratio` is low, the sidecar is flushing before work accumulates. Check `SIE_BATCHER_COALESCE_MS`, `SIE_BATCHER_MAX_BATCH_REQUESTS`, and the `SIE_ADAPTIVE_*` quantum knobs before changing Python adapter settings."
+ }
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 0, "y": 30 },
+ "id": 20,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "mean"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "short", "custom": { "drawStyle": "line", "fillOpacity": 10 } } },
+ "targets": [
+ {
+ "expr": "sum(rate(sie_worker_scheduler_batch_items_sum{namespace=\"$namespace\"}[1m])) by (pod) / sum(rate(sie_worker_scheduler_batch_items_count{namespace=\"$namespace\"}[1m])) by (pod)",
+ "legendFormat": "{{pod}} items",
+ "refId": "A"
+ },
+ {
+ "expr": "sum(rate(sie_worker_scheduler_batch_cost_sum{namespace=\"$namespace\"}[1m])) by (pod) / sum(rate(sie_worker_scheduler_batch_cost_count{namespace=\"$namespace\"}[1m])) by (pod) / 1000",
+ "legendFormat": "{{pod}} cost (k)",
+ "refId": "B"
+ }
+ ],
+ "title": "Rust scheduler batch size (items & k cost per forward)"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 12, "y": 30 },
+ "id": 21,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "none" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "ms", "custom": { "drawStyle": "line", "fillOpacity": 0 } } },
+ "targets": [
+ {
+ "expr": "avg(sie_worker_scheduler_adaptive_wait_ms{namespace=\"$namespace\"}) by (pod, model)",
+ "legendFormat": "{{pod}} wait",
+ "refId": "A"
+ },
+ {
+ "expr": "avg(sie_worker_scheduler_adaptive_observed_p50_ms{namespace=\"$namespace\"}) by (pod, model)",
+ "legendFormat": "{{pod}} p50",
+ "refId": "B"
+ },
+ {
+ "expr": "avg(sie_worker_scheduler_adaptive_target_p50_ms{namespace=\"$namespace\"}) by (pod, model)",
+ "legendFormat": "{{pod}} target",
+ "refId": "C"
+ }
+ ],
+ "title": "Rust scheduler adaptive controller: wait / p50 / target"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 0, "y": 38 },
+ "id": 22,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "mean"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "none" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "short", "custom": { "drawStyle": "line", "fillOpacity": 10 } } },
+ "targets": [
+ {
+ "expr": "avg(sie_worker_scheduler_adaptive_cost{namespace=\"$namespace\"}) by (pod, model)",
+ "legendFormat": "{{pod}} batch-cost (tokens)",
+ "refId": "A"
+ }
+ ],
+ "title": "Rust scheduler adaptive max_batch_cost"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 12, "y": 38 },
+ "id": 23,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "max"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "none" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": {
+ "defaults": {
+ "unit": "percentunit",
+ "min": 0, "max": 1,
+ "custom": { "drawStyle": "line", "fillOpacity": 20 },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ { "color": "red", "value": null },
+ { "color": "yellow", "value": 0.5 },
+ { "color": "green", "value": 0.75 }
+ ]
+ }
+ }
+ },
+ "targets": [
+ {
+ "expr": "avg(sie_worker_scheduler_adaptive_fill_ratio{namespace=\"$namespace\"}) by (pod, model)",
+ "legendFormat": "{{pod}} fill",
+ "refId": "A"
+ }
+ ],
+ "title": "Adaptive fill ratio (actual_cost / max_cost)"
+ },
+ {
+ "gridPos": { "h": 6, "w": 12, "x": 0, "y": 46 },
+ "id": 24,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["max"], "displayMode": "list", "placement": "bottom", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "short", "custom": { "drawStyle": "line", "fillOpacity": 10 } } },
+ "targets": [
+ {
+ "expr": "sum(rate(sie_worker_scheduler_enqueued_items_total{namespace=\"$namespace\"}[1m])) by (pod, model, operation)",
+ "legendFormat": "{{pod}} {{operation}} enq/s",
+ "refId": "A"
+ }
+ ],
+ "title": "Rust scheduler enqueues / s"
+ },
+ {
+ "gridPos": { "h": 6, "w": 12, "x": 12, "y": 46 },
+ "id": 25,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["sum"], "displayMode": "list", "placement": "bottom", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "short", "custom": { "drawStyle": "bars", "fillOpacity": 60 } } },
+ "targets": [
+ {
+ "expr": "sum(rate(sie_worker_scheduler_starvation_resets_total{namespace=\"$namespace\"}[5m])) by (pod, model)",
+ "legendFormat": "{{pod}} resets/s",
+ "refId": "A"
+ }
+ ],
+ "title": "Starvation resets rate (non-zero = self-heal firing)"
+ },
+ {
+ "gridPos": { "h": 2, "w": 24, "x": 0, "y": 52 },
+ "id": 103,
+ "type": "text",
+ "options": {
+ "mode": "markdown",
+ "content": "## GPU device counters (DCGM)\nL4 TDP = **72 W**, stock max proc clock = **2040 MHz**. Sustained power ≥ 65 W with proc clock ≤ 1500 MHz is the **power-capped** signature. See sie-perf-lab/docs/l4-cluster-perf-tuning.md §6.\n\n**MFU proxies** (below): `DCGM_FI_PROF_SM_ACTIVE` ≈ fraction of cycles an SM has ≥1 warp assigned (saturation). `DCGM_FI_PROF_PIPE_FP16_ACTIVE` + `PIPE_TENSOR_ACTIVE` = fraction of cycles the FP16/HMMA pipes are computing — our embedding model runs FP16 so `PIPE_FP16_ACTIVE` ≫ `PIPE_TENSOR_ACTIVE` is expected on varlen flash-attn."
+ }
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 0, "y": 54 },
+ "id": 30,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "mean"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": {
+ "defaults": {
+ "unit": "watt",
+ "custom": { "drawStyle": "line", "fillOpacity": 10 },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ { "color": "green", "value": null },
+ { "color": "yellow", "value": 55 },
+ { "color": "red", "value": 68 }
+ ]
+ }
+ }
+ },
+ "targets": [
+ {
+ "expr": "avg(DCGM_FI_DEV_POWER_USAGE{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}}",
+ "refId": "A"
+ }
+ ],
+ "title": "GPU power draw (72W TDP)"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 12, "y": 54 },
+ "id": 31,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "min", "mean"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "asc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": {
+ "defaults": {
+ "unit": "rotmhz",
+ "max": 2040,
+ "custom": { "drawStyle": "line", "fillOpacity": 10 },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ { "color": "red", "value": null },
+ { "color": "yellow", "value": 1500 },
+ { "color": "green", "value": 1900 }
+ ]
+ }
+ }
+ },
+ "targets": [
+ {
+ "expr": "avg(DCGM_FI_DEV_SM_CLOCK{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}} sm_clock",
+ "refId": "A"
+ }
+ ],
+ "title": "GPU proc clock (stock max 2040 MHz; throttled < 1500)"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 0, "y": 62 },
+ "id": 32,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "mean"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": { "defaults": { "unit": "percent", "min": 0, "max": 100, "custom": { "drawStyle": "line", "fillOpacity": 10 } } },
+ "targets": [
+ {
+ "expr": "avg(DCGM_FI_DEV_GPU_UTIL{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}} sm%",
+ "refId": "A"
+ },
+ {
+ "expr": "avg(DCGM_FI_DEV_MEM_COPY_UTIL{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}} mem%",
+ "refId": "B"
+ }
+ ],
+ "title": "SM vs memory utilisation"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 12, "y": 62 },
+ "id": 33,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "max"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": {
+ "defaults": {
+ "unit": "celsius",
+ "custom": { "drawStyle": "line", "fillOpacity": 10 },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ { "color": "green", "value": null },
+ { "color": "yellow", "value": 75 },
+ { "color": "red", "value": 85 }
+ ]
+ }
+ }
+ },
+ "targets": [
+ {
+ "expr": "avg(DCGM_FI_DEV_GPU_TEMP{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}}",
+ "refId": "A"
+ }
+ ],
+ "title": "GPU temperature"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 0, "y": 70 },
+ "id": 34,
+ "description": "DCGM_FI_PROF_SM_ACTIVE is the ratio of cycles at least one warp is resident on an SM — the right 'GPU saturated?' signal (DCGM_FI_DEV_GPU_UTIL above is the coarse nvidia-smi one). Sustained ≥0.9 with tensor/FP16 pipe ≥0.4 means the L4 is compute-bound on tensor ops.",
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "mean", "max"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": {
+ "defaults": {
+ "unit": "percentunit",
+ "min": 0,
+ "max": 1,
+ "custom": { "drawStyle": "line", "fillOpacity": 10 },
+ "thresholds": {
+ "mode": "absolute",
+ "steps": [
+ { "color": "red", "value": null },
+ { "color": "yellow", "value": 0.6 },
+ { "color": "green", "value": 0.85 }
+ ]
+ }
+ }
+ },
+ "targets": [
+ {
+ "expr": "avg(DCGM_FI_PROF_SM_ACTIVE{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}} sm_active",
+ "refId": "A"
+ }
+ ],
+ "title": "SM active (cycles with ≥1 warp) — saturation proxy"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 12, "y": 70 },
+ "id": 35,
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "max"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": {
+ "defaults": {
+ "unit": "mbytes",
+ "custom": { "drawStyle": "line", "fillOpacity": 10 }
+ }
+ },
+ "targets": [
+ {
+ "expr": "avg(DCGM_FI_DEV_FB_USED{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}} FB",
+ "refId": "A"
+ }
+ ],
+ "title": "GPU framebuffer used (MiB; L4 has 24 GiB)"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 0, "y": 78 },
+ "id": 36,
+ "description": "FP16 pipe ratio over the full device: our gte-multilingual-base runs in torch.float16 and its flash-attn GEMMs dispatch onto the FP16 pipe. HMMA (Tensor Core) is a subset; if TENSOR_ACTIVE < FP16_ACTIVE the attention impl is not hitting tensor cores (varlen flash-attn does).",
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "mean", "max"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": {
+ "defaults": {
+ "unit": "percentunit",
+ "min": 0,
+ "max": 1,
+ "custom": { "drawStyle": "line", "fillOpacity": 10 }
+ }
+ },
+ "targets": [
+ {
+ "expr": "avg(DCGM_FI_PROF_PIPE_FP16_ACTIVE{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}} fp16",
+ "refId": "A"
+ },
+ {
+ "expr": "avg(DCGM_FI_PROF_PIPE_TENSOR_ACTIVE{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}} tensor(hmma)",
+ "refId": "B"
+ }
+ ],
+ "title": "FP16 / Tensor-core pipe active — MFU proxy"
+ },
+ {
+ "gridPos": { "h": 8, "w": 12, "x": 12, "y": 78 },
+ "id": 37,
+ "description": "DRAM active tells us if we're memory-bandwidth bound (embedding models usually are at short seq and small batch, compute-bound at long seq / large batch). High `dram_active` with low `pipe_fp16_active` = HBM-bandwidth limited. PCIe RX+TX = host<->device transfer volume; should be small for an on-GPU inference loop.",
+ "type": "timeseries",
+ "options": {
+ "legend": { "calcs": ["lastNotNull", "mean"], "displayMode": "table", "placement": "right", "showLegend": true },
+ "tooltip": { "mode": "multi", "sort": "desc" }
+ },
+ "pluginVersion": "10.0.0",
+ "fieldConfig": {
+ "defaults": {
+ "custom": { "drawStyle": "line", "fillOpacity": 10 }
+ },
+ "overrides": [
+ { "matcher": { "id": "byRegexp", "options": "/dram/" }, "properties": [{ "id": "unit", "value": "percentunit" }, { "id": "max", "value": 1 }] },
+ { "matcher": { "id": "byRegexp", "options": "/pcie/" }, "properties": [{ "id": "unit", "value": "Bps" }] }
+ ]
+ },
+ "targets": [
+ {
+ "expr": "avg(DCGM_FI_PROF_DRAM_ACTIVE{namespace=\"$namespace\"}) by (pod)",
+ "legendFormat": "{{pod}} dram_active",
+ "refId": "A"
+ },
+ {
+ "expr": "sum(rate(DCGM_FI_PROF_PCIE_RX_BYTES{namespace=\"$namespace\"}[1m]) + rate(DCGM_FI_PROF_PCIE_TX_BYTES{namespace=\"$namespace\"}[1m])) by (pod)",
+ "legendFormat": "{{pod}} pcie_bps",
+ "refId": "B"
+ }
+ ],
+ "title": "DRAM active + PCIe bytes/s — memory-bandwidth bound?"
+ }
+ ],
+ "refresh": "10s",
+ "schemaVersion": 38,
+ "tags": ["sie", "perf", "tuning", "l4"],
+ "templating": {
+ "list": [
+ {
+ "current": { "selected": false, "text": "perf-lab", "value": "perf-lab" },
+ "hide": 0,
+ "includeAll": false,
+ "label": "Namespace",
+ "multi": false,
+ "name": "namespace",
+ "options": [],
+ "query": "label_values(sie_worker_ipc_pool_size, namespace)",
+ "refresh": 2,
+ "regex": "",
+ "skipUrlSync": false,
+ "sort": 0,
+ "type": "query"
+ }
+ ]
+ },
+ "time": { "from": "now-30m", "to": "now" },
+ "timepicker": {},
+ "timezone": "",
+ "title": "SIE Perf Tuning (L4)",
+ "uid": "sie-perf-tuning",
+ "version": 2,
+ "weekStart": ""
+}
diff --git a/deploy/helm/sie-cluster/templates/NOTES.txt b/deploy/helm/sie-cluster/templates/NOTES.txt
index c09b4f265..5a30dad51 100644
--- a/deploy/helm/sie-cluster/templates/NOTES.txt
+++ b/deploy/helm/sie-cluster/templates/NOTES.txt
@@ -1,31 +1,32 @@
{{- include "sie-cluster.validateNats" . -}}
{{- include "sie-cluster.validateTls" . -}}
+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml -}}
SIE Cluster {{ .Chart.Version }} deployed to namespace {{ include "sie-cluster.namespace" . }}.
Gateway: http://{{ include "sie-cluster.gateway.serviceName" . }}.{{ include "sie-cluster.namespace" . }}.svc:{{ .Values.gateway.service.port }}
{{- if index .Values "kube-prometheus-stack" "install" }}
-Prometheus: enabled — kubectl port-forward -n {{ include "sie-cluster.namespace" . }} svc/prometheus-operated 9090
-Grafana: enabled — kubectl port-forward -n {{ include "sie-cluster.namespace" . }} svc/{{ .Release.Name }}-grafana 3000:80
+Prometheus: enabled - kubectl port-forward -n {{ include "sie-cluster.namespace" . }} svc/prometheus-operated 9090
+Grafana: enabled - kubectl port-forward -n {{ include "sie-cluster.namespace" . }} svc/{{ .Release.Name }}-grafana 3000:80
Grafana password: kubectl get secret -n {{ include "sie-cluster.namespace" . }} {{ .Release.Name }}-grafana -o jsonpath="{.data.admin-password}" | base64 -d
{{- end }}
{{- if .Values.keda.install }}
KEDA: enabled
{{- end }}
-{{- if and .Values.ingress.tls.enabled (eq .Values.ingress.tls.mode "cert-manager") }}
+{{- if and $tls.enabled (eq (default "byo" $tls.mode) "cert-manager") }}
TLS via cert-manager: certificate is being issued via ACME HTTP-01 challenge.
This typically takes 30–120s on first install. Track progress with:
kubectl -n {{ include "sie-cluster.namespace" . }} get certificate -w
The gateway will return TLS errors briefly until the certificate is Ready.
{{- end }}
-{{- if and .Values.ingress.tls.enabled (eq .Values.ingress.tls.mode "self-signed") }}
+{{- if and $tls.enabled (eq (default "byo" $tls.mode) "self-signed") }}
TLS via self-signed CA: a root CA, CA ClusterIssuer, and leaf cert are being issued by cert-manager.
This typically takes 10-30s on first install. Track progress with:
kubectl -n {{ include "sie-cluster.namespace" . }} get certificate -w
Export the root CA (e.g. to trust on a client machine):
- kubectl -n {{ include "sie-cluster.namespace" . }} get secret {{ .Values.ingress.tls.selfSigned.rootCA.secretName }} \
+ kubectl -n {{ include "sie-cluster.namespace" . }} get secret {{ $tls.selfSigned.rootCA.secretName }} \
-o jsonpath='{.data.ca\.crt}' | base64 -d > sie-root-ca.crt
{{- if .Values.certManagerBundle.trustBundle.enabled }}
The root CA is also replicated to selected namespaces as ConfigMap {{ .Values.certManagerBundle.trustBundle.name | quote }}
diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tpl
index de8ae2248..d0c48d61c 100644
--- a/deploy/helm/sie-cluster/templates/_helpers.tpl
+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl
@@ -285,7 +285,23 @@ Consume with: include "sie-cluster.ingress.hosts" . | fromJsonArray
Validation: TLS / cert-manager / trust-manager configuration consistency.
Runs from NOTES.txt so every install/upgrade is checked, regardless of which (or no) Issuer template renders.
*/}}
+{{- define "sie-cluster.ingressTlsConfig" -}}
+{{- $tls := deepCopy (default (dict) .Values.ingress.tlsConfig) -}}
+{{- if and (hasKey .Values.ingress "tls") (kindIs "map" .Values.ingress.tls) -}}
+{{- $legacy := .Values.ingress.tls -}}
+{{- $legacyActive := or (default false $legacy.enabled) (and (hasKey $legacy "mode") (ne (default "byo" $legacy.mode) "byo")) -}}
+{{- if and (not (default false $tls.enabled)) $legacyActive -}}
+{{- $tls = mergeOverwrite $tls $legacy -}}
+{{- else -}}
+{{- $tls = mergeOverwrite (deepCopy $legacy) $tls -}}
+{{- end -}}
+{{- end -}}
+{{- toYaml $tls -}}
+{{- end }}
+
{{- define "sie-cluster.validateTls" -}}
+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}
+{{- $hosts := include "sie-cluster.ingress.hosts" . | fromJsonArray }}
{{- /* CRD existence is no longer a reliable "is cert-manager installed" signal — we vendor the
cert-manager and trust-manager CRDs under crds/, so the CRD lands on every install regardless
of whether a cert-manager Deployment exists. Helm's lookup() can't filter by label, so we
@@ -310,7 +326,7 @@ Runs from NOTES.txt so every install/upgrade is checked, regardless of which (or
{{- $tmInstall := .Values.certManagerBundle.trustManager.install }}
{{- if $cmInstall }}
{{- if and $cmDeploy (not .Values.certManagerBundle.allowExistingCRDs) }}
-{{- fail "Refusing to install bundled cert-manager: a cert-manager Deployment already exists in the cluster. Two cert-manager controllers reconciling the same CRDs will corrupt issuance state. Remediation: (a) set certManagerBundle.certManager.install=false and use ingress.tls.mode=cert-manager against the existing install, OR (b) uninstall the existing cert-manager first, OR (c) set certManagerBundle.allowExistingCRDs=true (DANGEROUS — only if you understand the consequences)." }}
+{{- fail "Refusing to install bundled cert-manager: a cert-manager Deployment already exists in the cluster. Two cert-manager controllers reconciling the same CRDs will corrupt issuance state. Remediation: (a) set certManagerBundle.certManager.install=false and use ingress.tlsConfig.mode=cert-manager against the existing install, OR (b) uninstall the existing cert-manager first, OR (c) set certManagerBundle.allowExistingCRDs=true (DANGEROUS — only if you understand the consequences)." }}
{{- end }}
{{- end }}
{{- /* Note: we deliberately do NOT fail here when (mode=self-signed | trustManager.install=true |
@@ -320,39 +336,41 @@ Runs from NOTES.txt so every install/upgrade is checked, regardless of which (or
Job hook is the authoritative apply-time check; if cert-manager truly isn't present at apply
time, the cert-manager.io / trust.cert-manager.io resources will fail to reconcile and
surface in `kubectl get certificate`. */ -}}
-{{- if .Values.ingress.tls.enabled }}
-{{- $mode := .Values.ingress.tls.mode }}
+{{- if $tls.enabled }}
+{{- $mode := default "byo" $tls.mode }}
{{- if not (or (eq $mode "byo") (eq $mode "cert-manager") (eq $mode "self-signed") (eq $mode "disabled")) }}
-{{- fail (printf "Invalid configuration: ingress.tls.mode=%q. Must be one of: \"byo\", \"cert-manager\", \"self-signed\", \"disabled\"." $mode) }}
+{{- fail (printf "Invalid configuration: ingress.tlsConfig.mode=%q. Must be one of: \"byo\", \"cert-manager\", \"self-signed\", \"disabled\"." $mode) }}
{{- end }}
{{- if eq $mode "cert-manager" }}
-{{- if not (include "sie-cluster.ingress.hosts" . | fromJsonArray) }}
-{{- fail "Invalid configuration: ingress.tls.mode=cert-manager requires ingress.host or ingress.hosts to be set (cert-manager has nothing to issue a certificate against without a hostname)." }}
+{{- if not $hosts }}
+{{- fail "Invalid configuration: ingress.tlsConfig.mode=cert-manager requires ingress.host or ingress.hosts to be set (cert-manager has nothing to issue a certificate against without a hostname)." }}
{{- end }}
-{{- $kind := .Values.ingress.tls.certManager.kind }}
+{{- $certManager := default (dict) $tls.certManager }}
+{{- $kind := default "" $certManager.kind }}
{{- if not (or (eq $kind "ClusterIssuer") (eq $kind "Issuer")) }}
-{{- fail (printf "Invalid configuration: ingress.tls.certManager.kind=%q. Must be either \"ClusterIssuer\" or \"Issuer\" (case-sensitive)." $kind) }}
+{{- fail (printf "Invalid configuration: ingress.tlsConfig.certManager.kind=%q. Must be either \"ClusterIssuer\" or \"Issuer\" (case-sensitive)." $kind) }}
{{- end }}
-{{- if .Values.ingress.tls.certManager.create }}
-{{- if not .Values.ingress.tls.certManager.server }}
-{{- fail "Invalid configuration: ingress.tls.certManager.create=true requires ingress.tls.certManager.server to be set (ACME directory URL is required)." }}
+{{- if $certManager.create }}
+{{- if not $certManager.server }}
+{{- fail "Invalid configuration: ingress.tlsConfig.certManager.create=true requires ingress.tlsConfig.certManager.server to be set (ACME directory URL is required)." }}
{{- end }}
-{{- if not .Values.ingress.tls.certManager.privateKeySecretRef }}
-{{- fail "Invalid configuration: ingress.tls.certManager.create=true requires ingress.tls.certManager.privateKeySecretRef to be set (ACME account key Secret name is required)." }}
+{{- if not $certManager.privateKeySecretRef }}
+{{- fail "Invalid configuration: ingress.tlsConfig.certManager.create=true requires ingress.tlsConfig.certManager.privateKeySecretRef to be set (ACME account key Secret name is required)." }}
{{- end }}
-{{- if not .Values.ingress.tls.certManager.email }}
-{{- fail "Invalid configuration: ingress.tls.certManager.create=true requires ingress.tls.certManager.email to be set (ACME account registration needs an email)." }}
+{{- if not $certManager.email }}
+{{- fail "Invalid configuration: ingress.tlsConfig.certManager.create=true requires ingress.tlsConfig.certManager.email to be set (ACME account registration needs an email)." }}
{{- end }}
{{- else }}
-{{- if not .Values.ingress.tls.certManager.name }}
-{{- fail "Invalid configuration: ingress.tls.certManager.create=false requires ingress.tls.certManager.name to be set (without a name there is no existing Issuer/ClusterIssuer to annotate against)." }}
+{{- if not $certManager.name }}
+{{- fail "Invalid configuration: ingress.tlsConfig.certManager.create=false requires ingress.tlsConfig.certManager.name to be set (without a name there is no existing Issuer/ClusterIssuer to annotate against)." }}
{{- end }}
{{- end }}
{{- end }}
{{- if eq $mode "self-signed" }}
-{{- $hosts := include "sie-cluster.ingress.hosts" . | fromJsonArray }}
-{{- if and (empty $hosts) (empty .Values.ingress.tls.selfSigned.leaf.dnsNames) (empty .Values.ingress.tls.selfSigned.leaf.ipAddresses) }}
-{{- fail "Invalid configuration: ingress.tls.mode=self-signed requires at least one of ingress.hosts (or ingress.host), ingress.tls.selfSigned.leaf.dnsNames, or ingress.tls.selfSigned.leaf.ipAddresses to be set (the leaf certificate needs at least one SAN)." }}
+{{- $selfSigned := default (dict) $tls.selfSigned }}
+{{- $leaf := default (dict) $selfSigned.leaf }}
+{{- if and (empty $hosts) (empty $leaf.dnsNames) (empty $leaf.ipAddresses) }}
+{{- fail "Invalid configuration: ingress.tlsConfig.mode=self-signed requires at least one of ingress.hosts (or ingress.host), ingress.tlsConfig.selfSigned.leaf.dnsNames, or ingress.tlsConfig.selfSigned.leaf.ipAddresses to be set (the leaf certificate needs at least one SAN)." }}
{{- end }}
{{- end }}
{{- end }}
diff --git a/deploy/helm/sie-cluster/templates/cluster-issuer.yaml b/deploy/helm/sie-cluster/templates/cluster-issuer.yaml
index c4e1f515a..778aab3ec 100644
--- a/deploy/helm/sie-cluster/templates/cluster-issuer.yaml
+++ b/deploy/helm/sie-cluster/templates/cluster-issuer.yaml
@@ -1,23 +1,25 @@
-{{- if and .Values.ingress.tls.enabled (eq .Values.ingress.tls.mode "cert-manager") .Values.ingress.tls.certManager.create }}
-{{- $issuerName := .Values.ingress.tls.certManager.name }}
+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}
+{{- $certManager := default (dict) $tls.certManager }}
+{{- if and $tls.enabled (eq (default "byo" $tls.mode) "cert-manager") $certManager.create }}
+{{- $issuerName := $certManager.name }}
{{- if not $issuerName }}{{ $issuerName = printf "%s-letsencrypt-prod" (include "sie-cluster.fullname" .) }}{{ end }}
apiVersion: cert-manager.io/v1
-kind: {{ .Values.ingress.tls.certManager.kind }}
+kind: {{ $certManager.kind }}
metadata:
name: {{ $issuerName }}
- {{- if eq .Values.ingress.tls.certManager.kind "Issuer" }}
+ {{- if eq $certManager.kind "Issuer" }}
namespace: {{ include "sie-cluster.namespace" . }}
{{- end }}
labels:
{{- include "sie-cluster.labels" . | nindent 4 }}
spec:
acme:
- server: {{ .Values.ingress.tls.certManager.server | quote }}
- email: {{ .Values.ingress.tls.certManager.email | quote }}
+ server: {{ $certManager.server | quote }}
+ email: {{ $certManager.email | quote }}
privateKeySecretRef:
- name: {{ .Values.ingress.tls.certManager.privateKeySecretRef | quote }}
+ name: {{ $certManager.privateKeySecretRef | quote }}
solvers:
- http01:
ingress:
- ingressClassName: {{ default .Values.ingress.className .Values.ingress.tls.certManager.ingressClassName }}
+ ingressClassName: {{ default .Values.ingress.className $certManager.ingressClassName }}
{{- end }}
diff --git a/deploy/helm/sie-cluster/templates/config-deployment.yaml b/deploy/helm/sie-cluster/templates/config-deployment.yaml
index 501191661..cb2e3971b 100644
--- a/deploy/helm/sie-cluster/templates/config-deployment.yaml
+++ b/deploy/helm/sie-cluster/templates/config-deployment.yaml
@@ -11,7 +11,7 @@ spec:
{{- /*
sie-config is intentionally hardcoded to a single replica.
- State it owns (see packages/sie_gateway/docs/architecture-guide.md §3, §11):
+ State it owns (see packages/sie_gateway/docs/architecture-guide.md sections 3 and 11):
- epoch counter on disk (RMW increment)
- per-process asyncio.Lock serializing writes
- per-process Idempotency-Key LRU cache
diff --git a/deploy/helm/sie-cluster/templates/dashboard-configmaps.yaml b/deploy/helm/sie-cluster/templates/dashboard-configmaps.yaml
index ca033044f..3ebb18d3f 100644
--- a/deploy/helm/sie-cluster/templates/dashboard-configmaps.yaml
+++ b/deploy/helm/sie-cluster/templates/dashboard-configmaps.yaml
@@ -79,4 +79,20 @@ metadata:
data:
sie-generation.json: |-
{{ .Files.Get "files/dashboards/generation.json" | indent 4 }}
+
+---
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: {{ include "sie-cluster.fullname" . }}-dashboard-perf-tuning
+ namespace: {{ include "sie-cluster.namespace" . }}
+ labels:
+ {{- include "sie-cluster.labels" . | nindent 4 }}
+ app.kubernetes.io/component: dashboard
+ grafana_dashboard: "1"
+ annotations:
+ grafana_folder: SIE
+data:
+ sie-perf-tuning.json: |-
+{{ .Files.Get "files/dashboards/perf-tuning.json" | indent 4 }}
{{- end }}
diff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml
index 47b97b740..b50102250 100644
--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml
+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml
@@ -1,7 +1,7 @@
{{- /* Validate: at most one static overlay may be active. Zero overlays is the
- default — the gateway fetches bundles+models from sie-config at startup
+ default; the gateway fetches bundles+models from sie-config at startup
and has NO baked-in filesystem seed (see
- packages/sie_gateway/docs/architecture-guide.md §4). */}}
+ packages/sie_gateway/docs/architecture-guide.md section 4). */}}
{{- $modesEnabled := list }}
{{- if .Values.gateway.embeddedConfigs.enabled }}{{- $modesEnabled = append $modesEnabled "embeddedConfigs" }}{{- end }}
{{- if .Values.gateway.configMap.enabled }}{{- $modesEnabled = append $modesEnabled "configMap" }}{{- end }}
@@ -11,17 +11,18 @@
{{- /* Validate: gateway needs SOME source of bundles/models. Since the image
no longer bakes a seed, disabling sie-config without also enabling a
static overlay would leave the gateway permanently empty and 404 every
- model request — an obvious deployment-time bug that's worth catching
+ model request; an obvious deployment-time bug that's worth catching
before the cluster runs. */}}
{{- if and (not .Values.config.enabled) (eq (len $modesEnabled) 0) }}
- {{- fail "gateway: config.enabled=false requires one of gateway.embeddedConfigs.enabled or gateway.configMap.enabled — the gateway image no longer bakes bundles/models, so something must provide them. See packages/sie_gateway/docs/architecture-guide.md §11 caveat 7." }}
+ {{- fail "gateway: config.enabled=false requires one of gateway.embeddedConfigs.enabled or gateway.configMap.enabled; the gateway image no longer bakes bundles/models, so something must provide them. See packages/sie_gateway/docs/architecture-guide.md section 11 caveat 7." }}
{{- end }}
{{- /* Validate: `clusterRouting` is queue-only today. The Rust gateway has
- no direct-mode code path — the legacy "direct" value was a Python-gateway
- artifact and is now a footgun (operators requesting direct would silently
+ no direct-mode code path; "direct" belongs to Python-gateway deployments
+ and is now a footgun (operators requesting direct would silently
get queue behavior). Workers still honor SIE_CLUSTER_ROUTING=queue for
pull-loop gating; see packages/sie_server/src/sie_server/app/app_factory.py.
- Queue mode requires NATS+JetStream and an object-store payload store. */}}
+ Queue mode requires NATS+JetStream; large-payload offload additionally
+ requires a shared object-store payload store. */}}
{{- $routing := default "queue" .Values.clusterRouting }}
{{- if ne $routing "queue" }}
{{- fail (printf "clusterRouting=%q is not supported; the gateway is queue-only. Set clusterRouting: queue or leave unset." $routing) }}
@@ -129,6 +130,13 @@ spec:
value: {{ include "sie-cluster.worker.serviceName" . }}
- name: SIE_MULTI_ROUTER
value: {{ gt (int .Values.gateway.replicas) 1 | quote }}
+ {{- $defaultHealthMode := ternary "nats" "" (and .Values.nats.enabled .Values.workers.common.workerSidecar.enabled) }}
+ {{- $explicitHealthMode := default "" .Values.gateway.healthMode }}
+ {{- $healthMode := default $defaultHealthMode $explicitHealthMode }}
+ {{- if $healthMode }}
+ - name: SIE_GATEWAY_HEALTH_MODE
+ value: {{ $healthMode | quote }}
+ {{- end }}
# Available GPU types (from Helm values, survives scale-to-zero)
- name: SIE_GATEWAY_CONFIGURED_GPUS
valueFrom:
@@ -180,11 +188,15 @@ spec:
value: {{ include "sie-cluster.config.serviceName" . | quote }}
{{- end }}
{{- end }}
+ {{- with .Values.queueRouting }}
+ - name: SIE_STREAM_MAX_AGE_S
+ value: {{ .streamMaxAgeSec | default 120 | quote }}
+ {{- end }}
{{- if .Values.config.enabled }}
# URL of the sie-config control plane. The gateway uses it for
# the cold-start GET /v1/configs/export bootstrap and the 30-s
# GET /v1/configs/epoch drift poll. See
- # packages/sie_gateway/docs/architecture-guide.md §4.
+ # packages/sie_gateway/docs/architecture-guide.md section 4.
- name: SIE_CONFIG_SERVICE_URL
value: {{ include "sie-cluster.config.internalUrl" . | quote }}
{{- if .Values.config.auth.adminTokenSecretName }}
@@ -208,7 +220,7 @@ spec:
# Optional ConfigMap overlay: when enabled, the gateway reads its
# bundle/model seed from /configs at startup. By default neither
# overlay is on and the gateway fetches everything from sie-config
- # via /v1/configs/bundles + /v1/configs/export — see
+ # via /v1/configs/bundles + /v1/configs/export; see
# packages/sie_gateway/src/state/config_bootstrap.rs.
- name: SIE_BUNDLES_DIR
value: /configs/bundles
diff --git a/deploy/helm/sie-cluster/templates/hooks/cert-manager-conflict-check.yaml b/deploy/helm/sie-cluster/templates/hooks/cert-manager-conflict-check.yaml
index 8ead51462..8e11ecc71 100644
--- a/deploy/helm/sie-cluster/templates/hooks/cert-manager-conflict-check.yaml
+++ b/deploy/helm/sie-cluster/templates/hooks/cert-manager-conflict-check.yaml
@@ -3,8 +3,9 @@
(b) Bundle off + cert-manager-dependent mode (self-signed, trust-manager, trustBundle):
fail if cert-manager is NOT present (presence check).
Both cases share the label-based detection logic and the same RBAC. */ -}}
-{{- $tlsMode := .Values.ingress.tls.mode }}
-{{- $needsCm := or .Values.certManagerBundle.trustManager.install .Values.certManagerBundle.trustBundle.enabled (and .Values.ingress.tls.enabled (or (eq $tlsMode "self-signed") (eq $tlsMode "cert-manager"))) }}
+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}
+{{- $tlsMode := default "byo" $tls.mode }}
+{{- $needsCm := or .Values.certManagerBundle.trustManager.install .Values.certManagerBundle.trustBundle.enabled (and $tls.enabled (or (eq $tlsMode "self-signed") (eq $tlsMode "cert-manager"))) }}
{{- $bundleOn := .Values.certManagerBundle.certManager.install }}
{{- if or $bundleOn $needsCm }}
{{- $fullname := include "sie-cluster.fullname" . }}
@@ -116,7 +117,7 @@ spec:
Refusing to install bundled cert-manager because two controllers reconciling
the same CRDs will corrupt issuance state.
Remediation:
- (a) set certManagerBundle.certManager.install=false and use ingress.tls.mode=cert-manager
+ (a) set certManagerBundle.certManager.install=false and use ingress.tlsConfig.mode=cert-manager
against the existing install, OR
(b) uninstall the existing cert-manager first, OR
(c) set certManagerBundle.allowExistingCRDs=true (DANGEROUS).
diff --git a/deploy/helm/sie-cluster/templates/hooks/prometheus-ready-test.yaml b/deploy/helm/sie-cluster/templates/hooks/prometheus-ready-test.yaml
index bb372845c..691b1c405 100644
--- a/deploy/helm/sie-cluster/templates/hooks/prometheus-ready-test.yaml
+++ b/deploy/helm/sie-cluster/templates/hooks/prometheus-ready-test.yaml
@@ -1,7 +1,7 @@
{{- if and .Values.healthGates.enabled .Values.autoscaling.enabled }}
{{- /*
When kube-prometheus-stack is installed as a sub-chart, Prometheus runs in the release
- namespace — not the hardcoded "monitoring" namespace. Auto-derive both the namespace
+ namespace; not the hardcoded "monitoring" namespace. Auto-derive both the namespace
and address so the health gate Job can reach Prometheus without manual overrides.
*/ -}}
{{- $promNs := .Values.healthGates.monitoringNamespace }}
diff --git a/deploy/helm/sie-cluster/templates/ingress.yaml b/deploy/helm/sie-cluster/templates/ingress.yaml
index d446c69e2..d767b12b0 100644
--- a/deploy/helm/sie-cluster/templates/ingress.yaml
+++ b/deploy/helm/sie-cluster/templates/ingress.yaml
@@ -1,5 +1,6 @@
{{- if .Values.ingress.enabled }}
{{- $hosts := include "sie-cluster.ingress.hosts" . | fromJsonArray }}
+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
@@ -33,9 +34,10 @@ metadata:
{{- /* cert-manager mode: rely on ingress-shim to auto-create the leaf Certificate from the annotation.
self-signed mode renders an explicit Certificate (see self-signed-issuer.yaml); adding the
annotation here would race ingress-shim with the explicit Cert (both targeting the same Secret). */ -}}
- {{- if and .Values.ingress.tls.enabled (eq .Values.ingress.tls.mode "cert-manager") }}
- {{- $issuerAnnotation := ternary "cert-manager.io/cluster-issuer" "cert-manager.io/issuer" (eq .Values.ingress.tls.certManager.kind "ClusterIssuer") }}
- {{- $issuerName := .Values.ingress.tls.certManager.name }}
+ {{- if and $tls.enabled (eq (default "byo" $tls.mode) "cert-manager") }}
+ {{- $certManager := default (dict) $tls.certManager }}
+ {{- $issuerAnnotation := ternary "cert-manager.io/cluster-issuer" "cert-manager.io/issuer" (eq $certManager.kind "ClusterIssuer") }}
+ {{- $issuerName := $certManager.name }}
{{- if not $issuerName }}{{ $issuerName = printf "%s-letsencrypt-prod" (include "sie-cluster.fullname" .) }}{{ end }}
{{- $cmDefaults := dict $issuerAnnotation $issuerName }}
{{- $annotations = merge $annotations $cmDefaults }}
@@ -48,13 +50,13 @@ spec:
{{- if .Values.ingress.className }}
ingressClassName: {{ .Values.ingress.className }}
{{- end }}
- {{- if and .Values.ingress.tls.enabled $hosts }}
+ {{- if and $tls.enabled $hosts }}
tls:
- hosts:
{{- range $hosts }}
- {{ . | quote }}
{{- end }}
- secretName: {{ .Values.ingress.tls.secretName }}
+ secretName: {{ $tls.secretName }}
{{- end }}
rules:
{{- range (default (list "") $hosts) }}
diff --git a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml
index e089d16ed..26d290f0e 100644
--- a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml
+++ b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml
@@ -13,7 +13,7 @@
hook Job. This avoids the chicken-and-egg problem where Helm validates ScaledObject CRDs
before the KEDA sub-chart has installed them.
*/ -}}
-# ── RBAC for the apply Job (weight 1 — must exist before the Job at weight 2) ─
+# RBAC for the apply Job (weight 1; must exist before the Job at weight 2)
apiVersion: v1
kind: ServiceAccount
metadata:
@@ -62,7 +62,7 @@ subjects:
name: {{ include "sie-cluster.keda.apply.serviceAccountName" . }}
namespace: {{ include "sie-cluster.namespace" . }}
---
-# ── ConfigMap containing rendered ScaledObject manifests (weight 1 — mounted by Job at weight 2) ─
+# ConfigMap containing rendered ScaledObject manifests (weight 1; mounted by Job at weight 2)
# Each key is a separate YAML file applied by the hook Job via kubectl apply -f /config/
apiVersion: v1
kind: ConfigMap
@@ -152,10 +152,10 @@ data:
serverAddress: {{ $promAddr }}
metricName: sie_gateway_rejected_rate_{{ $poolName }}
# Filter out reasons the SDK already retries against the same
- # worker pool — they are per-request transient signals, not
+ # worker pool; they are per-request transient signals, not
# "we need more workers" signals:
# - resource_exhausted: worker hit GPU OOM after recovery
- # (cache_clear → evict_lru → split_batch). The SDK retries
+ # (cache_clear -> evict_lru -> split_batch). The SDK retries
# with bounded exponential backoff; scaling up here would
# cold-start a new GPU pod for what is a transient memory
# pressure event on an otherwise-healthy worker.
@@ -175,8 +175,8 @@ data:
# trigger.
#
# Note on regex anchoring: PromQL ``=~`` / ``!~`` are RE2 with
- # implicit ``^…$`` full-string anchors. The list below matches
- # exact reason values only — a future suffixed reason like
+ # implicit full-string anchors. The list below matches
+ # exact reason values only; a future suffixed reason like
# ``resource_exhausted_extended`` would NOT be excluded and
# would drive scale-up. If new retryable reasons are added in
# ``proxy.rs::record_rejected_request``, append them here.
@@ -210,7 +210,7 @@ data:
query: sum(rate(sie_gateway_requests_total[1m])) or vector(0)
threshold: "100"
---
-# ── Hook Job: wait for KEDA CRDs then apply ScaledObjects ───────────────────
+# Hook Job: wait for KEDA CRDs then apply ScaledObjects
apiVersion: batch/v1
kind: Job
metadata:
diff --git a/deploy/helm/sie-cluster/templates/oauth2-proxy-ingress.yaml b/deploy/helm/sie-cluster/templates/oauth2-proxy-ingress.yaml
index 8c4802be6..05f989797 100644
--- a/deploy/helm/sie-cluster/templates/oauth2-proxy-ingress.yaml
+++ b/deploy/helm/sie-cluster/templates/oauth2-proxy-ingress.yaml
@@ -1,5 +1,6 @@
{{- if and .Values.auth.enabled .Values.ingress.enabled }}
{{- $hosts := include "sie-cluster.ingress.hosts" . | fromJsonArray }}
+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
@@ -16,13 +17,13 @@ spec:
{{- if .Values.ingress.className }}
ingressClassName: {{ .Values.ingress.className }}
{{- end }}
- {{- if and .Values.ingress.tls.enabled $hosts }}
+ {{- if and $tls.enabled $hosts }}
tls:
- hosts:
{{- range $hosts }}
- {{ . | quote }}
{{- end }}
- secretName: {{ .Values.ingress.tls.secretName }}
+ secretName: {{ $tls.secretName }}
{{- end }}
rules:
{{- range (default (list "") $hosts) }}
diff --git a/deploy/helm/sie-cluster/templates/rbac.yaml b/deploy/helm/sie-cluster/templates/rbac.yaml
index 4e9f98ce3..ffcc7cc44 100644
--- a/deploy/helm/sie-cluster/templates/rbac.yaml
+++ b/deploy/helm/sie-cluster/templates/rbac.yaml
@@ -31,7 +31,7 @@ subjects:
namespace: {{ include "sie-cluster.namespace" . }}
---
# Role for gateway to manage resource pools (ConfigMaps + Leases)
-# Per DESIGN.md Section 10.3: Pools use ConfigMap for spec/status, Lease for TTL
+# Pools use ConfigMap for spec/status and Lease for TTL
# See: Rust gateway pool management
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
diff --git a/deploy/helm/sie-cluster/templates/self-signed-issuer.yaml b/deploy/helm/sie-cluster/templates/self-signed-issuer.yaml
index f20a732f2..c306bfa3b 100644
--- a/deploy/helm/sie-cluster/templates/self-signed-issuer.yaml
+++ b/deploy/helm/sie-cluster/templates/self-signed-issuer.yaml
@@ -1,7 +1,8 @@
-{{- if and .Values.ingress.tls.enabled (eq .Values.ingress.tls.mode "self-signed") }}
+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}
+{{- if and $tls.enabled (eq (default "byo" $tls.mode) "self-signed") }}
{{- $fullname := include "sie-cluster.fullname" . }}
{{- $ns := include "sie-cluster.namespace" . }}
-{{- $self := .Values.ingress.tls.selfSigned }}
+{{- $self := $tls.selfSigned }}
{{- /* Root CA lives in cert-manager's --cluster-resource-namespace so the CA ClusterIssuer can find its Secret. */ -}}
{{- $rootCaNs := default $ns $self.rootCA.namespace }}
apiVersion: cert-manager.io/v1
@@ -55,7 +56,7 @@ metadata:
labels:
{{- include "sie-cluster.labels" . | nindent 4 }}
spec:
- secretName: {{ .Values.ingress.tls.secretName | quote }}
+ secretName: {{ $tls.secretName | quote }}
duration: {{ $self.leaf.duration | quote }}
renewBefore: {{ $self.leaf.renewBefore | quote }}
privateKey:
diff --git a/deploy/helm/sie-cluster/templates/servicemonitor.yaml b/deploy/helm/sie-cluster/templates/servicemonitor.yaml
index 6a8127c9f..d5943e8ee 100644
--- a/deploy/helm/sie-cluster/templates/servicemonitor.yaml
+++ b/deploy/helm/sie-cluster/templates/servicemonitor.yaml
@@ -1,12 +1,17 @@
{{- if .Values.serviceMonitor.enabled }}
-# ServiceMonitor for Prometheus Operator
-# Scrapes metrics from the gateway, sie-config, and all worker pools (any
-# service that exposes the `http` port under the chart's common selector
-# labels).
+{{/*
+Per-component ServiceMonitors. A single monitor with the shared
+`sie-cluster.selectorLabels` selector matches the gateway, config, and
+worker Services; only the worker Service exposes the `worker-metrics` port,
+so Prometheus would log scrape failures against gateway/config for that
+port. Split into one ServiceMonitor per component so each monitor only
+scrapes the ports it knows exist.
+*/}}
+# Gateway ServiceMonitor
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
- name: {{ include "sie-cluster.fullname" . }}
+ name: {{ include "sie-cluster.fullname" . }}-gateway
namespace: {{ include "sie-cluster.namespace" . }}
labels:
{{- include "sie-cluster.labels" . | nindent 4 }}
@@ -16,7 +21,7 @@ metadata:
spec:
selector:
matchLabels:
- {{- include "sie-cluster.selectorLabels" . | nindent 6 }}
+ {{- include "sie-cluster.gateway.selectorLabels" . | nindent 6 }}
namespaceSelector:
matchNames:
- {{ include "sie-cluster.namespace" . }}
@@ -25,4 +30,36 @@ spec:
interval: {{ .Values.serviceMonitor.interval }}
scrapeTimeout: {{ .Values.serviceMonitor.scrapeTimeout }}
path: /metrics
+---
+# Worker ServiceMonitor (Python + optional worker-sidecar)
+apiVersion: monitoring.coreos.com/v1
+kind: ServiceMonitor
+metadata:
+ name: {{ include "sie-cluster.fullname" . }}-worker
+ namespace: {{ include "sie-cluster.namespace" . }}
+ labels:
+ {{- include "sie-cluster.labels" . | nindent 4 }}
+ {{- with .Values.serviceMonitor.labels }}
+ {{- toYaml . | nindent 4 }}
+ {{- end }}
+spec:
+ selector:
+ matchLabels:
+ {{- include "sie-cluster.worker.selectorLabels" . | nindent 6 }}
+ namespaceSelector:
+ matchNames:
+ - {{ include "sie-cluster.namespace" . }}
+ endpoints:
+ - port: http
+ interval: {{ .Values.serviceMonitor.interval }}
+ scrapeTimeout: {{ .Values.serviceMonitor.scrapeTimeout }}
+ path: /metrics
+ {{- if .Values.workers.common.workerSidecar.enabled }}
+ # worker-sidecar metrics (NATS pull loop, backend routing,
+ # circuit breaker state, per-backend latency histograms).
+ - port: worker-metrics
+ interval: {{ .Values.serviceMonitor.interval }}
+ scrapeTimeout: {{ .Values.serviceMonitor.scrapeTimeout }}
+ path: /metrics
+ {{- end }}
{{- end }}
diff --git a/deploy/helm/sie-cluster/templates/trust-bundle.yaml b/deploy/helm/sie-cluster/templates/trust-bundle.yaml
index acc91f1a6..1c45170a4 100644
--- a/deploy/helm/sie-cluster/templates/trust-bundle.yaml
+++ b/deploy/helm/sie-cluster/templates/trust-bundle.yaml
@@ -1,4 +1,5 @@
-{{- if and .Values.certManagerBundle.trustBundle.enabled (eq .Values.ingress.tls.mode "self-signed") }}
+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}
+{{- if and .Values.certManagerBundle.trustBundle.enabled (eq (default "byo" $tls.mode) "self-signed") }}
apiVersion: trust.cert-manager.io/v1alpha1
kind: Bundle
metadata:
@@ -8,7 +9,7 @@ metadata:
spec:
sources:
- secret:
- name: {{ .Values.ingress.tls.selfSigned.rootCA.secretName | quote }}
+ name: {{ $tls.selfSigned.rootCA.secretName | quote }}
key: ca.crt
target:
configMap:
diff --git a/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml b/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml
index 7eda8bc8c..38abaa398 100644
--- a/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml
+++ b/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml
@@ -8,6 +8,9 @@
{{- $platform := default $root.Values.workers.common.platform $pool.platform }}
{{- $imageTag := default $root.Chart.AppVersion $root.Values.workers.common.image.tag }}
{{- $workerImage := printf "%s:%s-%s-%s" $root.Values.workers.common.image.repository $imageTag $platform $imageBundle }}
+{{- $rs := $root.Values.workers.common.workerSidecar }}
+{{- $rsTag := default $root.Chart.AppVersion $rs.image.tag }}
+{{- $rsImage := printf "%s:%s" $rs.image.repository $rsTag }}
---
apiVersion: apps/v1
kind: DaemonSet
@@ -46,6 +49,19 @@ spec:
limits:
cpu: "10m"
memory: "16Mi"
+ {{- if $rs.enabled }}
+ - name: pull-sie-worker-sidecar-image
+ image: {{ $rsImage }}
+ imagePullPolicy: {{ $rs.image.pullPolicy }}
+ command: ["true"]
+ resources:
+ requests:
+ cpu: "1m"
+ memory: "8Mi"
+ limits:
+ cpu: "10m"
+ memory: "16Mi"
+ {{- end }}
containers:
- name: pause
image: registry.k8s.io/pause:3.10
diff --git a/deploy/helm/sie-cluster/templates/worker-service.yaml b/deploy/helm/sie-cluster/templates/worker-service.yaml
index 3bcf3afde..acd05b649 100644
--- a/deploy/helm/sie-cluster/templates/worker-service.yaml
+++ b/deploy/helm/sie-cluster/templates/worker-service.yaml
@@ -13,5 +13,11 @@ spec:
port: {{ .Values.workers.common.port }}
targetPort: http
protocol: TCP
+ {{- if .Values.workers.common.workerSidecar.enabled }}
+ - name: worker-metrics
+ port: {{ .Values.workers.common.workerSidecar.metricsPort }}
+ targetPort: metrics
+ protocol: TCP
+ {{- end }}
selector:
{{- include "sie-cluster.worker.selectorLabels" . | nindent 4 }}
diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
index 232f109a9..cfd5f9ebb 100644
--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml
@@ -1,4 +1,21 @@
{{- $root := . -}}
+{{/*
+Safety guard: the worker-sidecar container is the production data path (NATS ->
+Rust -> UDS IPC -> Python adapter process). The sidecar needs
+``SIE_NATS_URL`` and refuses to start without one, so enabling the
+sidecar without NATS produces a pod that CrashLoops forever. Fail
+fast at render time.
+*/}}
+{{- $routing := default "queue" $root.Values.clusterRouting }}
+{{- if and (eq $routing "queue") (not $root.Values.workers.common.workerSidecar.enabled) }}
+{{- fail "clusterRouting=queue requires workers.common.workerSidecar.enabled=true (the Python adapter process does not consume JetStream)" }}
+{{- end }}
+{{- if and $root.Values.workers.common.workerSidecar.enabled (not $root.Values.nats.enabled) }}
+{{- fail "workers.common.workerSidecar.enabled=true requires nats.enabled=true (the sidecar needs SIE_NATS_URL and has no default)" }}
+{{- end }}
+{{- if and $root.Values.workers.common.workerSidecar.enabled (not $root.Values.nats.config.jetstream.enabled) }}
+{{- fail "workers.common.workerSidecar.enabled=true requires nats.config.jetstream.enabled=true (the sidecar consumes JetStream)" }}
+{{- end }}
{{- range $poolName, $pool := .Values.workers.pools }}
{{- if $pool.enabled }}
{{- $bundle := default $root.Values.workers.common.bundle $pool.bundle }}
@@ -119,20 +136,8 @@ spec:
- name: SIE_NATS_URL
value: {{ $root.Values.nats.url | default (printf "nats://%s:4222" ($root.Values.nats.serviceName | default (printf "%s-nats" $root.Release.Name))) | quote }}
{{- end }}
- {{- if and $root.Values.clusterRouting (eq $root.Values.clusterRouting "queue") }}
- - name: SIE_CLUSTER_ROUTING
- value: {{ $root.Values.clusterRouting | quote }}
- name: SIE_POOL
value: {{ $queuePool | quote }}
- - name: SIE_GATEWAY_URL
- value: {{ include "sie-cluster.gateway.internalUrl" $root | quote }}
- {{- if $root.Values.gateway.auth.tokenSecretName }}
- - name: SIE_GATEWAY_API_KEY
- valueFrom:
- secretKeyRef:
- name: {{ $root.Values.gateway.auth.tokenSecretName }}
- key: {{ $root.Values.gateway.auth.tokenSecretKey }}
- {{- end }}
{{- with $root.Values.queueRouting }}
- name: SIE_NAK_DELAY_S
value: {{ .nakDelaySec | default 5 | quote }}
@@ -142,15 +147,6 @@ spec:
value: {{ .streamMaxAgeSec | default 120 | quote }}
- name: SIE_NATS_FETCH_BUDGET
value: {{ .natsFetchBudget | default 64 | quote }}
- {{- with .poolAdmission }}
- - name: SIE_POOL_ADMISSION_CHECK_INTERVAL_S
- value: {{ .checkIntervalSec | default 10 | quote }}
- - name: SIE_POOL_ADMISSION_PAUSE_S
- value: {{ .pauseSec | default 1 | quote }}
- - name: SIE_POOL_ADMISSION_STALE_AFTER_S
- value: {{ .staleAfterSec | default 30 | quote }}
- {{- end }}
- {{- end }}
{{- end }}
{{- $payloadStoreUrl := include "sie-cluster.payloadStoreUrl" $root }}
{{- if $payloadStoreUrl }}
@@ -170,6 +166,23 @@ spec:
value: {{ printf "%s-%s" $platform $bundle | quote }}
- name: SIE_DEPLOYMENT_ENV
value: {{ if and $root.Values.telemetry $root.Values.telemetry.deploymentEnv }}{{ $root.Values.telemetry.deploymentEnv | quote }}{{ else }}"production"{{ end }}
+ {{- if $root.Values.workers.common.workerSidecar.enabled }}
+ # worker-sidecar owns the NATS loop; Python exposes the IPC
+ # server over a shared Unix socket. The chart fails render
+ # (at the top of this file) if the sidecar is enabled
+ # without NATS.
+ - name: SIE_IPC_SOCKET_PATH
+ value: /var/run/sie/ipc.sock
+ - 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, so the pod
+ # has exactly one active batcher.
+ - name: SIE_WORKER_PASSTHROUGH
+ value: "1"
+ {{- end }}
+ {{- end }}
{{- with $root.Values.workers.common.extraEnv }}
{{- toYaml . | nindent 12 }}
{{- end }}
@@ -215,6 +228,228 @@ spec:
mountPath: /models
- name: shm
mountPath: /dev/shm
+ {{- if $root.Values.workers.common.workerSidecar.enabled }}
+ - name: sie-ipc
+ mountPath: /var/run/sie
+ {{- end }}
+ {{- if $root.Values.workers.common.workerSidecar.enabled }}
+ # worker-sidecar
+ # Owns the NATS JetStream pull loop and forwards work into
+ # the Python adapter process over a shared Unix socket.
+ - name: worker-sidecar
+ {{- $rs := $root.Values.workers.common.workerSidecar }}
+ {{- $configReconcile := default dict $rs.configReconcile }}
+ {{- $rsTag := default $root.Chart.AppVersion $rs.image.tag }}
+ image: {{ printf "%s:%s" $rs.image.repository $rsTag }}
+ imagePullPolicy: {{ $rs.image.pullPolicy }}
+ ports:
+ - name: metrics
+ containerPort: {{ $rs.metricsPort }}
+ protocol: TCP
+ env:
+ - name: SIE_WORKER_METRICS_PORT
+ value: {{ $rs.metricsPort | quote }}
+ - name: SIE_IPC_SOCKET_PATH
+ value: /var/run/sie/ipc.sock
+ - name: SIE_POOL
+ value: {{ $queuePool | quote }}
+ - name: SIE_BUNDLE
+ value: {{ $bundle | quote }}
+ - name: SIE_GATEWAY_URL
+ value: {{ include "sie-cluster.gateway.internalUrl" $root | quote }}
+ {{- if $root.Values.gateway.auth.tokenSecretName }}
+ - name: SIE_GATEWAY_API_KEY
+ valueFrom:
+ secretKeyRef:
+ name: {{ $root.Values.gateway.auth.tokenSecretName }}
+ key: {{ $root.Values.gateway.auth.tokenSecretKey }}
+ {{- end }}
+ - name: SIE_WORKER_ID
+ valueFrom:
+ fieldRef:
+ fieldPath: metadata.name
+ - name: RUST_LOG
+ value: {{ $rs.logLevel | quote }}
+ {{- if $root.Values.nats.enabled }}
+ - name: SIE_NATS_URL
+ value: {{ $root.Values.nats.url | default (printf "nats://%s:4222" ($root.Values.nats.serviceName | default (printf "%s-nats" $root.Release.Name))) | quote }}
+ {{- end }}
+ {{- if $root.Values.config.enabled }}
+ - name: SIE_NATS_CONFIG_TRUSTED_PRODUCERS
+ value: {{ include "sie-cluster.config.serviceName" $root | quote }}
+ {{- end }}
+ {{- if and $root.Values.config.enabled (dig "enabled" true $configReconcile) }}
+ # sie-config reconciliation catches worker-side missed Core NATS
+ # config deltas by polling /v1/configs/epoch and replaying
+ # /v1/configs/export through Python IPC.
+ - name: SIE_CONFIG_SERVICE_URL
+ value: {{ include "sie-cluster.config.internalUrl" $root | quote }}
+ {{- if $root.Values.config.auth.adminTokenSecretName }}
+ - name: SIE_ADMIN_TOKEN
+ valueFrom:
+ secretKeyRef:
+ name: {{ $root.Values.config.auth.adminTokenSecretName }}
+ key: {{ $root.Values.config.auth.adminTokenSecretKey }}
+ {{- end }}
+ {{- if $configReconcile.pollIntervalMs }}
+ - name: SIE_WORKER_CONFIG_POLL_INTERVAL_MS
+ value: {{ $configReconcile.pollIntervalMs | quote }}
+ {{- end }}
+ {{- if hasKey $configReconcile "fullExportIntervalMs" }}
+ - name: SIE_WORKER_CONFIG_FULL_EXPORT_INTERVAL_MS
+ value: {{ $configReconcile.fullExportIntervalMs | quote }}
+ {{- end }}
+ {{- end }}
+ {{- with $root.Values.queueRouting }}
+ - name: SIE_NAK_DELAY_S
+ value: {{ .nakDelaySec | default 5 | quote }}
+ - name: SIE_MAX_DELIVER
+ value: {{ .maxDeliver | default 20 | quote }}
+ - name: SIE_NATS_FETCH_BUDGET
+ value: {{ .natsFetchBudget | default 64 | quote }}
+ # Keep stream retention in lockstep with the gateway and sidecar.
+ # Whoever creates the stream first wins, so both producers and
+ # consumers must agree on max_age or retries race against purge.
+ - name: SIE_STREAM_MAX_AGE_S
+ value: {{ .streamMaxAgeSec | default 120 | quote }}
+ {{- if .maxAckPending }}
+ - name: SIE_MAX_ACK_PENDING
+ value: {{ .maxAckPending | quote }}
+ {{- end }}
+ {{- with .poolAdmission }}
+ - name: SIE_POOL_ADMISSION_ENABLED
+ value: {{ if hasKey . "enabled" }}{{ .enabled | quote }}{{ else }}"true"{{ end }}
+ - name: SIE_POOL_ADMISSION_CHECK_INTERVAL_S
+ value: {{ .checkIntervalSec | default 10 | quote }}
+ - name: SIE_POOL_ADMISSION_PAUSE_S
+ value: {{ .pauseSec | default 1 | quote }}
+ - name: SIE_POOL_ADMISSION_STALE_AFTER_S
+ value: {{ .staleAfterSec | default 30 | quote }}
+ {{- end }}
+ {{- end }}
+ {{- $natsConsumerReconcile := default dict $rs.natsConsumerReconcile }}
+ {{- if hasKey $natsConsumerReconcile "intervalMs" }}
+ - name: SIE_NATS_CONSUMER_RECONCILE_INTERVAL_MS
+ value: {{ $natsConsumerReconcile.intervalMs | quote }}
+ {{- end }}
+ {{- if $rs.maxConcurrentBatches }}
+ - name: SIE_MAX_CONCURRENT_BATCHES
+ value: {{ $rs.maxConcurrentBatches | quote }}
+ {{- end }}
+ {{- if $rs.ipcPoolSize }}
+ # Size of the Rust-to-Python IPC connection pool. Should match
+ # (or exceed) SIE_MAX_CONCURRENT_BATCHES so the IPC layer
+ # isn't the binding constraint on dispatcher concurrency.
+ # When unset the Rust binary falls back to the dispatcher's
+ # own default (4).
+ - name: SIE_IPC_POOL_SIZE
+ value: {{ $rs.ipcPoolSize | quote }}
+ {{- end }}
+ {{- if $rs.pingIntervalMs }}
+ - name: SIE_WORKER_PING_INTERVAL_MS
+ value: {{ $rs.pingIntervalMs | quote }}
+ {{- end }}
+ {{- if $rs.readyStaleMult }}
+ # /readyz freshness-window multiplier:
+ # freshness_ms = ping_interval_ms * ready_stale_mult
+ - name: SIE_WORKER_READYZ_STALE_MULT
+ value: {{ $rs.readyStaleMult | quote }}
+ {{- end }}
+ # NATS health-heartbeat publisher.
+ #
+ # With the worker-sidecar data path, the gateway builds its
+ # queue WorkerRegistry strictly from `sie.health.>` messages.
+ # Use `dig` rather than `default` so an explicit
+ # `healthPublish.enabled: false` stays false.
+ - name: SIE_HEALTH_PUBLISH_ENABLED
+ value: {{ dig "healthPublish" "enabled" true $rs | quote }}
+ {{- if $rs.healthPublish.intervalMs }}
+ - name: SIE_HEALTH_PUBLISH_INTERVAL_MS
+ value: {{ $rs.healthPublish.intervalMs | quote }}
+ {{- end }}
+ - name: SIE_MACHINE_PROFILE
+ value: {{ $rs.healthPublish.machineProfile | default $machineProfile | quote }}
+ {{- if $pool.gpu }}
+ {{- if $pool.gpu.count }}
+ - name: SIE_GPU_COUNT
+ value: {{ $pool.gpu.count | quote }}
+ {{- end }}
+ {{- end }}
+ {{- if $payloadStoreUrl }}
+ - name: SIE_PAYLOAD_STORE_URL
+ value: {{ $payloadStoreUrl | quote }}
+ {{- end }}
+ {{- if $rs.metricModelAllowlist }}
+ - name: SIE_METRIC_MODEL_ALLOWLIST
+ value: {{ $rs.metricModelAllowlist | quote }}
+ {{- end }}
+ # Queue-mode scheduler tuning. Each typed field maps to
+ # one env var; rendered before `extraEnv` so an
+ # operator-provided override wins.
+ {{- if $rs.pipelineDepth }}
+ - name: SIE_RUST_PIPELINE_DEPTH
+ value: {{ $rs.pipelineDepth | quote }}
+ {{- end }}
+ {{- if $rs.batcher }}
+ {{- if $rs.batcher.coalesceMs }}
+ - name: SIE_BATCHER_COALESCE_MS
+ value: {{ $rs.batcher.coalesceMs | quote }}
+ {{- end }}
+ {{- if $rs.batcher.maxBatchRequests }}
+ - name: SIE_BATCHER_MAX_BATCH_REQUESTS
+ value: {{ $rs.batcher.maxBatchRequests | quote }}
+ {{- end }}
+ {{- end }}
+ {{- if $rs.adaptive }}
+ {{- if $rs.adaptive.minQuantumMs }}
+ - name: SIE_ADAPTIVE_MIN_QUANTUM_MS
+ value: {{ $rs.adaptive.minQuantumMs | quote }}
+ {{- end }}
+ {{- if $rs.adaptive.maxQuantumMs }}
+ - name: SIE_ADAPTIVE_MAX_QUANTUM_MS
+ value: {{ $rs.adaptive.maxQuantumMs | quote }}
+ {{- end }}
+ {{- if $rs.adaptive.targetP50Ms }}
+ - name: SIE_ADAPTIVE_TARGET_P50_MS
+ value: {{ $rs.adaptive.targetP50Ms | quote }}
+ {{- end }}
+ {{- end }}
+ {{- with $rs.extraEnv }}
+ {{- toYaml . | nindent 12 }}
+ {{- end }}
+ {{- if $rs.probes.enabled }}
+ # worker-sidecar K8s probes
+ # Off by default while the Python container's existing
+ # /healthz + /readyz on port 8080 remain the K8s contract.
+ startupProbe:
+ httpGet:
+ path: /healthz
+ port: metrics
+ periodSeconds: {{ $rs.probes.startup.periodSeconds | default 5 }}
+ failureThreshold: {{ $rs.probes.startup.failureThreshold | default 60 }}
+ livenessProbe:
+ httpGet:
+ path: /healthz
+ port: metrics
+ initialDelaySeconds: {{ $rs.probes.liveness.initialDelaySeconds | default 10 }}
+ periodSeconds: {{ $rs.probes.liveness.periodSeconds | default 30 }}
+ timeoutSeconds: {{ $rs.probes.liveness.timeoutSeconds | default 5 }}
+ failureThreshold: {{ $rs.probes.liveness.failureThreshold | default 3 }}
+ readinessProbe:
+ httpGet:
+ path: /readyz
+ port: metrics
+ initialDelaySeconds: {{ $rs.probes.readiness.initialDelaySeconds | default 3 }}
+ periodSeconds: {{ $rs.probes.readiness.periodSeconds | default 5 }}
+ timeoutSeconds: {{ $rs.probes.readiness.timeoutSeconds | default 3 }}
+ failureThreshold: {{ $rs.probes.readiness.failureThreshold | default 3 }}
+ {{- end }}
+ resources:
+ {{- toYaml $rs.resources | nindent 12 }}
+ volumeMounts:
+ - name: sie-ipc
+ mountPath: /var/run/sie
+ {{- end }}
{{- with $pool.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
@@ -244,5 +479,13 @@ spec:
- name: model-cache
emptyDir:
sizeLimit: {{ $root.Values.workers.common.cacheStorageSize }}
+ {{- if $root.Values.workers.common.workerSidecar.enabled }}
+ # Shared Unix-socket directory between the Python adapter and
+ # the worker-sidecar (in-Pod IPC, no network hop).
+ - name: sie-ipc
+ emptyDir:
+ medium: Memory
+ sizeLimit: 64Mi
+ {{- end }}
{{- end }}
{{- end }}
diff --git a/deploy/helm/sie-cluster/values-aws.yaml b/deploy/helm/sie-cluster/values-aws.yaml
index 51ae053ed..9df32e259 100644
--- a/deploy/helm/sie-cluster/values-aws.yaml
+++ b/deploy/helm/sie-cluster/values-aws.yaml
@@ -58,7 +58,7 @@ ingress:
# 1) cert-manager + Let's Encrypt (external cert-manager install):
# hosts:
# - sie.example.com
- # tls:
+ # tlsConfig:
# enabled: true
# mode: cert-manager
# certManager:
@@ -67,7 +67,7 @@ ingress:
# 2) self-signed (air-gapped / on-prem; bundles cert-manager — single-tenant clusters only):
# hosts:
# - sie.example.com
- # tls:
+ # tlsConfig:
# enabled: true
# mode: self-signed
# # And at the top level:
@@ -76,7 +76,7 @@ ingress:
# # install: true
#
# 3) disabled (TLS terminated upstream of the Ingress):
- # tls:
+ # tlsConfig:
# enabled: false
# mode: disabled
diff --git a/deploy/helm/sie-cluster/values-gke.yaml b/deploy/helm/sie-cluster/values-gke.yaml
index 1b9507cc3..1f12ce21e 100644
--- a/deploy/helm/sie-cluster/values-gke.yaml
+++ b/deploy/helm/sie-cluster/values-gke.yaml
@@ -71,7 +71,7 @@ ingress:
# 1) cert-manager + Let's Encrypt (external cert-manager install):
# hosts:
# - sie.example.com
- # tls:
+ # tlsConfig:
# enabled: true
# mode: cert-manager
# certManager:
@@ -80,7 +80,7 @@ ingress:
# 2) self-signed (air-gapped / on-prem; bundles cert-manager — single-tenant clusters only):
# hosts:
# - sie.example.com
- # tls:
+ # tlsConfig:
# enabled: true
# mode: self-signed
# # And at the top level:
@@ -89,7 +89,7 @@ ingress:
# # install: true
#
# 3) disabled (TLS terminated upstream of the Ingress):
- # tls:
+ # tlsConfig:
# enabled: false
# mode: disabled
diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yaml
index cb894cec9..4bc51deda 100644
--- a/deploy/helm/sie-cluster/values.yaml
+++ b/deploy/helm/sie-cluster/values.yaml
@@ -9,7 +9,7 @@
# cold start (retried with backoff) and every 30s via
# GET /v1/configs/epoch for drift detection. Live updates flow
# on sie.config.models.* NATS subjects. POST /v1/configs/models
-# is not registered on the gateway — axum returns 405.
+# is not registered on the gateway; axum returns 405.
# - workers: GPU pods driven by pool manager.
# -- Global settings
@@ -21,9 +21,9 @@ global:
# -- Filesystem seed paths consumed only by sie-config (the gateway no longer
# bakes a seed: it pulls bundles+models from sie-config at startup via
-# /v1/configs/bundles and /v1/configs/export — see
+# /v1/configs/bundles and /v1/configs/export; see
# packages/sie_gateway/src/state/config_bootstrap.rs). Kept under `sharedPaths`
-# for the legacy gateway ConfigMap overlays (gateway.embeddedConfigs /
+# for standalone gateway ConfigMap overlays (gateway.embeddedConfigs /
# gateway.configMap) which still mount their bundle/model files from disk; in
# the default deploy these are sie-config-only knobs.
sharedPaths:
@@ -36,7 +36,7 @@ sharedPaths:
# image, service, and (optional) persistent config store PVC.
#
# Single-replica caveat: running with replicas=1 is a conscious control-plane SPOF.
-# See packages/sie_gateway/docs/architecture-guide.md §11 for the failure model.
+# See packages/sie_gateway/docs/architecture-guide.md section 11 for the failure model.
config:
# -- Deploy the sie-config workload. Set false to skip rendering the
# Deployment, Service, and PVC (useful for dev environments that rely on
@@ -44,11 +44,11 @@ config:
enabled: true
# NOTE: replica count is intentionally hardcoded to 1 in
- # templates/config-deployment.yaml — there is no `replicas` key here by
+ # templates/config-deployment.yaml; there is no `replicas` key here by
# design. Going multi-replica requires leader election + shared
# idempotency + a single-writer discipline on the epoch file, plus an
# RWX PVC (or leader-only mount). See the template comment and
- # packages/sie_gateway/docs/architecture-guide.md §3 and §11.
+ # packages/sie_gateway/docs/architecture-guide.md sections 3 and 11.
image:
repository: ghcr.io/superlinked/sie-config
@@ -93,8 +93,8 @@ config:
# -- Liveness/readiness/startup probe timing. The httpGet path/port are
# contracts owned by the template (sie-config exposes /healthz and /readyz);
- # only the timing fields below are overridable. Defaults match the previous
- # hardcoded values (modulo the dropped startupProbe.initialDelaySeconds).
+ # only the timing fields below are overridable. Defaults preserve the chart's
+ # existing probe budget.
probes:
startup:
periodSeconds: 5
@@ -137,6 +137,11 @@ gateway:
# restart is an unacceptable blip on inference traffic.
replicas: 1
+ # -- Worker-health discovery mode. Empty lets the chart choose the
+ # routing-safe default: "nats" when NATS and the worker-sidecar are
+ # enabled, otherwise the gateway binary default.
+ healthMode: ""
+
image:
repository: ghcr.io/superlinked/sie-gateway
tag: "" # Defaults to appVersion
@@ -198,18 +203,18 @@ gateway:
# workers); use this for unrelated future tunables or for emergency
# diagnostics overrides.
#
- # Example — bump log verbosity for one pod without touching the chart:
+ # Example: bump log verbosity for one pod without touching the chart:
# - name: SIE_LOG_LEVEL
# value: "debug"
#
- # Do not use extraEnv to set SIE_GATEWAY_HEALTH_MODE=nats unless you also run
- # a worker-side publisher for sie.health.>. The chart intentionally does not
- # expose gateway.healthMode until NATS worker health is wired end to end.
+ # Do not use extraEnv to set SIE_GATEWAY_HEALTH_MODE; use
+ # gateway.healthMode above so the template keeps ownership of the
+ # env wiring.
extraEnv: []
# -- Liveness/readiness/startup probe timing. Mirrors config.probes; httpGet
- # path/port are owned by the template. Defaults match the previous hardcoded
- # values (modulo the dropped startupProbe.initialDelaySeconds).
+ # path/port are owned by the template. Defaults preserve the chart's existing
+ # probe budget.
probes:
startup:
periodSeconds: 5
@@ -325,6 +330,18 @@ workers:
# env vars, `--bundle` flag, and metrics still reflect `bundle`.
imageBundle: ""
+ # -- Python ModelWorker passthrough mode. When `true` (and the Rust
+ # sidecar is enabled), the Python adapter process bypasses its internal
+ # BatchFormer / FCFS / adaptive controller; every IPC frame from
+ # the worker-sidecar is treated as a fully-formed GPU batch and runs
+ # as exactly one forward pass. In queue mode this keeps a single
+ # batcher in the system: the Rust scheduler. Set to `false` only
+ # for compatibility checks against Python-side batching.
+ # The chart only emits SIE_WORKER_PASSTHROUGH when the worker-sidecar
+ # is enabled; without a sidecar in front, passthrough would leave
+ # the pod with no batcher at all.
+ passthroughMode: true
+
# -- Logical queue pool consumed by workers in queue-routing mode.
# Defaults to "default" so Helm WorkerGroups serve unpinned SDK traffic.
# Override per worker pool with workers.pools.<name>.queuePool only for
@@ -361,11 +378,11 @@ workers:
# var at startup; nested settings use the ``__`` delimiter (e.g.
# ``SIE_OOM_RECOVERY__ENABLED``).
#
- # Common knobs (full reference in product/design.md §3.6):
+ # Common worker knobs:
#
# # Convenience kill switch for OOM recovery (incident triage).
- # # When set, server returns the legacy 500 INFERENCE_ERROR for OOM
- # # instead of attempting cache_clear → evict_lru → split_batch.
+ # # When set, server returns the compatibility 500 INFERENCE_ERROR for OOM
+ # # instead of attempting cache_clear -> evict_lru -> split_batch.
# - name: SIE_DISABLE_OOM_RECOVERY
# value: "1"
#
@@ -393,10 +410,10 @@ workers:
#
# Defaults are tightened to reduce kubelet probe-poll latency on the
# cold-start path (issue #814):
- # - startupProbe.periodSeconds 10 → 3, failureThreshold 60 → 200
- # (preserves the ≥600s budget: 200 × 3s = 600s for model downloads
+ # - startupProbe.periodSeconds 10 -> 3, failureThreshold 60 -> 200
+ # (preserves the >=600s budget: 200 x 3s = 600s for model downloads
# and GPU loading)
- # - readinessProbe.initialDelaySeconds dropped, periodSeconds 10 → 2
+ # - readinessProbe.initialDelaySeconds dropped, periodSeconds 10 -> 2
# so kubelet flips the pod to Ready within ~2s of mark_ready()
probes:
startup:
@@ -411,15 +428,184 @@ workers:
periodSeconds: 2
timeoutSeconds: 10
failureThreshold: 3
+ # -- worker-sidecar configuration
+ # When enabled, a Rust worker-sidecar is added to every
+ # worker Pod. The sidecar owns the NATS JetStream consumer and
+ # calls into the Python ``sie_server`` container over a Unix
+ # socket mounted on a shared emptyDir. The chart enforces (via a
+ # template ``fail``) that ``workerSidecar.enabled`` requires
+ # ``nats.enabled: true`` because the sidecar has no default
+ # ``SIE_NATS_URL`` and refuses to start without one.
+ workerSidecar:
+ # -- Enable the worker-sidecar. This is the production
+ # data path (NATS -> Rust -> UDS IPC -> Python). The Python adapter process
+ # does not pull from NATS on its own, so queue-mode worker pools
+ # require this sidecar to provide a JetStream consumer.
+ enabled: true
+ image:
+ repository: ghcr.io/superlinked/sie-server-sidecar
+ # -- Image tag. Leave empty to use .Chart.AppVersion.
+ tag: ""
+ pullPolicy: IfNotPresent
+ # -- Metrics port (Prometheus scrape target on the sidecar).
+ metricsPort: 9095
+ # -- Log level for the worker-sidecar (maps to RUST_LOG).
+ logLevel: info
+ # -- Bound Prometheus model-label cardinality. When set, any
+ # model_id not in this list is reported as "other" on per-model
+ # metrics. Comma-separated list.
+ metricModelAllowlist: ""
+ # -- Per-model-group batch concurrency cap for the dispatcher.
+ # Leave empty to use the binary default (4).
+ maxConcurrentBatches: ""
+ # -- Size of the Rust-to-Python 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.
+ # 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).
+ ipcPoolSize: ""
+ # -- IPC heartbeat cadence. Must stay comfortably below Python's
+ # SIE_IPC_STALE_AFTER_MS (default 10000); architecture guide
+ # recommends ping < stale/3. Leave empty to use the binary default
+ # (2000ms).
+ pingIntervalMs: ""
+ # -- /readyz freshness-window multiplier. The sidecar's readiness
+ # flips red once the most recent successful Ping is older than
+ # `pingIntervalMs * readyStaleMult`. Leave empty for the binary
+ # default.
+ readyStaleMult: ""
+ # -- NATS health-heartbeat publisher.
+ # With the worker-sidecar data path, the gateway builds its
+ # queue WorkerRegistry from `sie.health.<worker_id>` messages. See
+ # packages/sie_server_sidecar/src/health_publisher.rs and
+ # packages/sie_gateway/src/discovery/nats_health.rs.
+ healthPublish:
+ # -- Whether the sidecar should publish heartbeats. Default
+ # `true`; set to `false` only when another worker-health source
+ # is authoritative for queue routing.
+ enabled: true
+ # -- Heartbeat cadence in milliseconds. Leave empty for the
+ # binary default.
+ intervalMs: ""
+ # -- Machine-profile label echoed in heartbeats. Used only
+ # when an inbound request carries `X-SIE-MACHINE-PROFILE`;
+ # empty uses the resolved pool machineProfile.
+ machineProfile: ""
+ # -- Worker-side config reconciliation against sie-config.
+ # The sidecar already consumes live bundle-scoped NATS deltas; this
+ # poller catches missed deltas by comparing /v1/configs/epoch and
+ # replaying /v1/configs/export through Python IPC.
+ configReconcile:
+ enabled: true
+ # -- Epoch poll cadence in milliseconds.
+ pollIntervalMs: 30000
+ # -- Slow full-export reconcile cadence in milliseconds. Covers
+ # no-config-store clusters where epoch remains 0. Set 0 to disable
+ # after the startup export.
+ fullExportIntervalMs: 300000
+ # -- K8s probes on the worker-sidecar.
+ # Disabled by default while the Python container's existing
+ # /healthz + /readyz remain the K8s contract.
+ probes:
+ enabled: false
+ startup:
+ periodSeconds: 5
+ failureThreshold: 60
+ liveness:
+ initialDelaySeconds: 10
+ periodSeconds: 30
+ timeoutSeconds: 5
+ failureThreshold: 3
+ readiness:
+ initialDelaySeconds: 3
+ periodSeconds: 5
+ timeoutSeconds: 3
+ failureThreshold: 3
+ # -- Pipeline depth: how many IPC dispatches can be in-flight to
+ # Python concurrently. The Rust binary defaults to 2; making it
+ # explicit here so the helm chart documents production intent.
+ # 1 = strict serial dispatch (regression-bisect knob); 2 = one
+ # batch processing in Python while the next forms/ships in Rust;
+ # > 2 inflates per-batch latency without throughput gain because
+ # Python's executor is single-CUDA-stream.
+ # See `packages/sie_server_sidecar/src/dispatcher.rs::pipeline_depth`.
+ pipelineDepth: 2
+ # -- BatchFormer tuning for queue-mode workers. These defaults
+ # keep Rust-side batch formation responsive while leaving the
+ # adapter to execute each IPC frame as one forward pass.
+ batcher:
+ # -- Coalesce window ceiling in ms. Lower = more responsive
+ # to inflow jitter and bounds tail latency when traffic is
+ # below saturation.
+ coalesceMs: 5
+ # -- Hard cap on items per batch. This gives the scheduler
+ # headroom for short arrival bursts without unbounded
+ # tail-batch growth.
+ maxBatchRequests: 12
+ # -- 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
+ # -- Quantum ceiling in ms (`SIE_ADAPTIVE_MAX_QUANTUM_MS`).
+ maxQuantumMs: 15
+ # -- Target queue-path p50 the controller nudges toward in
+ # ms (`SIE_ADAPTIVE_TARGET_P50_MS`).
+ targetP50Ms: 50
+ # -- Slow stream/durable reconcile. This re-ensures the JetStream
+ # stream and durable consumer without touching the hot pull stream.
+ # Set 0 to disable; the binary clamps non-zero values below 10s.
+ natsConsumerReconcile:
+ intervalMs: 30000
+ # -- Extra env vars passed through to the sidecar (rendered AFTER
+ # the typed fields above, so any duplicate name overrides them).
+ extraEnv: []
+ # -- Resource requests/limits for the sidecar. Conservative
+ # defaults; the heavy lifting still happens in the Python pod.
+ resources:
+ requests:
+ cpu: "500m"
+ memory: "512Mi"
+ limits:
+ cpu: "2"
+ memory: "2Gi"
# -- Worker pools (one StatefulSet per pool)
# Each map entry creates a WorkerGroup: one StatefulSet + one pre-pull DaemonSet.
# The map key names the Kubernetes WorkerGroup, not the SDK logical pool.
# WorkerGroup naming convention: <machineProfile> (e.g. l4, a100-40gb, cpu).
- # All pools scale to zero by default — enable the ones you need.
+ # All pools scale to zero by default; enable the ones you need.
+ #
+ # Per-pool keys (alphabetical, with defaults):
+ # bundle: string. Overrides workers.common.bundle. Required to
+ # match a real bundle in sie_config; otherwise the
+ # sidecar refuses to start.
+ # enabled: bool. Skip rendering when false.
+ # gpu.count: int. 0 disables nvidia.com/gpu request on the pod.
+ # gpu.product: string. nvidia.com/gpu.product node-label match.
+ # gpuType: short label (l4, a100-40gb, cpu, …) used by the
+ # gateway for routing/metrics. Doubles as the
+ # statefulset suffix.
+ # machineProfile: long label used by KEDA scalers + Prometheus.
+ # maxReplicas: KEDA upper bound.
+ # minReplicas: baseline replicas (0 = scale-to-zero).
+ # nodeSelector: map. Merged with workers.common.nodeSelector.
+ # platform: Optional override (e.g. "cpu"). Used as the
+ # image-tag suffix for the worker image
+ # (e.g. `<repo>:<tag>-cpu-<bundle>`),
+ # NOT propagated to a pod env var.
+ # resources: requests/limits for the Python ``worker``
+ # container (the GPU-bound forward-pass server).
+ # tolerations: extra tolerations on top of the chart defaults.
+ #
+ # NOTE: a stray ``engine`` key on a pool is silently ignored by
+ # this chart (only ``pytorch``-style pods are rendered).
pools:
- # ── L4 GPU ───────────────────────────────────────────────
+ # L4 GPU
l4:
enabled: false
@@ -457,7 +643,7 @@ workers:
operator: Exists
effect: NoSchedule
- # ── A100 40GB ────────────────────────────────────────────
+ # A100 40GB
a100-40gb:
enabled: false
@@ -482,7 +668,7 @@ workers:
operator: Exists
effect: NoSchedule
- # ── A100 80GB ────────────────────────────────────────────
+ # A100 80GB
a100-80gb:
enabled: false
@@ -507,7 +693,7 @@ workers:
operator: Exists
effect: NoSchedule
- # ── CPU (local testing with kind, no GPU) ────────────────
+ # CPU (local testing with kind, no GPU)
cpu:
enabled: false
@@ -542,7 +728,7 @@ autoscaling:
enabled: false
# -- Prometheus address for KEDA metrics queries.
- # Ignored when kube-prometheus-stack.install=true — address is auto-derived from
+ # Ignored when kube-prometheus-stack.install=true; address is auto-derived from
# the release namespace. Set this when using an externally-managed Prometheus.
prometheusAddress: http://prometheus-operated.monitoring.svc.cluster.local:9090
@@ -579,7 +765,11 @@ ingress:
# Ignored when `hosts` is non-empty; otherwise treated as a one-element `hosts`.
host: ""
# -- TLS configuration
- tls:
+ # -- SIE ingress TLS configuration. Named tlsConfig instead of tls
+ # to avoid colliding with Loki/Alloy sub-chart ingress.tls values,
+ # which use list-shaped TLS entries. Legacy ingress.tls object values
+ # are still honored by the templates.
+ tlsConfig:
enabled: false
# Mode: byo | cert-manager | self-signed | disabled (case-sensitive)
# byo: user supplies a kubernetes.io/tls Secret named `secretName`. (default — backward compatible)
@@ -604,7 +794,7 @@ ingress:
# avoids collisions when two SIE releases share a cluster). Override to a static name only when there is
# known to be no other SIE release on this cluster.
name: ""
- # ACME settings (used only when create=true). Flat (no nested `acme:` block) — ACME is the only supported issuer path.
+ # ACME settings (used only when create=true). Flat (no nested `acme:` block); ACME is the only supported issuer path.
server: https://acme-v02.api.letsencrypt.org/directory
# Email for ACME account registration. REQUIRED when create=true. Empty value triggers a helm install/upgrade fail.
email: ""
@@ -640,7 +830,7 @@ ingress:
# CA ClusterIssuer that signs leaf certs from the root CA.
caClusterIssuer:
name: sie-self-signed-ca
- # Leaf Certificate for the Ingress (consumed via ingress.tls.secretName).
+ # Leaf Certificate for the Ingress (consumed via ingress.tlsConfig.secretName).
leaf:
# 2160h = 90d (Let's Encrypt-style lifetime); cert-manager renews at duration - renewBefore.
duration: 2160h
@@ -788,9 +978,9 @@ nats:
# -- Override the NATS service name used to build the default SIE_NATS_URL.
# Defaults to "<release>-nats" if not set.
serviceName: ""
- # -- JetStream configuration for queue-based routing (SIE_CLUSTER_ROUTING=queue).
- # JetStream is required for the work queue. It is NOT required for config distribution
- # (which uses plain NATS pub/sub).
+ # -- JetStream configuration for the work queue.
+ # JetStream is required for inference (the gateway is queue-only).
+ # It is NOT required for config distribution (plain NATS pub/sub).
# NOTE: These keys are passed to the NATS sub-chart (nats/nats) which expects
# config.jetstream.memoryStore.maxSize (not memStorage/size).
config:
@@ -821,6 +1011,14 @@ nats:
# JetStream detailed metrics (streams + consumers)
NATS_EXPORTER_OPTS: "-connz -routez -subz -jsz=all"
+# -- cert-manager/trust-manager subchart install toggles. Default off because
+# most clusters already manage certificate controllers at the platform layer.
+certManagerBundle:
+ certManager:
+ install: false
+ trustManager:
+ install: false
+
# -- Cluster routing mode. Today the only supported value is "queue": the
# gateway publishes work items to NATS JetStream and workers pull them.
# The Rust gateway has no direct-mode code path (queue-only since the
@@ -841,20 +1039,20 @@ queueRouting:
# Messages older than this are discarded. Set higher for slow model loads.
streamMaxAgeSec: 120
# -- NATS fetch budget: max messages pulled per fetch() call.
- # This is the primary driver of GPU batch size in queue mode — the worker
+ # This is the primary driver of GPU batch size in queue mode; the worker
# groups fetched messages by model and dispatches them as a single forward pass.
# Higher values improve GPU utilization under load but increase per-request latency.
natsFetchBudget: 64
# -- Worker admission gate for capped pools. Workers ask the gateway whether
# their pod is in the pool's assigned_workers before pulling from NATS.
poolAdmission:
+ enabled: true
checkIntervalSec: 10
pauseSec: 1
staleAfterSec: 30
# -- Payload store for large work item payloads (images, long documents).
# When a work item exceeds 1MB, the payload is offloaded to this store.
-# Only used when clusterRouting=queue.
# IMPORTANT: payloadStore.url must point to shared storage accessible by both
# gateway and worker pods. Use s3://bucket/prefix or gs://bucket/prefix.
# Local filesystem paths (e.g., /tmp/payloads) will NOT work in queue mode
@@ -875,11 +1073,6 @@ queueRouting:
# default (e.g., a separate bucket); leaving it empty is the right call
# for most clusters.
payloadStore:
- # -- DEPRECATED, kept for backward compatibility only. The chart no longer
- # reads this field; the payload store is enabled whenever the effective URL
- # (see auto-derivation rules above) resolves to a non-empty value. Set
- # payloadStore.url to "" and clusterCache.enabled to false to disable.
- enabled: false
# -- Payload store URL. Must be an S3 or GCS URL (s3://bucket/prefix or gs://bucket/prefix).
# Local paths are rejected when clusterRouting=queue (see gateway-deployment.yaml validation).
# Leave empty to auto-derive from workers.common.clusterCache.url (recommended).
@@ -901,7 +1094,7 @@ payloadStore:
# subchart values here for things cert-manager actually understands.
# Bundling is for SINGLE-TENANT clusters where SIE is the sole workload. If your cluster already
# runs cert-manager, leave certManagerBundle.certManager.install=false and use
-# ingress.tls.mode=cert-manager against the existing install — bundling hard-fails via a pre-install
+# ingress.tlsConfig.mode=cert-manager against the existing install — bundling hard-fails via a pre-install
# conflict-detection Job hook.
cert-manager:
crds:
@@ -930,9 +1123,9 @@ cert-manager:
#
# IMPORTANT: trust-manager's --trust-namespace defaults to "cert-manager" — it will only find
# source Secrets in that namespace. The self-signed root CA Secret is written to
-# ingress.tls.selfSigned.rootCA.namespace (defaults to release namespace). For the bundled
+# ingress.tlsConfig.selfSigned.rootCA.namespace (defaults to release namespace). For the bundled
# trustBundle to sync, those two namespaces MUST match. Either:
-# (a) set ingress.tls.selfSigned.rootCA.namespace: cert-manager (route the root CA into the
+# (a) set ingress.tlsConfig.selfSigned.rootCA.namespace: cert-manager (route the root CA into the
# same namespace trust-manager looks in), OR
# (b) override trust-manager.app.trust.namespace at install time:
# --set trust-manager.app.trust.namespace=<release-namespace>
@@ -1201,7 +1394,7 @@ alloy:
# Setting create=false tells the sub-chart to mount the ConfigMap created by the parent chart.
# name and key must match what templates/alloy-configmap.yaml emits.
create: false
- # NOTE: Static name — values.yaml is not templated so .Release.Name cannot
+ # NOTE: Static name; values.yaml is not templated so .Release.Name cannot
# be used here. If deploying multiple releases in the same namespace, override
# this to a unique name to avoid ConfigMap conflicts.
name: "sie-alloy-config"
diff --git a/deploy/k8s/keda-scaledobject.yaml b/deploy/k8s/keda-scaledobject.yaml
index 9a8c87694..1035d1a65 100644
--- a/deploy/k8s/keda-scaledobject.yaml
+++ b/deploy/k8s/keda-scaledobject.yaml
@@ -1,7 +1,6 @@
# SIE KEDA ScaledObject Configuration
#
# GPU-optimized autoscaling for SIE inference workloads.
-# Based on research: product/research/cloud_deployment_research.md
#
# Prerequisites:
# - KEDA installed (via Terraform: install_keda = true)
diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.toml
index 9f107caaf..16e2e011a 100644
--- a/integrations/sie_chroma/pyproject.toml
+++ b/integrations/sie_chroma/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-chroma"
-version = "0.4.1"
+version = "0.4.2"
description = "SIE integration for ChromaDB"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.toml
index 26e3eb1c9..a94365f54 100644
--- a/integrations/sie_crewai/pyproject.toml
+++ b/integrations/sie_crewai/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-crewai"
-version = "0.4.1"
+version = "0.4.2"
description = "SIE integration for CrewAI"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.toml
index 43aed4cbf..feac429cc 100644
--- a/integrations/sie_dspy/pyproject.toml
+++ b/integrations/sie_dspy/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-dspy"
-version = "0.4.1"
+version = "0.4.2"
description = "SIE integration for DSPy"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.toml
index 50f27cf3a..3df165405 100644
--- a/integrations/sie_haystack/pyproject.toml
+++ b/integrations/sie_haystack/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-haystack"
-version = "0.4.1"
+version = "0.4.2"
description = "SIE integration for Haystack"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.toml
index f0bb3709e..c58227c89 100644
--- a/integrations/sie_lancedb/pyproject.toml
+++ b/integrations/sie_lancedb/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-lancedb"
-version = "0.4.1"
+version = "0.4.2"
description = "SIE integration for LanceDB"
requires-python = ">=3.12"
dependencies = [
diff --git a/integrations/sie_lancedb/tests/test_integration.py b/integrations/sie_lancedb/tests/test_integration.py
index 875c64f3c..16c7e54a8 100644
--- a/integrations/sie_lancedb/tests/test_integration.py
+++ b/integrations/sie_lancedb/tests/test_integration.py
@@ -15,7 +15,7 @@ import os
import lancedb
import pytest
-import sie_lancedb # noqa: F401 — registers "sie" and "sie-multivector"
+import sie_lancedb # registers "sie" and "sie-multivector" + used directly as sie_lancedb.SIE{Reranker,Extractor}
from lancedb.embeddings import get_registry
from lancedb.pydantic import LanceModel, Vector
@@ -94,8 +94,6 @@ class TestHybridSearchWithReranker:
def test_hybrid_search_with_reranker(self, sie_url: str, db) -> None:
"""Hybrid search (vector + FTS) with SIE cross-encoder reranking."""
- from sie_lancedb import SIEReranker
-
sie = (
get_registry()
.get("sie")
@@ -122,7 +120,7 @@ class TestHybridSearchWithReranker:
table.create_fts_index("text", replace=True)
- reranker = SIEReranker(
+ reranker = sie_lancedb.SIEReranker(
base_url=sie_url,
model="jinaai/jina-reranker-v2-base-multilingual",
)
@@ -146,9 +144,7 @@ class TestEntityExtraction:
def test_extract_entities(self, sie_url: str) -> None:
"""Direct entity extraction from text."""
- from sie_lancedb import SIEExtractor
-
- extractor = SIEExtractor(
+ extractor = sie_lancedb.SIEExtractor(
base_url=sie_url,
model="urchade/gliner_multi-v2.1",
)
@@ -167,8 +163,6 @@ class TestEntityExtraction:
def test_enrich_table(self, sie_url: str, db) -> None:
"""Enrich a LanceDB table with extracted entities."""
- from sie_lancedb import SIEExtractor
-
table = db.create_table(
"enrich_test",
data=[
@@ -179,7 +173,7 @@ class TestEntityExtraction:
mode="overwrite",
)
- extractor = SIEExtractor(
+ extractor = sie_lancedb.SIEExtractor(
base_url=sie_url,
model="urchade/gliner_multi-v2.1",
)
diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.toml
index 63231b7d8..4daec7de1 100644
--- a/integrations/sie_langchain/pyproject.toml
+++ b/integrations/sie_langchain/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-langchain"
-version = "0.4.1"
+version = "0.4.2"
description = "SIE integration for LangChain"
requires-python = ">=3.10"
dependencies = [
diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.toml
index 2ebc960e4..d672ac5a3 100644
--- a/integrations/sie_llamaindex/pyproject.toml
+++ b/integrations/sie_llamaindex/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-llamaindex"
-version = "0.4.1"
+version = "0.4.2"
description = "SIE integration for LlamaIndex"
requires-python = ">=3.10"
dependencies = [
diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.toml
index 6529040de..bf022ce5c 100644
--- a/integrations/sie_qdrant/pyproject.toml
+++ b/integrations/sie_qdrant/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-qdrant"
-version = "0.4.1"
+version = "0.4.2"
description = "SIE integration for Qdrant"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.json
index 772331cec..c64773d2d 100644
--- a/integrations/sie_ts_chroma/package.json
+++ b/integrations/sie_ts_chroma/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-chroma",
- "version": "0.4.1",
+ "version": "0.4.2",
"description": "SIE embedding function for ChromaDB",
"type": "module",
"main": "./dist/index.cjs",
@@ -35,10 +35,10 @@
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
- "chromadb": "^1.9.0",
- "tsup": "^8.3.5",
- "typescript": "^5.7.2",
- "vitest": "^2.1.8"
+ "chromadb": "^1.10.5",
+ "tsup": "^8.5.1",
+ "typescript": "^5.9.3",
+ "vitest": "^2.1.9"
},
"engines": {
"node": ">=22.0.0"
diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.json
index 5c5eac0ca..06cc0e27f 100644
--- a/integrations/sie_ts_lancedb/package.json
+++ b/integrations/sie_ts_lancedb/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-lancedb",
- "version": "0.4.1",
+ "version": "0.4.2",
"description": "SIE embedding function and reranker for LanceDB",
"type": "module",
"main": "./dist/index.cjs",
@@ -36,10 +36,10 @@
"devDependencies": {
"@biomejs/biome": "^1.9.4",
"@lancedb/lancedb": "^0.17.0",
- "apache-arrow": "^18.0.0",
- "tsup": "^8.3.5",
- "typescript": "^5.7.2",
- "vitest": "^2.1.8"
+ "apache-arrow": "^18.1.0",
+ "tsup": "^8.5.1",
+ "typescript": "^5.9.3",
+ "vitest": "^2.1.9"
},
"engines": {
"node": ">=22.0.0"
diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.json
index 4bcb1010b..f0bdf1e5d 100644
--- a/integrations/sie_ts_langchain/package.json
+++ b/integrations/sie_ts_langchain/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-langchain",
- "version": "0.4.1",
+ "version": "0.4.2",
"description": "SIE embeddings integration for LangChain.js",
"type": "module",
"main": "./dist/index.cjs",
@@ -35,10 +35,10 @@
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
- "@langchain/core": "^0.3.0",
- "tsup": "^8.3.5",
- "typescript": "^5.7.2",
- "vitest": "^2.1.8"
+ "@langchain/core": "^0.3.80",
+ "tsup": "^8.5.1",
+ "typescript": "^5.9.3",
+ "vitest": "^2.1.9"
},
"engines": {
"node": ">=22.0.0"
diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.json
index 649671e9f..5a09c5e7e 100644
--- a/integrations/sie_ts_llamaindex/package.json
+++ b/integrations/sie_ts_llamaindex/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-llamaindex",
- "version": "0.4.1",
+ "version": "0.4.2",
"description": "SIE embeddings integration for LlamaIndex.TS",
"type": "module",
"main": "./dist/index.cjs",
@@ -35,10 +35,10 @@
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
- "llamaindex": "^0.8.0",
- "tsup": "^8.3.5",
- "typescript": "^5.7.2",
- "vitest": "^2.1.8"
+ "llamaindex": "^0.8.37",
+ "tsup": "^8.5.1",
+ "typescript": "^5.9.3",
+ "vitest": "^2.1.9"
},
"engines": {
"node": ">=22.0.0"
diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.toml
index c87686c56..f61c596a7 100644
--- a/integrations/sie_weaviate/pyproject.toml
+++ b/integrations/sie_weaviate/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-weaviate"
-version = "0.4.1"
+version = "0.4.2"
description = "SIE integration for Weaviate"
readme = "README.md"
requires-python = ">=3.10"
diff --git a/integrations/sie_weaviate/tests/conftest.py b/integrations/sie_weaviate/tests/conftest.py
index e519f072e..4dd6a65d1 100644
--- a/integrations/sie_weaviate/tests/conftest.py
+++ b/integrations/sie_weaviate/tests/conftest.py
@@ -146,22 +146,6 @@ def mock_sie_client() -> MagicMock:
item_dicts = [{"text": _get_text(i)} for i in items]
return _create_mock_extract_result(item_dicts, labels=labels)
- def mock_extract_classify(
- _model: str,
- items: Any,
- *,
- labels: list[str] | None = None,
- **kwargs: Any,
- ) -> list[dict] | dict:
- if not isinstance(items, list):
- items = [items]
- item_dicts = [{"text": _get_text(items[0])}]
- results = _create_mock_classify_result(item_dicts, labels=labels)
- return results[0]
-
- item_dicts = [{"text": _get_text(i)} for i in items]
- return _create_mock_classify_result(item_dicts, labels=labels)
-
client.encode = MagicMock(side_effect=mock_encode)
# Default extract returns entities; tests that need classification
# swap the side_effect on the second call.
diff --git a/package.json b/package.json
index a09c16136..f0bb68e5e 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
"lint": "pnpm -r run lint"
},
"devDependencies": {
- "typescript": "^5.7.2"
+ "typescript": "^5.9.3"
},
"packageManager": "[email protected]",
"workspaces": [
@@ -17,5 +17,18 @@
"integrations/sie_ts_llamaindex",
"integrations/sie_ts_chroma",
"integrations/sie_ts_lancedb"
- ]
+ ],
+ "pnpm": {
+ "overrides": {
+ "esbuild": ">=0.25.0",
+ "form-data": ">=4.0.4",
+ "langsmith": ">=0.6.0",
+ "protobufjs": ">=7.5.8",
+ "qs": ">=6.15.2",
+ "tar": ">=7.5.11",
+ "uuid": ">=11.1.1",
+ "vite": "^6.4.2",
+ "ws": ">=8.20.1"
+ }
+ }
}
diff --git a/packages/sie_config/Dockerfile b/packages/sie_config/Dockerfile
index 240f4f300..67c335d38 100644
--- a/packages/sie_config/Dockerfile
+++ b/packages/sie_config/Dockerfile
@@ -9,7 +9,7 @@
# docker run -p 8080:8080 sie-config:latest
# =============================================================================
-# Stage 1: Builder - install dependencies with pip
+# Dependency builder: install service dependencies
# =============================================================================
FROM python:3.12-slim AS builder
@@ -37,9 +37,9 @@ RUN find .venv -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
&& find .venv -type d -name "test" -exec rm -rf {} + 2>/dev/null || true
# =============================================================================
-# Stage 2: Runtime - minimal image
+# Runtime image: minimal config service
# =============================================================================
-FROM python:3.12-slim
+FROM python:3.12-slim AS runtime
# Create non-root user
RUN useradd --create-home --shell /bin/bash sie
diff --git a/packages/sie_config/pyproject.toml b/packages/sie_config/pyproject.toml
index 08a47d2d6..0293d7e80 100644
--- a/packages/sie_config/pyproject.toml
+++ b/packages/sie_config/pyproject.toml
@@ -32,6 +32,6 @@ packages = ["src/sie_config"]
[dependency-groups]
dev = [
- "pytest>=8.3,<9",
- "pytest-asyncio>=0.24,<1",
+ "pytest>=9.0.3",
+ "pytest-asyncio>=1.0",
]
diff --git a/packages/sie_config/src/sie_config/config_api.py b/packages/sie_config/src/sie_config/config_api.py
index 95626396a..2ac2d4ab4 100644
--- a/packages/sie_config/src/sie_config/config_api.py
+++ b/packages/sie_config/src/sie_config/config_api.py
@@ -17,7 +17,13 @@ from fastapi import APIRouter, HTTPException, Request, Response
from sie_config import metrics as sie_metrics
from sie_config.config_store import ConfigStore
-from sie_config.model_registry import BundleConflictError, ModelNotFoundError, ModelRegistry, parse_model_spec
+from sie_config.model_registry import (
+ BundleConflictError,
+ ModelNotFoundError,
+ ModelRegistry,
+ ProfileConflictError,
+ parse_model_spec,
+)
from sie_config.nats_publisher import NatsPublisher, PartialPublishError
from sie_config.types import AuditEntry
@@ -488,12 +494,45 @@ async def add_model(request: Request) -> Response:
# never leaves the registry inconsistent with disk.
try:
created_profiles, skipped_profiles, affected_bundles = model_registry.validate_model_config(config)
+ except ProfileConflictError as e:
+ raise HTTPException(
+ status_code=409,
+ detail={
+ "error": "content_conflict",
+ "model_id": e.model,
+ "conflicting_profiles": e.profiles,
+ "message": str(e),
+ },
+ ) from e
except ValueError as e:
raise HTTPException(
status_code=422,
detail={"error": "validation_error", "details": [{"message": str(e)}]},
) from e
+ existing_config = model_registry.get_full_config(model_id)
+ if existing_config:
+ conflicting_fields = []
+ for key, new_value in config.items():
+ if key == "profiles":
+ continue
+ if key in existing_config and existing_config[key] != new_value:
+ conflicting_fields.append(key)
+ if conflicting_fields:
+ raise HTTPException(
+ status_code=409,
+ detail={
+ "error": "content_conflict",
+ "model_id": model_id,
+ "conflicting_fields": sorted(conflicting_fields),
+ "message": (
+ f"Top-level field(s) {sorted(conflicting_fields)} already "
+ "exist with different values. Config API is append-only; "
+ "mutating existing metadata is not supported via this endpoint."
+ ),
+ },
+ )
+
# 2. 409 conflict detection against what's already on disk.
# Only runs for pure-replay writes (no new profiles would be
# created). The `skipped_profiles` list already filters out
@@ -979,10 +1018,16 @@ async def export_snapshot(request: Request) -> Response:
}
)
+ bundle_config_hashes = {
+ bundle_id: model_registry.compute_bundle_config_hash(bundle_id)
+ for bundle_id in model_registry.list_bundles()
+ }
+
snapshot = {
"snapshot_version": 1,
"epoch": epoch,
"generated_at": datetime.now(UTC).isoformat(),
+ "bundle_config_hashes": bundle_config_hashes,
"models": models,
}
return Response(content=orjson.dumps(snapshot), media_type="application/json")
diff --git a/packages/sie_config/src/sie_config/model_registry.py b/packages/sie_config/src/sie_config/model_registry.py
index 4e5820490..7b418bf69 100644
--- a/packages/sie_config/src/sie_config/model_registry.py
+++ b/packages/sie_config/src/sie_config/model_registry.py
@@ -43,14 +43,71 @@ class BundleConflictError(Exception):
)
+class ProfileConflictError(ValueError):
+ """Existing profile cannot be changed through the append-only Config API."""
+
+ def __init__(self, model: str, profiles: list[str]) -> None:
+ self.model = model
+ self.profiles = profiles
+ super().__init__(
+ f"Profile(s) {profiles} on model '{model}' already exist with different content. Config API is append-only."
+ )
+
+
+# Set of recognised execution engines for the ``engine`` bundle field.
+# Locks in the disjoint-bundles convention discussed in the IPC/UDS audit
+# (2026-04-26): a model that's served by two different engines declares
+# two profiles, each pointing at the namespaced adapter, and the gateway
+# routes to the bundle whose ``engine`` matches the worker image at hand.
+#
+# Add new engines here only when there's a real worker image speaking that
+# backend — every value must round-trip through the gateway's bundle
+# resolution and the worker's IPC contract. Drift is the easiest way to
+# silently mis-route traffic, so we surface unknown values as a config
+# load error rather than tolerating them.
+KNOWN_ENGINES: frozenset[str] = frozenset({"pytorch"})
+DEFAULT_ENGINE: str = "pytorch"
+
+# Adapter-module prefix expected for each engine. The gateway's matcher
+# is engine-agnostic (it intersects ``bundle.adapters`` with the model's
+# ``adapter_path`` modules), so this constraint is enforced at config-
+# load time rather than at the matcher level — a mismatch is a deploy
+# bug, not a runtime fall-through. Today we ship one engine; extend in
+# lock-step with KNOWN_ENGINES (mirroring
+# ``sie_gateway::types::bundle::engine_adapter_prefixes``).
+_ENGINE_ADAPTER_PREFIXES: dict[str, tuple[str, ...]] = {
+ "pytorch": ("sie_server.adapters.",),
+}
+
+
@dataclass
class BundleInfo:
- """Information about a bundle."""
+ """Information about a bundle.
+
+ Attributes:
+ name: Bundle identifier (matches the YAML filename stem unless
+ overridden by an explicit ``name:`` field).
+ priority: Lower wins. The gateway's ``resolve_bundle`` returns
+ the lowest-priority compatible bundle by default.
+ adapters: Python module paths (e.g.
+ ``sie_server.adapters.<family>``) that this bundle's
+ worker image can serve.
+ default: Whether this is the operator-blessed fallback bundle
+ in the event of an ambiguous resolution. Surfaced as
+ metadata; the priority field is what actually decides ties.
+ engine: Execution engine the bundle's worker image speaks
+ (today the only recognised value is ``"pytorch"`` for the
+ Python adapter image; see ``KNOWN_ENGINES``). Defaults to
+ ``"pytorch"`` for back-compat with bundle YAMLs written
+ before this field existed. The gateway uses ``engine`` to
+ disambiguate when a model resolves to multiple bundles.
+ """
name: str
priority: int
adapters: list[str] = field(default_factory=list)
default: bool = False
+ engine: str = DEFAULT_ENGINE
@dataclass
@@ -156,14 +213,62 @@ class ModelRegistry:
priority = data.get("priority", 100)
adapters = data.get("adapters", [])
default = data.get("default", False)
+ # ``engine`` defaults to ``DEFAULT_ENGINE`` (== "pytorch")
+ # so existing bundle YAMLs keep working without edits.
+ # Unknown values are a hard error — silently coercing
+ # to "pytorch" would let a typo'd ``engine: pytroch``
+ # mis-route traffic and push diagnosis to the
+ # symptom side.
+ engine = data.get("engine", DEFAULT_ENGINE)
+ if engine not in KNOWN_ENGINES:
+ logger.error(
+ "Bundle %r at %s declares engine=%r which is not in "
+ "KNOWN_ENGINES=%s — skipping load. Update the bundle "
+ "YAML or add the engine to sie_config.model_registry.",
+ name,
+ bundle_path,
+ engine,
+ sorted(KNOWN_ENGINES),
+ )
+ continue
+
+ # Adapter-namespace consistency check. The gateway's
+ # matcher intersects ``bundle.adapters`` with each
+ # model's ``adapter_path`` modules, so a bundle
+ # that accidentally lists adapters outside this
+ # engine's namespace would produce
+ # ``UnsupportedModel`` errors at runtime. Catching
+ # this at config-load time makes the failure mode
+ # an obvious deploy-rejection rather than a stream
+ # of cryptic IPC NAKs.
+ expected_prefixes = _ENGINE_ADAPTER_PREFIXES.get(engine, ())
+ if expected_prefixes:
+ bad_adapters = [a for a in adapters if not any(a.startswith(p) for p in expected_prefixes)]
+ if bad_adapters:
+ logger.warning(
+ "Bundle %r (engine=%r) lists adapter(s) outside the "
+ "expected namespace(s) %s: %s — these will not be "
+ "servable by a worker speaking this engine.",
+ name,
+ engine,
+ expected_prefixes,
+ bad_adapters,
+ )
new_bundles[name] = BundleInfo(
name=name,
priority=priority,
adapters=adapters,
default=default,
+ engine=engine,
+ )
+ logger.debug(
+ "Loaded bundle '%s': priority=%d, engine=%s, adapters=%d",
+ name,
+ priority,
+ engine,
+ len(adapters),
)
- logger.debug("Loaded bundle '%s': priority=%d, adapters=%d", name, priority, len(adapters))
except Exception:
logger.exception("Failed to load bundle: %s", bundle_path)
@@ -233,8 +338,8 @@ class ModelRegistry:
# Not fatal: routable profiles keep serving traffic, the log below
# surfaces the bad profiles in sie-config logs without waiting for
# every sie-gateway to hit "Adapter(s) not in any known bundle"
- # during bootstrap, and PR #704's test_bundle_coverage regression
- # test catches this pre-merge in CI.
+ # during bootstrap. The bundle-coverage regression test catches
+ # this pre-merge in CI.
all_bundle_adapters: set[str] = set()
for bundle in new_bundles.values():
all_bundle_adapters.update(bundle.adapters)
@@ -393,6 +498,7 @@ class ModelRegistry:
"name": b.name,
"priority": b.priority,
"adapters": sorted(b.adapters),
+ "engine": b.engine,
}
for b in sorted(bundles, key=lambda x: x.name)
]
@@ -507,18 +613,24 @@ class ModelRegistry:
skipped_profiles: list[str] = []
if existing:
+ existing_full_profiles = self._model_full_configs.get(sie_id, {}).get("profiles", {})
+ conflicting_profiles: list[str] = []
for profile_name, profile in profiles.items():
if profile_name in self.get_model_profile_names(sie_id):
+ stored_full = existing_full_profiles.get(profile_name)
+ if stored_full is not None and stored_full != profile:
+ conflicting_profiles.append(profile_name)
+ continue
stored = self._model_profile_configs.get(sie_id, {}).get(profile_name)
incoming = _canonical_profile_dict(profile)
if stored is not None and stored != incoming:
- raise ValueError(
- f"Profile '{profile_name}' on model '{sie_id}' already exists "
- f"with different config (append-only -- cannot modify)"
- )
+ conflicting_profiles.append(profile_name)
+ continue
skipped_profiles.append(profile_name)
else:
created_profiles.append(profile_name)
+ if conflicting_profiles:
+ raise ProfileConflictError(sie_id, conflicting_profiles)
else:
created_profiles = list(profiles.keys()) # type: ignore
diff --git a/packages/sie_config/src/sie_config/nats_publisher.py b/packages/sie_config/src/sie_config/nats_publisher.py
index 33a66bcb4..ba14d8839 100644
--- a/packages/sie_config/src/sie_config/nats_publisher.py
+++ b/packages/sie_config/src/sie_config/nats_publisher.py
@@ -138,11 +138,12 @@ class NatsPublisher:
For each affected bundle, builds one canonical ``ConfigNotification``
payload and publishes it to two subjects:
- 1. ``sie.config.models.{bundle}`` -- consumed by workers
+ 1. ``sie.config.models.{bundle}`` -- reserved for worker-side apply
2. ``sie.config.models._all`` -- consumed by Rust gateways
- The same payload shape goes to both subjects so every subscriber sees
- the full set of fields that ``sie_gateway`` expects
+ worker-sidecar containers consume the bundle-scoped subject. The same
+ payload shape goes to both subjects so every subscriber sees the full
+ set of fields that ``sie_gateway`` expects
(``router_id``, ``bundle_id``, ``epoch``, ``bundle_config_hash``,
``model_id``, ``profiles_added``, ``model_config``, ``affected_bundles``).
See ``packages/sie_gateway/src/nats/manager.rs::ConfigNotification``.
diff --git a/packages/sie_config/tests/test_config_api.py b/packages/sie_config/tests/test_config_api.py
index d1fe06181..b1cf45bc3 100644
--- a/packages/sie_config/tests/test_config_api.py
+++ b/packages/sie_config/tests/test_config_api.py
@@ -128,6 +128,46 @@ class TestConfigAPIModels:
assert data["created_profiles"] == []
assert data["existing_profiles_skipped"] == ["default"]
+ def test_add_model_conflicting_existing_profile_returns_409_without_store(self) -> None:
+ client = TestClient(_create_test_app(self._bundles, self._models))
+ yaml_body = (
+ "sie_id: new/conflict\n"
+ "profiles:\n"
+ " default:\n"
+ " adapter_path: sie_server.adapters.bert_flash:Bert\n"
+ " max_batch_tokens: 8192\n"
+ " max_sequence_length: 256\n"
+ )
+ resp1 = client.post("/v1/configs/models", content=yaml_body)
+ assert resp1.status_code == 201
+
+ conflict_body = yaml_body.replace("max_sequence_length: 256", "max_sequence_length: 128")
+ resp2 = client.post("/v1/configs/models", content=conflict_body)
+ assert resp2.status_code == 409
+ data = resp2.json()
+ assert data["detail"]["error"] == "content_conflict"
+ assert data["detail"]["conflicting_profiles"] == ["default"]
+
+ def test_add_model_conflicting_top_level_field_returns_409_without_store(self) -> None:
+ client = TestClient(_create_test_app(self._bundles, self._models))
+ yaml_body = (
+ "sie_id: new/top-level-conflict\n"
+ "max_sequence_length: 256\n"
+ "profiles:\n"
+ " default:\n"
+ " adapter_path: sie_server.adapters.bert_flash:Bert\n"
+ " max_batch_tokens: 8192\n"
+ )
+ resp1 = client.post("/v1/configs/models", content=yaml_body)
+ assert resp1.status_code == 201
+
+ conflict_body = yaml_body.replace("max_sequence_length: 256", "max_sequence_length: 128")
+ resp2 = client.post("/v1/configs/models", content=conflict_body)
+ assert resp2.status_code == 409
+ data = resp2.json()
+ assert data["detail"]["error"] == "content_conflict"
+ assert data["detail"]["conflicting_fields"] == ["max_sequence_length"]
+
def test_list_models_includes_api_added(self) -> None:
yaml_body = "sie_id: api/model\nprofiles:\n default:\n adapter_path: sie_server.adapters.bert_flash:Bert\n max_batch_tokens: 8192\n"
self.client.post("/v1/configs/models", content=yaml_body)
@@ -364,6 +404,10 @@ class TestConfigAPIExport:
assert data["snapshot_version"] == 1
assert data["epoch"] == 0
assert "generated_at" in data
+ assert data["bundle_config_hashes"]["default"]
+ assert data["bundle_config_hashes"]["default"] == self.app.state.model_registry.compute_bundle_config_hash(
+ "default"
+ )
assert len(data["models"]) == 1
assert data["models"][0]["model_id"] == "test/model"
assert data["models"][0]["affected_bundles"] == ["default"]
@@ -386,6 +430,7 @@ class TestConfigAPIExport:
assert resp.status_code == 200
data = resp.json()
assert data["models"] == []
+ assert data["bundle_config_hashes"] == {"default": ""}
assert data["epoch"] == 0
def test_export_generated_at_is_utc_iso8601(self) -> None:
diff --git a/packages/sie_config/tests/test_model_registry.py b/packages/sie_config/tests/test_model_registry.py
index c58b6dda8..04c2bd6a3 100644
--- a/packages/sie_config/tests/test_model_registry.py
+++ b/packages/sie_config/tests/test_model_registry.py
@@ -4,7 +4,10 @@ import threading
from pathlib import Path
import pytest
+from sie_config import model_registry
from sie_config.model_registry import (
+ DEFAULT_ENGINE,
+ KNOWN_ENGINES,
BundleConflictError,
BundleInfo,
ModelInfo,
@@ -53,6 +56,11 @@ class TestBundleInfo:
assert info.priority == 10
assert info.adapters == []
assert info.default is False
+ assert info.engine == DEFAULT_ENGINE
+
+ def test_bundle_info_engine_explicit(self) -> None:
+ info = BundleInfo(name="example", priority=5, engine="pytorch")
+ assert info.engine == "pytorch"
class TestModelInfo:
@@ -282,11 +290,10 @@ class TestModelRegistryAdapterMatching:
We deliberately do not fail reload() on this: the baked-in
inconsistency is caught pre-merge by
- ``packages/sie_server/tests/config/test_bundle_coverage.py`` (added
- in PR #704), and failing here would take down the entire control
- plane for a two-model config bug. Callers (e.g. readiness probes,
- alerts) are expected to treat ``unrouteable_models`` as a
- soft-error surface instead.
+ ``packages/sie_server/tests/config/test_bundle_coverage.py``, and
+ failing here would take down the entire control plane for a two-model
+ config bug. Callers (e.g. readiness probes, alerts) are expected to
+ treat ``unrouteable_models`` as a soft-error surface instead.
"""
with tempfile.TemporaryDirectory() as tmpdir:
tmppath = Path(tmpdir)
@@ -424,6 +431,29 @@ class TestModelRegistryThreadSafety:
registry.reload()
assert registry.compute_bundles_hash() != before
+ def test_compute_bundles_hash_changes_on_engine_edit(
+ self, temp_config_dirs, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ # Engine controls gateway routing, so engine-only bundle edits must
+ # trigger bundle drift reconciliation even when adapters are unchanged.
+ bundles_dir, models_dir = temp_config_dirs
+ registry = ModelRegistry(bundles_dir, models_dir)
+ before = registry.compute_bundles_hash()
+
+ monkeypatch.setattr(model_registry, "KNOWN_ENGINES", frozenset({"pytorch", "future-engine"}))
+ (bundles_dir / "default.yaml").write_text(
+ "name: default\n"
+ "priority: 10\n"
+ "default: true\n"
+ "engine: future-engine\n"
+ "adapters:\n"
+ " - sie_server.adapters.bge_m3\n"
+ " - sie_server.adapters.sentence_transformer\n"
+ " - sie_server.adapters.cross_encoder\n"
+ )
+ registry.reload()
+ assert registry.compute_bundles_hash() != before
+
def test_compute_bundles_hash_independent_of_adapter_list_order(self, temp_config_dirs) -> None:
# Two YAMLs that list the same adapters in different order describe
# the same bundle semantically. The hash MUST NOT change — otherwise
@@ -493,7 +523,7 @@ class TestUnrouteableModelsSurface:
bundle declares) is reported via :pyattr:`ModelRegistry.unrouteable_models`
and a single aggregated ERROR log at reload time, but never fatal.
- The rationale is that PR #704's regression test
+ The rationale is that the bundle-coverage regression test
(``packages/sie_server/tests/config/test_bundle_coverage.py``) already
catches this in CI before it ships, so the runtime guard is
defense-in-depth only. Failing reload() would take down the whole
@@ -624,7 +654,7 @@ class TestUnrouteableModelsSurface:
when ``ModelInfo.bundles == []``, but bundles is the union across
profiles, so a single good profile would hide every bad sibling.
- Regression test for the cursor[bot] blocking comment on PR #705:
+ Regression test for baked-in/runtime parity:
``add_model_config`` already rejects the same shape at write time
via ``new_adapter_modules - all_bundle_adapters``; ``reload()``
now mirrors that so baked-in drift is surfaced identically.
@@ -668,8 +698,8 @@ class TestUnrouteableModelsSurface:
otherwise ``unrouteable_models`` lies to readiness probes until
the next disk-reload.
- (Regression test for the coderabbitai PR #705 comment about
- ``_unrouteable_models`` being stale after runtime writes.)
+ Regression test for ``_unrouteable_models`` being stale after
+ runtime writes.
"""
with tempfile.TemporaryDirectory() as tmpdir:
tmppath = Path(tmpdir)
@@ -711,3 +741,83 @@ class TestUnrouteableModelsSurface:
}
)
assert registry.unrouteable_models == {}
+
+
+# --------------------------------------------------------------------
+# engine field — locks in the disjoint-bundles convention from the
+# 2026-04-26 IPC/UDS audit. A model that's served by two different
+# engines declares two profiles, each pointing at the namespaced
+# adapter, and the gateway routes to the bundle whose ``engine``
+# matches the worker image at hand. These tests pin the wire shape
+# and validation contract.
+# --------------------------------------------------------------------
+
+
+class TestEngineField:
+ @staticmethod
+ def _mk_dirs(tmppath: Path) -> tuple[Path, Path]:
+ bundles_dir = tmppath / "bundles"
+ models_dir = tmppath / "models"
+ bundles_dir.mkdir()
+ models_dir.mkdir()
+ return bundles_dir, models_dir
+
+ def test_engine_defaults_to_pytorch_when_omitted(self) -> None:
+ with tempfile.TemporaryDirectory() as tmpdir:
+ bundles_dir, models_dir = self._mk_dirs(Path(tmpdir))
+ (bundles_dir / "default.yaml").write_text(
+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.bge_m3\n"
+ )
+
+ registry = ModelRegistry(bundles_dir, models_dir)
+ info = registry.get_bundle_info("default")
+ assert info is not None
+ assert info.engine == DEFAULT_ENGINE
+ assert info.engine == "pytorch"
+
+ def test_engine_unknown_value_skips_bundle(self, caplog: pytest.LogCaptureFixture) -> None:
+ with tempfile.TemporaryDirectory() as tmpdir:
+ bundles_dir, models_dir = self._mk_dirs(Path(tmpdir))
+ (bundles_dir / "good.yaml").write_text(
+ "name: good\npriority: 10\nadapters:\n - sie_server.adapters.bge_m3\n"
+ )
+ (bundles_dir / "typo.yaml").write_text(
+ "name: typo\nengine: pytroch\npriority: 10\nadapters:\n - sie_server.adapters.foo\n"
+ )
+
+ with caplog.at_level(logging.ERROR, logger="sie_config.model_registry"):
+ registry = ModelRegistry(bundles_dir, models_dir)
+
+ bundles = registry.list_bundles()
+ assert "good" in bundles
+ assert "typo" not in bundles
+ assert any(
+ rec.levelname == "ERROR" and "engine" in rec.getMessage() and "pytroch" in rec.getMessage()
+ for rec in caplog.records
+ )
+
+ def test_engine_namespace_mismatch_is_warned_but_loads(self, caplog: pytest.LogCaptureFixture) -> None:
+ with tempfile.TemporaryDirectory() as tmpdir:
+ bundles_dir, models_dir = self._mk_dirs(Path(tmpdir))
+ (bundles_dir / "mixed.yaml").write_text(
+ "name: mixed\n"
+ "engine: pytorch\n"
+ "priority: 10\n"
+ "adapters:\n"
+ " - sie_server.adapters.bert_flash\n"
+ " - some_unrelated.module\n"
+ )
+
+ with caplog.at_level(logging.WARNING, logger="sie_config.model_registry"):
+ registry = ModelRegistry(bundles_dir, models_dir)
+
+ info = registry.get_bundle_info("mixed")
+ assert info is not None
+ assert info.engine == "pytorch"
+ assert len(info.adapters) == 2
+ assert any(
+ rec.levelname == "WARNING" and "some_unrelated.module" in rec.getMessage() for rec in caplog.records
+ )
+
+ def test_known_engines_only_pytorch(self) -> None:
+ assert frozenset({"pytorch"}) == KNOWN_ENGINES
diff --git a/packages/sie_config/tests/test_model_registry_mutation.py b/packages/sie_config/tests/test_model_registry_mutation.py
index e1ee132b9..3cdfede92 100644
--- a/packages/sie_config/tests/test_model_registry_mutation.py
+++ b/packages/sie_config/tests/test_model_registry_mutation.py
@@ -95,7 +95,25 @@ class TestAddModelConfig:
"default": {"adapter_path": "sie_server.adapters.bert_flash:B", "max_batch_tokens": 1},
},
}
- with pytest.raises(ValueError, match="already exists with different config"):
+ with pytest.raises(ValueError, match="already exist with different content"):
+ registry.add_model_config(config)
+
+ def test_add_conflicting_non_hash_profile_field_raises(self) -> None:
+ registry, _ = _setup_registry(
+ self._root / "conflict_non_hash",
+ models={"existing/model": "sie_server.adapters.bert_flash:B"},
+ )
+ config = {
+ "sie_id": "existing/model",
+ "profiles": {
+ "default": {
+ "adapter_path": "sie_server.adapters.bert_flash:B",
+ "max_batch_tokens": 8192,
+ "max_sequence_length": 128,
+ },
+ },
+ }
+ with pytest.raises(ValueError, match="already exist with different content"):
registry.add_model_config(config)
def test_unroutable_adapter_raises(self) -> None:
diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lock
index a8dc2da15..ba7d518e7 100644
--- a/packages/sie_gateway/Cargo.lock
+++ b/packages/sie_gateway/Cargo.lock
@@ -128,33 +128,33 @@ dependencies = [
[[package]]
name = "async-nats"
-version = "0.38.0"
+version = "0.49.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "76433c4de73442daedb3a59e991d94e85c14ebfc33db53dfcd347a21cd6ef4f8"
+checksum = "407486109ea5cfdf53fde05f46996dadf0547518a4d49f050d25f405ae31ed2d"
dependencies = [
"base64",
"bytes",
- "futures",
+ "futures-util",
"memchr",
"nkeys",
"nuid",
- "once_cell",
"pin-project",
"portable-atomic",
- "rand 0.8.5",
+ "rand 0.10.1",
"regex",
"ring",
- "rustls-native-certs 0.7.3",
- "rustls-pemfile",
- "rustls-webpki 0.102.8",
+ "rustls-native-certs 0.8.4",
+ "rustls-pki-types",
+ "rustls-webpki",
"serde",
"serde_json",
"serde_nanos",
"serde_repr",
- "thiserror 1.0.69",
+ "thiserror 2.0.18",
"time",
"tokio",
"tokio-rustls",
+ "tokio-stream",
"tokio-util",
"tokio-websockets",
"tracing",
@@ -203,9 +203,9 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "autocfg"
-version = "1.5.0"
+version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "axum"
@@ -236,9 +236,9 @@ dependencies = [
[[package]]
name = "axum"
-version = "0.8.8"
+version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8b52af3cb4058c895d37317bb27508dccc8e5f2d39454016b297bf4a400597b8"
+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core 0.5.6",
"base64",
@@ -263,7 +263,7 @@ dependencies = [
"sha1",
"sync_wrapper",
"tokio",
- "tokio-tungstenite 0.28.0",
+ "tokio-tungstenite 0.29.0",
"tower 0.5.3",
"tower-layer",
"tower-service",
@@ -317,7 +317,7 @@ checksum = "b62ddb9cb1ec0a098ad4bbf9344d0713fa193ae1a80af55febcff2627b6a00c1"
dependencies = [
"getrandom 0.2.17",
"instant",
- "rand 0.8.5",
+ "rand 0.8.6",
]
[[package]]
@@ -340,9 +340,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitflags"
-version = "2.11.0"
+version = "2.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
+checksum = "84d7ced0ae9557296835c32bf1b1e02b44c746701f898460fb000d7eaa84f00a"
[[package]]
name = "block-buffer"
@@ -355,9 +355,9 @@ dependencies = [
[[package]]
name = "bumpalo"
-version = "3.20.2"
+version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "bytes"
@@ -370,9 +370,9 @@ dependencies = [
[[package]]
name = "cc"
-version = "1.2.59"
+version = "1.2.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b7a4d3ec6524d28a329fc53654bbadc9bdd7b0431f5d65f1a56ffb28a1ee5283"
+checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f"
dependencies = [
"find-msvc-tools",
"shlex",
@@ -390,6 +390,17 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+[[package]]
+name = "chacha20"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.0",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "chrono"
version = "0.4.44"
@@ -406,9 +417,9 @@ dependencies = [
[[package]]
name = "clap"
-version = "4.6.0"
+version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351"
+checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
dependencies = [
"clap_builder",
"clap_derive",
@@ -428,9 +439,9 @@ dependencies = [
[[package]]
name = "clap_derive"
-version = "4.6.0"
+version = "4.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a"
+checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
dependencies = [
"heck",
"proc-macro2",
@@ -500,6 +511,15 @@ dependencies = [
"libc",
]
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "crossbeam-channel"
version = "0.5.15"
@@ -532,7 +552,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
dependencies = [
"cfg-if",
- "cpufeatures",
+ "cpufeatures 0.2.17",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
@@ -588,9 +608,9 @@ dependencies = [
[[package]]
name = "dashmap"
-version = "6.1.0"
+version = "6.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5041cc499144891f3790297212f32a74fb938e5136a14943f338ef9e0ae276cf"
+checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c"
dependencies = [
"cfg-if",
"crossbeam-utils",
@@ -602,9 +622,9 @@ dependencies = [
[[package]]
name = "data-encoding"
-version = "2.10.0"
+version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d7a1e2f27636f116493b8b860f5546edb47c8d8f8ea73e1d2a20be88e28d1fea"
+checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
[[package]]
name = "deadpool"
@@ -657,9 +677,9 @@ dependencies = [
[[package]]
name = "displaydoc"
-version = "0.2.5"
+version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
+checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
dependencies = [
"proc-macro2",
"quote",
@@ -708,9 +728,9 @@ dependencies = [
[[package]]
name = "either"
-version = "1.15.0"
+version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
+checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
[[package]]
name = "enum-ordinalize"
@@ -771,9 +791,9 @@ dependencies = [
[[package]]
name = "fastrand"
-version = "2.3.0"
+version = "2.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
+checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
[[package]]
name = "fiat-crypto"
@@ -783,13 +803,12 @@ checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "filetime"
-version = "0.2.27"
+version = "0.2.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f98844151eee8917efc50bd9e8318cb963ae8b297431495d3f758616ea5c57db"
+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
dependencies = [
"cfg-if",
"libc",
- "libredox",
]
[[package]]
@@ -972,6 +991,7 @@ dependencies = [
"cfg-if",
"libc",
"r-efi 6.0.0",
+ "rand_core 0.10.1",
"wasip2",
"wasip3",
]
@@ -984,9 +1004,9 @@ checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "h2"
-version = "0.4.13"
+version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"
+checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733"
dependencies = [
"atomic-waker",
"bytes",
@@ -994,7 +1014,7 @@ dependencies = [
"futures-core",
"futures-sink",
"http",
- "indexmap 2.13.1",
+ "indexmap 2.14.0",
"slab",
"tokio",
"tokio-util",
@@ -1026,9 +1046,9 @@ dependencies = [
[[package]]
name = "hashbrown"
-version = "0.16.1"
+version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "headers"
@@ -1094,9 +1114,9 @@ dependencies = [
[[package]]
name = "http"
-version = "1.4.0"
+version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
+checksum = "8be7462df143984c4598a256ef469b251d7d7f9e271135073e78fc535414f3d0"
dependencies = [
"bytes",
"itoa",
@@ -1145,9 +1165,9 @@ checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"
[[package]]
name = "hyper"
-version = "1.9.0"
+version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca"
+checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498"
dependencies = [
"atomic-waker",
"bytes",
@@ -1187,21 +1207,20 @@ dependencies = [
[[package]]
name = "hyper-rustls"
-version = "0.27.7"
+version = "0.27.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"
+checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
dependencies = [
"http",
"hyper",
"hyper-util",
"log",
"rustls",
- "rustls-native-certs 0.8.3",
- "rustls-pki-types",
+ "rustls-native-certs 0.8.4",
"tokio",
"tokio-rustls",
"tower-service",
- "webpki-roots",
+ "webpki-roots 1.0.7",
]
[[package]]
@@ -1234,7 +1253,7 @@ dependencies = [
"libc",
"percent-encoding",
"pin-project-lite",
- "socket2 0.6.3",
+ "socket2 0.6.4",
"tokio",
"tower-service",
"tracing",
@@ -1371,9 +1390,9 @@ dependencies = [
[[package]]
name = "idna_adapter"
-version = "1.2.1"
+version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
dependencies = [
"icu_normalizer",
"icu_properties",
@@ -1391,12 +1410,12 @@ dependencies = [
[[package]]
name = "indexmap"
-version = "2.13.1"
+version = "2.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "45a8a2b9cb3e0b0c1803dbb0758ffac5de2f425b23c28f518faabd9d805342ff"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
dependencies = [
"equivalent",
- "hashbrown 0.16.1",
+ "hashbrown 0.17.1",
"serde",
"serde_core",
]
@@ -1436,16 +1455,6 @@ version = "2.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
-[[package]]
-name = "iri-string"
-version = "0.7.12"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "25e659a4bb38e810ebc252e53b5814ff908a8c58c2a9ce2fae1bbec24cbf4e20"
-dependencies = [
- "memchr",
- "serde",
-]
-
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
@@ -1461,6 +1470,15 @@ dependencies = [
"either",
]
+[[package]]
+name = "itertools"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+dependencies = [
+ "either",
+]
+
[[package]]
name = "itoa"
version = "1.0.18"
@@ -1469,9 +1487,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "js-sys"
-version = "0.3.94"
+version = "0.3.99"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2e04e2ef80ce82e13552136fabeef8a5ed1f985a96805761cbb9a2c34e7664d9"
+checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11"
dependencies = [
"cfg-if",
"futures-util",
@@ -1529,9 +1547,9 @@ dependencies = [
[[package]]
name = "kqueue"
-version = "1.1.1"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a"
+checksum = "273c0752728918e0ac4976f2b275b6fefb9ecd400585dec929419f3844cd87b5"
dependencies = [
"kqueue-sys",
"libc",
@@ -1539,11 +1557,11 @@ dependencies = [
[[package]]
name = "kqueue-sys"
-version = "1.0.4"
+version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b"
+checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"
dependencies = [
- "bitflags 1.3.2",
+ "bitflags 2.12.1",
"libc",
]
@@ -1672,21 +1690,9 @@ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libc"
-version = "0.2.184"
+version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af"
-
-[[package]]
-name = "libredox"
-version = "0.1.15"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ddbf48fd451246b1f8c2610bd3b4ac0cc6e149d89832867093ab69a17194f08"
-dependencies = [
- "bitflags 2.11.0",
- "libc",
- "plain",
- "redox_syscall 0.7.3",
-]
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "linux-raw-sys"
@@ -1717,9 +1723,9 @@ dependencies = [
[[package]]
name = "log"
-version = "0.4.29"
+version = "0.4.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+checksum = "113b30b4cd05f7c06868fdb2854f66a7b9fece9a48425351cd532e810d74024f"
[[package]]
name = "lru-slab"
@@ -1760,9 +1766,9 @@ dependencies = [
[[package]]
name = "memchr"
-version = "2.8.0"
+version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
+checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
[[package]]
name = "mime"
@@ -1784,9 +1790,9 @@ dependencies = [
[[package]]
name = "mio"
-version = "1.2.0"
+version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"
+checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"
dependencies = [
"libc",
"wasi",
@@ -1804,7 +1810,7 @@ dependencies = [
"ed25519-dalek",
"getrandom 0.2.17",
"log",
- "rand 0.8.5",
+ "rand 0.8.6",
"signatory",
]
@@ -1814,7 +1820,7 @@ version = "6.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6205bd8bb1e454ad2e27422015fb5e4f2bcc7e08fa8f27058670d208324a4d2d"
dependencies = [
- "bitflags 2.11.0",
+ "bitflags 2.12.1",
"crossbeam-channel",
"filetime",
"fsevent-sys",
@@ -1842,14 +1848,14 @@ version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc895af95856f929163a0aa20c26a78d26bfdc839f51b9d5aa7a5b79e52b7e83"
dependencies = [
- "rand 0.8.5",
+ "rand 0.8.6",
]
[[package]]
name = "num-conv"
-version = "0.2.1"
+version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967"
+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "num-traits"
@@ -1883,12 +1889,12 @@ dependencies = [
"futures",
"humantime",
"hyper",
- "itertools",
+ "itertools 0.13.0",
"md-5",
"parking_lot",
"percent-encoding",
"quick-xml",
- "rand 0.8.5",
+ "rand 0.8.6",
"reqwest",
"ring",
"rustls-pemfile",
@@ -1995,7 +2001,7 @@ dependencies = [
"once_cell",
"opentelemetry",
"percent-encoding",
- "rand 0.8.5",
+ "rand 0.8.6",
"serde_json",
"thiserror 1.0.69",
"tokio",
@@ -2035,7 +2041,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
- "redox_syscall 0.5.18",
+ "redox_syscall",
"smallvec",
"windows-link",
]
@@ -2110,18 +2116,18 @@ dependencies = [
[[package]]
name = "pin-project"
-version = "1.1.11"
+version = "1.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f1749c7ed4bcaf4c3d0a3efc28538844fb29bcdd7d2b67b2be7e20ba861ff517"
+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"
dependencies = [
"pin-project-internal",
]
[[package]]
name = "pin-project-internal"
-version = "1.1.11"
+version = "1.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d9b20ed30f105399776b9c883e68e536ef602a16ae6f596d2c473591d6ad64c6"
+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
dependencies = [
"proc-macro2",
"quote",
@@ -2144,12 +2150,6 @@ dependencies = [
"spki",
]
-[[package]]
-name = "plain"
-version = "0.2.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
-
[[package]]
name = "portable-atomic"
version = "1.13.1"
@@ -2201,32 +2201,31 @@ dependencies = [
[[package]]
name = "procfs"
-version = "0.16.0"
+version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "731e0d9356b0c25f16f33b5be79b1c57b562f141ebfcdb0ad8ac2c13a24293b4"
+checksum = "cc5b72d8145275d844d4b5f6d4e1eef00c8cd889edb6035c21675d1bb1f45c9f"
dependencies = [
- "bitflags 2.11.0",
+ "bitflags 2.12.1",
"hex",
- "lazy_static",
"procfs-core",
"rustix 0.38.44",
]
[[package]]
name = "procfs-core"
-version = "0.16.0"
+version = "0.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2d3554923a69f4ce04c4a754260c338f505ce22642d3830e049a399fc2059a29"
+checksum = "239df02d8349b06fc07398a3a1697b06418223b1c7725085e801e7c0fc6a12ec"
dependencies = [
- "bitflags 2.11.0",
+ "bitflags 2.12.1",
"hex",
]
[[package]]
name = "prometheus"
-version = "0.13.4"
+version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d33c28a30771f7f96db69893f78b857f7450d7e0237e9c8fc6427a81bae7ed1"
+checksum = "3ca5326d8d0b950a9acd87e6a3f94745394f62e4dae1b1ee22b2bc0c394af43a"
dependencies = [
"cfg-if",
"fnv",
@@ -2236,7 +2235,7 @@ dependencies = [
"parking_lot",
"procfs",
"protobuf",
- "thiserror 1.0.69",
+ "thiserror 2.0.18",
]
[[package]]
@@ -2256,7 +2255,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"
dependencies = [
"anyhow",
- "itertools",
+ "itertools 0.14.0",
"proc-macro2",
"quote",
"syn",
@@ -2264,9 +2263,23 @@ dependencies = [
[[package]]
name = "protobuf"
-version = "2.28.0"
+version = "3.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d65a1d4ddae7d8b5de68153b48f6aa3bba8cb002b243dbdbc55a5afbc98f99f4"
+dependencies = [
+ "once_cell",
+ "protobuf-support",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "protobuf-support"
+version = "3.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "106dd99e98437432fed6519dedecfade6a06a73bb7b2a1e019fdd2bee5778d94"
+checksum = "3e36c2f31e0a47f9280fb347ef5e461ffcd2c52dd520d8e216b52f93b0b0d7d6"
+dependencies = [
+ "thiserror 1.0.69",
+]
[[package]]
name = "quick-xml"
@@ -2291,7 +2304,7 @@ dependencies = [
"quinn-udp",
"rustc-hash",
"rustls",
- "socket2 0.6.3",
+ "socket2 0.6.4",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -2307,7 +2320,7 @@ dependencies = [
"bytes",
"getrandom 0.3.4",
"lru-slab",
- "rand 0.9.2",
+ "rand 0.9.4",
"ring",
"rustc-hash",
"rustls",
@@ -2328,9 +2341,9 @@ dependencies = [
"cfg_aliases",
"libc",
"once_cell",
- "socket2 0.6.3",
+ "socket2 0.6.4",
"tracing",
- "windows-sys 0.59.0",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -2356,9 +2369,9 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
-version = "0.8.5"
+version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
+checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
dependencies = [
"libc",
"rand_chacha 0.3.1",
@@ -2367,14 +2380,25 @@ dependencies = [
[[package]]
name = "rand"
-version = "0.9.2"
+version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
+checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
dependencies = [
"rand_chacha 0.9.0",
"rand_core 0.9.5",
]
+[[package]]
+name = "rand"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.2",
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "rand_chacha"
version = "0.3.1"
@@ -2414,21 +2438,18 @@ dependencies = [
]
[[package]]
-name = "redox_syscall"
-version = "0.5.18"
+name = "rand_core"
+version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
-dependencies = [
- "bitflags 2.11.0",
-]
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "redox_syscall"
-version = "0.7.3"
+version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6ce70a74e890531977d37e532c34d45e9055d2409ed08ddba14529471ed0be16"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
- "bitflags 2.11.0",
+ "bitflags 2.12.1",
]
[[package]]
@@ -2483,7 +2504,7 @@ dependencies = [
"pin-project-lite",
"quinn",
"rustls",
- "rustls-native-certs 0.8.3",
+ "rustls-native-certs 0.8.4",
"rustls-pki-types",
"serde",
"serde_json",
@@ -2500,7 +2521,7 @@ dependencies = [
"wasm-bindgen-futures",
"wasm-streams",
"web-sys",
- "webpki-roots",
+ "webpki-roots 1.0.7",
]
[[package]]
@@ -2568,7 +2589,7 @@ version = "0.38.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
dependencies = [
- "bitflags 2.11.0",
+ "bitflags 2.12.1",
"errno",
"libc",
"linux-raw-sys 0.4.15",
@@ -2581,7 +2602,7 @@ version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
- "bitflags 2.11.0",
+ "bitflags 2.12.1",
"errno",
"libc",
"linux-raw-sys 0.12.1",
@@ -2590,15 +2611,15 @@ dependencies = [
[[package]]
name = "rustls"
-version = "0.23.37"
+version = "0.23.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
+checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b"
dependencies = [
"log",
"once_cell",
"ring",
"rustls-pki-types",
- "rustls-webpki 0.103.13",
+ "rustls-webpki",
"subtle",
"zeroize",
]
@@ -2618,9 +2639,9 @@ dependencies = [
[[package]]
name = "rustls-native-certs"
-version = "0.8.3"
+version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
dependencies = [
"openssl-probe 0.2.1",
"rustls-pki-types",
@@ -2639,25 +2660,14 @@ dependencies = [
[[package]]
name = "rustls-pki-types"
-version = "1.14.0"
+version = "1.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"
+checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9"
dependencies = [
"web-time",
"zeroize",
]
-[[package]]
-name = "rustls-webpki"
-version = "0.102.8"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9"
-dependencies = [
- "ring",
- "rustls-pki-types",
- "untrusted",
-]
-
[[package]]
name = "rustls-webpki"
version = "0.103.13"
@@ -2744,7 +2754,7 @@ version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
dependencies = [
- "bitflags 2.11.0",
+ "bitflags 2.12.1",
"core-foundation 0.9.4",
"core-foundation-sys",
"libc",
@@ -2757,7 +2767,7 @@ version = "3.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
dependencies = [
- "bitflags 2.11.0",
+ "bitflags 2.12.1",
"core-foundation 0.10.1",
"core-foundation-sys",
"libc",
@@ -2843,9 +2853,9 @@ dependencies = [
[[package]]
name = "serde_json"
-version = "1.0.149"
+version = "1.0.150"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
dependencies = [
"itoa",
"memchr",
@@ -2903,7 +2913,7 @@ version = "0.9.34+deprecated"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"
dependencies = [
- "indexmap 2.13.1",
+ "indexmap 2.14.0",
"itoa",
"ryu",
"serde",
@@ -2917,7 +2927,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
- "cpufeatures",
+ "cpufeatures 0.2.17",
"digest",
]
@@ -2928,7 +2938,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
- "cpufeatures",
+ "cpufeatures 0.2.17",
"digest",
]
@@ -2943,18 +2953,18 @@ dependencies = [
[[package]]
name = "shlex"
-version = "1.3.0"
+version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "sie-gateway"
-version = "0.4.1"
+version = "0.4.2"
dependencies = [
"arc-swap",
"async-nats",
"async-trait",
- "axum 0.8.8",
+ "axum 0.8.9",
"base64",
"bytes",
"chrono",
@@ -2976,7 +2986,7 @@ dependencies = [
"opentelemetry_sdk",
"percent-encoding",
"prometheus",
- "rand 0.8.5",
+ "rand 0.8.6",
"reqwest",
"rmp",
"rmp-serde",
@@ -3081,9 +3091,9 @@ dependencies = [
[[package]]
name = "socket2"
-version = "0.6.3"
+version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
+checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"
dependencies = [
"libc",
"windows-sys 0.61.2",
@@ -3268,17 +3278,17 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
-version = "1.51.0"
+version = "1.52.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2bd1c4c0fc4a7ab90fc15ef6daaa3ec3b893f004f915f2392557ed23237820cd"
+checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"
dependencies = [
"bytes",
"libc",
- "mio 1.2.0",
+ "mio 1.2.1",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
- "socket2 0.6.3",
+ "socket2 0.6.4",
"tokio-macros",
"windows-sys 0.61.2",
]
@@ -3330,14 +3340,14 @@ dependencies = [
[[package]]
name = "tokio-tungstenite"
-version = "0.28.0"
+version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857"
+checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"
dependencies = [
"futures-util",
"log",
"tokio",
- "tungstenite 0.28.0",
+ "tungstenite 0.29.0",
]
[[package]]
@@ -3366,13 +3376,13 @@ dependencies = [
"futures-sink",
"http",
"httparse",
- "rand 0.8.5",
+ "rand 0.8.6",
"ring",
- "rustls-native-certs 0.8.3",
"rustls-pki-types",
"tokio",
"tokio-rustls",
"tokio-util",
+ "webpki-roots 0.26.11",
]
[[package]]
@@ -3416,7 +3426,7 @@ dependencies = [
"indexmap 1.9.3",
"pin-project",
"pin-project-lite",
- "rand 0.8.5",
+ "rand 0.8.6",
"slab",
"tokio",
"tokio-util",
@@ -3444,23 +3454,23 @@ dependencies = [
[[package]]
name = "tower-http"
-version = "0.6.8"
+version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
dependencies = [
"base64",
- "bitflags 2.11.0",
+ "bitflags 2.12.1",
"bytes",
"futures-util",
"http",
"http-body",
- "iri-string",
"mime",
"pin-project-lite",
"tower 0.5.3",
"tower-layer",
"tower-service",
"tracing",
+ "url",
]
[[package]]
@@ -3595,7 +3605,7 @@ dependencies = [
"http",
"httparse",
"log",
- "rand 0.9.2",
+ "rand 0.9.4",
"sha1",
"thiserror 2.0.18",
"utf-8",
@@ -3603,26 +3613,25 @@ dependencies = [
[[package]]
name = "tungstenite"
-version = "0.28.0"
+version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442"
+checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"
dependencies = [
"bytes",
"data-encoding",
"http",
"httparse",
"log",
- "rand 0.9.2",
+ "rand 0.9.4",
"sha1",
"thiserror 2.0.18",
- "utf-8",
]
[[package]]
name = "typenum"
-version = "1.19.0"
+version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "ucd-trie"
@@ -3686,11 +3695,11 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "utoipa"
-version = "5.4.0"
+version = "5.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2fcc29c80c21c31608227e0912b2d7fddba57ad76b606890627ba8ee7964e993"
+checksum = "8bde15df68e80b16c7d16b9616e80770ad158988daa56a27dccd1e55558b0160"
dependencies = [
- "indexmap 2.13.1",
+ "indexmap 2.14.0",
"serde",
"serde_json",
"utoipa-gen",
@@ -3698,9 +3707,9 @@ dependencies = [
[[package]]
name = "utoipa-gen"
-version = "5.4.0"
+version = "5.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6d79d08d92ab8af4c5e8a6da20c47ae3f61a0f1dabc1997cdf2d082b757ca08b"
+checksum = "6ba0b99ee52df3028635d93840c797102da61f8a7bb3cf751032455895b52ef8"
dependencies = [
"proc-macro2",
"quote",
@@ -3709,9 +3718,9 @@ dependencies = [
[[package]]
name = "uuid"
-version = "1.23.0"
+version = "1.23.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5ac8b6f42ead25368cf5b098aeb3dc8a1a2c05a3eee8a9a1a68c640edbfc79d9"
+checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7"
dependencies = [
"getrandom 0.4.2",
"js-sys",
@@ -3757,11 +3766,11 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "wasip2"
-version = "1.0.2+wasi-0.2.9"
+version = "1.0.3+wasi-0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
+checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"
dependencies = [
- "wit-bindgen",
+ "wit-bindgen 0.57.1",
]
[[package]]
@@ -3770,14 +3779,14 @@ version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
dependencies = [
- "wit-bindgen",
+ "wit-bindgen 0.51.0",
]
[[package]]
name = "wasm-bindgen"
-version = "0.2.117"
+version = "0.2.122"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0"
+checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409"
dependencies = [
"cfg-if",
"once_cell",
@@ -3788,9 +3797,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
-version = "0.4.67"
+version = "0.4.72"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03623de6905b7206edd0a75f69f747f134b7f0a2323392d664448bf2d3c5d87e"
+checksum = "9473dbd2991ae90b6291c3c32c30c6187ac49aa32f9905d1cce280ec1e110b0f"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -3798,9 +3807,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
-version = "0.2.117"
+version = "0.2.122"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be"
+checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -3808,9 +3817,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
-version = "0.2.117"
+version = "0.2.122"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2"
+checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e"
dependencies = [
"bumpalo",
"proc-macro2",
@@ -3821,9 +3830,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
-version = "0.2.117"
+version = "0.2.122"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b"
+checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437"
dependencies = [
"unicode-ident",
]
@@ -3845,7 +3854,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
dependencies = [
"anyhow",
- "indexmap 2.13.1",
+ "indexmap 2.14.0",
"wasm-encoder",
"wasmparser",
]
@@ -3869,17 +3878,17 @@ version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
dependencies = [
- "bitflags 2.11.0",
+ "bitflags 2.12.1",
"hashbrown 0.15.5",
- "indexmap 2.13.1",
+ "indexmap 2.14.0",
"semver",
]
[[package]]
name = "web-sys"
-version = "0.3.94"
+version = "0.3.99"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cd70027e39b12f0849461e08ffc50b9cd7688d942c1c8e3c7b22273236b4dd0a"
+checksum = "6d621441cfc37b84979402712047321980c178f299193a3589d05b99e8763436"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -3897,9 +3906,18 @@ dependencies = [
[[package]]
name = "webpki-roots"
-version = "1.0.6"
+version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "22cfaf3c063993ff62e73cb4311efde4db1efb31ab78a3e5c457939ad5cc0bed"
+checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
+dependencies = [
+ "webpki-roots 1.0.7",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d"
dependencies = [
"rustls-pki-types",
]
@@ -4021,6 +4039,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.5",
+]
+
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -4054,13 +4081,30 @@ dependencies = [
"windows_aarch64_gnullvm 0.52.6",
"windows_aarch64_msvc 0.52.6",
"windows_i686_gnu 0.52.6",
- "windows_i686_gnullvm",
+ "windows_i686_gnullvm 0.52.6",
"windows_i686_msvc 0.52.6",
"windows_x86_64_gnu 0.52.6",
"windows_x86_64_gnullvm 0.52.6",
"windows_x86_64_msvc 0.52.6",
]
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm 0.53.1",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
+]
+
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
@@ -4073,6 +4117,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
@@ -4085,6 +4135,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
@@ -4097,12 +4153,24 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
@@ -4115,6 +4183,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
@@ -4127,6 +4201,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
@@ -4139,6 +4219,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
@@ -4151,6 +4237,12 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
[[package]]
name = "wiremock"
version = "0.6.5"
@@ -4183,6 +4275,12 @@ dependencies = [
"wit-bindgen-rust-macro",
]
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
[[package]]
name = "wit-bindgen-core"
version = "0.51.0"
@@ -4202,7 +4300,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
dependencies = [
"anyhow",
"heck",
- "indexmap 2.13.1",
+ "indexmap 2.14.0",
"prettyplease",
"syn",
"wasm-metadata",
@@ -4232,8 +4330,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
dependencies = [
"anyhow",
- "bitflags 2.11.0",
- "indexmap 2.13.1",
+ "bitflags 2.12.1",
+ "indexmap 2.14.0",
"log",
"serde",
"serde_derive",
@@ -4252,7 +4350,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
dependencies = [
"anyhow",
"id-arena",
- "indexmap 2.13.1",
+ "indexmap 2.14.0",
"log",
"semver",
"serde",
@@ -4299,18 +4397,18 @@ dependencies = [
[[package]]
name = "zerocopy"
-version = "0.8.48"
+version = "0.8.50"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"
+checksum = "3b065d4f0e55f82fae73202e189638116a87c55ab6b8e6c2721e13dd9d854ad1"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
-version = "0.8.48"
+version = "0.8.50"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"
+checksum = "0b631b19d36a892ab55420c92dbc83ccd79274f25be714855d3074aa71cab639"
dependencies = [
"proc-macro2",
"quote",
@@ -4319,9 +4417,9 @@ dependencies = [
[[package]]
name = "zerofrom"
-version = "0.1.7"
+version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
dependencies = [
"zerofrom-derive",
]
diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.toml
index 938e4dd7c..0288274b2 100644
--- a/packages/sie_gateway/Cargo.toml
+++ b/packages/sie_gateway/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "sie-gateway"
-version = "0.4.1"
+version = "0.4.2"
edition = "2021"
publish = false
@@ -24,7 +24,7 @@ serde_yaml = "0.9"
clap = { version = "4", features = ["derive", "env"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["json", "env-filter"] }
-prometheus = { version = "0.13", features = ["process"] }
+prometheus = { version = "0.14", features = ["process"] }
thiserror = "2"
dashmap = "6"
tower = "0.5"
@@ -54,7 +54,7 @@ md-5 = "0.10"
xxhash-rust = { version = "0.8", features = ["xxh3"] }
# Phase 8: NATS integration
-async-nats = "0.38"
+async-nats = "0.49"
uuid = { version = "1", features = ["v4", "v7"] }
# Phase 10: Queue mode (msgpack serialization)
@@ -73,7 +73,7 @@ object_store = { version = "0.11", optional = true, features = ["aws", "gcp"] }
url = { version = "2", optional = true }
utoipa = "5.4.0"
-# W3C Trace Context propagation (M5+). The gateway extracts the
+# W3C Trace Context propagation. The gateway extracts the
# inbound `traceparent` / `tracestate` HTTP headers, opens a child
# span around proxy/publish, and injects the resulting context into
# the JetStream work envelope so the worker can continue the trace.
diff --git a/packages/sie_gateway/Dockerfile b/packages/sie_gateway/Dockerfile
index e085b11ee..6c6407aee 100644
--- a/packages/sie_gateway/Dockerfile
+++ b/packages/sie_gateway/Dockerfile
@@ -1,4 +1,4 @@
-FROM rust:1.95.0-slim-bookworm AS chef
+FROM rust:1.96.0-slim-bookworm AS chef
RUN cargo install cargo-chef --locked
WORKDIR /app
diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.md
index 96ae1032a..df0db4a50 100644
--- a/packages/sie_gateway/README.md
+++ b/packages/sie_gateway/README.md
@@ -2,7 +2,7 @@
Runtime gateway for elastic GPU inference deployments. It routes the four SIE primitives: `encode`, `score`, and `extract` over NATS JetStream (queue transport, at-least-once delivery), plus OpenAI-compatible and SIE-native **generation** endpoints (`/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/generate/{model}`) over direct-dispatch per-worker streams with cache-aware prefix routing. The gateway also owns pool coordination and worker health. Config writes live in `sie-config`; the gateway is a pure consumer of config state, bootstrapping from `GET /v1/configs/export` and subscribing to NATS deltas.
-Generation is treated as a supported fourth primitive (see [`docs/adr/0001-generation-is-a-supported-primitive.md`](../../docs/adr/0001-generation-is-a-supported-primitive.md) and `product/design.md` Section 5.10–5.14 for the contract — defer to those documents for the full surface).
+Generation is treated as a supported fourth primitive.
See [`docs/architecture-guide.md`](docs/architecture-guide.md) for the authoritative code-audited architecture document (covers both this service and `sie-config`).
@@ -49,7 +49,8 @@ SIE_NATS_URL=nats://localhost:4222 \
Notes:
-- `encode` / `score` / `extract` are queue-only: if no usable NATS client is available, these requests return `503`. Generation endpoints use direct-dispatch and do not depend on JetStream for their hot path (NATS Core is still used for worker health and config distribution).
+- `encode` / `score` / `extract` are queue-only: if no usable NATS client is available, these requests return `503`.
+- Generation endpoints use direct-dispatch and do not depend on JetStream for their hot path (NATS Core is still used for worker health and config distribution). There is no direct worker HTTP fallback mode and no `SIE_CLUSTER_ROUTING` toggle.
## CLI
@@ -87,7 +88,7 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio
| `SIE_GATEWAY_K8S_NAMESPACE` | `default` | K8s namespace |
| `SIE_GATEWAY_K8S_SERVICE` | `sie-worker` | K8s service name |
| `SIE_GATEWAY_K8S_PORT` | `8080` | K8s worker port |
-| `SIE_GATEWAY_HEALTH_MODE` | `ws` | Worker health transport. Supported value: `ws`. `nats` is experimental/internal and requires a worker-side `sie.health.>` publisher, which is not wired by default |
+| `SIE_GATEWAY_HEALTH_MODE` | `ws` | Health mode: `ws` or `nats` |
| `SIE_NATS_URL` | | NATS server URL. The process can start without it, but inference requests will return `503` until a usable client exists |
| `SIE_AUTH_MODE` | `none` | Auth mode for inbound requests: `none` disables, `token` (alias `static`) enforces. Unknown values fail-open-to-bypass; `main` logs a startup error naming the bad value |
| `SIE_AUTH_TOKENS` | | CSV of valid bearer tokens for inference and pool/config read endpoints. If unset, the singular `SIE_AUTH_TOKEN` is used as a fallback. When auth is enabled and this list is empty, non-probe requests return `500` |
@@ -110,7 +111,7 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio
| `SIE_GATEWAY_GPU_ALIASES` | | JSON map of request aliases to canonical machine profiles |
| `SIE_BUNDLES_DIR` | `bundles` | Optional bundle filesystem seed. Unset in default Helm deploys: the gateway pulls bundles from `sie-config` via `GET /v1/configs/bundles{,/{id}}` at startup and the registry's filesystem reload is a no-op. Only set by the `gateway.embeddedConfigs` / `gateway.configMap` overlays which mount a ConfigMap at `/configs/bundles`. |
| `SIE_MODELS_DIR` | `models` | Optional model filesystem seed. Same semantics as `SIE_BUNDLES_DIR`: unset in default deploys, runtime model writes always go to `sie-config` and the gateway replays them via `GET /v1/configs/export`. |
-| `SIE_PAYLOAD_STORE_URL` | `payload_store` | Payload offload store path; `s3://` and `gs://` require the `cloud-storage` feature |
+| `SIE_PAYLOAD_STORE_URL` | unset | Shared payload offload store path. When unset, large-payload offload is disabled. Queue deployments should use `s3://` or `gs://`; local filesystem paths only work when gateway and workers share the same path |
## API Endpoints
@@ -137,7 +138,7 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio
### Generation (direct-dispatch per-worker streams)
-Generation is a supported fourth primitive. The contract is defined in `product/design.md` Section 5.10–5.14; this README only lists the routes. Strict allow-list parsing on the OpenAI-compatible endpoints — unknown fields reject with `400 unsupported_field`.
+Generation is a supported fourth primitive. Strict allow-list parsing on the OpenAI-compatible endpoints means unknown fields reject with `400 unsupported_field`.
| Method | Path | Description |
|--------|------|-------------|
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index f7e1363ec..1e6a76327 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -1,6 +1,6 @@
# SIE Architecture
-This document describes the current deployed architecture of the SIE control plane and inference edge. It is code-audited against the `sie-internal` monorepo (`packages/sie_gateway`, `packages/sie_config`, `packages/sie_sdk`). Every behavior described here is what the code does on this branch.
+This document describes the current deployed architecture of the SIE control plane and inference edge. It is verified against the `sie-internal` monorepo (`packages/sie_gateway`, `packages/sie_config`, `packages/sie_sdk`). Every behavior described here is what the code does on this branch.
Top-level summary:
@@ -36,7 +36,7 @@ Key terms used throughout this document:
- **Pool**: an operational routing group of workers managed by the gateway. Answers "which compatible workers should this request be queued to right now?". Pools are a runtime concept stored in Kubernetes.
- **Config store**: `sie-config`'s backing store for persisted state. Per-model YAML files plus a plain-text monotonic `epoch` counter, laid out as `{base}/models/{id-with-/-as-__}.yaml` and `{base}/epoch`. The backend is selected by the `SIE_CONFIG_STORE_DIR` scheme: a local path (default — backed by an opt-in PVC in Helm), `s3://…`, or `gs://…`.
- **Config epoch**: a monotonic integer. Every `sie-config` write that creates new profiles bumps it by one. The gateway tracks it locally as `ConfigEpoch` for drift detection.
-- **`bundle_config_hash`**: a content hash over the routable-profile fields (`adapter_path`, `max_batch_tokens`, `compute_precision`, `adapter_options`) for every model whose adapters match a bundle. Used by admin tooling and workers to tell "has this worker picked up the new config for this bundle yet?"
+- **`bundle_config_hash`**: a content hash over the routable-profile fields (`adapter_path`, `max_batch_tokens`, `compute_precision`, `adapter_options`) for every model whose adapters match a bundle. Used by admin tooling and workers to tell whether a worker's local registry matches the gateway's expected config for this bundle.
## 2. Inference Request Path
@@ -57,10 +57,11 @@ Rules enforced on the inference path:
- The inference hot path is queue-only. There is no direct-HTTP fallback. `src/handlers/proxy.rs` is the queue-submission handler despite its name.
- If the queue transport is unavailable (no usable NATS client at init), the gateway returns `503`. It does not fall back to direct mode.
- Unknown model ids fast-fail with `404` whenever the in-memory `ModelRegistry` has been populated (either by the filesystem seed or by a successful bootstrap / delta from `sie-config`). In the pre-bootstrap edge case where the registry is still empty — no seed, no export applied yet — the proxy falls back to the caller-supplied bundle (or `"default"`) so an unseeded gateway can still publish work to a cold pool that a caller pinned via `X-SIE-Pool`. Once any model is registered, this fallback is disabled and the 404 contract applies.
+- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. Explicit `X-SIE-Pool` remains an operator override; deliveries with hashes unknown to the worker-sidecar are NAKed before Python IPC.
- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway returns `202 provisioning` with `Retry-After: 120` and records pending demand for KEDA. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.
- On no-consumer conditions for the JetStream publish the gateway returns `503` with `Retry-After: 120`. On backpressure conditions the gateway returns `503` with `Retry-After: 5`.
- On queue result timeouts the gateway returns `503` with `X-SIE-Error-Code: MODEL_LOADING` and `Retry-After: 5`. The most common trigger is a worker cold-loading the target model on demand (worker NAKs the JetStream message and redelivers after load); the SDK retries this under the same `provision_timeout_s` budget used for worker-emitted `MODEL_LOADING` responses.
-- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED` (worker-side OOM recovery exhausted — `Retry-After: 5`), `MODEL_LOADING`, and `LORA_LOADING`. **Mixed batches** (different codes per item) keep going through the legacy `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.
+- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED` (worker-side OOM recovery exhausted — `Retry-After: 5`), `MODEL_LOADING`, and `LORA_LOADING`. **Mixed batches** (different codes per item) keep going through the compatibility `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.
- When **every** failed item carries **`MODEL_LOAD_FAILED`**, the gateway returns **`502 Bad Gateway`** with the SDK-style **`error`** object (`code`, `message`, `error_class`, `attempts`, `permanent`) — matching the terminal model-load contract consumed by SDK retry logic (no `Retry-After`; the SDK must not burn the `MODEL_LOADING` retry budget). The gateway synthesises conservative `attempts` / `permanent` fields on this queue path when the worker payload does not carry registry-shaped failure metadata.
Encode / extract tuning fields (`output_types`, `instruction`, `options`, `labels`, `output_schema`, `is_query`) are read **only** from the nested JSON **`params`** object (and the msgpack analogue: a top-level **`params`** map). The score path continues to read `query` / `instruction` / `options` at the top level of the request body, matching `sie_server`.
@@ -74,7 +75,7 @@ Gateway-generated **JSON error** bodies (validation, routing, auth, config read,
All config mutations go to `sie-config`. The gateway has no write handler.
1. Admin or deploy tooling sends `POST /v1/configs/models` with a model config YAML body to `sie-config`. Auth: `_check_write_auth` (`packages/sie_config/src/sie_config/config_api.py`) requires a bearer matching `SIE_ADMIN_TOKEN` when that variable is set; if `SIE_ADMIN_TOKEN` is unset and `SIE_AUTH_TOKEN` is set, writes are rejected with `403` (the inference token never grants write access); if neither token is set (dev/local only) writes are accepted unauthenticated. Production deployments always set `SIE_ADMIN_TOKEN`.
-2. **Pre-lock stage** (outside the per-app write lock, on the FastAPI event loop): parse the YAML body and — when a top-level `sie_id` is present — run `_validate_model_id` (regex + `..`/`\\` rejection + `status`-suffix rejection). Reject invalid input with `400` before any state is touched.
+2. **Pre-lock validation** (outside the per-app write lock, on the FastAPI event loop): parse the YAML body and — when a top-level `sie_id` is present — run `_validate_model_id` (regex + `..`/`\\` rejection + `status`-suffix rejection). Reject invalid input with `400` before any state is touched.
3. **Critical section** under `_get_write_lock` (a lazy, per-app `asyncio.Lock` stored on `app.state`):
1. `ModelRegistry.validate_model_config` — pure check against the in-memory registry (no mutation), run under the registry's internal `threading.RLock`. Validation rejects any write whose post-state resolves to zero routable bundles (`422`), so an `extends`-only profile cannot land a brand-new model that no worker bundle can serve. Appending a new `extends`-only profile to an already-routable model is allowed.
2. **Compute `created_profiles` vs `existing_profiles_skipped`.** The write is treated as append-only: profiles already present in the registry with a compatible body are reported as skipped, not rewritten. If there are no new profiles *and* at least one skip, an on-disk conflict check compares the incoming YAML against `ConfigStore`'s existing file for this model (guards against disk drift from the in-memory registry).
@@ -95,7 +96,8 @@ Ordering guarantees:
NATS publish behavior:
- One `ConfigNotification` message is published per affected bundle to `sie.config.models.{bundle_id}`, and a byte-identical copy to `sie.config.models._all`.
-- If publish fails for a subset of bundles, `NatsPublisher` continues publishing to the remaining bundles and raises `PartialPublishError` at the end with the failed bundle list. The write itself is still durable on disk. The response `warnings` field names the failed bundles; affected workers will stay on the previous epoch until the gateway's poller triggers a re-export.
+- Gateway code consumes `sie.config.models._all`. Worker-sidecar containers consume their bundle-scoped subject and forward accepted deltas to Python over IPC `ApplyModelConfig`.
+- If publish fails for a subset of bundles, `NatsPublisher` continues publishing to the remaining bundles and raises `PartialPublishError` at the end with the failed bundle list. The write itself is still durable on disk. The response `warnings` field names the failed bundles; gateway convergence is repaired by the poller/export path if `_all` is missed. Worker-sidecar convergence is repaired by the worker export reconciler when `SIE_CONFIG_SERVICE_URL` is set.
Idempotency:
@@ -178,13 +180,13 @@ Per-tick decisions:
- Transient `/epoch` failures are logged and swallowed. The next tick retries. Neither the local epoch nor the stored bundles hash is reset on poll failure.
- The poller **always** compares local vs. remote, including when `local_epoch == 0` or `stored_bundles_hash == ""`. This matters for fresh clusters: if `sie-config`'s very first write (→ epoch 1) is lost on the wire, the gateway must catch `remote=1 > local=0` and trigger recovery. Gating on "non-zero local" would wedge a fresh gateway until a restart.
-Operational consequence: adding or changing a bundle in `sie-config` propagates to running gateways within one `DEFAULT_POLL_INTERVAL` (≤ 30s worst case). No `kubectl rollout restart deployment/sie-gateway` is required — that was true of an earlier revision of this design, which relied on bundles being baked into the gateway image.
+Operational consequence: adding or changing a bundle in `sie-config` propagates to running gateways within one `DEFAULT_POLL_INTERVAL` (≤ 30s worst case). No `kubectl rollout restart deployment/sie-gateway` is required for the gateway to learn the updated bundle set.
### 4.3 Live deltas
Independently of bootstrap and polling, `NatsManager` subscribes to `sie.config.models._all` (Core pub/sub) as soon as the NATS client is ready. For each incoming `ConfigNotification`:
-- **Producer-trust check first.** The `producer_id` (wire key `router_id`) must be in the trusted-producer allowlist. Default allowlist is `["sie-config"]`, configurable via `SIE_NATS_CONFIG_TRUSTED_PRODUCERS=a,b,c`. Matching is exact equality OR K8s pod-name prefix (`sie-config` also matches `sie-config-5f7b6d8c-kxwvr` and `sie-config-0`, but not `sie-configuration`). Untrusted notifications are dropped before any registry mutation or epoch advance; a log warning names the rejected producer. Set `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER=true` to disable validation (dev/local only — `main.rs` emits a startup audit warning when this is on).
+- **Producer-trust check first.** The `producer_id` (wire key `router_id`) must be in the trusted-producer allowlist. Default allowlist is `["sie-config"]`, configurable via `SIE_NATS_CONFIG_TRUSTED_PRODUCERS=a,b,c`; Helm sets it to the rendered config Deployment name (for example `sie-sie-cluster-config`) so Kubernetes pod names from that Deployment match. Matching is exact equality OR K8s pod-name prefix (`sie-config` also matches `sie-config-5f7b6d8c-kxwvr` and `sie-config-0`, but not `sie-configuration`). Untrusted notifications are dropped before any registry mutation or epoch advance; a log warning names the rejected producer. Set `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER=true` to disable validation (dev/local only — `main.rs` emits a startup warning when this is on).
- An **empty-or-whitespace `model_config` body** (pure epoch bump) advances `ConfigEpoch` via `set_max(notification.epoch)` and returns.
- A non-empty body is parsed as `ModelConfig` YAML. If the parse fails, the epoch is NOT advanced and the event is logged. The poller will catch up.
- On successful parse, `ModelRegistry.add_model_config` is called. If it returns `Ok`, the epoch is advanced. If it returns `Err` (e.g. append-only conflict, unroutable adapter), the epoch is NOT advanced.
@@ -216,7 +218,7 @@ Concurrency on the gateway's `ModelRegistry`:
## 6. Worker-Ack Status (`GET /v1/configs/models/{id}/status`)
-Admin tooling uses this endpoint after a `sie-config` write to confirm that configured workers have picked up the new `bundle_config_hash` for each affected bundle.
+Admin tooling uses this endpoint after a `sie-config` write to observe whether configured workers are reporting the expected `bundle_config_hash` for each affected bundle. Worker-sidecar containers advance that hash after their bundle-scoped NATS delta is accepted by Python IPC `ApplyModelConfig`, or after the worker export reconciler replays the missed bundle entry from `sie-config`.
Response shape:
@@ -281,8 +283,8 @@ Per-subject transport:
| Inference work (`encode` / `score` / `extract`) | `sie.work.{model}.{pool}` | JetStream | Durability and max-delivery semantics required. Work-item payload is msgpack. One stream per pool (`WORK_POOL_{pool}`) captures all non-generation work for the pool; see §8.2. |
| Generation direct-dispatch | `sie.work.{model}.{pool}.{worker_id}` | JetStream | Worker-specific stream used only by pools that host generation-capable models. Non-generation workers must not create or poll this stream; keeping them pool-only preserves queue batching for `encode` / `score` / `extract`. |
| Inference results | `_INBOX.{router_id}.{request_id}` | NATS Core | Gateway is waiting synchronously; a brief blip after publish but before delivery means the result is lost and the client retries (the gateway returns `503` with `X-SIE-Error-Code: MODEL_LOADING` and `Retry-After: 5` — see §2). Result payload is msgpack. |
-| Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Durability comes from the snapshot/export path (§4), not the bus. JSON payload (control plane, not hot path). Workers subscribe per-bundle; the gateway subscribes on `_all`. |
-| Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`); the **default `health_mode=ws`** uses the WebSocket path, and a NATS-mode publisher is not present in the current worker code. Until a worker-side publisher is added, NATS health mode is effectively a no-op consumer. |
+| Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Gateway durability comes from the snapshot/export path (§4), not the bus. JSON payload (control plane, not hot path). The gateway subscribes on `_all`; worker-sidecar containers subscribe on their bundle subject and apply through Python IPC. |
+| Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`). Worker-sidecar containers publish this heartbeat and include the latest bundle hash after successful config apply; the **default `health_mode=ws`** still uses the Python WebSocket path. |
| DLQ advisories | `$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>` | NATS Core (advisory) | JetStream emits these; the gateway subscribes in `queue/dlq.rs`. |
| DLQ storage | `sie.dlq.{model_token}` | JetStream | Single stream `DEAD_LETTERS` (Limits retention, memory storage, 24 h `max_age`) captures `sie.dlq.>`. `model_token` is derived from the advisory's original work subject by taking the model segment and replacing `/` with `_`. |
@@ -299,19 +301,21 @@ max_age: 60s (gateway-side)
max_msgs: 100_000
```
-The Python worker (`sie_server.nats_pull_loop`) independently calls `add_stream` with the **same** name but a **different default `max_age` of 120 s** (`SIE_STREAM_MAX_AGE_S`). `get_or_create_stream` / `add_stream` does not update an existing stream's config, so whichever side races to the broker first wins. To avoid drift, pick one owner (either the gateway or the worker); the Helm values should set `SIE_STREAM_MAX_AGE_S` on workers to match the gateway's constant, or the gateway should read the same env.
+The worker-sidecar (`packages/sie_server_sidecar`, binary `sie-server-sidecar`) also calls `add_stream` with the **same** name but a default `max_age` of 120 s (`SIE_STREAM_MAX_AGE_S`). `get_or_create_stream` / `add_stream` does not update an existing stream's config, so whichever side races to the broker first wins. To avoid drift, pick one owner (either the gateway or the worker); the Helm values should set `SIE_STREAM_MAX_AGE_S` on workers to match the gateway's constant, or the gateway should read the same env.
The stream's subject filter `sie.work.*.{pool}` matches **exactly one token** in the model position. NATS subject tokens legally contain `/`, so `BAAI/bge-m3` works directly. They cannot contain `.`, `*`, `>`, or whitespace, so any model whose `sie_id` contains one of those characters would — without normalization — expand into multiple tokens, not match the stream filter, and get rejected at the broker.
-To prevent that, the Rust gateway's `work_subject(model, pool)` in `packages/sie_gateway/src/queue/publisher.rs` calls a private `normalize_model_id` helper that mirrors the Python SDK (`sie_sdk.queue_types.normalize_model_id`): `/` → `__`, `.` → `_dot_`, and `*`/`>`/space → `_`. So `vidore/colqwen2.5-v0.2` publishes on `sie.work.vidore__colqwen2_dot_5-v0_dot_2.default` — exactly four tokens, matches the consumer filter. The DLQ token extractor in `queue/dlq.rs` splits the advisory subject on `.` and takes `parts[2]`, which with the normalization in place is already a single safe token; the existing `/` → `_` replacement there is now a no-op for correctly published subjects and a fallback for any legacy un-normalized messages still in-flight at the time of upgrade.
+To prevent that, the Rust gateway's `work_subject(model, pool)` in `packages/sie_gateway/src/queue/publisher.rs` calls a private `normalize_model_id` helper that mirrors the Python SDK (`sie_sdk.queue_types.normalize_model_id`): `/` → `__`, `.` → `_dot_`, and `*`/`>`/space → `_`. So `vidore/colqwen2.5-v0.2` publishes on `sie.work.vidore__colqwen2_dot_5-v0_dot_2.default` — exactly four tokens, matches the consumer filter. The DLQ token extractor in `queue/dlq.rs` splits the advisory subject on `.` and takes `parts[2]`, which with the normalization in place is already a single safe token.
-Generation adds a worker-specific subject, `sie.work.{model}.{pool}.{worker_id}`, which has one additional token after the pool. That subject intentionally does not match the pool stream's `sie.work.*.{pool}` filter. The worker runtime must bind the worker-specific stream only when the local pool hosts a generation model; encode-only pools should have exactly one hot JetStream consumer, the pool consumer. This is a batching invariant, not just a resource optimization: adding an idle direct-dispatch pull loop to encode workers can perturb shared NATS intake and collapse the queue-side batch size.
+Generation adds a worker-specific subject, `sie.work.{model}.{pool}.{worker_id}`, which has one additional token after the pool. That subject intentionally does not match the pool stream's `sie.work.*.{pool}` filter. The worker runtime binds the worker-specific stream only when the local pool hosts a generation model; encode-only pools keep the pre-generation queue runtime: exactly one hot JetStream consumer, the pool pull loop, the existing adaptive fetch timeout, and the existing dispatch path. This is a batching invariant, not just a resource optimization: generation-only machinery, including the streaming processor, cancel subscription, grammar prewarm, and direct-dispatch pull loop, must not start on encode-only workers because it can perturb shared NATS intake and collapse queue-side batch size. If live config reconciliation adds a generation model to a previously encode-only sidecar, the sidecar rechecks `WorkerCapabilities` and activates this worker-specific stream exactly once.
+
+The same isolation applies in the gateway. `encode` / `score` / `extract` and `/v1/embeddings` must not pay generation-specific proxy spans, HRW/direct-dispatch routing, per-worker subjects, or trace-context envelope injection. Their work items stay on the pool JetStream subject and keep the pre-generation queue-publish hot path. Generation endpoints may open gateway spans and inject W3C trace context only on generation direct-dispatch or generation fallback work. New gateway hot-path decisions should use the shared endpoint classifier and its regression tests, not one-off string checks.
### 8.3 Publisher/consumer ownership
Publishers and consumers:
-- **Config deltas**: published exclusively by `sie-config`. The gateway's `NatsManager` is subscribe-only on `_all` and never publishes on these subjects. Delta payload includes a `router_id` field whose value is `sie-config`'s pod/host identifier. The Rust gateway deserializes this field into a struct member named `producer_id`; `router_id` is declared as a `#[serde(alias)]` so both the current `router_id` wire name and any legacy `producer_id` name parse cleanly.
+- **Config deltas**: published exclusively by `sie-config`. The gateway's `NatsManager` is subscribe-only on `_all` and never publishes on these subjects. Delta payload includes a `router_id` field whose value is `sie-config`'s pod/host identifier. The Rust gateway deserializes this field into a struct member named `producer_id`; `router_id` is declared as a `#[serde(alias)]` so both the current `router_id` wire name and the wire-compatible `producer_id` name parse cleanly.
- **Queue work**: published exclusively by the gateway. Consumed by workers.
- **Results**: published exclusively by workers. Consumed by the originating gateway.
@@ -362,7 +366,7 @@ The gateway has no persistent config store. `SIE_CONFIG_STORE_DIR` and `SIE_CONF
- `sie-gateway` and `sie-config` are separate Kubernetes Deployments with separate images, built via `tools/mise_tasks/docker_task.py` (invoked as `mise run docker --{gateway,config,bake}`). On a `v*` git tag, `.github/workflows/release-docker.yml` publishes `ghcr.io/superlinked/sie-{config,gateway}:<tag>` and the per-platform/bundle `sie-server:<tag>-<platform>-<bundle>` matrix (plus floating `:latest` variants) to GHCR, which the Helm chart consumes by default. The `aws_docker`/`aws_deploy` tasks handle manual pushes to ECR/AR for cluster-local iteration.
- `sie-config` runs as **a single replica**. Multi-replica is blocked by the in-memory idempotency cache (see §11 "Known operational caveats"). Config persistence is opt-in: when `config.configStore.enabled: true` in the Helm values, a PVC is mounted at `/var/lib/sie-config` (default mount path) and `SIE_CONFIG_STORE_DIR` / `SIE_CONFIG_RESTORE` are set so the store survives pod restarts; with the default `enabled: false`, the store is ephemeral (backed by the pod filesystem) and a pod restart resets the epoch to 0 and drops every API-added model — `sie-config` does not subscribe to NATS (it is the sole publisher) so there is no replay path, and the registry rebuilds from the image-baked `/app/bundles` + `/app/models` baseline only. Every gateway replica's `state::config_poller` then detects `remote_epoch < local_epoch` and force-resets to match the restarted `sie-config`, picking up whatever baseline it now advertises. Operators who need API-added models to survive `sie-config` restarts must set `config.configStore.enabled: true`. The Helm chart (`deploy/helm/sie-cluster/values.yaml`) documents the SPOF posture.
- `sie-gateway` scales horizontally. Each replica maintains its own in-memory `ModelRegistry` and its own `ConfigEpoch`. They all converge on the same state via a combination of bootstrap, deltas, and the poller; they do not coordinate with each other.
-- Bundles live on `sie-config`'s filesystem at `SIE_BUNDLES_DIR` (default `/app/bundles`, set via `sharedPaths.bundlesDir`) and are baked into its image. `sie-config` reads them at startup, validates writes against them, and re-serves them over HTTP at `GET /v1/configs/bundles{,/{id}}`. The gateway fetches that surface during `state::config_bootstrap::bootstrap` and installs it via `ModelRegistry::install_bundles` — there is no second copy. The legacy `gateway.embeddedConfigs` / `gateway.configMap` overlays still exist for the rare case of running the gateway without `sie-config` (e.g., self-contained smoke tests); they mount a ConfigMap at `/configs/bundles` which the registry's filesystem reload picks up before the (no-op) bootstrap runs. In all cases, updating bundles is a `sie-config` redeploy and the gateway picks up the change on its next bootstrap or poller-driven reconcile, not via a runtime API call.
+- Bundles live on `sie-config`'s filesystem at `SIE_BUNDLES_DIR` (default `/app/bundles`, set via `sharedPaths.bundlesDir`) and are baked into its image. `sie-config` reads them at startup, validates writes against them, and re-serves them over HTTP at `GET /v1/configs/bundles{,/{id}}`. The gateway fetches that surface during `state::config_bootstrap::bootstrap` and installs it via `ModelRegistry::install_bundles` — there is no second copy. The `gateway.embeddedConfigs` / `gateway.configMap` overlays still exist for the rare case of running the gateway without `sie-config` (e.g., self-contained smoke tests); they mount a ConfigMap at `/configs/bundles` which the registry's filesystem reload picks up before the (no-op) bootstrap runs. In all cases, updating bundles is a `sie-config` redeploy and the gateway picks up the change on its next bootstrap or poller-driven reconcile, not via a runtime API call.
- Pools are stored in Kubernetes `ConfigMap`s and `Lease`s read/written by the gateway. `sie-config` is not involved in pool management.
- NATS / JetStream runs as its own workload. The gateway's `NatsManager` builds `async_nats::ConnectOptions` with `retry_on_initial_connect()` so the process does not fail to start if NATS is briefly unavailable; reconnect behavior after initial connect relies on `async-nats`'s default policy (indefinite reconnect with backoff).
@@ -415,8 +419,8 @@ Gateway (`sie-gateway`):
- `SIE_AUTH_TOKEN` / `SIE_AUTH_TOKENS` — tokens accepted by the gateway's own inference API (`/v1/encode`, `/v1/score`, `/v1/extract`) and for read-side pool/config routes. Not used for outbound calls to `sie-config`. When `SIE_AUTH_MODE` enables auth but this list is empty, every non-probe request returns `500`.
- `SIE_AUTH_MODE` — `token` (alias: `static`) enforces auth; `none` (default) disables it. Typos are fail-open-to-bypass by design; `audit_auth` logs a startup error naming the bad value so operators see it in `kubectl logs`.
- `SIE_AUTH_EXEMPT_OPERATIONAL` — when `true`, `/`, `/health`, `/metrics`, and `/ws/*` are exempt from auth (they expose worker URLs, bundle assignments, queue depth, GPU inventory — treat as sensitive). Default `false`. **`/healthz` and `/readyz` are always exempt from auth** so kubelet probes never fail with **`401`/`403`** because of a missing bearer token. `/readyz` reports process readiness only; worker health remains visible through `/health` and inference responses.
-- `SIE_NATS_CONFIG_TRUSTED_PRODUCERS` — comma-separated producer allowlist for `sie.config.models._all`. Default `sie-config`. Matching is exact OR K8s pod-name prefix (see §4.3). Untrusted notifications are dropped; the `config_poller` still closes the gap.
-- `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` — `true` disables producer validation entirely. Intended for local/dev. `main.rs` emits a startup audit warning when on.
+- `SIE_NATS_CONFIG_TRUSTED_PRODUCERS` — comma-separated producer allowlist for `sie.config.models._all`. Binary default is `sie-config`; Helm sets the release-scoped config Deployment name. Matching is exact OR K8s pod-name prefix (see §4.3). Untrusted notifications are dropped; the `config_poller` still closes the gap.
+- `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` — `true` disables producer validation entirely. Intended for local/dev. `main.rs` emits a startup warning when on.
- NATS connection variables per the existing gateway configuration.
Config service (`sie-config`):
@@ -482,7 +486,7 @@ Both services expose Prometheus metrics on `GET /metrics`. The gateway uses the
### 15.1 Request and latency — gateway
-Emitted from a Tower middleware (`MetricsLayer` in `middleware/metrics.rs`) that wraps the proxy routes. Putting it in middleware rather than inline in handlers is the reason these counters now cover every response including early rejections (validation, auth, capacity, timeout) — previously ~27 exit paths in `handlers/proxy.rs` were silently skipping the counter bump.
+Emitted from a Tower middleware (`MetricsLayer` in `middleware/metrics.rs`) that wraps the proxy routes. Putting it in middleware rather than inline in handlers ensures these counters cover every response including early rejections (validation, auth, capacity, timeout).
- `sie_gateway_requests_total{endpoint,status,machine_profile}` — counter.
- `sie_gateway_request_latency_seconds{endpoint,machine_profile}` — histogram. Wall-clock from middleware entry to response.
@@ -620,7 +624,7 @@ Subject: sie.work.BAAI__bge-m3.default
Stream: WORK_POOL_default
```
-The work subject is constructed by `work_subject(model, pool)` in `queue/publisher.rs`, which runs the model id through `normalize_model_id` (the Rust mirror of `sie_sdk.queue_types.normalize_model_id`: `/` → `__`, `.` → `_dot_`, `*`/`>`/space → `_`). The result is always exactly four dot-separated tokens so it matches the worker's `sie.work.*.{pool}` consumer filter — this is the guarantee that makes dotted ids like `vidore/colqwen2.5-v0.2` work. The DLQ path extracts the third token from the advisory subject, replaces any leftover `/` with `_` as a legacy fallback, and publishes on `sie.dlq.{model_normalized}` — so `sie.work.BAAI__bge-m3.default` becomes `sie.dlq.BAAI__bge-m3` when a message hits max-deliveries.
+The work subject is constructed by `work_subject(model, pool)` in `queue/publisher.rs`, which runs the model id through `normalize_model_id` (the Rust mirror of `sie_sdk.queue_types.normalize_model_id`: `/` → `__`, `.` → `_dot_`, `*`/`>`/space → `_`). The result is always exactly four dot-separated tokens so it matches the worker's `sie.work.*.{pool}` consumer filter — this is the guarantee that makes dotted ids like `vidore/colqwen2.5-v0.2` work. The DLQ path extracts the third token from the advisory subject, applies the same compatibility slash normalization, and publishes on `sie.dlq.{model_normalized}` — so `sie.work.BAAI__bge-m3.default` becomes `sie.dlq.BAAI__bge-m3` when a message hits max-deliveries.
**Step 2 — Gateway publishes work items to JetStream** (`queue/publisher.rs`). For a 2-item request the gateway publishes two msgpack work items:
@@ -699,7 +703,7 @@ POST /v1/pools
}
```
-`gpus` is required capacity; `gpu_caps` is an optional assignment cap. The `default` pool has zero requirements and no caps. Capped workers poll pool status every 10 seconds before NATS pulls. HA gateways sort workers deterministically and persist named-pool assignment status.
+`gpus` is required capacity; `gpu_caps` is an optional assignment cap. The `default` pool has zero requirements and no caps. The worker-sidecar polls pool status every 10 seconds before NATS pulls when the admission gate is enabled. Capped named pools fail closed unless this pod appears in `status.assigned_workers`; the `default` pool fails open during transient gateway/status errors so baseline capacity remains available. HA gateways sort workers deterministically and persist named-pool assignment status.
Helm publishes canonical machine profiles in `SIE_GATEWAY_CONFIGURED_GPUS` and request aliases in `SIE_GATEWAY_GPU_ALIASES`.
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.json
index ec8f4c140..9dc5dcae6 100644
--- a/packages/sie_gateway/openapi.json
+++ b/packages/sie_gateway/openapi.json
@@ -173,7 +173,7 @@
"type": "string"
},
"tool_calls": {
- "description": "Per-candidate tool-call list (Workstream B). Present when the model\nemitted one or more tool calls for this choice; absent otherwise.\nEach entry has the OpenAI shape ``{id, type:\"function\",\nfunction:{name, arguments}}`` where ``arguments`` is a JSON-encoded string."
+ "description": "Per-candidate tool-call list. Present when the model\nemitted one or more tool calls for this choice; absent otherwise.\nEach entry has the OpenAI shape ``{id, type:\"function\",\nfunction:{name, arguments}}`` where ``arguments`` is a JSON-encoded string."
}
},
"required": [
@@ -183,7 +183,7 @@
"type": "object"
},
"ChatCompletionMessage": {
- "description": "One chat message in an OpenAI chat-completions request.\n\nPer the strict allow-list parser (Workstream A), ``content`` is either a\nplain string OR a list of text-only content parts (``{type:\"text\"|\"input_text\",\ntext:\"...\"}``); ``image_url`` and ``input_image`` parts reject with 400\n``unsupported_field`` until a vision-capable model ships. Assistant\nmessages that carry ``tool_calls`` may set ``content: null``.\n\n``tool_calls`` is accepted only on ``role:\"assistant\"`` messages; each\nentry has the validated shape ``{id, type:\"function\", function:{name, arguments}}``\nwhere ``arguments`` is a JSON-encoded string (OpenAI convention).\n``tool_call_id`` is required on ``role:\"tool\"`` messages and rejected\non every other role.",
+ "description": "One chat message in an OpenAI chat-completions request.\n\nPer the strict allow-list parser, ``content`` is either a\nplain string OR a list of text-only content parts (``{type:\"text\"|\"input_text\",\ntext:\"...\"}``); ``image_url`` and ``input_image`` parts reject with 400\n``unsupported_field`` until a vision-capable model ships. Assistant\nmessages that carry ``tool_calls`` may set ``content: null``.\n\n``tool_calls`` is accepted only on ``role:\"assistant\"`` messages; each\nentry has the validated shape ``{id, type:\"function\", function:{name, arguments}}``\nwhere ``arguments`` is a JSON-encoded string (OpenAI convention).\n``tool_call_id`` is required on ``role:\"tool\"`` messages and rejected\non every other role.",
"properties": {
"content": {
"description": "Either a string or an array of text-only content parts (`{type:\"text\"|\"input_text\", text:\"...\"}`). Image content parts (`image_url` / `input_image`) reject with 400 unsupported_field until a vision-capable model ships. May be `null` on a `role:\"assistant\"` message that carries `tool_calls`.",
@@ -277,7 +277,7 @@
"type": "object"
},
"ChatCompletionRequest": {
- "description": "OpenAI-compatible ``POST /v1/chat/completions`` request.\n\n**Strict allow-list:** unknown top-level fields reject with 400\n``unsupported_field``. Type-invalid values for accepted fields reject\nwith 400 ``invalid_request``.\n\n**Known-rejected fields** (per `product/design.md` §5.14):\n- ``functions`` / ``function_call`` — deprecated by OpenAI; use ``tools`` instead.\n- ``modalities``, ``audio``, ``metadata``, ``store``, ``service_tier``,\n ``prediction``, ``reasoning_effort``, ``verbosity`` — out of scope.\n\n**Streaming:** ``stream: true`` is supported (SSE ``chat.completion.chunk``).\n``n > 1`` streaming fans candidates out as per-``choice_index``-tagged delta\nchunks with a per-choice closure carrying ``finish_reason`` (and a per-choice\n``delta.role:\"assistant\"`` once per choice) before the single global ``[DONE]``.",
+ "description": "OpenAI-compatible ``POST /v1/chat/completions`` request.\n\n**Strict allow-list:** unknown top-level fields reject with 400\n``unsupported_field``. Type-invalid values for accepted fields reject\nwith 400 ``invalid_request``.\n\n**Known-rejected fields**:\n- ``functions`` / ``function_call`` — deprecated by OpenAI; use ``tools`` instead.\n- ``modalities``, ``audio``, ``metadata``, ``store``, ``service_tier``,\n ``prediction``, ``reasoning_effort``, ``verbosity`` — out of scope.\n\n**Streaming:** ``stream: true`` is supported (SSE ``chat.completion.chunk``).\n``n > 1`` streaming fans candidates out as per-``choice_index``-tagged delta\nchunks with a per-choice closure carrying ``finish_reason`` (and a per-choice\n``delta.role:\"assistant\"`` once per choice) before the single global ``[DONE]``.",
"properties": {
"best_of": {
"description": "Generate this many candidates and return the top `n` by cumulative logprob. Integer in [1, 128]. Cross-field rule: `best_of >= n` (otherwise 400 invalid_request). Rejected with 400 unsupported_field when `stream: true` (mirrors OpenAI).",
@@ -289,6 +289,9 @@
"null"
]
},
+ "chat_template_kwargs": {
+ "description": "Per-request overrides for kwargs passed to the tokenizer's\n``apply_chat_template`` call. Object whose entries are merged on\ntop of the model YAML's ``chat_template_kwargs`` (the YAML wins\nfor keys present in both — adjust the YAML when a request needs\nto defeat a baked-in default). Typical use: pass\n``{\"enable_thinking\": false}`` to the Qwen3 family to suppress\n``<think>`` reasoning on a per-request basis. Absent → only the\nmodel YAML's defaults apply."
+ },
"frequency_penalty": {
"description": "OpenAI ``frequency_penalty`` in ``[-2.0, 2.0]``; out-of-range or\nnon-numeric values yield 400 ``invalid_request``.",
"format": "float",
@@ -350,6 +353,15 @@
},
"type": "array"
},
+ "min_tokens": {
+ "description": "SGLang ``sampling_params.min_new_tokens``: integer ``>= 0`` capping\nhow many tokens the model must emit before any stop condition can\nfire. Use to work around models that occasionally emit the stop\ntoken as the very first decoded token (e.g. Qwen3.6 thinking-off\nunder greedy decode). Absent → sampler default (no minimum).",
+ "format": "int32",
+ "minimum": 0,
+ "type": [
+ "integer",
+ "null"
+ ]
+ },
"model": {
"type": "string"
},
@@ -693,7 +705,7 @@
"type": "object"
},
"CompletionsRequest": {
- "description": "OpenAI-compatible ``POST /v1/completions`` request (legacy raw-prompt surface).\n\n**Strict allow-list** (Workstream A): unknown fields reject with 400\n``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.\n\n**Known-rejected fields** (per `product/design.md` §5.14):\n- ``echo`` — rejected with 400 ``unsupported_field``.\n- ``suffix`` — rejected with 400 ``unsupported_field``.\n- ``logprobs`` — rejected with 400 ``unsupported_field`` (the legacy\n ``{tokens, token_logprobs}`` response shape is a follow-up; chat\n ``logprobs`` is available on ``/v1/chat/completions``).\n- ``best_of`` — rejected with 400 ``unsupported_field`` (use chat).\n- ``n > 1`` — rejected with 400 ``unsupported_field`` (chat is the\n multi-candidate surface). ``n == 1`` (or absent) is a no-op.\n- Batched array ``prompt`` — rejected with 400 ``unsupported_field``;\n send one prompt string.\n\n**Streaming:** ``stream: true`` is supported (SSE ``text_completion``).\n\n**Response body wire change:** the always-null ``logprobs`` field has\nbeen dropped from the response body (Workstream A); SDKs that destructure\n``choices[].logprobs`` should treat absence as the new normal.",
+ "description": "OpenAI-compatible ``POST /v1/completions`` request (legacy raw-prompt surface).\n\n**Strict allow-list**: unknown fields reject with 400\n``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.\n\n**Known-rejected fields**:\n- ``echo`` — rejected with 400 ``unsupported_field``.\n- ``suffix`` — rejected with 400 ``unsupported_field``.\n- ``logprobs`` — rejected with 400 ``unsupported_field`` (the legacy\n ``{tokens, token_logprobs}`` response shape is a follow-up; chat\n ``logprobs`` is available on ``/v1/chat/completions``).\n- ``best_of`` — rejected with 400 ``unsupported_field`` (use chat).\n- ``n > 1`` — rejected with 400 ``unsupported_field`` (chat is the\n multi-candidate surface). ``n == 1`` (or absent) is a no-op.\n- Batched array ``prompt`` — rejected with 400 ``unsupported_field``;\n send one prompt string.\n\n**Streaming:** ``stream: true`` is supported (SSE ``text_completion``).\n\n**Response body wire change:** the always-null ``logprobs`` field has\nbeen dropped from the response body; SDKs that destructure\n``choices[].logprobs`` should treat absence as the new normal.",
"properties": {
"frequency_penalty": {
"description": "In ``[-2.0, 2.0]``; out-of-range or non-numeric values yield 400.",
@@ -1724,7 +1736,7 @@
"description": "Capability summary surfaced on each entry of ``GET /v1/models``.\n\nMirrors the JSON shape constructed in\n``types/model.rs::to_model_info_value``. All fields are optional —\ntheir presence depends on what the model config declares.",
"properties": {
"grammar": {
- "description": "Grammar kinds the model's active backend supports\n(``json_schema`` | ``regex`` | ``ebnf``). EBNF presence depends\non the backend: SGLang's Outlines backend does not implement\nEBNF, so a profile with ``grammar_backend: outlines`` advertises\nonly ``[\"json_schema\", \"regex\"]``; xgrammar/llguidance profiles\nadvertise all three. See ADR-0002.",
+ "description": "Grammar kinds the model's active backend supports\n(``json_schema`` | ``regex`` | ``ebnf``). EBNF presence depends\non the backend: SGLang's Outlines backend does not implement\nEBNF, so a profile with ``grammar_backend: outlines`` advertises\nonly ``[\"json_schema\", \"regex\"]``; xgrammar/llguidance profiles\nadvertise all three.",
"items": {
"type": "string"
},
@@ -2518,10 +2530,10 @@
"type": "object"
},
"ResponsesRequest": {
- "description": "OpenAI-compatible ``POST /v1/responses`` request (Responses MVP).\n\n**Strict allow-list** (Workstream A): unknown fields reject with 400\n``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.\n\n**Known-rejected fields** (per `product/design.md` §5.14):\n- ``tools`` / ``tool_choice`` — rejected with 400 ``unsupported_field``.\n- ``previous_response_id`` — rejected with 400 ``unsupported_field``\n (Responses MVP is stateless single-turn).\n- ``reasoning`` — rejected with 400 ``unsupported_field``.\n- ``background`` — rejected with 400 ``unsupported_field``.\n- ``metadata`` — rejected with 400 ``unsupported_field``.\n- ``instructions`` — rejected with 400 ``unsupported_field``.\n- ``stream: true`` — rejected with 400 ``unsupported_field`` (SSE on\n Responses is deferred; use ``stream: false`` or omit).\n- Multimodal ``image_url`` / ``input_image`` content parts on the array\n form — rejected with 400 ``unsupported_field`` until a VL profile ships.",
+ "description": "OpenAI-compatible ``POST /v1/responses`` request (Responses MVP).\n\n**Strict allow-list**: unknown fields reject with 400\n``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.\n\n**Known-rejected fields**:\n- ``tools`` / ``tool_choice`` — rejected with 400 ``unsupported_field``.\n- ``previous_response_id`` — rejected with 400 ``unsupported_field``\n (Responses MVP is stateless single-turn).\n- ``reasoning`` — rejected with 400 ``unsupported_field``.\n- ``background`` — rejected with 400 ``unsupported_field``.\n- ``metadata`` — rejected with 400 ``unsupported_field``.\n- ``instructions`` — rejected with 400 ``unsupported_field``.\n- ``stream: true`` — rejected with 400 ``unsupported_field`` (SSE on\n Responses is deferred; use ``stream: false`` or omit).\n- Multimodal ``image_url`` / ``input_image`` content parts on the array\n form — rejected with 400 ``unsupported_field`` until a VL profile ships.",
"properties": {
"input": {
- "description": "Either a string prompt OR an array of `{role, content}` messages (Workstream A array-input support). Array form: `role` is one of `\"system\" | \"user\" | \"assistant\" | \"developer\"` (\"developer\" normalizes to \"system\"). `content` is a string or an array of text-only content parts; image parts (`image_url` / `input_image`) reject with 400 unsupported_field. The array must not be empty.",
+ "description": "Either a string prompt OR an array of `{role, content}` messages (array-input support). Array form: `role` is one of `\"system\" | \"user\" | \"assistant\" | \"developer\"` (\"developer\" normalizes to \"system\"). `content` is a string or an array of text-only content parts; image parts (`image_url` / `input_image`) reject with 400 unsupported_field. The array must not be empty.",
"oneOf": [
{
"type": "string"
@@ -2599,7 +2611,7 @@
]
},
"stream": {
- "description": "Accepted only as `false` (or absent). `true` rejects with 400 unsupported_field (Responses SSE is deferred; tracked in `product/design.md` §5.14).",
+ "description": "Accepted only as `false` (or absent). `true` rejects with 400 unsupported_field because Responses SSE is not supported yet.",
"enum": [
false,
null
@@ -2858,7 +2870,7 @@
"url": "https://www.apache.org/licenses/LICENSE-2.0.html"
},
"title": "SIE Gateway",
- "version": "0.4.1"
+ "version": "0.4.2"
},
"openapi": "3.1.0",
"paths": {
@@ -3064,7 +3076,7 @@
},
"/v1/chat/completions": {
"post": {
- "description": "OpenAI-compatible chat completions. Strict allow-list parser (see `product/design.md` §5.14): unknown top-level fields reject with 400 `unsupported_field`. Streaming (`stream: true`) is supported and emits SSE `chat.completion.chunk` events; `n > 1` streaming fans candidates out as per-`choice_index` delta chunks with per-choice closure chunks (each carrying `finish_reason`) before the single global `[DONE]`. Content is either a string or an array of text-only content parts; image content parts (`image_url` / `input_image`) reject with 400 `unsupported_field`. `lora_adapter` is forwarded to the worker as a top-level `lora_path` generation kwarg.",
+ "description": "OpenAI-compatible chat completions. Strict allow-list parser: unknown top-level fields reject with 400 `unsupported_field`. Streaming (`stream: true`) is supported and emits SSE `chat.completion.chunk` events; `n > 1` streaming fans candidates out as per-`choice_index` delta chunks with per-choice closure chunks (each carrying `finish_reason`) before the single global `[DONE]`. Content is either a string or an array of text-only content parts; image content parts (`image_url` / `input_image`) reject with 400 `unsupported_field`. `lora_adapter` is forwarded to the worker as a top-level `lora_path` generation kwarg.",
"operationId": "proxy_chat",
"parameters": [
{
@@ -3190,7 +3202,7 @@
},
"/v1/completions": {
"post": {
- "description": "OpenAI-compatible legacy Completions. Strict allow-list parser (`product/design.md` §5.14): unknown top-level fields reject with 400 `unsupported_field`. `stream: true` is supported (SSE `text_completion`). Known-rejected fields: `echo`, `suffix`, `logprobs`, `best_of`, `n > 1`, batched array `prompt` — each rejects with 400 `unsupported_field`. The response body no longer carries the always-null `logprobs` field (Workstream A wire change).",
+ "description": "OpenAI-compatible legacy Completions. Strict allow-list parser: unknown top-level fields reject with 400 `unsupported_field`. `stream: true` is supported (SSE `text_completion`). Known-rejected fields: `echo`, `suffix`, `logprobs`, `best_of`, `n > 1`, batched array `prompt` — each rejects with 400 `unsupported_field`. The response body no longer carries the always-null `logprobs` field.",
"operationId": "proxy_completions",
"requestBody": {
"content": {
@@ -3649,6 +3661,18 @@
]
}
},
+ {
+ "description": "Explicit engine routing override",
+ "in": "header",
+ "name": "X-SIE-Engine",
+ "required": false,
+ "schema": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
{
"description": "Client SDK version for skew warnings",
"in": "header",
@@ -3974,6 +3998,18 @@
]
}
},
+ {
+ "description": "Explicit engine routing override",
+ "in": "header",
+ "name": "X-SIE-Engine",
+ "required": false,
+ "schema": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
{
"description": "Client SDK version for skew warnings",
"in": "header",
@@ -4330,6 +4366,18 @@
]
}
},
+ {
+ "description": "Explicit engine routing override",
+ "in": "header",
+ "name": "X-SIE-Engine",
+ "required": false,
+ "schema": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
{
"description": "Client SDK version for skew warnings",
"in": "header",
@@ -5259,7 +5307,7 @@
},
"/v1/responses": {
"post": {
- "description": "OpenAI Responses API (MVP). Strict allow-list parser (`product/design.md` §5.14): unknown top-level fields reject with 400 `unsupported_field`. `input` is either a string prompt OR an array of `{role, content}` messages (Workstream A array-input support). Known-rejected fields: `tools`, `tool_choice`, `previous_response_id`, `reasoning`, `background`, `metadata`, `instructions` — each rejects with 400 `unsupported_field`. `stream: true` is rejected (Responses SSE is deferred). Multimodal image content parts reject with 400 `unsupported_field` on the array form.",
+ "description": "OpenAI Responses API (MVP). Strict allow-list parser: unknown top-level fields reject with 400 `unsupported_field`. `input` is either a string prompt OR an array of `{role, content}` messages. Known-rejected fields: `tools`, `tool_choice`, `previous_response_id`, `reasoning`, `background`, `metadata`, `instructions` — each rejects with 400 `unsupported_field`. `stream: true` is rejected (Responses SSE is deferred). Multimodal image content parts reject with 400 `unsupported_field` on the array form.",
"operationId": "proxy_responses",
"requestBody": {
"content": {
@@ -5377,6 +5425,18 @@
]
}
},
+ {
+ "description": "Explicit engine routing override",
+ "in": "header",
+ "name": "X-SIE-Engine",
+ "required": false,
+ "schema": {
+ "type": [
+ "string",
+ "null"
+ ]
+ }
+ },
{
"description": "Client SDK version for skew warnings",
"in": "header",
diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rs
index 2720cb360..14463a091 100644
--- a/packages/sie_gateway/src/config.rs
+++ b/packages/sie_gateway/src/config.rs
@@ -53,6 +53,7 @@ pub struct Config {
// Tuning
pub request_timeout: f64,
pub max_stream_pending: u64,
+ pub stream_max_age_s: u64,
// Configured GPUs (survives scale-to-zero)
pub configured_gpus: Vec<String>,
@@ -212,6 +213,7 @@ impl Config {
request_timeout: env_float("SIE_GATEWAY_REQUEST_TIMEOUT", 30.0),
max_stream_pending: env_u64("SIE_GATEWAY_MAX_STREAM_PENDING", 50_000),
+ stream_max_age_s: env_u64("SIE_STREAM_MAX_AGE_S", 120),
configured_gpus,
gpu_profile_map,
@@ -236,7 +238,7 @@ impl Config {
}
},
- payload_store_url: env_default("SIE_PAYLOAD_STORE_URL", "payload_store"),
+ payload_store_url: env_default("SIE_PAYLOAD_STORE_URL", ""),
}
}
@@ -601,7 +603,7 @@ mod tests {
fn test_payload_store_url_default() {
without_env(&["SIE_PAYLOAD_STORE_URL"], || {
let cfg = Config::load();
- assert_eq!(cfg.payload_store_url, "payload_store");
+ assert_eq!(cfg.payload_store_url, "");
});
}
@@ -616,6 +618,22 @@ mod tests {
);
}
+ #[test]
+ fn test_stream_max_age_default_matches_worker_contract() {
+ without_env(&["SIE_STREAM_MAX_AGE_S"], || {
+ let cfg = Config::load();
+ assert_eq!(cfg.stream_max_age_s, 120);
+ });
+ }
+
+ #[test]
+ fn test_stream_max_age_from_env() {
+ with_env(&[("SIE_STREAM_MAX_AGE_S", "240")], || {
+ let cfg = Config::load();
+ assert_eq!(cfg.stream_max_age_s, 240);
+ });
+ }
+
#[test]
fn test_admin_token_populates_config_service_token() {
with_env(&[("SIE_ADMIN_TOKEN", "super-secret")], || {
@@ -665,6 +683,7 @@ mod tests {
multi_router: false,
request_timeout: 0.0,
max_stream_pending: 0,
+ stream_max_age_s: 0,
configured_gpus: Vec::new(),
gpu_profile_map: HashMap::new(),
bundles_dir: String::new(),
diff --git a/packages/sie_gateway/src/endpoint.rs b/packages/sie_gateway/src/endpoint.rs
new file mode 100644
index 000000000..0bfb72ecc
--- /dev/null
+++ b/packages/sie_gateway/src/endpoint.rs
@@ -0,0 +1,63 @@
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum InferenceEndpoint {
+ Encode,
+ Score,
+ Extract,
+ Embeddings,
+ Generate,
+ Unknown,
+}
+
+impl InferenceEndpoint {
+ #[cfg(test)]
+ pub(crate) const NON_GENERATION_QUEUE_LABELS: [&'static str; 4] =
+ ["encode", "score", "extract", "embeddings"];
+
+ pub(crate) fn from_label(label: &str) -> Self {
+ match label {
+ "encode" => Self::Encode,
+ "score" => Self::Score,
+ "extract" => Self::Extract,
+ "embeddings" => Self::Embeddings,
+ "generate" => Self::Generate,
+ _ => Self::Unknown,
+ }
+ }
+
+ pub(crate) fn uses_generation_gateway_tracing(self) -> bool {
+ matches!(self, Self::Generate)
+ }
+
+ pub(crate) fn injects_queue_trace_context(self) -> bool {
+ matches!(self, Self::Generate)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::InferenceEndpoint;
+
+ #[test]
+ fn non_generation_queue_labels_do_not_enable_generation_features() {
+ for label in InferenceEndpoint::NON_GENERATION_QUEUE_LABELS {
+ let endpoint = InferenceEndpoint::from_label(label);
+ assert!(!endpoint.uses_generation_gateway_tracing());
+ assert!(!endpoint.injects_queue_trace_context());
+ }
+ }
+
+ #[test]
+ fn generate_is_the_only_generation_trace_endpoint() {
+ let endpoint = InferenceEndpoint::from_label("generate");
+ assert!(endpoint.uses_generation_gateway_tracing());
+ assert!(endpoint.injects_queue_trace_context());
+ }
+
+ #[test]
+ fn unknown_labels_fail_closed_to_non_generation_behavior() {
+ let endpoint = InferenceEndpoint::from_label("chat");
+ assert_eq!(endpoint, InferenceEndpoint::Unknown);
+ assert!(!endpoint.uses_generation_gateway_tracing());
+ assert!(!endpoint.injects_queue_trace_context());
+ }
+}
diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rs
index a1bf793c1..d2fde5ed2 100644
--- a/packages/sie_gateway/src/handlers/config_api.rs
+++ b/packages/sie_gateway/src/handlers/config_api.rs
@@ -453,6 +453,7 @@ mod tests {
multi_router: false,
request_timeout: 30.0,
max_stream_pending: 50_000,
+ stream_max_age_s: 120,
configured_gpus: Vec::new(),
gpu_profile_map: HashMap::new(),
bundles_dir: bundles_dir.to_string(),
diff --git a/packages/sie_gateway/src/handlers/grammar.rs b/packages/sie_gateway/src/handlers/grammar.rs
index b3f0afdbb..43bac5a6f 100644
--- a/packages/sie_gateway/src/handlers/grammar.rs
+++ b/packages/sie_gateway/src/handlers/grammar.rs
@@ -20,7 +20,7 @@
//! ``$ref`` rejection note: the spec wording is "external ``$ref``";
//! v1 rejects **all** ``$ref`` (including internal ``#/...``) for
//! implementation simplicity. The error message and the OpenAPI spec
-//! both call this out; M5+ can refine if customer pressure justifies
+//! both call this out; this can be refined if customer pressure justifies
//! the JSON-pointer resolver.
use axum::http::StatusCode;
@@ -339,7 +339,7 @@ fn walk_schema_inner(
let message = if kw == "$ref" {
// Grammar v1 blanket-rejects all ``$ref``,
// including internal ``#/...``. The spec
- // wording is "external ``$ref``"; M5+ may
+ // wording is "external ``$ref``"; later revisions may
// refine. Documented in OpenAPI.
"'$ref' is not supported (the grammar surface rejects all $ref including internal)"
.to_string()
diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rs
index 882d5d1fe..b95a160ee 100644
--- a/packages/sie_gateway/src/handlers/models.rs
+++ b/packages/sie_gateway/src/handlers/models.rs
@@ -341,6 +341,7 @@ mod route_tests {
multi_router: false,
request_timeout: 30.0,
max_stream_pending: 50_000,
+ stream_max_age_s: 120,
configured_gpus: Vec::new(),
gpu_profile_map: HashMap::new(),
bundles_dir: bundles_dir.to_string(),
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 5c170866c..8b7ed6749 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -12,6 +12,7 @@ use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::{debug, error, info, warn};
+use crate::endpoint::InferenceEndpoint;
use crate::http_error::{
code as err_code, embeddings_error, json_detail, json_detail_merge, json_openai_error,
openai_code as oai_code, openai_type as oai_type,
@@ -137,6 +138,55 @@ static SDK_VERSION_CACHE: std::sync::LazyLock<DashMap<Arc<str>, Option<u32>>> =
std::sync::LazyLock::new(DashMap::new);
const SDK_VERSION_CACHE_CAP: usize = 1024;
+#[allow(dead_code)]
+static HOP_BY_HOP_HEADERS: &[&str] = &[
+ "connection",
+ "keep-alive",
+ "proxy-authenticate",
+ "proxy-authorization",
+ "te",
+ "trailers",
+ "transfer-encoding",
+ "upgrade",
+ "host",
+];
+
+#[allow(dead_code)]
+fn is_hop_by_hop(name: &str) -> bool {
+ HOP_BY_HOP_HEADERS
+ .iter()
+ .any(|h| h.eq_ignore_ascii_case(name))
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum EnginePinParse {
+ None,
+ Some(String),
+ Unknown(String),
+ InvalidUtf8,
+}
+
+fn parse_engine_pin(headers: &HeaderMap) -> EnginePinParse {
+ let Some(raw) = headers.get("x-sie-engine") else {
+ return EnginePinParse::None;
+ };
+ let s = match raw.to_str() {
+ Ok(s) => s,
+ Err(_) => return EnginePinParse::InvalidUtf8,
+ };
+ let trimmed = s.trim();
+ if trimmed.is_empty() {
+ return EnginePinParse::None;
+ }
+ use crate::types::bundle::KNOWN_ENGINES;
+ let normalised = trimmed.to_ascii_lowercase();
+ if KNOWN_ENGINES.contains(&normalised.as_str()) {
+ EnginePinParse::Some(normalised)
+ } else {
+ EnginePinParse::Unknown(trimmed.to_string())
+ }
+}
+
/// Outcome of resolving the JetStream pool to publish work for a request.
#[derive(Debug, PartialEq, Eq)]
enum PoolResolution {
@@ -194,13 +244,14 @@ fn is_valid_pool_name(pool: &str) -> bool {
/// Kept as a free function so it can be unit-tested without standing up
/// an `AppState` / `WorkPublisher`.
///
-/// Rules (see `product/design.md` §10 and
-/// `packages/sie_gateway/docs/architecture-guide.md` §2):
+/// Rules:
/// - If the caller pinned a pool via `X-SIE-Pool`, trust them and publish
/// there unconditionally. This preserves the "power user" path where
/// the client knows exactly which pool it wants (including cold ones
-/// that are expected to scale up on demand).
+/// that are expected to scale up on demand). The worker-side hash guard
+/// still rejects deliveries whose expected hash is unknown locally.
/// - Otherwise look up a healthy default-pool worker for `(bundle, gpu)`.
+/// The worker must also report the gateway's expected bundle config hash.
/// If GPU was specified and the exact tuple has no worker, fall back to
/// any default-pool worker on `bundle` (covers single-GPU clusters where
/// the profile-level distinction is cosmetic).
@@ -214,6 +265,7 @@ async fn resolve_effective_pool(
bundle: &str,
gpu: &str,
pool_name: &str,
+ bundle_config_hash: &str,
) -> PoolLookup {
if !pool_name.is_empty() {
// Caller pinned a pool. We still try one registry probe inside
@@ -225,7 +277,7 @@ async fn resolve_effective_pool(
false
} else {
registry
- .resolve_queue_pool_in_pool(bundle, gpu, pool_name)
+ .resolve_queue_pool_in_pool(bundle, gpu, pool_name, bundle_config_hash)
.await
.is_some()
};
@@ -238,7 +290,7 @@ async fn resolve_effective_pool(
// Primary lookup. Folds the "was the exact tuple routable?"
// question into the same registry load we use to pick a pool.
let primary = registry
- .resolve_queue_pool_in_pool(bundle, gpu, DEFAULT_POOL_NAME)
+ .resolve_queue_pool_in_pool(bundle, gpu, DEFAULT_POOL_NAME, bundle_config_hash)
.await;
let exact_gpu_match = !gpu.is_empty() && primary.is_some();
@@ -250,7 +302,7 @@ async fn resolve_effective_pool(
Some(p) => Some(p),
None if !gpu.is_empty() => {
registry
- .resolve_queue_pool_in_pool(bundle, "", DEFAULT_POOL_NAME)
+ .resolve_queue_pool_in_pool(bundle, "", DEFAULT_POOL_NAME, bundle_config_hash)
.await
}
None => None,
@@ -322,6 +374,7 @@ fn build_provisioning_response(gpu: &str, bundle: &str) -> Response {
("model" = String, Path, description = "Model id; percent-encode slashes when using OpenAPI-generated clients"),
("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),
("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override"),
+ ("X-SIE-Engine" = Option<String>, Header, description = "Explicit engine routing override"),
("X-SIE-SDK-Version" = Option<String>, Header, description = "Client SDK version for skew warnings")
),
request_body = crate::openapi::EncodeRequest,
@@ -352,6 +405,7 @@ pub async fn proxy_encode(state: State<Arc<AppState>>, req: Request) -> impl Int
("model" = String, Path, description = "Model id; percent-encode slashes when using OpenAPI-generated clients"),
("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),
("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override"),
+ ("X-SIE-Engine" = Option<String>, Header, description = "Explicit engine routing override"),
("X-SIE-SDK-Version" = Option<String>, Header, description = "Client SDK version for skew warnings")
),
request_body = crate::openapi::ScoreRequest,
@@ -382,6 +436,7 @@ pub async fn proxy_score(state: State<Arc<AppState>>, req: Request) -> impl Into
("model" = String, Path, description = "Model id; percent-encode slashes when using OpenAPI-generated clients"),
("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),
("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override"),
+ ("X-SIE-Engine" = Option<String>, Header, description = "Explicit engine routing override"),
("X-SIE-SDK-Version" = Option<String>, Header, description = "Client SDK version for skew warnings")
),
request_body = crate::openapi::ExtractRequest,
@@ -489,30 +544,29 @@ async fn proxy_request(
// SDK version skew detection
check_sdk_version(req.headers());
- // M5: same trace-context plumbing as `proxy_chat`. Extract the
- // inbound W3C parent, open a gateway span, attach it as current
- // so downstream `publish_*` calls inject the gateway span ID
- // into the work envelope. No envelope shape change when the
- // inbound request omits `traceparent` — the gateway just opens
- // a new trace root.
- let parent_cx = crate::observability::propagation::extract_context_from_headers(req.headers());
- let span_name = if endpoint == "generate" {
- "gateway.proxy_generate"
+ // Keep the pre-generation queue hot path untouched for encode /
+ // score / extract. Native `/v1/generate/{model}` is the only route
+ // through this helper that needs gateway-side trace propagation;
+ // OpenAI generation routes have their own tracing blocks.
+ let proxy_span = if should_trace_proxy_request(endpoint) {
+ let parent_cx =
+ crate::observability::propagation::extract_context_from_headers(req.headers());
+ let proxy_span = tracing::info_span!(
+ "gateway.proxy",
+ otel.name = "gateway.proxy_generate",
+ sie.endpoint = endpoint,
+ sie.request_id = tracing::field::Empty,
+ sie.model = tracing::field::Empty,
+ );
+ {
+ use tracing_opentelemetry::OpenTelemetrySpanExt;
+ proxy_span.set_parent(parent_cx);
+ }
+ Some(proxy_span)
} else {
- "gateway.proxy_request"
+ None
};
- let proxy_span = tracing::info_span!(
- "gateway.proxy",
- otel.name = span_name,
- sie.endpoint = endpoint,
- sie.request_id = tracing::field::Empty,
- sie.model = tracing::field::Empty,
- );
- {
- use tracing_opentelemetry::OpenTelemetrySpanExt;
- proxy_span.set_parent(parent_cx);
- }
- let _proxy_span_guard = proxy_span.enter();
+ let _proxy_span_guard = proxy_span.as_ref().map(|span| span.enter());
// Extract model from path: /v1/{endpoint}/{model...}
let prefix = format!("/v1/{}/", endpoint);
@@ -561,6 +615,39 @@ async fn proxy_request(
Some(bundle_override.as_str())
};
+ // Optional ``X-SIE-Engine`` header lets the caller pin engine
+ // selection when a model resolves to multiple bundles across
+ // engines. Today only ``"pytorch"`` is recognised, so the header
+ // is effectively a no-op (or a 400 if the caller types something
+ // else); the plumbing is preserved for the day a second engine
+ // lands. Lowercase normalisation + UTF-8 validation lives in
+ // ``parse_engine_pin`` (unit-tested below).
+ let engine_pin = match parse_engine_pin(req.headers()) {
+ EnginePinParse::None => None,
+ EnginePinParse::Some(eng) => Some(eng),
+ EnginePinParse::Unknown(raw) => {
+ use crate::types::bundle::KNOWN_ENGINES;
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(json_detail(
+ err_code::INVALID_REQUEST,
+ format!("X-SIE-Engine value {:?} is not in {:?}", raw, KNOWN_ENGINES),
+ )),
+ )
+ .into_response();
+ }
+ EnginePinParse::InvalidUtf8 => {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(json_detail(
+ err_code::INVALID_REQUEST,
+ "X-SIE-Engine header must be valid UTF-8 (got non-printable bytes)",
+ )),
+ )
+ .into_response();
+ }
+ };
+
// Try model registry resolution. Three cases:
// 1. Model is known → resolve bundle (404 on BundleConflict, etc.)
// 2. Model unknown, registry populated → 404 (fail fast; avoids queueing
@@ -569,10 +656,11 @@ async fn proxy_request(
// override or "default". This is the pre-bootstrap / no-config
// deployment path; workers may still match on bundle+gpu alone.
let bundle = if state.model_registry.model_exists(&model_name) {
- match state
- .model_registry
- .resolve_bundle(&model_name, bundle_override_ref)
- {
+ match state.model_registry.resolve_bundle_with_engine(
+ &model_name,
+ bundle_override_ref,
+ engine_pin.as_deref(),
+ ) {
Ok(b) => b,
Err(ResolveError::ModelNotFound(e)) => {
return endpoint_error_response(
@@ -622,6 +710,13 @@ async fn proxy_request(
bundle_override.clone()
};
+ let engine = state
+ .model_registry
+ .get_bundle_info(&bundle)
+ .map(|info| info.engine)
+ .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 = req
.headers()
@@ -741,6 +836,8 @@ async fn proxy_request(
);
};
+ let bundle_config_hash = state.model_registry.compute_bundle_config_hash(&bundle);
+
// Resolve the effective pool in one shot. `resolve_effective_pool`
// folds the demand-tracking probe ("was there an exact (bundle,
// gpu) match?") into the same registry load it uses to pick a
@@ -750,7 +847,14 @@ async fn proxy_request(
// preference but no exact-tuple worker was registered, regardless
// of whether we still serve this request via bundle-fallback or a
// pinned pool (see `test_scaling.py::test_pending_demand_*`).
- let lookup = resolve_effective_pool(&state.registry, &bundle, &gpu, &pool_name).await;
+ let lookup = resolve_effective_pool(
+ &state.registry,
+ &bundle,
+ &gpu,
+ &pool_name,
+ &bundle_config_hash,
+ )
+ .await;
if !gpu.is_empty() && !lookup.exact_gpu_match {
state.demand_tracker.record(&gpu, &bundle);
}
@@ -758,6 +862,16 @@ async fn proxy_request(
let effective_pool = match lookup.resolution {
PoolResolution::Pool(p) => p,
PoolResolution::Provisioning => {
+ let gpu_label = if gpu.is_empty() { "any" } else { gpu.as_str() };
+ info!(
+ gpu = %gpu_label,
+ bundle = %bundle,
+ engine = %engine,
+ "no queue worker available, returning 202",
+ );
+ metrics::PROVISIONING_RESPONSES
+ .with_label_values(&[gpu_label])
+ .inc();
// Note: if the caller expressed a GPU preference, demand
// was already recorded above via `exact_gpu_match = false`.
// We still record here (idempotent — see
@@ -890,6 +1004,7 @@ async fn proxy_request(
endpoint,
&model_name,
&bundle,
+ &engine,
&gpu,
&effective_pool,
&body_bytes,
@@ -898,10 +1013,15 @@ async fn proxy_request(
&token_id,
content_length,
Instant::now(),
+ &bundle_config_hash,
)
.await
}
+fn should_trace_proxy_request(endpoint: &str) -> bool {
+ InferenceEndpoint::from_label(endpoint).uses_generation_gateway_tracing()
+}
+
/// Route request through the queue-only JetStream path.
///
/// `pool` is always pre-resolved by the caller via
@@ -919,6 +1039,7 @@ async fn queue_mode_proxy(
endpoint: &str,
model: &str,
bundle: &str,
+ engine: &str,
gpu: &str,
pool: &str,
body_bytes: &[u8],
@@ -927,6 +1048,7 @@ async fn queue_mode_proxy(
token_id: &str,
content_length: i64,
start: Instant,
+ bundle_config_hash: &str,
) -> Response {
// Parse body once, extract items + params (avoids double parse)
let (items, params) = match parse_queue_request(body_bytes, is_msgpack_in, endpoint) {
@@ -1056,9 +1178,6 @@ async fn queue_mode_proxy(
}
}
- // Compute bundle config hash for worker config-skew detection
- let bundle_config_hash = state.model_registry.compute_bundle_config_hash(bundle);
-
// Generate has its own publish + result-collection path
// (streaming chunk aggregation instead of one-shot WorkResult fan-in).
if endpoint == "generate" {
@@ -1094,9 +1213,10 @@ async fn queue_mode_proxy(
work_publisher: work_publisher_arc,
model: model.to_string(),
bundle: bundle.to_string(),
+ engine: engine.to_string(),
gpu: gpu.to_string(),
pool: pool.to_string(),
- bundle_config_hash: bundle_config_hash.clone(),
+ bundle_config_hash: bundle_config_hash.to_string(),
work_params: params,
endpoint: super::sse::SseEndpoint::Generate,
})
@@ -1110,9 +1230,10 @@ async fn queue_mode_proxy(
work_publisher_arc,
model,
bundle,
+ engine,
gpu,
pool,
- &bundle_config_hash,
+ bundle_config_hash,
&params,
use_msgpack_out,
token_id,
@@ -1129,8 +1250,9 @@ async fn queue_mode_proxy(
endpoint,
model,
bundle,
+ engine,
gpu,
- &bundle_config_hash,
+ bundle_config_hash,
items,
&params,
)
@@ -1543,6 +1665,7 @@ pub(crate) async fn run_streaming_generate(
work_publisher: Arc<publisher::WorkPublisher>,
model: &str,
bundle: &str,
+ engine: &str,
gpu: &str,
pool: &str,
bundle_config_hash: &str,
@@ -1635,7 +1758,7 @@ pub(crate) async fn run_streaming_generate(
// Capture this before the move into `publish_generate_streaming`.
let was_direct_dispatched = matches!(target, publisher::PublishTarget::Worker { .. });
let (request_id, rx, activity) = match work_publisher
- .publish_generate_streaming(target, bundle, gpu, bundle_config_hash, params)
+ .publish_generate_streaming(target, bundle, engine, gpu, bundle_config_hash, params)
.await
{
Ok(r) => r,
@@ -1708,6 +1831,20 @@ pub(crate) async fn run_streaming_generate(
// `republished` field on `StreamCollector`) so the two paths
// cannot double-publish.
let mut republished_for_first_chunk = false;
+ // Capture the pool's consumer count at dispatch time so the H9
+ // single-worker suppression below uses the topology we actually
+ // dispatched against. Re-reading at timeout could see a count of 1
+ // after a 2-worker pool lost its chosen worker mid-flight, and
+ // suppress a republish that could have failed over to the
+ // remaining worker. (We accept the inverse hazard — a worker
+ // joining mid-flight in a single-worker pool keeps the suppression
+ // active — because the cancel-tombstone race that motivates this
+ // guard cannot fire on a worker that wasn't registered at
+ // dispatch.)
+ let single_consumer_pool_at_dispatch = was_direct_dispatched
+ && work_publisher
+ .pool_consumer_count(pool)
+ .is_some_and(|n| n <= 1);
// Drive the wait loop. We hold a single pinned receiver across
// iterations and re-arm the inter-chunk timer on every chunk
@@ -1736,7 +1873,24 @@ pub(crate) async fn run_streaming_generate(
// is true), in which case waiting another full
// first_chunk_timeout would double the user-visible latency
// for no benefit (no new work was published).
- if was_direct_dispatched && !republished_for_first_chunk {
+ //
+ // Single-consumer-pool guard: in pools with exactly one
+ // worker the H9 republish lands on the same worker that's
+ // already running the original attempt, and the
+ // ``publish_cancel`` we'd fire first arrives as a cancel-
+ // tombstone on the pool-republished message — the worker
+ // then refuses to decode with ``request cancelled before
+ // this worker registered; pool-republished attempt is
+ // authoritative``. There is no alternative worker to
+ // failover *to*, so the fallback can only ever harm
+ // throughput here. Extend the deadline to ``overall`` so
+ // the original attempt gets the legitimate end-to-end
+ // budget; if the worker really is dead the
+ // overall_timeout path will surface that.
+ if was_direct_dispatched
+ && !republished_for_first_chunk
+ && !single_consumer_pool_at_dispatch
+ {
republished_for_first_chunk = true;
// At-least-once-execution hazard: the original
// direct-dispatched worker may simply be SLOW (cold
@@ -1778,6 +1932,27 @@ pub(crate) async fn run_streaming_generate(
}
}
}
+ if single_consumer_pool_at_dispatch
+ && was_direct_dispatched
+ && !republished_for_first_chunk
+ {
+ // Single-worker fallback skip: don't surface
+ // first_chunk_timeout to the client — the only worker
+ // is the one we're already waiting on, and the
+ // overall_timeout path will catch a genuinely dead
+ // worker. Mark republished so this branch doesn't
+ // re-trigger on subsequent ticks, and push the
+ // first_chunk_deadline to the overall_deadline so
+ // tokio's select arm at line ~1824 stops firing.
+ republished_for_first_chunk = true;
+ first_chunk_deadline = overall_deadline;
+ tracing::debug!(
+ request_id = %request_id,
+ pool = %pool,
+ "first_chunk_timeout — single-worker pool, suppressing republish; continuing on overall_timeout"
+ );
+ continue;
+ }
break Err("first_chunk");
}
if let Some(la) = last_at {
@@ -2076,6 +2251,7 @@ async fn queue_mode_streaming_generate(
work_publisher: Arc<publisher::WorkPublisher>,
model: &str,
bundle: &str,
+ engine: &str,
gpu: &str,
pool: &str,
bundle_config_hash: &str,
@@ -2090,6 +2266,7 @@ async fn queue_mode_streaming_generate(
work_publisher,
model,
bundle,
+ engine,
gpu,
pool,
bundle_config_hash,
@@ -2206,6 +2383,17 @@ struct ChatRequestParams {
/// penalty); forwarded to SGLang's ``repetition_penalty``. Absent →
/// sampler default.
repetition_penalty: Option<f64>,
+ /// SGLang ``sampling_params.min_new_tokens``: minimum tokens to emit
+ /// before any stop condition can end the response. Integer ``>= 0``;
+ /// absent → no minimum. See the field doc on ``ChatCompletionRequest``
+ /// in :mod:`openapi.rs` for the canonical use case (anti-stop-first
+ /// fix on Qwen3.6 greedy decoding).
+ min_tokens: Option<u32>,
+ /// Per-request chat-template kwargs (e.g. ``{"enable_thinking":
+ /// false}``); forwarded verbatim to the worker which merges them on
+ /// top of the model YAML's defaults at template-render time. Absent
+ /// → only the model YAML's defaults apply.
+ chat_template_kwargs: Option<serde_json::Value>,
/// Routing hints plumbed through to the work envelope.
routing_key: Option<String>,
prompt_cache_key: Option<String>,
@@ -2855,6 +3043,46 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {
}
}
}
+ // -- min_tokens: SGLang ``sampling_params.min_new_tokens``. Integer
+ // >= 0; values >= u32::MAX or negative reject. Absent → no
+ // minimum. Workaround for stop-first artefacts (e.g. Qwen3.6
+ // greedy decoding occasionally emits the stop token first).
+ let mut min_tokens: Option<u32> = None;
+ if let Some(val) = obj.get("min_tokens") {
+ if !val.is_null() {
+ match val.as_i64() {
+ Some(k) if (0..=u32::MAX as i64).contains(&k) => {
+ min_tokens = Some(k as u32);
+ }
+ _ => {
+ return bad(
+ "'min_tokens' must be an integer >= 0",
+ Some("min_tokens"),
+ oai_code::INVALID_REQUEST,
+ );
+ }
+ }
+ }
+ }
+ // -- chat_template_kwargs: opaque map of kwargs for the tokenizer's
+ // ``apply_chat_template``. Validated only as an object (or null);
+ // the worker merges it onto the model YAML defaults at render
+ // time. Reject non-object values so a bad client doesn't smuggle
+ // a string/array past the schema and then crash render in the
+ // worker.
+ let mut chat_template_kwargs: Option<serde_json::Value> = None;
+ if let Some(val) = obj.get("chat_template_kwargs") {
+ if !val.is_null() {
+ if !val.is_object() {
+ return bad(
+ "'chat_template_kwargs' must be an object",
+ Some("chat_template_kwargs"),
+ oai_code::INVALID_REQUEST,
+ );
+ }
+ chat_template_kwargs = Some(val.clone());
+ }
+ }
// -- n: parsed and surfaced on :class:`ChatRequestParams.n` so the
// wire envelope (``GenerateParams.n``) drives the worker's
@@ -3231,6 +3459,8 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {
"presence_penalty",
"top_k",
"repetition_penalty",
+ "min_tokens",
+ "chat_template_kwargs",
"n",
"best_of",
"lora_adapter",
@@ -3288,6 +3518,8 @@ fn chat_params_from_json(body: &serde_json::Value) -> ChatParamsResult {
presence_penalty,
top_k,
repetition_penalty,
+ min_tokens,
+ chat_template_kwargs,
routing_key,
prompt_cache_key,
grammar,
@@ -3898,6 +4130,7 @@ fn resolve_model_and_bundle(
/// publisher, plus audit fields. Produced by [`resolve_generation_route`].
struct ResolvedRoute {
gpu: String,
+ engine: String,
effective_pool: String,
bundle_config_hash: String,
work_publisher: Arc<publisher::WorkPublisher>,
@@ -3985,7 +4218,20 @@ async fn resolve_generation_route(
.into_response());
};
- let lookup = resolve_effective_pool(&state.registry, bundle, &gpu, &pool_name).await;
+ let bundle_config_hash = state.model_registry.compute_bundle_config_hash(bundle);
+ let engine = state
+ .model_registry
+ .get_bundle_info(bundle)
+ .map(|info| info.engine)
+ .unwrap_or_else(|| crate::types::bundle::DEFAULT_ENGINE.to_string());
+ let lookup = resolve_effective_pool(
+ &state.registry,
+ bundle,
+ &gpu,
+ &pool_name,
+ &bundle_config_hash,
+ )
+ .await;
if !gpu.is_empty() && !lookup.exact_gpu_match {
state.demand_tracker.record(&gpu, bundle);
}
@@ -4017,7 +4263,6 @@ async fn resolve_generation_route(
}
};
- let bundle_config_hash = state.model_registry.compute_bundle_config_hash(bundle);
let token_id = extract_bearer_token(hdr)
.map(|t| mask_token(&t))
.unwrap_or_default();
@@ -4029,6 +4274,7 @@ async fn resolve_generation_route(
Ok(ResolvedRoute {
gpu,
+ engine,
effective_pool,
bundle_config_hash,
work_publisher: work_publisher_arc,
@@ -4276,6 +4522,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
// Shared with /v1/completions via resolve_generation_route.
let ResolvedRoute {
gpu,
+ engine,
effective_pool,
bundle_config_hash,
work_publisher: work_publisher_arc,
@@ -4305,6 +4552,8 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
presence_penalty: params.presence_penalty,
top_k: params.top_k,
repetition_penalty: params.repetition_penalty,
+ min_tokens: params.min_tokens,
+ chat_template_kwargs: params.chat_template_kwargs,
grammar: params.grammar,
routing_key: params.routing_key.clone(),
prompt_cache_key: params.prompt_cache_key.clone(),
@@ -4339,6 +4588,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
work_publisher: work_publisher_arc,
model: model_name.clone(),
bundle: bundle.clone(),
+ engine: engine.clone(),
gpu: gpu.clone(),
pool: effective_pool.clone(),
bundle_config_hash: bundle_config_hash.clone(),
@@ -4355,6 +4605,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res
work_publisher_arc,
&model_name,
&bundle,
+ &engine,
&gpu,
&effective_pool,
&bundle_config_hash,
@@ -4870,6 +5121,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
let ResolvedRoute {
gpu,
+ engine,
effective_pool,
bundle_config_hash,
work_publisher: work_publisher_arc,
@@ -4906,6 +5158,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
work_publisher: work_publisher_arc,
model: model_name.clone(),
bundle: bundle.clone(),
+ engine: engine.clone(),
gpu: gpu.clone(),
pool: effective_pool.clone(),
bundle_config_hash: bundle_config_hash.clone(),
@@ -4920,6 +5173,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)
work_publisher_arc,
&model_name,
&bundle,
+ &engine,
&gpu,
&effective_pool,
&bundle_config_hash,
@@ -5431,6 +5685,7 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
};
let ResolvedRoute {
gpu,
+ engine,
effective_pool,
bundle_config_hash,
work_publisher: work_publisher_arc,
@@ -5459,6 +5714,7 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -
work_publisher_arc,
&model_name,
&bundle,
+ &engine,
&gpu,
&effective_pool,
&bundle_config_hash,
@@ -7328,10 +7584,13 @@ fn generate_params_from_json(
stop,
frequency_penalty,
presence_penalty,
- // top_k / repetition_penalty are exposed only via the chat route
- // today; SIE-native /v1/generate stays a thin prompt wrapper.
+ // top_k / repetition_penalty / min_tokens / chat_template_kwargs
+ // are exposed only via the chat route today; SIE-native
+ // /v1/generate stays a thin prompt wrapper and ignores them.
top_k: None,
repetition_penalty: None,
+ min_tokens: None,
+ chat_template_kwargs: None,
grammar,
routing_key,
prompt_cache_key,
@@ -7674,10 +7933,13 @@ fn generate_params_from_rmpv(
stop,
frequency_penalty,
presence_penalty,
- // top_k / repetition_penalty are exposed only via the chat route
- // today; SIE-native /v1/generate stays a thin prompt wrapper.
+ // top_k / repetition_penalty / min_tokens / chat_template_kwargs
+ // are exposed only via the chat route today; SIE-native
+ // /v1/generate stays a thin prompt wrapper and ignores them.
top_k: None,
repetition_penalty: None,
+ min_tokens: None,
+ chat_template_kwargs: None,
grammar,
routing_key,
prompt_cache_key,
@@ -7847,38 +8109,23 @@ fn try_decode_rmpv_numpy(entries: &[(rmpv::Value, rmpv::Value)]) -> Option<serde
.unwrap_or_default();
let flat_values = decode_dtype_values(dtype, data)?;
-
- // The `shape` is worker-supplied and otherwise unbounded. Validate
- // that it actually describes `flat_values` before reshaping:
- // `product(shape)` must equal the decoded element count. This both
- // rejects a corrupt/mismatched shape (clear `None` instead of a
- // truncated tensor) and, crucially, prevents a malformed dimension
- // (e.g. `shape = [1, 4_000_000_000]` against a 4-element buffer) from
- // driving a multi-GB `Vec::with_capacity` in `reshape_recursive`.
- // `checked_mul` guards the product computation itself against
- // overflow. An empty/1-D shape is passed through to `reshape_array`,
- // which treats it as a flat array.
- if !shape.is_empty() {
- let mut product: usize = 1;
- for &dim in &shape {
- product = match product.checked_mul(dim) {
- Some(p) => p,
- None => {
- warn!("numpy shape product overflows usize; rejecting");
- return None;
- }
- };
- }
- if product != flat_values.len() {
- warn!(
- shape_product = product,
- flat_len = flat_values.len(),
- "numpy shape does not match decoded element count; rejecting"
- );
- return None;
- }
+ let expected_len = if shape.is_empty() {
+ flat_values.len()
+ } else {
+ shape
+ .iter()
+ .try_fold(1usize, |acc, dim| acc.checked_mul(*dim))?
+ };
+ if expected_len != flat_values.len() {
+ warn!(
+ dtype = %dtype,
+ expected_len,
+ actual_len = flat_values.len(),
+ shape = ?shape,
+ "numpy sentinel shape does not match decoded data length"
+ );
+ return None;
}
-
Some(reshape_array(&flat_values, &shape))
}
@@ -8265,6 +8512,7 @@ fn openai_embedding_items_to_data(
params(
("X-SIE-MACHINE-PROFILE" = Option<String>, Header, description = "Preferred GPU or machine profile"),
("X-SIE-Pool" = Option<String>, Header, description = "Explicit pool routing override"),
+ ("X-SIE-Engine" = Option<String>, Header, description = "Explicit engine routing override"),
("X-SIE-SDK-Version" = Option<String>, Header, description = "Client SDK version for skew warnings")
),
responses(
@@ -8390,6 +8638,7 @@ pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Re
if n.eq_ignore_ascii_case("authorization")
|| n.eq_ignore_ascii_case("x-sie-machine-profile")
|| n.eq_ignore_ascii_case("x-sie-pool")
+ || n.eq_ignore_ascii_case("x-sie-engine")
|| n.eq_ignore_ascii_case("x-sie-sdk-version")
{
inner_headers.insert(name.clone(), val.clone());
@@ -8630,6 +8879,21 @@ mod tests {
assert_eq!(resolve_path_model_id("org__model", &registry), "Org/Model");
}
+ #[test]
+ fn test_proxy_request_tracing_is_generation_only() {
+ assert!(should_trace_proxy_request("generate"));
+ for endpoint in crate::endpoint::InferenceEndpoint::NON_GENERATION_QUEUE_LABELS {
+ assert!(
+ !should_trace_proxy_request(endpoint),
+ "{endpoint} must keep the pre-generation proxy hot path"
+ );
+ }
+ assert!(
+ !should_trace_proxy_request("unknown"),
+ "unknown endpoints must fail closed to the non-generation hot path"
+ );
+ }
+
// ── is_valid_pool_name (pool subject-injection guard) ──────────
#[test]
@@ -10088,6 +10352,101 @@ mod tests {
assert_eq!(resolve_machine_profile("h100", &m), "h100");
}
+ // ── is_hop_by_hop ──────────────────────────────────────────────
+
+ #[test]
+ fn test_is_hop_by_hop_true() {
+ assert!(is_hop_by_hop("connection"));
+ assert!(is_hop_by_hop("Connection"));
+ assert!(is_hop_by_hop("Transfer-Encoding"));
+ assert!(is_hop_by_hop("host"));
+ assert!(is_hop_by_hop("keep-alive"));
+ }
+
+ #[test]
+ fn test_is_hop_by_hop_false() {
+ assert!(!is_hop_by_hop("content-type"));
+ assert!(!is_hop_by_hop("authorization"));
+ assert!(!is_hop_by_hop("x-custom-header"));
+ }
+
+ // ── parse_engine_pin ───────────────────────────────────────────
+
+ fn hdr(raw: &[u8]) -> HeaderMap {
+ let mut m = HeaderMap::new();
+ m.insert(
+ HeaderName::from_static("x-sie-engine"),
+ HeaderValue::from_bytes(raw).expect("test value should be valid"),
+ );
+ m
+ }
+
+ #[test]
+ fn test_parse_engine_pin_absent() {
+ let m = HeaderMap::new();
+ assert_eq!(parse_engine_pin(&m), EnginePinParse::None);
+ }
+
+ #[test]
+ fn test_parse_engine_pin_empty_or_whitespace_is_none() {
+ assert_eq!(parse_engine_pin(&hdr(b"")), EnginePinParse::None);
+ assert_eq!(parse_engine_pin(&hdr(b" ")), EnginePinParse::None);
+ assert_eq!(parse_engine_pin(&hdr(b"\t")), EnginePinParse::None);
+ }
+
+ #[test]
+ fn test_parse_engine_pin_lowercase_known_passes_through() {
+ assert_eq!(
+ parse_engine_pin(&hdr(b"pytorch")),
+ EnginePinParse::Some("pytorch".to_string()),
+ );
+ }
+
+ #[test]
+ fn test_parse_engine_pin_normalises_case_and_whitespace() {
+ // Mixed/upper case must round-trip to the lowercase canonical
+ // form so downstream registry lookups don't miss-match.
+ assert_eq!(
+ parse_engine_pin(&hdr(b"PyTorch")),
+ EnginePinParse::Some("pytorch".to_string()),
+ );
+ assert_eq!(
+ parse_engine_pin(&hdr(b" PYTORCH ")),
+ EnginePinParse::Some("pytorch".to_string()),
+ );
+ }
+
+ #[test]
+ fn test_parse_engine_pin_unknown_token_is_unknown() {
+ // ``candle`` was the only other engine we used to ship; it's
+ // gone now, so it joins ``jax`` in the unknown bucket.
+ assert_eq!(
+ parse_engine_pin(&hdr(b"candle")),
+ EnginePinParse::Unknown("candle".to_string()),
+ );
+ assert_eq!(
+ parse_engine_pin(&hdr(b"jax")),
+ EnginePinParse::Unknown("jax".to_string()),
+ );
+ // Whitespace stripped before reporting the raw token, so the
+ // 400 message stays readable.
+ assert_eq!(
+ parse_engine_pin(&hdr(b" jax ")),
+ EnginePinParse::Unknown("jax".to_string()),
+ );
+ }
+
+ #[test]
+ fn test_parse_engine_pin_invalid_utf8_is_invalid() {
+ // 0xFF is an invalid UTF-8 lead byte.
+ let mut m = HeaderMap::new();
+ m.insert(
+ HeaderName::from_static("x-sie-engine"),
+ HeaderValue::from_bytes(&[0xFFu8]).expect("bytes always valid"),
+ );
+ assert_eq!(parse_engine_pin(&m), EnginePinParse::InvalidUtf8);
+ }
+
#[test]
fn test_parse_queue_request_reads_nested_params() {
let body = serde_json::to_vec(&json!({
@@ -10240,8 +10599,7 @@ mod tests {
/// top-level array / scalar is almost always a mis-encoded
/// client request; silently accepting it as a single item
/// used to let the request fail later in worker-specific
- /// ways instead of at ingress (see review feedback on
- /// PR #716).
+ /// ways instead of at ingress.
#[test]
fn test_parse_queue_request_msgpack_rejects_non_map_top_level() {
let array_body = rmp_serde::to_vec(&rmpv::Value::Array(vec![
@@ -10318,7 +10676,7 @@ mod tests {
// ── msgpack_numpy conversion tests ──────────────────────────
//
// These exercise the fused `rmpv_to_response_json` path. All
- // fixtures use the exact rmpv shape that Python workers emit
+ // fixtures use the exact rmpv shape that Python adapter processes emit
// via `msgpack_numpy` — a `Map` whose `data` key holds a
// `Binary` blob — so the tests double as a wire-format guard:
// if Python-side encoding ever changes, these flip first.
@@ -10412,6 +10770,23 @@ mod tests {
assert!((row1[0].as_f64().unwrap() - 4.0).abs() < 1e-6);
}
+ #[test]
+ fn test_rmpv_to_response_json_rejects_mismatched_numpy_shape() {
+ let bytes: Vec<u8> = [1.0f32, 2.0, 3.0]
+ .iter()
+ .flat_map(|f| f.to_le_bytes())
+ .collect();
+ let value = numpy_sentinel("<f4", &[2, 3], bytes);
+ if let rmpv::Value::Map(entries) = value {
+ assert!(
+ try_decode_rmpv_numpy(&entries).is_none(),
+ "mismatched shape must not silently truncate decoded values"
+ );
+ } else {
+ panic!("numpy_sentinel helper must return a map");
+ }
+ }
+
#[test]
fn test_rmpv_to_response_json_empty_data() {
let value = numpy_sentinel("<f4", &[0], Vec::new());
@@ -10555,7 +10930,7 @@ mod tests {
}
/// End-to-end guard: build a msgpack payload the way a real
- /// Python worker would (sentinel map with `data` as `Binary`),
+ /// Python adapter process would (sentinel map with `data` as `Binary`),
/// decode via `rmp_serde::from_slice` → `rmpv_to_response_json`,
/// and check that bin data is decoded inline without byte-array
/// inflation. Non-numpy fields (`text`) must survive untouched.
@@ -10590,7 +10965,7 @@ mod tests {
}
/// The hot path fuses msgpack_numpy decode into the rmpv walk.
- /// This test builds the exact shape Python workers produce — a
+ /// This test builds the exact shape Python adapter processes produce — a
/// map whose `data` field is an `rmpv::Value::Binary` blob —
/// and confirms the fused function decodes the dtype directly
/// from the byte slice, without ever materialising a
@@ -10756,7 +11131,7 @@ mod tests {
// `Provisioning` so the caller returns `202 + Retry-After` and
// records pending demand for KEDA.
let reg = pool_registry();
- let out = resolve_effective_pool(&reg, "default", "", "").await;
+ let out = resolve_effective_pool(&reg, "default", "", "", "").await;
assert_eq!(out.resolution, PoolResolution::Provisioning);
// No GPU expressed → exact_gpu_match is definitionally false.
assert!(!out.exact_gpu_match);
@@ -10769,7 +11144,7 @@ mod tests {
let reg = pool_registry();
reg.update_worker("http://w1:8080", worker_msg("default", "a100", "pool-a"))
.await;
- let out = resolve_effective_pool(&reg, "premium", "l4", "").await;
+ let out = resolve_effective_pool(&reg, "premium", "l4", "", "").await;
assert_eq!(out.resolution, PoolResolution::Provisioning);
assert!(!out.exact_gpu_match);
}
@@ -10786,7 +11161,7 @@ mod tests {
)
.await;
- let out = resolve_effective_pool(&reg, "default", "l4-spot", "").await;
+ let out = resolve_effective_pool(&reg, "default", "l4-spot", "", "").await;
assert_eq!(out.resolution, PoolResolution::Provisioning);
assert!(!out.exact_gpu_match);
}
@@ -10799,7 +11174,7 @@ mod tests {
let reg = pool_registry();
reg.update_worker("http://w1:8080", worker_msg("default", "a100", "default"))
.await;
- let out = resolve_effective_pool(&reg, "default", "l4", "").await;
+ let out = resolve_effective_pool(&reg, "default", "l4", "", "").await;
assert_eq!(out.resolution, PoolResolution::Pool("default".to_string()));
// Exact tuple (default, l4) had no worker — even though we
// still routed via the bundle-only fallback, the caller must
@@ -10817,7 +11192,7 @@ mod tests {
worker_msg("default", "l4-spot", "default"),
)
.await;
- let out = resolve_effective_pool(&reg, "default", "", "").await;
+ let out = resolve_effective_pool(&reg, "default", "", "", "").await;
assert_eq!(out.resolution, PoolResolution::Pool("default".to_string()));
// No GPU preference → no demand tracking applicable.
assert!(!out.exact_gpu_match);
@@ -10833,7 +11208,7 @@ mod tests {
worker_msg("default", "l4-spot", "default"),
)
.await;
- let out = resolve_effective_pool(&reg, "default", "l4-spot", "").await;
+ let out = resolve_effective_pool(&reg, "default", "l4-spot", "", "").await;
assert_eq!(out.resolution, PoolResolution::Pool("default".to_string()));
assert!(out.exact_gpu_match);
}
@@ -10844,7 +11219,7 @@ mod tests {
// empty registry must route there so a known cold pool can be
// targeted (worker will scale up independently).
let reg = pool_registry();
- let out = resolve_effective_pool(&reg, "default", "", "my-bench").await;
+ let out = resolve_effective_pool(&reg, "default", "", "my-bench", "").await;
assert_eq!(out.resolution, PoolResolution::Pool("my-bench".to_string()));
assert!(!out.exact_gpu_match);
}
@@ -10858,7 +11233,7 @@ mod tests {
let reg = pool_registry();
reg.update_worker("http://w1:8080", worker_msg("default", "l4-spot", "pool-a"))
.await;
- let out = resolve_effective_pool(&reg, "default", "l4-spot", "my-bench").await;
+ let out = resolve_effective_pool(&reg, "default", "l4-spot", "my-bench", "").await;
assert_eq!(out.resolution, PoolResolution::Pool("my-bench".to_string()));
assert!(!out.exact_gpu_match);
}
@@ -10871,7 +11246,7 @@ mod tests {
worker_msg("default", "l4-spot", "my-bench"),
)
.await;
- let out = resolve_effective_pool(&reg, "default", "l4-spot", "my-bench").await;
+ let out = resolve_effective_pool(&reg, "default", "l4-spot", "my-bench", "").await;
assert_eq!(out.resolution, PoolResolution::Pool("my-bench".to_string()));
assert!(out.exact_gpu_match);
}
@@ -10885,7 +11260,33 @@ mod tests {
let reg = pool_registry();
reg.update_worker("http://w1:8080", worker_msg("default", "a100", "pool-a"))
.await;
- let out = resolve_effective_pool(&reg, "default", "l4", "my-bench").await;
+ let out = resolve_effective_pool(&reg, "default", "l4", "my-bench", "").await;
+ assert_eq!(out.resolution, PoolResolution::Pool("my-bench".to_string()));
+ assert!(!out.exact_gpu_match);
+ }
+
+ #[tokio::test]
+ async fn test_resolve_effective_pool_provisions_when_hash_is_stale() {
+ let reg = pool_registry();
+ reg.update_worker(
+ "http://w1:8080",
+ worker_msg("default", "l4-spot", "default"),
+ )
+ .await;
+ let out = resolve_effective_pool(&reg, "default", "l4-spot", "", "new-hash").await;
+ assert_eq!(out.resolution, PoolResolution::Provisioning);
+ assert!(!out.exact_gpu_match);
+ }
+
+ #[tokio::test]
+ async fn test_resolve_effective_pool_pinned_pool_still_overrides_stale_hash() {
+ let reg = pool_registry();
+ reg.update_worker(
+ "http://w1:8080",
+ worker_msg("default", "l4-spot", "default"),
+ )
+ .await;
+ let out = resolve_effective_pool(&reg, "default", "l4-spot", "my-bench", "new-hash").await;
assert_eq!(out.resolution, PoolResolution::Pool("my-bench".to_string()));
assert!(!out.exact_gpu_match);
}
@@ -11305,6 +11706,49 @@ mod tests {
assert_eq!(v["error"]["param"], "top_k");
}
+ /// ``min_tokens`` non-negative integer parses through.
+ #[test]
+ fn test_chat_params_from_json_accepts_min_tokens() {
+ let mut body = _chat_body_min("m");
+ body["min_tokens"] = serde_json::json!(10);
+ let p = _expect_chat_ok(body);
+ assert_eq!(p.min_tokens, Some(10));
+ }
+
+ /// ``min_tokens`` negative rejects with param attribution.
+ #[tokio::test]
+ async fn test_chat_params_from_json_rejects_negative_min_tokens() {
+ let mut body = _chat_body_min("m");
+ body["min_tokens"] = serde_json::json!(-1);
+ let v = _expect_chat_err(body).await;
+ assert_eq!(v["error"]["code"], "invalid_request");
+ assert_eq!(v["error"]["param"], "min_tokens");
+ }
+
+ /// ``chat_template_kwargs`` as an object parses and round-trips.
+ #[test]
+ fn test_chat_params_from_json_accepts_chat_template_kwargs_object() {
+ let mut body = _chat_body_min("m");
+ body["chat_template_kwargs"] = serde_json::json!({"enable_thinking": false});
+ let p = _expect_chat_ok(body);
+ assert_eq!(
+ p.chat_template_kwargs
+ .as_ref()
+ .and_then(|v| v.get("enable_thinking")),
+ Some(&serde_json::json!(false))
+ );
+ }
+
+ /// ``chat_template_kwargs`` non-object rejects.
+ #[tokio::test]
+ async fn test_chat_params_from_json_rejects_non_object_chat_template_kwargs() {
+ let mut body = _chat_body_min("m");
+ body["chat_template_kwargs"] = serde_json::json!("oops");
+ let v = _expect_chat_err(body).await;
+ assert_eq!(v["error"]["code"], "invalid_request");
+ assert_eq!(v["error"]["param"], "chat_template_kwargs");
+ }
+
/// ``repetition_penalty`` outside ``(0.0, 2.0]`` rejects (both ends).
#[tokio::test]
async fn test_chat_params_from_json_rejects_repetition_penalty_out_of_range() {
diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rs
index 25c1d56e3..6016a2736 100644
--- a/packages/sie_gateway/src/handlers/sse.rs
+++ b/packages/sie_gateway/src/handlers/sse.rs
@@ -78,6 +78,7 @@ pub struct SseParams<'a> {
pub work_publisher: Arc<WorkPublisher>,
pub model: String,
pub bundle: String,
+ pub engine: String,
pub gpu: String,
pub pool: String,
pub bundle_config_hash: String,
@@ -101,6 +102,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
work_publisher,
model,
bundle,
+ engine,
gpu,
pool,
bundle_config_hash,
@@ -168,7 +170,14 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
let was_direct_dispatched = matches!(target, publisher::PublishTarget::Worker { .. });
let (request_id, outcome_rx, chunk_rx) = match work_publisher
- .publish_generate_streaming_sse(target, &bundle, &gpu, &bundle_config_hash, &work_params)
+ .publish_generate_streaming_sse(
+ target,
+ &bundle,
+ &engine,
+ &gpu,
+ &bundle_config_hash,
+ &work_params,
+ )
.await
{
Ok(triple) => triple,
diff --git a/packages/sie_gateway/src/health_mode.rs b/packages/sie_gateway/src/health_mode.rs
index e4474ff42..1f8dd0db5 100644
--- a/packages/sie_gateway/src/health_mode.rs
+++ b/packages/sie_gateway/src/health_mode.rs
@@ -5,8 +5,8 @@
pub enum HealthModeDisposition {
/// Default supported path: WebSocket worker health.
WebSocketDefault,
- /// Experimental path: subscribe to `sie.health.>` when URL + client exist.
- TryNatsExperimental,
+ /// Subscribe to `sie.health.>` when URL + client exist.
+ TryNats,
/// `nats` requested but `SIE_NATS_URL` is unset or empty.
FallbackWebSocketMissingNatsUrl,
/// `nats` requested but no usable NATS client is available yet.
@@ -26,7 +26,7 @@ pub fn health_mode_disposition(
"ws" => HealthModeDisposition::WebSocketDefault,
"nats" if !nats_url_nonempty => HealthModeDisposition::FallbackWebSocketMissingNatsUrl,
"nats" if !nats_client_available => HealthModeDisposition::FallbackWebSocketNoNatsClient,
- "nats" => HealthModeDisposition::TryNatsExperimental,
+ "nats" => HealthModeDisposition::TryNats,
_ => HealthModeDisposition::FallbackWebSocketUnsupported,
}
}
@@ -64,10 +64,10 @@ mod tests {
}
#[test]
- fn nats_with_url_and_client_is_experimental_path() {
+ fn nats_with_url_and_client_is_ready() {
assert_eq!(
health_mode_disposition("nats", true, true),
- HealthModeDisposition::TryNatsExperimental
+ HealthModeDisposition::TryNats
);
}
diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rs
index 57308b497..9b13f67a9 100644
--- a/packages/sie_gateway/src/main.rs
+++ b/packages/sie_gateway/src/main.rs
@@ -1,5 +1,6 @@
mod config;
mod discovery;
+mod endpoint;
mod error;
mod handlers;
mod health_mode;
@@ -307,9 +308,9 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {
}
}
- // Set up health manager based on mode. WebSocket health is the supported
- // product path; NATS health is an internal/experimental consumer until
- // workers publish `sie.health.>` by default.
+ // Set up health manager based on mode. Helm selects NATS health for the
+ // worker-sidecar queue path so the registry receives queue pool names and
+ // bundle config hashes from `sie.health.>` heartbeats.
//
// Core NATS subscriptions are resumed by the client on reconnect; do not spawn
// duplicate `NatsHealthManager::start` loops on `reconnect_notify` (see PR review).
@@ -343,10 +344,7 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {
"unsupported gateway health mode requested; falling back to WS"
);
}
- HealthModeDisposition::TryNatsExperimental => {
- tracing::warn!(
- "NATS health mode is experimental/internal and requires workers to publish sie.health.>; if no publisher exists, the worker registry can remain empty"
- );
+ HealthModeDisposition::TryNats => {
if let Some(client) = nats_manager.get_client().await {
info!("using NATS health mode (shared connection)");
let nats_mgr = Arc::new(NatsHealthManager::new(Arc::clone(&registry)));
@@ -506,6 +504,7 @@ async fn run_server(cfg: Config) -> Result<(), Box<dyn std::error::Error>> {
payload_store,
Duration::from_secs_f64(config.request_timeout),
config.max_stream_pending,
+ Duration::from_secs(config.stream_max_age_s),
));
if let Err(e) = publisher.start_inbox_subscription(&client).await {
diff --git a/packages/sie_gateway/src/metrics.rs b/packages/sie_gateway/src/metrics.rs
index a5be46637..da3e90ca5 100644
--- a/packages/sie_gateway/src/metrics.rs
+++ b/packages/sie_gateway/src/metrics.rs
@@ -1038,14 +1038,14 @@ pub fn clear_fulfilled_demand(
// Gather current demand label pairs from the metric
let metric_families = REGISTRY.gather();
for mf in &metric_families {
- if mf.get_name() != "sie_gateway_pending_demand" {
+ if mf.name() != "sie_gateway_pending_demand" {
continue;
}
for m in mf.get_metric() {
let labels: std::collections::HashMap<&str, &str> = m
.get_label()
.iter()
- .map(|l| (l.get_name(), l.get_value()))
+ .map(|l| (l.name(), l.value()))
.collect();
if let Some(&gpu) = labels.get("machine_profile") {
let bundle = labels.get("bundle").copied().unwrap_or("default");
@@ -1216,19 +1216,19 @@ mod tests {
let families = REGISTRY.gather();
let lease = families
.iter()
- .find(|mf| mf.get_name() == "sie_gateway_active_lease_gpus")
+ .find(|mf| mf.name() == "sie_gateway_active_lease_gpus")
.expect("sie_gateway_active_lease_gpus should still be present after reset");
let stale_present = lease.get_metric().iter().any(|m| {
m.get_label().iter().any(|l| {
- (l.get_name() == "machine_profile" && l.get_value() == "stale-gpu")
- || (l.get_name() == "bundle" && l.get_value() == "stale-bundle")
+ (l.name() == "machine_profile" && l.value() == "stale-gpu")
+ || (l.name() == "bundle" && l.value() == "stale-bundle")
})
});
assert!(!stale_present, "stale label combination survived reset");
let sentinel_present = lease
.get_metric()
.iter()
- .any(|m| m.get_label().iter().all(|l| l.get_value().is_empty()));
+ .any(|m| m.get_label().iter().all(|l| l.value().is_empty()));
assert!(
sentinel_present,
"empty-label sentinel missing after update_pool_metrics(&[])"
@@ -1338,12 +1338,12 @@ mod tests {
let families = REGISTRY.gather();
let stale_present = families
.iter()
- .filter(|mf| mf.get_name() == "sie_gateway_worker_queue_depth")
+ .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.get_name() == "worker" && l.get_value() == "ghost-worker")
+ .any(|l| l.name() == "worker" && l.value() == "ghost-worker")
});
assert!(
!stale_present,
@@ -1372,12 +1372,12 @@ mod tests {
let families = REGISTRY.gather();
let stale_present = families
.iter()
- .filter(|mf| mf.get_name() == "sie_gateway_model_workers")
+ .filter(|mf| mf.name() == "sie_gateway_model_workers")
.flat_map(|mf| mf.get_metric().iter())
.any(|m| {
m.get_label()
.iter()
- .any(|l| l.get_name() == "model" && l.get_value() == "org/ghost-model")
+ .any(|l| l.name() == "model" && l.value() == "org/ghost-model")
});
assert!(
!stale_present,
@@ -1688,14 +1688,14 @@ mod tests {
let families = REGISTRY.gather();
let ttft_series = families
.iter()
- .find(|mf| mf.get_name() == "sie_gateway_generation_ttft_seconds")
+ .find(|mf| mf.name() == "sie_gateway_generation_ttft_seconds")
.expect("ttft family present")
.get_metric()
.iter()
.filter(|m| {
m.get_label()
.iter()
- .any(|l| l.get_name() == "model" && l.get_value() == "card/model")
+ .any(|l| l.name() == "model" && l.value() == "card/model")
})
.count();
assert_eq!(
@@ -1705,14 +1705,14 @@ mod tests {
let token_series = families
.iter()
- .find(|mf| mf.get_name() == "sie_gateway_generation_total_tokens")
+ .find(|mf| mf.name() == "sie_gateway_generation_total_tokens")
.expect("total_tokens family present")
.get_metric()
.iter()
.filter(|m| {
m.get_label()
.iter()
- .any(|l| l.get_name() == "model" && l.get_value() == "card/model")
+ .any(|l| l.name() == "model" && l.value() == "card/model")
})
.count();
assert_eq!(
@@ -1777,17 +1777,17 @@ mod tests {
let families = REGISTRY.gather();
let mut model_values: std::collections::HashSet<String> = std::collections::HashSet::new();
for mf in &families {
- if mf.get_name() != "sie_gateway_generation_ttft_seconds" {
+ if mf.name() != "sie_gateway_generation_ttft_seconds" {
continue;
}
for m in mf.get_metric() {
let labels = m.get_label();
let is_atk_pool = labels
.iter()
- .any(|l| l.get_name() == "pool" && l.get_value() == "atk-pool");
+ .any(|l| l.name() == "pool" && l.value() == "atk-pool");
if is_atk_pool {
- if let Some(model_label) = labels.iter().find(|l| l.get_name() == "model") {
- model_values.insert(model_label.get_value().to_string());
+ if let Some(model_label) = labels.iter().find(|l| l.name() == "model") {
+ model_values.insert(model_label.value().to_string());
}
}
}
@@ -1868,7 +1868,7 @@ mod tests {
"sie_gateway_provisioning_responses_total",
] {
assert!(
- !pre.iter().any(|mf| mf.get_name() == needle),
+ !pre.iter().any(|mf| mf.name() == needle),
"precondition violated: {needle} still in gather() after reset"
);
}
@@ -1892,7 +1892,7 @@ mod tests {
] {
let found = post
.iter()
- .find(|mf| mf.get_name() == needle)
+ .find(|mf| mf.name() == needle)
.unwrap_or_else(|| panic!("{needle} missing after init + scrape path"));
assert!(
!found.get_metric().is_empty(),
@@ -1948,7 +1948,7 @@ mod tests {
let families: std::collections::HashSet<String> = REGISTRY
.gather()
.iter()
- .map(|mf| mf.get_name().to_string())
+ .map(|mf| mf.name().to_string())
.collect();
for expected in [
"sie_gateway_generation_ttft_seconds",
diff --git a/packages/sie_gateway/src/middleware/auth.rs b/packages/sie_gateway/src/middleware/auth.rs
index b2eeb73a6..da0669dca 100644
--- a/packages/sie_gateway/src/middleware/auth.rs
+++ b/packages/sie_gateway/src/middleware/auth.rs
@@ -343,6 +343,7 @@ mod tests {
multi_router: false,
request_timeout: 0.0,
max_stream_pending: 0,
+ stream_max_age_s: 0,
configured_gpus: Vec::new(),
gpu_profile_map: HashMap::new(),
bundles_dir: String::new(),
diff --git a/packages/sie_gateway/src/middleware/metrics.rs b/packages/sie_gateway/src/middleware/metrics.rs
index aa51ad07a..c838cf664 100644
--- a/packages/sie_gateway/src/middleware/metrics.rs
+++ b/packages/sie_gateway/src/middleware/metrics.rs
@@ -319,14 +319,14 @@ mod tests {
// family and look up the matching series.
let families = metrics::REGISTRY.gather();
for mf in &families {
- if mf.get_name() != "sie_gateway_request_latency_seconds" {
+ if mf.name() != "sie_gateway_request_latency_seconds" {
continue;
}
for m in mf.get_metric() {
let labels: std::collections::HashMap<&str, &str> = m
.get_label()
.iter()
- .map(|l| (l.get_name(), l.get_value()))
+ .map(|l| (l.name(), l.value()))
.collect();
if labels.get("endpoint").copied() == Some(endpoint)
&& labels.get("machine_profile").copied() == Some(machine_profile)
@@ -424,9 +424,9 @@ mod tests {
let families = metrics::REGISTRY.gather();
families
.iter()
- .filter(|mf| mf.get_name() == "sie_gateway_requests_total")
+ .filter(|mf| mf.name() == "sie_gateway_requests_total")
.flat_map(|mf| mf.get_metric().iter())
- .map(|m| m.get_counter().get_value())
+ .map(|m| m.counter.value())
.sum()
};
@@ -439,9 +439,9 @@ mod tests {
let families = metrics::REGISTRY.gather();
families
.iter()
- .filter(|mf| mf.get_name() == "sie_gateway_requests_total")
+ .filter(|mf| mf.name() == "sie_gateway_requests_total")
.flat_map(|mf| mf.get_metric().iter())
- .map(|m| m.get_counter().get_value())
+ .map(|m| m.counter.value())
.sum()
};
diff --git a/packages/sie_gateway/src/nats/manager.rs b/packages/sie_gateway/src/nats/manager.rs
index aaba9aad5..e8510ad8b 100644
--- a/packages/sie_gateway/src/nats/manager.rs
+++ b/packages/sie_gateway/src/nats/manager.rs
@@ -11,6 +11,7 @@
//! `sie-config`'s `/v1/configs/epoch` and triggers a full
//! `GET /v1/configs/export` re-fetch.
+use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
@@ -331,6 +332,13 @@ impl NatsManager {
match self.model_registry.add_model_config(config) {
Ok(_) => {
+ if !notification.bundle_config_hash.is_empty() {
+ self.model_registry
+ .install_bundle_config_hashes(HashMap::from([(
+ notification.bundle_id.clone(),
+ notification.bundle_config_hash.clone(),
+ )]));
+ }
self.config_epoch.set_max(notification.epoch);
metrics::CONFIG_DELTAS
.with_label_values(&[kind, "applied"])
@@ -682,6 +690,7 @@ profiles:
let mut profiles = registry.get_model_profile_names("test/model");
profiles.sort();
assert_eq!(profiles, vec!["default".to_string(), "fast".to_string()]);
+ assert_eq!(registry.compute_bundle_config_hash("default"), "hash3");
}
#[tokio::test]
diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rs
index 53499601a..efa0cac1e 100644
--- a/packages/sie_gateway/src/openapi.rs
+++ b/packages/sie_gateway/src/openapi.rs
@@ -336,7 +336,7 @@ fn patch_chat_request_schema(value: &mut Value) {
return;
};
- // Per-choice streaming (Workstream B): n > 1 with stream:true is now
+ // Per-choice streaming: n > 1 with stream:true is now
// supported (per-choice_index delta + per-choice closure chunks ride
// before the single global [DONE]).
properties.insert(
@@ -761,7 +761,7 @@ fn patch_responses_request_schema(value: &mut Value) {
"input".to_string(),
json!({
"description": "Either a string prompt OR an array of `{role, content}` messages \
- (Workstream A array-input support). Array form: `role` is one of \
+ (array-input support). Array form: `role` is one of \
`\"system\" | \"user\" | \"assistant\" | \"developer\"` (\"developer\" \
normalizes to \"system\"). `content` is a string or an array of \
text-only content parts; image parts (`image_url` / `input_image`) \
@@ -808,8 +808,7 @@ fn patch_responses_request_schema(value: &mut Value) {
"stream".to_string(),
json!({
"description": "Accepted only as `false` (or absent). `true` rejects with 400 \
- unsupported_field (Responses SSE is deferred; tracked in \
- `product/design.md` §5.14).",
+ unsupported_field because Responses SSE is not supported yet.",
"type": ["boolean", "null"],
"enum": [false, null],
}),
@@ -837,8 +836,8 @@ fn patch_chat_completion_paths(value: &mut Value) {
op_obj.insert(
"description".to_string(),
json!(
- "OpenAI-compatible chat completions. Strict allow-list parser (see \
- `product/design.md` §5.14): unknown top-level fields reject with 400 \
+ "OpenAI-compatible chat completions. Strict allow-list parser: \
+ unknown top-level fields reject with 400 \
`unsupported_field`. Streaming (`stream: true`) is supported and emits \
SSE `chat.completion.chunk` events; `n > 1` streaming fans candidates \
out as per-`choice_index` delta chunks with per-choice closure chunks \
@@ -864,13 +863,12 @@ fn patch_completions_path(value: &mut Value) {
op_obj.insert(
"description".to_string(),
json!(
- "OpenAI-compatible legacy Completions. Strict allow-list parser \
- (`product/design.md` §5.14): unknown top-level fields reject with 400 \
+ "OpenAI-compatible legacy Completions. Strict allow-list parser: \
+ unknown top-level fields reject with 400 \
`unsupported_field`. `stream: true` is supported (SSE `text_completion`). \
Known-rejected fields: `echo`, `suffix`, `logprobs`, `best_of`, `n > 1`, \
batched array `prompt` — each rejects with 400 `unsupported_field`. The \
- response body no longer carries the always-null `logprobs` field \
- (Workstream A wire change)."
+ response body no longer carries the always-null `logprobs` field."
),
);
op_obj.insert(
@@ -909,10 +907,10 @@ fn patch_responses_path(value: &mut Value) {
op_obj.insert(
"description".to_string(),
json!(
- "OpenAI Responses API (MVP). Strict allow-list parser \
- (`product/design.md` §5.14): unknown top-level fields reject with 400 \
+ "OpenAI Responses API (MVP). Strict allow-list parser: \
+ unknown top-level fields reject with 400 \
`unsupported_field`. `input` is either a string prompt OR an array of \
- `{role, content}` messages (Workstream A array-input support). \
+ `{role, content}` messages. \
Known-rejected fields: `tools`, `tool_choice`, `previous_response_id`, \
`reasoning`, `background`, `metadata`, `instructions` — each rejects \
with 400 `unsupported_field`. `stream: true` is rejected (Responses SSE \
@@ -1442,7 +1440,7 @@ pub struct GenerateResponse {
/// One chat message in an OpenAI chat-completions request.
///
-/// Per the strict allow-list parser (Workstream A), ``content`` is either a
+/// Per the strict allow-list parser, ``content`` is either a
/// plain string OR a list of text-only content parts (``{type:"text"|"input_text",
/// text:"..."}``); ``image_url`` and ``input_image`` parts reject with 400
/// ``unsupported_field`` until a vision-capable model ships. Assistant
@@ -1481,7 +1479,7 @@ pub struct ChatCompletionMessage {
/// ``unsupported_field``. Type-invalid values for accepted fields reject
/// with 400 ``invalid_request``.
///
-/// **Known-rejected fields** (per `product/design.md` §5.14):
+/// **Known-rejected fields**:
/// - ``functions`` / ``function_call`` — deprecated by OpenAI; use ``tools`` instead.
/// - ``modalities``, ``audio``, ``metadata``, ``store``, ``service_tier``,
/// ``prediction``, ``reasoning_effort``, ``verbosity`` — out of scope.
@@ -1530,6 +1528,23 @@ pub struct ChatCompletionRequest {
/// (``1.0`` = no penalty). Absent → sampler default.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repetition_penalty: Option<f32>,
+ /// SGLang ``sampling_params.min_new_tokens``: integer ``>= 0`` capping
+ /// how many tokens the model must emit before any stop condition can
+ /// fire. Use to work around models that occasionally emit the stop
+ /// token as the very first decoded token (e.g. Qwen3.6 thinking-off
+ /// under greedy decode). Absent → sampler default (no minimum).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub min_tokens: Option<u32>,
+ /// Per-request overrides for kwargs passed to the tokenizer's
+ /// ``apply_chat_template`` call. Object whose entries are merged on
+ /// top of the model YAML's ``chat_template_kwargs`` (the YAML wins
+ /// for keys present in both — adjust the YAML when a request needs
+ /// to defeat a baked-in default). Typical use: pass
+ /// ``{"enable_thinking": false}`` to the Qwen3 family to suppress
+ /// ``<think>`` reasoning on a per-request basis. Absent → only the
+ /// model YAML's defaults apply.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub chat_template_kwargs: Option<Value>,
/// Number of candidate completions, ``[1, 128]``. ``n>1`` returns a
/// multi-entry ``choices`` array. Streaming with ``n>1`` is supported:
/// per-``choice_index`` delta chunks plus per-choice closure chunks
@@ -1628,7 +1643,7 @@ pub struct ChatCompletionRequest {
pub struct ChatCompletionChoiceMessage {
pub role: String,
pub content: String,
- /// Per-candidate tool-call list (Workstream B). Present when the model
+ /// Per-candidate tool-call list. Present when the model
/// emitted one or more tool calls for this choice; absent otherwise.
/// Each entry has the OpenAI shape ``{id, type:"function",
/// function:{name, arguments}}`` where ``arguments`` is a JSON-encoded string.
@@ -1670,10 +1685,10 @@ pub struct ChatCompletionResponse {
/// OpenAI-compatible ``POST /v1/completions`` request (legacy raw-prompt surface).
///
-/// **Strict allow-list** (Workstream A): unknown fields reject with 400
+/// **Strict allow-list**: unknown fields reject with 400
/// ``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.
///
-/// **Known-rejected fields** (per `product/design.md` §5.14):
+/// **Known-rejected fields**:
/// - ``echo`` — rejected with 400 ``unsupported_field``.
/// - ``suffix`` — rejected with 400 ``unsupported_field``.
/// - ``logprobs`` — rejected with 400 ``unsupported_field`` (the legacy
@@ -1688,7 +1703,7 @@ pub struct ChatCompletionResponse {
/// **Streaming:** ``stream: true`` is supported (SSE ``text_completion``).
///
/// **Response body wire change:** the always-null ``logprobs`` field has
-/// been dropped from the response body (Workstream A); SDKs that destructure
+/// been dropped from the response body; SDKs that destructure
/// ``choices[].logprobs`` should treat absence as the new normal.
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct CompletionsRequest {
@@ -1730,10 +1745,10 @@ pub struct CompletionsRequest {
/// OpenAI-compatible ``POST /v1/responses`` request (Responses MVP).
///
-/// **Strict allow-list** (Workstream A): unknown fields reject with 400
+/// **Strict allow-list**: unknown fields reject with 400
/// ``unsupported_field``. Type-invalid values reject with 400 ``invalid_request``.
///
-/// **Known-rejected fields** (per `product/design.md` §5.14):
+/// **Known-rejected fields**:
/// - ``tools`` / ``tool_choice`` — rejected with 400 ``unsupported_field``.
/// - ``previous_response_id`` — rejected with 400 ``unsupported_field``
/// (Responses MVP is stateless single-turn).
@@ -1749,7 +1764,7 @@ pub struct CompletionsRequest {
pub struct ResponsesRequest {
pub model: String,
/// Either a string prompt OR an array of ``{role, content}`` messages
- /// (Workstream A array-input support). Array form: ``role`` is one of
+ /// (array-input support). Array form: ``role`` is one of
/// ``"system" | "user" | "assistant" | "developer"`` (``"tool"`` is
/// nominally accepted but Responses tools are rejected so it is
/// effectively unreachable). ``content`` is a string or an array of
@@ -1947,7 +1962,7 @@ pub struct ModelCapabilitiesWire {
/// on the backend: SGLang's Outlines backend does not implement
/// EBNF, so a profile with ``grammar_backend: outlines`` advertises
/// only ``["json_schema", "regex"]``; xgrammar/llguidance profiles
- /// advertise all three. See ADR-0002.
+ /// advertise all three.
#[serde(skip_serializing_if = "Option::is_none")]
pub grammar: Option<Vec<String>>,
/// Whether the model supports tool / function calling.
@@ -2529,19 +2544,23 @@ mod tests {
}
#[test]
- fn openapi_document_does_not_advertise_internal_engine_header() {
+ fn openapi_document_advertises_engine_header_on_inference_paths() {
let spec = serde_json::to_value(openapi_document()).unwrap();
- for path_item in spec["paths"].as_object().unwrap().values() {
- for operation in path_item.as_object().unwrap().values() {
- let Some(parameters) = operation.get("parameters").and_then(|p| p.as_array())
- else {
- continue;
- };
- for parameter in parameters {
- let name = parameter["name"].as_str().unwrap_or_default();
- assert_ne!(name.to_ascii_lowercase(), "x-sie-engine");
- }
- }
+ for path in [
+ "/v1/encode/{model}",
+ "/v1/score/{model}",
+ "/v1/extract/{model}",
+ "/v1/embeddings",
+ ] {
+ let parameters = spec["paths"][path]["post"]["parameters"]
+ .as_array()
+ .unwrap_or_else(|| panic!("{path} must document parameters"));
+ assert!(
+ parameters.iter().any(|p| p["name"]
+ .as_str()
+ .is_some_and(|name| name.eq_ignore_ascii_case("x-sie-engine"))),
+ "{path} must document X-SIE-Engine"
+ );
}
}
@@ -2599,7 +2618,7 @@ mod tests {
// SIE-native passthrough endpoints keep the legacy `detail`-shaped
// error unions. `/v1/embeddings` is OpenAI-shaped and asserted
- // separately below (roadmap §3 item 1.4).
+ // separately below.
for path in [
"/v1/encode/{model}",
"/v1/score/{model}",
diff --git a/packages/sie_gateway/src/queue/payload_store.rs b/packages/sie_gateway/src/queue/payload_store.rs
index c1350e147..c1793de59 100644
--- a/packages/sie_gateway/src/queue/payload_store.rs
+++ b/packages/sie_gateway/src/queue/payload_store.rs
@@ -23,6 +23,22 @@ pub trait PayloadStore: Send + Sync {
async fn delete(&self, key: &str) -> Result<(), String>;
}
+/// Disabled payload store. Used when `SIE_PAYLOAD_STORE_URL` is unset so
+/// queue mode does not silently offload to gateway-local disk that worker
+/// pods cannot read.
+pub struct DisabledPayloadStore;
+
+#[async_trait]
+impl PayloadStore for DisabledPayloadStore {
+ async fn put(&self, _key: &str, _data: &[u8]) -> Result<String, String> {
+ Err("payload store not configured".to_string())
+ }
+
+ async fn delete(&self, _key: &str) -> Result<(), String> {
+ Ok(())
+ }
+}
+
/// Local filesystem payload store (default).
pub struct LocalPayloadStore {
base_dir: PathBuf,
@@ -158,6 +174,10 @@ impl PayloadStore for ObjectStorePayloadStore {
/// Factory function to create the appropriate payload store based on URL prefix.
pub async fn create_payload_store(url: &str) -> Arc<dyn PayloadStore> {
+ if url.trim().is_empty() {
+ return Arc::new(DisabledPayloadStore);
+ }
+
#[cfg(feature = "cloud-storage")]
{
if let Some(rest) = url.strip_prefix("s3://") {
@@ -240,6 +260,13 @@ mod tests {
let _store = create_payload_store(dir.path().to_str().unwrap()).await;
}
+ #[tokio::test]
+ async fn test_create_payload_store_empty_disables_offload() {
+ let store = create_payload_store("").await;
+ assert!(store.put("test.bin", b"data").await.is_err());
+ assert!(store.delete("test.bin").await.is_ok());
+ }
+
#[tokio::test]
async fn test_create_payload_store_s3_without_feature() {
let _store = create_payload_store("s3://my-bucket/prefix").await;
diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rs
index 9a876bde8..022cc9de5 100644
--- a/packages/sie_gateway/src/queue/publisher.rs
+++ b/packages/sie_gateway/src/queue/publisher.rs
@@ -16,6 +16,7 @@ use super::payload_store::PayloadStore;
use super::streaming::{
ChunkApplied, ChunkEnvelope, ChunkError, NakEnvelope, StreamCollector, StreamOutcome,
};
+use crate::endpoint::InferenceEndpoint;
use crate::metrics;
const PAYLOAD_OFFLOAD_THRESHOLD: usize = 1_024 * 1_024; // 1 MB
@@ -262,6 +263,17 @@ pub struct GenerateParams {
/// ``sampling_params["repetition_penalty"]``. Absent → sampler default.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub repetition_penalty: Option<f64>,
+ /// SGLang ``sampling_params["min_new_tokens"]``: integer ``>= 0``,
+ /// gateway-validated. Minimum tokens the model must emit before
+ /// any stop condition can fire. Absent → sampler default.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub min_tokens: Option<u32>,
+ /// Per-request kwargs forwarded to the tokenizer's
+ /// ``apply_chat_template``. Worker merges them on top of the model
+ /// YAML defaults (YAML wins on conflict). Validated as a JSON
+ /// object by the gateway. Absent → only YAML defaults apply.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub chat_template_kwargs: Option<serde_json::Value>,
/// Structured-output spec. Absent when the request omitted the
/// ``grammar`` field (SIE-native) or ``response_format`` (OpenAI
/// chat). Populated by :func:`handlers::grammar::parse_grammar`
@@ -363,6 +375,16 @@ pub struct WorkItem {
pub model_id: String,
#[serde(default)]
pub profile_id: String,
+ /// Execution engine the bundle that resolved this request
+ /// declares. Today only ``"pytorch"`` is recognised (see
+ /// ``KNOWN_ENGINES`` in ``types::bundle``). Workers can use
+ /// this as a sanity check (``assert engine == self.engine``)
+ /// or as a soft dispatch hint when a single pool ever ends up
+ /// multiplexing engines. Older workers default to ``""`` and
+ /// ignore the field — back-compat is preserved by
+ /// ``#[serde(default)]``.
+ #[serde(default)]
+ pub engine: String,
pub pool_name: String,
pub machine_profile: String,
/// Per-item payload. Carried as `rmpv::Value` so msgpack request
@@ -460,6 +482,7 @@ struct WorkItemRef<'a> {
pub operation: &'a str,
pub model_id: &'a str,
pub profile_id: &'a str,
+ pub engine: &'a str,
pub pool_name: &'a str,
pub machine_profile: &'a str,
pub item: Option<&'a rmpv::Value>,
@@ -502,6 +525,7 @@ struct WorkItemShared<'a> {
model: &'a str,
pool: &'a str,
gpu: &'a str,
+ engine: &'a str,
bundle_config_hash: &'a str,
router_id: &'a str,
reply_subject: &'a str,
@@ -557,6 +581,7 @@ pub struct WorkPublisher {
payload_store: Arc<dyn PayloadStore>,
result_timeout: Duration,
max_stream_pending: u64,
+ stream_max_age: Duration,
/// Pools we've already `get_or_create_stream`'d for, keyed by pool
/// name so we skip the admin-API round trip on subsequent
/// requests. The value is the pre-computed JetStream stream name
@@ -1045,6 +1070,7 @@ impl WorkPublisher {
payload_store: Arc<dyn PayloadStore>,
result_timeout: Duration,
max_stream_pending: u64,
+ stream_max_age: Duration,
) -> Self {
Self {
jetstream,
@@ -1052,6 +1078,7 @@ impl WorkPublisher {
payload_store,
result_timeout,
max_stream_pending,
+ stream_max_age,
ensured_streams: DashMap::new(),
stream_info_cache: DashMap::new(),
pending_results: DashMap::new(),
@@ -1095,6 +1122,25 @@ impl WorkPublisher {
&self.router_id
}
+ /// Number of JetStream consumers registered on the pool's
+ /// ``WORK_POOL_<pool>`` stream — refreshed by the stream-info
+ /// monitor. ``None`` when the pool hasn't been observed yet
+ /// (cold cache); ``Some(0)`` is possible briefly during worker
+ /// roll-over.
+ ///
+ /// Callers use this to gate the H9 first-chunk-fallback path: in
+ /// single-consumer pools the republish targets the same worker
+ /// that's already handling the original request, which produces
+ /// a self-induced cancel-tombstone race
+ /// (``cancel arrived before this worker registered;
+ /// pool-republished attempt is authoritative``). Skipping the
+ /// fallback in that shape preserves the legitimate overall_timeout
+ /// fallback for genuinely slow workers without trading it for a
+ /// guaranteed 503.
+ pub fn pool_consumer_count(&self, pool: &str) -> Option<usize> {
+ self.stream_info_cache.get(pool).map(|v| v.num_consumers)
+ }
+
/// Ensure the stream exists for the given pool (cached — admin call happens once per pool).
///
/// Returns the cached JetStream stream name as an `Arc<str>` so
@@ -1115,7 +1161,7 @@ impl WorkPublisher {
subjects,
retention: jetstream::stream::RetentionPolicy::WorkQueue,
storage: jetstream::stream::StorageType::Memory,
- max_age: Duration::from_secs(60),
+ max_age: self.stream_max_age,
max_messages: 100_000,
..Default::default()
})
@@ -1246,6 +1292,7 @@ impl WorkPublisher {
endpoint: &str,
model: &str,
_bundle: &str,
+ engine: &str,
gpu: &str,
bundle_config_hash: &str,
items: Vec<rmpv::Value>,
@@ -1294,12 +1341,10 @@ impl WorkPublisher {
.unwrap_or_default()
.as_secs_f64();
- // M5: capture the W3C Trace Context for envelope injection.
- // Done once per request so the propagator runs O(1) regardless
- // of fan-out width. Both fields are `None` when no gateway
- // span is recording — the envelope omits the keys in that
- // case (see `WorkItemRef.serde(skip_serializing_if)`).
- let (traceparent, tracestate) = crate::observability::propagation::inject_current_context();
+ // Generation queue fallback carries trace context. Encode /
+ // score / extract intentionally keep the pre-generation queue
+ // hot path and wire shape: no OTel lookup, no envelope fields.
+ let (traceparent, tracestate) = Self::trace_context_for_endpoint(endpoint);
// Every work item in a request shares the same pool / model /
// params block. `WorkItemRef` borrows these values so we don't
@@ -1311,6 +1356,7 @@ impl WorkPublisher {
model,
pool,
gpu,
+ engine,
bundle_config_hash,
router_id: &self.router_id,
reply_subject: &reply_subject,
@@ -1325,8 +1371,7 @@ impl WorkPublisher {
// so on any error we have to unwind the collector entry
// and whatever payloads the successful siblings already
// wrote to the offload store, otherwise both leak until
- // the result-timeout sweep kicks in (review feedback on
- // PR #716).
+ // the result-timeout sweep kicks in.
let publish_outcome = if endpoint == "score" {
self.publish_score(&shared, items, &subject)
.await
@@ -1396,6 +1441,18 @@ impl WorkPublisher {
Ok((request_id, rx))
}
+ fn trace_context_for_endpoint(endpoint: &str) -> (Option<String>, Option<String>) {
+ if Self::should_propagate_queue_trace(endpoint) {
+ crate::observability::propagation::inject_current_context()
+ } else {
+ (None, None)
+ }
+ }
+
+ fn should_propagate_queue_trace(endpoint: &str) -> bool {
+ InferenceEndpoint::from_label(endpoint).injects_queue_trace_context()
+ }
+
/// Publish the single work item for a score request.
///
/// The score endpoint collapses the whole request into one work
@@ -1423,6 +1480,7 @@ impl WorkPublisher {
operation: shared.endpoint,
model_id: shared.model,
profile_id: "default",
+ engine: shared.engine,
pool_name: shared.pool,
machine_profile: shared.gpu,
item: None,
@@ -1503,6 +1561,7 @@ impl WorkPublisher {
&self,
target: PublishTarget,
_bundle: &str,
+ engine: &str,
gpu: &str,
bundle_config_hash: &str,
params: &WorkParams,
@@ -1555,6 +1614,7 @@ impl WorkPublisher {
model: &model,
pool: &pool,
gpu,
+ engine,
bundle_config_hash,
router_id: &self.router_id,
reply_subject: &reply_subject,
@@ -1612,6 +1672,7 @@ impl WorkPublisher {
&self,
target: PublishTarget,
_bundle: &str,
+ engine: &str,
gpu: &str,
bundle_config_hash: &str,
params: &WorkParams,
@@ -1659,6 +1720,7 @@ impl WorkPublisher {
model: &model,
pool: &pool,
gpu,
+ engine,
bundle_config_hash,
router_id: &self.router_id,
reply_subject: &reply_subject,
@@ -1806,6 +1868,7 @@ impl WorkPublisher {
operation: shared.endpoint,
model_id: shared.model,
profile_id: "default",
+ engine: shared.engine,
pool_name: shared.pool,
machine_profile: shared.gpu,
item: None,
@@ -1844,7 +1907,7 @@ impl WorkPublisher {
.jetstream
.send_publish(
subject.to_string(),
- jetstream::context::Publish::build()
+ jetstream::message::PublishMessage::build()
.message_id(shared.request_id)
.payload(encoded.clone().into()),
)
@@ -1985,7 +2048,7 @@ impl WorkPublisher {
.jetstream
.send_publish(
subject.clone(),
- jetstream::context::Publish::build()
+ jetstream::message::PublishMessage::build()
.message_id(&msg_id)
.payload(payload.into()),
)
@@ -2047,6 +2110,7 @@ impl WorkPublisher {
operation: shared.endpoint,
model_id: shared.model,
profile_id: "default",
+ engine: shared.engine,
pool_name: shared.pool,
machine_profile: shared.gpu,
item: Some(&item_value),
@@ -2678,6 +2742,7 @@ mod tests {
operation: "encode".to_string(),
model_id: "BAAI/bge-m3".to_string(),
profile_id: String::new(),
+ engine: "pytorch".to_string(),
pool_name: "default".to_string(),
machine_profile: "l4-spot".to_string(),
item: Some(rmpv::Value::Map(vec![(
@@ -2728,6 +2793,25 @@ mod tests {
assert_eq!(decoded.bundle_config_hash, "abc123");
assert_eq!(decoded.router_id, "router-1");
assert_eq!(decoded.reply_subject, "_INBOX.r1.req-1");
+ assert_eq!(decoded.engine, "pytorch");
+ }
+
+ #[test]
+ fn test_work_item_engine_back_compat() {
+ let mut without_engine = serde_json::Map::new();
+ without_engine.insert("work_item_id".into(), "req-1.0".into());
+ without_engine.insert("request_id".into(), "req-1".into());
+ without_engine.insert("item_index".into(), 0.into());
+ without_engine.insert("total_items".into(), 1.into());
+ without_engine.insert("operation".into(), "encode".into());
+ without_engine.insert("model_id".into(), "m".into());
+ without_engine.insert("pool_name".into(), "default".into());
+ without_engine.insert("machine_profile".into(), "".into());
+ without_engine.insert("reply_subject".into(), "_INBOX.x.y".into());
+ let encoded = rmp_serde::to_vec_named(&without_engine).unwrap();
+ let decoded: WorkItem = rmp_serde::from_slice(&encoded).unwrap();
+ assert_eq!(decoded.engine, "");
+ assert_eq!(decoded.operation, "encode");
}
/// Regression: `WorkItemRef` is the borrowed view we use on the
@@ -2745,6 +2829,7 @@ mod tests {
operation: "encode".to_string(),
model_id: "BAAI/bge-m3".to_string(),
profile_id: "default".to_string(),
+ engine: "pytorch".to_string(),
pool_name: "default".to_string(),
machine_profile: "l4-spot".to_string(),
item: Some(rmpv::Value::Map(vec![(
@@ -2786,6 +2871,7 @@ mod tests {
operation: &owned.operation,
model_id: &owned.model_id,
profile_id: &owned.profile_id,
+ engine: &owned.engine,
pool_name: &owned.pool_name,
machine_profile: &owned.machine_profile,
item: Some(&item_value),
@@ -2862,6 +2948,7 @@ mod tests {
operation: "encode".to_string(),
model_id: "model".to_string(),
profile_id: String::new(),
+ engine: String::new(),
pool_name: "default".to_string(),
machine_profile: String::new(),
item: None,
@@ -3199,6 +3286,7 @@ mod tests {
operation: "generate".to_string(),
model_id: "m".to_string(),
profile_id: "default".to_string(),
+ engine: "pytorch".to_string(),
pool_name: "p".to_string(),
machine_profile: "g".to_string(),
item: None,
@@ -3346,6 +3434,7 @@ mod tests {
operation: "generate".to_string(),
model_id: "m".to_string(),
profile_id: "default".to_string(),
+ engine: "pytorch".to_string(),
pool_name: "p".to_string(),
machine_profile: "g".to_string(),
item: None,
@@ -3388,6 +3477,7 @@ mod tests {
operation: "generate".to_string(),
model_id: "m".to_string(),
profile_id: "default".to_string(),
+ engine: "pytorch".to_string(),
pool_name: "p".to_string(),
machine_profile: "g".to_string(),
item: None,
@@ -3460,6 +3550,61 @@ mod tests {
assert_eq!(parts[2].len(), 16, "span_id is 16 hex chars");
}
+ #[test]
+ fn test_queue_trace_context_stays_off_for_non_generation() {
+ use opentelemetry::trace::{TraceContextExt, Tracer, TracerProvider as _};
+ use opentelemetry::Context;
+ use opentelemetry_sdk::propagation::TraceContextPropagator;
+ use opentelemetry_sdk::trace::TracerProvider;
+
+ opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
+ let provider = TracerProvider::builder().build();
+ let tracer = provider.tracer("gateway-test");
+ let span = tracer.start("gateway.proxy_request");
+ let cx = Context::current().with_span(span);
+ let _guard = cx.attach();
+
+ for endpoint in InferenceEndpoint::NON_GENERATION_QUEUE_LABELS {
+ assert!(
+ !WorkPublisher::should_propagate_queue_trace(endpoint),
+ "{endpoint} must keep the pre-generation queue hot path"
+ );
+ let (tp, ts) = WorkPublisher::trace_context_for_endpoint(endpoint);
+ assert!(tp.is_none(), "{endpoint} unexpectedly injected traceparent");
+ assert!(ts.is_none(), "{endpoint} unexpectedly injected tracestate");
+ }
+ let (tp, ts) = WorkPublisher::trace_context_for_endpoint("unknown");
+ assert!(
+ tp.is_none(),
+ "unknown endpoint unexpectedly injected traceparent"
+ );
+ assert!(
+ ts.is_none(),
+ "unknown endpoint unexpectedly injected tracestate"
+ );
+ }
+
+ #[test]
+ fn test_queue_trace_context_is_generation_only() {
+ use opentelemetry::trace::{TraceContextExt, Tracer, TracerProvider as _};
+ use opentelemetry::Context;
+ use opentelemetry_sdk::propagation::TraceContextPropagator;
+ use opentelemetry_sdk::trace::TracerProvider;
+
+ opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());
+ let provider = TracerProvider::builder().build();
+ let tracer = provider.tracer("gateway-test");
+ let span = tracer.start("gateway.proxy_generate");
+ let cx = Context::current().with_span(span);
+ let _guard = cx.attach();
+
+ assert!(WorkPublisher::should_propagate_queue_trace("generate"));
+ let (tp, _ts) = WorkPublisher::trace_context_for_endpoint("generate");
+ let tp = tp.expect("generate queue fallback should propagate traceparent");
+ let parts: Vec<&str> = tp.split('-').collect();
+ assert_eq!(parts.len(), 4, "wire shape: version-trace-span-flags");
+ }
+
// ----- H9 — first-chunk-fallback rate limit ---------------------
/// The bucket admits exactly ``burst`` tokens immediately, then
diff --git a/packages/sie_gateway/src/routing/tests.rs b/packages/sie_gateway/src/routing/tests.rs
index 4e7b4ee17..697209073 100644
--- a/packages/sie_gateway/src/routing/tests.rs
+++ b/packages/sie_gateway/src/routing/tests.rs
@@ -228,7 +228,7 @@ fn raw_for_debug_field_absent_without_feature() {
assert!(r.hash.is_some());
}
-// ── Cache-aware (prefix-hash) routing (roadmap §6.3) ───────────────
+// ── Cache-aware (prefix-hash) routing ───────────────
const LONG_PREFIX: &str =
"You are a meticulous assistant. Always answer concisely and cite sources \
diff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rs
index b533441a0..7243ca3f2 100644
--- a/packages/sie_gateway/src/state/config_bootstrap.rs
+++ b/packages/sie_gateway/src/state/config_bootstrap.rs
@@ -49,6 +49,7 @@
//! against `GET /v1/configs/epoch` so any missed NATS deltas after the
//! initial bootstrap are caught within one poll interval.
+use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
@@ -75,7 +76,7 @@ const PATH_SEGMENT: &AsciiSet = &CONTROLS
use crate::state::bundles_hash::BundlesHash;
use crate::state::config_epoch::ConfigEpoch;
use crate::state::model_registry::ModelRegistry;
-use crate::types::bundle::BundleInfo;
+use crate::types::bundle::{BundleInfo, DEFAULT_ENGINE, KNOWN_ENGINES};
use crate::types::model::ModelConfig;
const BOOTSTRAP_TIMEOUT: Duration = Duration::from_secs(10);
@@ -87,6 +88,8 @@ struct ExportSnapshot {
#[serde(default)]
epoch: u64,
#[serde(default)]
+ bundle_config_hashes: HashMap<String, String>,
+ #[serde(default)]
models: Vec<ExportedModel>,
}
@@ -159,12 +162,18 @@ struct BundleSpec {
priority: i32,
#[serde(default)]
adapters: Vec<String>,
+ #[serde(default = "BundleSpec::default_engine")]
+ engine: String,
}
impl BundleSpec {
fn default_priority() -> i32 {
100
}
+
+ fn default_engine() -> String {
+ DEFAULT_ENGINE.to_string()
+ }
}
#[derive(Debug, thiserror::Error)]
@@ -345,10 +354,21 @@ impl BootstrapClient {
url: yaml_url.clone(),
body: format!("malformed bundle YAML: {}", e),
})?;
+ if !KNOWN_ENGINES.contains(&spec.engine.as_str()) {
+ return Err(BootstrapError::BadStatus {
+ status: 200,
+ url: yaml_url,
+ body: format!(
+ "unknown bundle engine {:?}; allowed={:?}",
+ spec.engine, KNOWN_ENGINES
+ ),
+ });
+ }
out.push(BundleInfo {
name: spec.name,
priority: spec.priority,
adapters: spec.adapters,
+ engine: spec.engine,
});
}
@@ -445,6 +465,10 @@ impl BootstrapClient {
}
}
+ if failed == 0 {
+ registry.install_bundle_config_hashes(snapshot.bundle_config_hashes);
+ }
+
Ok(BootstrapOutcome {
epoch: snapshot.epoch,
bundles_hash: pre_bootstrap.bundles_hash,
@@ -665,6 +689,7 @@ mod tests {
name: "default".to_string(),
priority: 10,
adapters: vec!["sie_server.adapters.sentence_transformer".to_string()],
+ engine: DEFAULT_ENGINE.to_string(),
}]);
(registry, temp)
}
@@ -725,6 +750,7 @@ mod tests {
"snapshot_version": 1,
"epoch": 42,
"generated_at": "2026-04-17T00:00:00Z",
+ "bundle_config_hashes": {"default": "control-plane-hash"},
"models": [
{
"model_id": "test/model",
@@ -749,6 +775,10 @@ mod tests {
assert_eq!(outcome.failed, 0);
assert_eq!(outcome.total, 1);
assert!(outcome.is_complete());
+ assert_eq!(
+ registry.compute_bundle_config_hash("default"),
+ "control-plane-hash"
+ );
assert_eq!(
registry.get_model_profile_names("test/model"),
vec!["default".to_string()],
@@ -861,7 +891,7 @@ mod tests {
#[tokio::test]
async fn fetch_epoch_tolerates_missing_bundles_hash_field() {
- // sie-config pre-dating the bundles_hash rollout returns only
+ // Older sie-config returns only
// `{"epoch": N}`. The field carries `#[serde(default)]` so we
// deserialize it as the empty string — the documented
// "nothing to sync" sentinel that makes the poller skip the
@@ -1215,6 +1245,36 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn fetch_bundles_rejects_unknown_engine() {
+ let server = MockServer::start().await;
+ Mock::given(method("GET"))
+ .and(path("/v1/configs/bundles"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
+ "bundles": [{"bundle_id": "bad-engine", "priority": 10, "adapter_count": 1, "source": "filesystem"}],
+ })))
+ .mount(&server)
+ .await;
+ Mock::given(method("GET"))
+ .and(path("/v1/configs/bundles/bad-engine"))
+ .respond_with(ResponseTemplate::new(200).set_body_string(
+ "name: bad-engine\npriority: 10\nengine: candle\nadapters:\n - sie_server.adapters.sentence_transformer\n",
+ ))
+ .mount(&server)
+ .await;
+
+ let client = BootstrapClient::new(server.uri(), None).unwrap();
+ let err = client.fetch_bundles().await.unwrap_err();
+ match err {
+ BootstrapError::BadStatus { status, body, .. } => {
+ assert_eq!(status, 200);
+ assert!(body.contains("unknown bundle engine"));
+ assert!(body.contains("candle"));
+ }
+ other => panic!("expected BadStatus, got {:?}", other),
+ }
+ }
+
/// Bundles fetched from `sie-config` must materialize into the registry
/// before the model-apply loop runs. We start from a registry with the
/// `default` bundle already installed (mimicking a previous successful
@@ -1310,11 +1370,13 @@ mod tests {
name: "a".to_string(),
priority: 10,
adapters: vec!["mod.a".to_string()],
+ engine: DEFAULT_ENGINE.to_string(),
},
BundleInfo {
name: "b".to_string(),
priority: 20,
adapters: vec!["mod.b".to_string()],
+ engine: DEFAULT_ENGINE.to_string(),
},
]);
let mut listed = registry.list_bundles();
@@ -1326,6 +1388,7 @@ mod tests {
name: "a".to_string(),
priority: 10,
adapters: vec!["mod.a".to_string()],
+ engine: DEFAULT_ENGINE.to_string(),
}]);
assert_eq!(registry.list_bundles(), vec!["a".to_string()]);
assert!(registry.get_bundle_info("b").is_none());
diff --git a/packages/sie_gateway/src/state/config_poller.rs b/packages/sie_gateway/src/state/config_poller.rs
index 08fc8586c..34cdb4efe 100644
--- a/packages/sie_gateway/src/state/config_poller.rs
+++ b/packages/sie_gateway/src/state/config_poller.rs
@@ -223,7 +223,7 @@ mod tests {
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
- use crate::types::bundle::BundleInfo;
+ use crate::types::bundle::{BundleInfo, DEFAULT_ENGINE};
/// Empty filesystem registry with a pre-installed `default` bundle — the
/// same shape `BootstrapClient::bootstrap` produces after the bundle
@@ -240,6 +240,7 @@ mod tests {
name: "default".to_string(),
priority: 10,
adapters: vec!["sie_server.adapters.sentence_transformer".to_string()],
+ engine: DEFAULT_ENGINE.to_string(),
}]);
(registry, temp)
}
diff --git a/packages/sie_gateway/src/state/k8s_pool_backend.rs b/packages/sie_gateway/src/state/k8s_pool_backend.rs
index 2470f963f..5d708fe29 100644
--- a/packages/sie_gateway/src/state/k8s_pool_backend.rs
+++ b/packages/sie_gateway/src/state/k8s_pool_backend.rs
@@ -541,7 +541,7 @@ mod tests {
#[test]
fn test_cas_retry_constants() {
- // Verify the retry parameters match the specification (PRD S9.3)
+ // Verify the retry parameters used by compare-and-swap lease updates.
assert_eq!(CAS_MAX_RETRIES, 10);
assert!((CAS_BASE_DELAY_MS - 100.0).abs() < f64::EPSILON);
assert!((CAS_BACKOFF_FACTOR - 1.5).abs() < f64::EPSILON);
diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rs
index 51ac08705..39b0f3216 100644
--- a/packages/sie_gateway/src/state/model_registry.rs
+++ b/packages/sie_gateway/src/state/model_registry.rs
@@ -1,4 +1,4 @@
-use std::collections::{HashMap, HashSet};
+use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
@@ -6,7 +6,7 @@ use arc_swap::ArcSwap;
use sha2::{Digest, Sha256};
use tracing::{debug, error, info, warn};
-use crate::types::bundle::BundleInfo;
+use crate::types::bundle::{engine_adapter_prefixes, BundleInfo, DEFAULT_ENGINE, KNOWN_ENGINES};
use crate::types::model::{
CanonicalProfile, ModelConfig, ModelEntry, ModelInfoExtras, ProfileConfig,
};
@@ -259,7 +259,7 @@ impl ModelRegistry {
let priority = data.get("priority").and_then(|v| v.as_i64()).unwrap_or(100) as i32;
- let adapters = data
+ let adapters: Vec<String> = data
.get("adapters")
.and_then(|v| v.as_sequence())
.map(|seq| {
@@ -269,10 +269,57 @@ impl ModelRegistry {
})
.unwrap_or_default();
+ // Engine: defaults to "pytorch" for back-compat with bundle
+ // YAMLs written before this field existed. Unknown values
+ // are a hard error — silently coercing to the default would
+ // let a typo'd ``engine: pytroch`` mis-route traffic and
+ // push diagnosis to the symptom side. Mirrors the
+ // equivalent check in ``sie_config/model_registry.py::reload``.
+ let engine = data
+ .get("engine")
+ .and_then(|v| v.as_str())
+ .unwrap_or(DEFAULT_ENGINE)
+ .to_string();
+ if !KNOWN_ENGINES.contains(&engine.as_str()) {
+ return Err(format!(
+ "bundle {:?} declares engine={:?} which is not in KNOWN_ENGINES={:?}; \
+ update the bundle YAML or add the engine to types::bundle::KNOWN_ENGINES",
+ name, engine, KNOWN_ENGINES,
+ )
+ .into());
+ }
+
+ // Adapter-namespace consistency check. The matcher
+ // (``resolve_bundle`` and ``compute_bundle_config_hash``)
+ // intersects ``bundle.adapters`` with each model's
+ // ``adapter_path`` modules — so a bundle that accidentally
+ // lists adapters outside this engine's namespace would
+ // produce ``UnsupportedModel`` IPC NAKs at runtime.
+ // Catching this at config-load time turns it into a
+ // deploy-time signal.
+ let expected_prefixes = engine_adapter_prefixes(&engine);
+ if !expected_prefixes.is_empty() {
+ let bad: Vec<&String> = adapters
+ .iter()
+ .filter(|a| !expected_prefixes.iter().any(|p| a.starts_with(p)))
+ .collect();
+ if !bad.is_empty() {
+ warn!(
+ bundle = %name,
+ engine = %engine,
+ expected = ?expected_prefixes,
+ bad_adapters = ?bad,
+ "bundle lists adapter(s) outside the expected namespace(s); \
+ these will not be servable by a worker speaking this engine"
+ );
+ }
+ }
+
Ok(BundleInfo {
name,
priority,
adapters,
+ engine,
})
}
@@ -680,6 +727,28 @@ impl ModelRegistry {
&self,
model: &str,
bundle_override: Option<&str>,
+ ) -> Result<String, ResolveError> {
+ self.resolve_bundle_with_engine(model, bundle_override, None)
+ }
+
+ /// Engine-aware variant of [`Self::resolve_bundle`].
+ ///
+ /// When `engine_filter` is `Some(engine)`, the candidate bundle
+ /// list for `model` is intersected with bundles whose
+ /// `BundleInfo.engine` matches before applying the existing
+ /// `(priority, name)` sort. This is what implements the
+ /// `X-SIE-Engine` header at the proxy layer; today only
+ /// `"pytorch"` is recognised so the filter is effectively a
+ /// no-op, but the plumbing is preserved for the day a second
+ /// engine lands.
+ ///
+ /// `engine_filter = None` is the back-compat path used by callers
+ /// that don't care about engine selection.
+ pub fn resolve_bundle_with_engine(
+ &self,
+ model: &str,
+ bundle_override: Option<&str>,
+ engine_filter: Option<&str>,
) -> Result<String, ResolveError> {
let snap = self.snapshot.load();
@@ -704,18 +773,36 @@ impl ModelRegistry {
}
};
+ let filtered: Vec<String> = match engine_filter {
+ Some(eng) => model_entry
+ .bundles
+ .iter()
+ .filter(|b| snap.bundles.get(*b).is_some_and(|info| info.engine == eng))
+ .cloned()
+ .collect(),
+ None => model_entry.bundles.clone(),
+ };
+
+ if filtered.is_empty() {
+ return Err(ResolveError::BundleConflict(BundleConflictError {
+ model: model.to_string(),
+ bundle: engine_filter.unwrap_or("").to_string(),
+ compatible_bundles: model_entry.bundles.clone(),
+ }));
+ }
+
if let Some(override_bundle) = bundle_override {
- if model_entry.bundles.contains(&override_bundle.to_string()) {
+ if filtered.contains(&override_bundle.to_string()) {
return Ok(override_bundle.to_string());
}
return Err(ResolveError::BundleConflict(BundleConflictError {
model: model.to_string(),
bundle: override_bundle.to_string(),
- compatible_bundles: model_entry.bundles.clone(),
+ compatible_bundles: filtered,
}));
}
- Ok(model_entry.bundles[0].clone())
+ Ok(filtered[0].clone())
}
pub fn model_exists(&self, model: &str) -> bool {
@@ -881,6 +968,26 @@ impl ModelRegistry {
.unwrap_or_default()
}
+ pub fn install_bundle_config_hashes(&self, hashes: HashMap<String, String>) {
+ if hashes.is_empty() {
+ return;
+ }
+
+ let _guard = self.write_lock.lock().unwrap();
+ let mut snap = (**self.snapshot.load()).clone();
+ for (bundle_name, hash) in hashes {
+ if !snap.bundles.contains_key(&bundle_name) {
+ continue;
+ }
+ if hash.is_empty() {
+ snap.bundle_config_hashes.remove(&bundle_name);
+ } else {
+ snap.bundle_config_hashes.insert(bundle_name, hash);
+ }
+ }
+ self.snapshot.store(Arc::new(snap));
+ }
+
/// Compute the config hash for a bundle (expensive: sort + JSON + SHA-256).
/// Called during reload() and add_model_config() to pre-populate the cache.
fn hash_bundle_config(
@@ -902,6 +1009,10 @@ impl ModelRegistry {
model_names.sort();
for model_name in model_names {
+ if Self::is_synthetic_profile_variant(model_name, models) {
+ continue;
+ }
+
let model_entry = &models[model_name];
if !model_entry.bundles.contains(&bundle_id.to_string()) {
continue;
@@ -914,7 +1025,7 @@ impl ModelRegistry {
continue;
}
- let mut profiles_for_hash: Vec<serde_json::Value> = Vec::new();
+ let mut profiles_for_hash: Vec<BTreeMap<&str, serde_json::Value>> = Vec::new();
let mut profile_names: Vec<&String> = model_entry.profile_names.iter().collect();
profile_names.sort();
@@ -927,24 +1038,39 @@ impl ModelRegistry {
}
}
- let config = serde_json::json!({
- "adapter_path": p_cfg.adapter_path,
- "max_batch_tokens": p_cfg.max_batch_tokens,
- "compute_precision": p_cfg.compute_precision,
- "adapter_options": p_cfg.adapter_options,
- });
-
- profiles_for_hash.push(serde_json::json!({
- "name": pname,
- "config": config,
- }));
+ let mut config = BTreeMap::new();
+ config.insert(
+ "adapter_options",
+ serde_json::to_value(&p_cfg.adapter_options)
+ .unwrap_or(serde_json::Value::Null),
+ );
+ config.insert(
+ "adapter_path",
+ serde_json::to_value(&p_cfg.adapter_path)
+ .unwrap_or(serde_json::Value::Null),
+ );
+ config.insert(
+ "compute_precision",
+ serde_json::to_value(&p_cfg.compute_precision)
+ .unwrap_or(serde_json::Value::Null),
+ );
+ config.insert(
+ "max_batch_tokens",
+ serde_json::to_value(p_cfg.max_batch_tokens)
+ .unwrap_or(serde_json::Value::Null),
+ );
+
+ let mut profile = BTreeMap::new();
+ profile.insert("config", serde_json::to_value(config).unwrap());
+ profile.insert("name", serde_json::Value::String(pname.clone()));
+ profiles_for_hash.push(profile);
}
}
- items.push(serde_json::json!({
- "sie_id": model_name,
- "profiles": profiles_for_hash,
- }));
+ let mut item = BTreeMap::new();
+ item.insert("profiles", serde_json::to_value(profiles_for_hash).unwrap());
+ item.insert("sie_id", serde_json::Value::String(model_name.clone()));
+ items.push(serde_json::to_value(item).unwrap());
}
if items.is_empty() {
@@ -957,6 +1083,17 @@ impl ModelRegistry {
format!("{:x}", hasher.finalize())
}
+ fn is_synthetic_profile_variant(
+ model_name: &str,
+ models: &HashMap<String, ModelEntry>,
+ ) -> bool {
+ model_name
+ .rsplit_once(':')
+ .is_some_and(|(base_model_name, profile_name)| {
+ !profile_name.is_empty() && models.contains_key(base_model_name)
+ })
+ }
+
pub fn add_model_config(&self, config: ModelConfig) -> Result<AddModelConfigOutcome, String> {
self.add_model_config_inner(config, false)
}
@@ -2132,8 +2269,8 @@ adapters:
/// cold-start and on epoch-poller catch-up. It treats the export as
/// the source of truth and overrides any divergent stored profile
/// config (with a warn log) instead of failing the entire bootstrap.
- /// Reproduces the v0.3.2 -> v0.3.3 `nemotron-8b` adapter swap that
- /// wedged sie-test until a manual `kubectl rollout restart`.
+ /// Reproduces the `nemotron-8b` adapter swap that wedged sie-test
+ /// until a manual gateway restart.
#[test]
fn test_add_model_config_authoritative_overrides_conflicting_profile() {
let (_dir, bundles_dir, models_dir) = create_test_dirs();
@@ -2481,6 +2618,93 @@ profiles:
assert!(empty.is_empty());
}
+ #[test]
+ fn test_compute_bundle_config_hash_ignores_profile_variant_aliases() {
+ let (_dir, bundles_dir, models_dir) = create_test_dirs();
+
+ fs::write(
+ bundles_dir.join("default.yaml"),
+ r#"
+name: default
+priority: 10
+adapters:
+ - sie_server.adapters.sentence_transformer
+"#,
+ )
+ .unwrap();
+
+ fs::write(
+ models_dir.join("example.yaml"),
+ r#"
+name: example/model
+profiles:
+ default:
+ adapter_path: "sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"
+ max_batch_tokens: 4096
+ small:
+ adapter_path: "sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"
+ max_batch_tokens: 2048
+ compute_precision: fp16
+"#,
+ )
+ .unwrap();
+
+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);
+ assert!(registry.model_exists("example/model:small"));
+
+ assert_eq!(
+ registry.compute_bundle_config_hash("default"),
+ "a4ce038148c529799f88014dde9360175c9e9536f353162cf3bc312c09f4cd23"
+ );
+ }
+
+ #[test]
+ fn test_install_bundle_config_hashes_overrides_local_hash() {
+ let (_dir, bundles_dir, models_dir) = create_test_dirs();
+
+ fs::write(
+ bundles_dir.join("default.yaml"),
+ r#"
+name: default
+priority: 10
+adapters:
+ - sie_server.adapters.sentence_transformer
+"#,
+ )
+ .unwrap();
+
+ fs::write(
+ models_dir.join("bge-m3.yaml"),
+ r#"
+name: BAAI/bge-m3
+profiles:
+ default:
+ adapter_path: "sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"
+ max_batch_tokens: 4096
+"#,
+ )
+ .unwrap();
+
+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);
+ assert_ne!(
+ registry.compute_bundle_config_hash("default"),
+ "authority-hash"
+ );
+
+ registry.install_bundle_config_hashes(HashMap::from([(
+ "default".to_string(),
+ "authority-hash".to_string(),
+ )]));
+ assert_eq!(
+ registry.compute_bundle_config_hash("default"),
+ "authority-hash"
+ );
+
+ registry
+ .install_bundle_config_hashes(HashMap::from([("default".to_string(), String::new())]));
+ assert_eq!(registry.compute_bundle_config_hash("default"), "");
+ }
+
#[test]
fn test_concurrent_add_model_config_preserves_all_writes() {
// Fix #4 regression: without `write_lock`, two threads that call
@@ -2585,4 +2809,111 @@ profiles:
assert_eq!(registry.list_models().len(), 1);
assert_eq!(registry.list_bundles().len(), 1);
}
+
+ // ---------------------------------------------------------------
+ // engine field. These tests pin the wire shape and validation
+ // contract so a future refactor can't quietly drop the field.
+ // Today only ``"pytorch"`` is recognised — see ``KNOWN_ENGINES``.
+ // ---------------------------------------------------------------
+
+ #[test]
+ fn test_engine_defaults_to_pytorch_when_omitted() {
+ let (_dir, bundles_dir, models_dir) = create_test_dirs();
+ fs::write(
+ bundles_dir.join("default.yaml"),
+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.sentence_transformer\n",
+ )
+ .unwrap();
+
+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);
+ let info = registry.get_bundle_info("default").unwrap();
+ assert_eq!(info.engine, DEFAULT_ENGINE);
+ assert_eq!(info.engine, "pytorch");
+ }
+
+ #[test]
+ fn test_engine_unknown_value_skips_bundle() {
+ // Unknown engine values are a hard error — silently coercing
+ // would let a typo'd ``engine: pytroch`` mis-route traffic.
+ // We surface this as "bundle skipped";
+ // the registry still loads, but the bad bundle is absent.
+ let (_dir, bundles_dir, models_dir) = create_test_dirs();
+ fs::write(
+ bundles_dir.join("good.yaml"),
+ "name: good\npriority: 10\nadapters:\n - sie_server.adapters.sentence_transformer\n",
+ )
+ .unwrap();
+ fs::write(
+ bundles_dir.join("typo.yaml"),
+ "name: typo\nengine: pytroch\npriority: 10\nadapters:\n - sie_server.adapters.foo\n",
+ )
+ .unwrap();
+
+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);
+ let bundles = registry.list_bundles();
+ assert!(bundles.contains(&"good".to_string()));
+ assert!(
+ !bundles.contains(&"typo".to_string()),
+ "bundle with unknown engine must be rejected at load time, not silently coerced"
+ );
+ }
+
+ #[test]
+ fn test_resolve_bundle_with_engine_filter_passes_through_for_only_engine() {
+ // Today there's exactly one engine in ``KNOWN_ENGINES``
+ // (``"pytorch"``), so the engine-filter codepath must be a
+ // no-op for any pytorch-backed bundle: with or without the
+ // filter, the same bundle resolves. Re-introduce a
+ // multi-engine version of this test when a second engine
+ // lands.
+ let (_dir, bundles_dir, models_dir) = create_test_dirs();
+ fs::write(
+ bundles_dir.join("default.yaml"),
+ r#"
+name: default
+priority: 10
+adapters:
+ - sie_server.adapters.bert_flash
+"#,
+ )
+ .unwrap();
+ fs::write(
+ models_dir.join("bert.yaml"),
+ r#"
+name: example/bert
+profiles:
+ default:
+ adapter_path: "sie_server.adapters.bert_flash:Adapter"
+"#,
+ )
+ .unwrap();
+
+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);
+
+ let plain = registry.resolve_bundle("example/bert", None).unwrap();
+ assert_eq!(plain, "default");
+
+ let filtered = registry
+ .resolve_bundle_with_engine("example/bert", None, Some("pytorch"))
+ .unwrap();
+ assert_eq!(filtered, "default");
+ }
+
+ #[test]
+ fn test_engine_known_engines_lockstep_with_bundle_module() {
+ // Belt-and-braces: prove the registry's KNOWN_ENGINES import
+ // resolves to the exact constant exported by the bundle types
+ // module, so a future move/rename trips compile-time rather
+ // than runtime. Also enforces the invariant that every known
+ // engine has a non-empty adapter-prefix list — without it the
+ // namespace check is a no-op.
+ for engine in KNOWN_ENGINES {
+ assert!(
+ !engine_adapter_prefixes(engine).is_empty(),
+ "every engine in KNOWN_ENGINES must have a non-empty \
+ adapter-prefix list (engine={engine}); add it to \
+ engine_adapter_prefixes() in types/bundle.rs"
+ );
+ }
+ }
}
diff --git a/packages/sie_gateway/src/state/pool_manager.rs b/packages/sie_gateway/src/state/pool_manager.rs
index b20533da6..63c8492a6 100644
--- a/packages/sie_gateway/src/state/pool_manager.rs
+++ b/packages/sie_gateway/src/state/pool_manager.rs
@@ -104,6 +104,9 @@ impl PoolManager {
let mut pools = self.pools.write().await;
let mut count = 0;
for pool in k8s_pools {
+ if !Self::should_restore_pool_from_k8s(&pool) {
+ continue;
+ }
if !pools.contains_key(&pool.spec.name) {
info!(pool = %pool.spec.name, "restored pool from K8s");
pools.insert(pool.spec.name.clone(), pool);
@@ -113,6 +116,10 @@ impl PoolManager {
Ok(count)
}
+ fn should_restore_pool_from_k8s(pool: &Pool) -> bool {
+ pool.spec.name != DEFAULT_POOL_NAME
+ }
+
fn now_secs() -> f64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -1325,6 +1332,28 @@ mod tests {
assert_eq!(count, 0);
}
+ #[test]
+ fn test_restore_from_k8s_skips_default_pool() {
+ let pool = Pool {
+ spec: PoolSpec {
+ name: DEFAULT_POOL_NAME.to_string(),
+ bundle: None,
+ gpus: HashMap::new(),
+ gpu_caps: HashMap::new(),
+ ttl_seconds: None,
+ minimum_worker_count: 0,
+ },
+ status: PoolStatus {
+ state: PoolState::Pending,
+ assigned_workers: Vec::new(),
+ created_at: 9999.0,
+ last_renewed: 9999.0,
+ },
+ };
+
+ assert!(!PoolManager::should_restore_pool_from_k8s(&pool));
+ }
+
#[tokio::test]
async fn test_k8s_backend_field_defaults_none() {
let pm = PoolManager::new(vec!["l4-spot".to_string()]);
diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rs
index 06ea73b2d..42c241029 100644
--- a/packages/sie_gateway/src/state/worker_registry.rs
+++ b/packages/sie_gateway/src/state/worker_registry.rs
@@ -394,14 +394,28 @@ impl WorkerRegistry {
unhealthy
}
+ /// Resolve the NATS pool name for queue mode routing.
+ /// Finds a healthy worker matching the bundle (and optionally GPU) that has
+ /// a pool_name set and reports the expected bundle config hash.
+ #[cfg(test)]
+ pub async fn resolve_queue_pool(
+ &self,
+ bundle: &str,
+ gpu: &str,
+ bundle_config_hash: &str,
+ ) -> Option<String> {
+ self.resolve_queue_pool_matching(bundle, gpu, None, bundle_config_hash)
+ }
+
/// Resolve the NATS pool name, constrained to a specific logical pool.
pub async fn resolve_queue_pool_in_pool(
&self,
bundle: &str,
gpu: &str,
pool_name: &str,
+ bundle_config_hash: &str,
) -> Option<String> {
- self.resolve_queue_pool_matching(bundle, gpu, Some(pool_name))
+ self.resolve_queue_pool_matching(bundle, gpu, Some(pool_name), bundle_config_hash)
}
fn resolve_queue_pool_matching(
@@ -409,13 +423,14 @@ impl WorkerRegistry {
bundle: &str,
gpu: &str,
pool_name: Option<&str>,
+ bundle_config_hash: &str,
) -> Option<String> {
let snap = self.snapshot.load();
// `by_bundle` is keyed with `w.bundle.to_lowercase()` in
// `RegistrySnapshot::build`, so the lookup has to use the
// same Unicode-aware lowercase to keep non-ASCII bundle
- // ids reachable (review feedback on PR #716). We only
+ // ids reachable. We only
// allocate once per request on this branch, so the cost
// is negligible compared to the per-candidate
// `to_lowercase()` that `eq_ignore_ascii_case` replaced
@@ -438,6 +453,9 @@ impl WorkerRegistry {
if !gpu.is_empty() && !w.machine_profile.eq_ignore_ascii_case(gpu) {
continue;
}
+ if !bundle_config_hash_matches(&w.bundle_config_hash, bundle_config_hash) {
+ continue;
+ }
return Some(w.pool_name.clone());
}
None
@@ -569,6 +587,10 @@ impl WorkerRegistry {
}
}
+fn bundle_config_hash_matches(worker_hash: &str, expected_hash: &str) -> bool {
+ expected_hash.is_empty() || worker_hash == expected_hash
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1168,7 +1190,7 @@ mod tests {
msg.machine_profile = "l4-spot".into();
reg.update_worker("http://w1:8080", msg).await;
- let pool = reg.resolve_queue_pool_matching("default", "l4-spot", None);
+ let pool = reg.resolve_queue_pool("default", "l4-spot", "").await;
assert_eq!(pool, Some("pool-a".to_string()));
}
@@ -1190,12 +1212,12 @@ mod tests {
reg.update_worker("http://w2:8080", isolated_msg).await;
let pool = reg
- .resolve_queue_pool_in_pool("default", "l4-spot", "eval-l4")
+ .resolve_queue_pool_in_pool("default", "l4-spot", "eval-l4", "")
.await;
assert_eq!(pool, Some("eval-l4".to_string()));
let missing = reg
- .resolve_queue_pool_in_pool("default", "l4-spot", "missing")
+ .resolve_queue_pool_in_pool("default", "l4-spot", "missing", "")
.await;
assert!(missing.is_none());
}
@@ -1209,7 +1231,7 @@ mod tests {
reg.update_worker("http://w1:8080", msg).await;
// No GPU filter
- let pool = reg.resolve_queue_pool_matching("premium", "", None);
+ let pool = reg.resolve_queue_pool("premium", "", "").await;
assert_eq!(pool, Some("pool-b".to_string()));
}
@@ -1221,7 +1243,7 @@ mod tests {
msg.bundle = "default".into();
reg.update_worker("http://w1:8080", msg).await;
- let pool = reg.resolve_queue_pool_matching("premium", "", None);
+ let pool = reg.resolve_queue_pool("premium", "", "").await;
assert!(pool.is_none());
}
@@ -1233,7 +1255,7 @@ mod tests {
msg.bundle = "default".into();
reg.update_worker("http://w1:8080", msg).await;
- let pool = reg.resolve_queue_pool_matching("default", "", None);
+ let pool = reg.resolve_queue_pool("default", "", "").await;
assert!(pool.is_none());
}
@@ -1246,10 +1268,47 @@ mod tests {
reg.update_worker("http://w1:8080", msg).await;
reg.mark_unhealthy("http://w1:8080").await;
- let pool = reg.resolve_queue_pool_matching("default", "", None);
+ let pool = reg.resolve_queue_pool("default", "", "").await;
assert!(pool.is_none());
}
+ #[tokio::test]
+ async fn test_resolve_queue_pool_requires_matching_config_hash_when_expected() {
+ let reg = registry();
+ let mut stale = make_msg(true);
+ stale.name = "stale".into();
+ stale.pool_name = "old-pool".into();
+ stale.bundle = "default".into();
+ stale.bundle_config_hash = "old".into();
+ reg.update_worker("http://w1:8080", stale).await;
+
+ let mut current = make_msg(true);
+ current.name = "current".into();
+ current.pool_name = "current-pool".into();
+ current.bundle = "default".into();
+ current.bundle_config_hash = "new".into();
+ reg.update_worker("http://w2:8080", current).await;
+
+ let pool = reg.resolve_queue_pool("default", "", "new").await;
+ assert_eq!(pool, Some("current-pool".to_string()));
+
+ let missing = reg.resolve_queue_pool("default", "", "missing").await;
+ assert!(missing.is_none());
+ }
+
+ #[tokio::test]
+ async fn test_resolve_queue_pool_empty_expected_hash_keeps_legacy_match() {
+ let reg = registry();
+ let mut msg = make_msg(true);
+ msg.pool_name = "pool-a".into();
+ msg.bundle = "default".into();
+ msg.bundle_config_hash = String::new();
+ reg.update_worker("http://w1:8080", msg).await;
+
+ let pool = reg.resolve_queue_pool("default", "", "").await;
+ assert_eq!(pool, Some("pool-a".to_string()));
+ }
+
// ── dispatch_workers_for / ring_snapshot_for ───────────────────
async fn make_dispatch_msg(
diff --git a/packages/sie_gateway/src/types/bundle.rs b/packages/sie_gateway/src/types/bundle.rs
index 505ca3082..94ece1699 100644
--- a/packages/sie_gateway/src/types/bundle.rs
+++ b/packages/sie_gateway/src/types/bundle.rs
@@ -1,5 +1,24 @@
use serde::{Deserialize, Serialize};
+/// Recognised execution engines for the ``engine`` bundle field.
+///
+/// We only ship one engine today (the Python ``sie_server`` adapter
+/// image). The plumbing — ``X-SIE-Engine`` header,
+/// ``resolve_bundle_with_engine``, ``WorkItem.engine`` — is kept
+/// alive as the contract for re-introducing a second engine later;
+/// for now there is exactly one valid value here.
+///
+/// Mirrors ``sie_config.model_registry.KNOWN_ENGINES`` on the Python
+/// side. Drift is a quiet mis-routing footgun, so both ends are kept
+/// in lock-step.
+pub const KNOWN_ENGINES: &[&str] = &["pytorch"];
+
+/// Default engine when a bundle YAML omits the field. Same as the
+/// only entry in ``KNOWN_ENGINES`` today; kept as a separate
+/// constant so the asymmetric "default vs known" contract still
+/// reads cleanly when a second engine lands.
+pub const DEFAULT_ENGINE: &str = "pytorch";
+
#[allow(dead_code)]
#[derive(Debug, Clone, Deserialize)]
pub struct BundleConfig {
@@ -10,6 +29,12 @@ pub struct BundleConfig {
pub adapters: Vec<String>,
#[serde(default)]
pub default: bool,
+ /// Execution engine the bundle's worker image speaks. Today
+ /// only ``"pytorch"`` (the Python adapter image) is recognised;
+ /// see ``KNOWN_ENGINES`` for the load-time check. Defaults to
+ /// ``"pytorch"`` for back-compat with pre-engine bundle YAMLs.
+ #[serde(default = "default_engine")]
+ pub engine: String,
#[serde(default)]
pub machine_profiles: Vec<BundleMachineProfile>,
#[serde(default)]
@@ -23,6 +48,11 @@ fn default_priority() -> i32 {
100
}
+#[allow(dead_code)]
+fn default_engine() -> String {
+ DEFAULT_ENGINE.to_string()
+}
+
#[allow(dead_code)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BundleMachineProfile {
@@ -42,6 +72,31 @@ pub struct BundleInfo {
pub name: String,
pub priority: i32,
pub adapters: Vec<String>,
+ /// See [`BundleConfig::engine`] — surfaced in routing logs,
+ /// metrics, and the published ``WorkItem.engine`` so workers
+ /// can verify they speak the right engine. Today only
+ /// ``"pytorch"`` is recognised (see ``KNOWN_ENGINES``).
+ #[allow(dead_code)]
+ pub engine: String,
+}
+
+/// Adapter-module prefixes considered legal for each engine.
+///
+/// The gateway's matcher intersects ``bundle.adapters`` with each
+/// model's ``adapter_path`` modules — so a bundle that accidentally
+/// lists an adapter outside this engine's namespace is caught at
+/// config-load time rather than producing ``UnsupportedModel`` IPC
+/// NAKs at runtime.
+///
+/// Returns an empty slice for unknown engines (caller decides what
+/// to do — typically the load already rejected the bundle, so this
+/// path is unreachable).
+#[allow(dead_code)]
+pub fn engine_adapter_prefixes(engine: &str) -> &'static [&'static str] {
+ match engine {
+ "pytorch" => &["sie_server.adapters."],
+ _ => &[],
+ }
}
#[cfg(test)]
@@ -73,6 +128,27 @@ default: true
assert!(config.adapters.is_empty());
assert!(!config.default);
assert!(config.machine_profiles.is_empty());
+ assert_eq!(config.engine, DEFAULT_ENGINE);
+ }
+
+ #[test]
+ fn test_engine_adapter_prefixes() {
+ assert_eq!(
+ engine_adapter_prefixes("pytorch"),
+ &["sie_server.adapters."]
+ );
+ // Unknown engine → empty slice. Caller is expected to have
+ // already rejected the bundle by checking ``KNOWN_ENGINES``.
+ assert!(engine_adapter_prefixes("candle").is_empty());
+ assert!(engine_adapter_prefixes("unknown").is_empty());
+ }
+
+ #[test]
+ fn test_known_engines_only_pytorch() {
+ // Lock-step parity with sie_config.model_registry.KNOWN_ENGINES.
+ // Today there's exactly one engine; this assertion catches
+ // drift at PR review time when a second engine is added.
+ assert_eq!(KNOWN_ENGINES, &["pytorch"]);
}
#[test]
diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rs
index 81438806c..9e9beff24 100644
--- a/packages/sie_gateway/src/types/model.rs
+++ b/packages/sie_gateway/src/types/model.rs
@@ -764,7 +764,7 @@ tasks:
#[test]
fn test_model_info_extras_generate_task_surfaces_tokens_output() {
- // Walking-skeleton (M4 Req 2): a generate task surfaces ``["tokens"]`` so
+ // A generate task surfaces ``["tokens"]`` so
// ``GET /v1/models`` advertises the capability accurately. Without
// this, generate-only models report ``outputs=[]`` and downstream
// clients can't tell what the model produces.
diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.toml
index a4971faa0..8e003ace9 100644
--- a/packages/sie_sdk/pyproject.toml
+++ b/packages/sie_sdk/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-sdk"
-version = "0.4.1"
+version = "0.4.2"
description = "Search Inference Engine - Python SDK"
requires-python = ">=3.12"
license = { text = "Apache-2.0" }
@@ -19,7 +19,7 @@ dependencies = [
# Data handling
"numpy>=2,<3",
- "pillow>=11,<12",
+ "pillow>=12.2.0",
# Config parsing (bundle utilities)
"pyyaml>=6,<7",
diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.py
index eab40cef8..fd2e24d5f 100644
--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py
+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py
@@ -177,6 +177,7 @@ def check_version_skew(sdk_version: str, server_version: str) -> str | None:
f"server {server_version}. Consider upgrading."
)
except (ValueError, IndexError):
+ # Best-effort version compare; non-semver inputs silently skip the warning.
pass
return None
@@ -428,6 +429,7 @@ def get_error_detail(response: _HttpResponse) -> dict[str, Any] | None:
if isinstance(detail, dict):
return detail
except (ValueError, KeyError, TypeError):
+ # Malformed error body — caller treats as "no detail" and falls back.
pass
return None
diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.py
index a5fc610eb..696c685d6 100644
--- a/packages/sie_sdk/src/sie_sdk/client/async_.py
+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py
@@ -2,7 +2,7 @@
Provides an async Python client for the Search Inference Engine server.
-Per DESIGN.md Section 8.1 and 9.6 - Async variants for all methods.
+Async variants for all client methods.
Example:
>>> async with SIEAsyncClient("http://localhost:8080") as client:
@@ -309,7 +309,7 @@ class _AioResponse:
class SIEAsyncClient:
"""Async client for the Search Inference Engine.
- Per DESIGN.md Section 8.1 and 9.6 - Async variants for all methods.
+ Async variants for all client methods.
Args:
base_url: Base URL of the SIE server (e.g., "http://localhost:8080").
@@ -1083,7 +1083,7 @@ class SIEAsyncClient:
single_item = not isinstance(items, list)
items_list = [items] if single_item else items
- # Convert images to JPEG bytes for transport (per design.md Section 4.3)
+ # Convert images to JPEG bytes for transport.
# Only copy items that have images — text-only items are passed through directly
items_for_wire = [
convert_item_images({**item}) if "images" in item else item # ty: ignore[invalid-argument-type]
@@ -1435,7 +1435,6 @@ class SIEAsyncClient:
if self._api_key:
headers["Authorization"] = f"Bearer {self._api_key}"
- last_error: Exception | None = None
for path in paths:
ws_url = self._ws_url(path)
try:
@@ -1449,15 +1448,10 @@ class SIEAsyncClient:
yield data
return
except websockets.exceptions.InvalidStatus as e:
- last_error = e
raise RequestError(f"WebSocket connection failed: {e.response.status_code}") from e
except (websockets.WebSocketException, OSError, json.JSONDecodeError) as e:
- last_error = e
raise SIEConnectionError(f"WebSocket error: {e}") from e
- if last_error:
- raise SIEConnectionError(f"WebSocket connection failed: {last_error}") from last_error
-
async def get_capacity(self, *, gpu: str | None = None) -> CapacityInfo:
"""Async version of get_capacity(). See SIEClient.get_capacity() for details."""
try:
diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.py
index d0edcd96d..06267cbdc 100644
--- a/packages/sie_sdk/src/sie_sdk/client/sync.py
+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py
@@ -2,8 +2,7 @@
Provides a Python client for the Search Inference Engine server.
-Per DESIGN.md Section 8.1:
-- Synchronous encode() method (async variants in M5)
+- Synchronous encode() method
- Accepts Item or list[Item], returns matching shape
- Uses msgpack for efficient serialization with native numpy support
- Returns numpy arrays directly
@@ -25,7 +24,7 @@ GPU Selection and Auto-Retry:
... provision_timeout_s=900, # Wait up to 15 min
... )
-Resource Pools (per DESIGN.md Section 10.3):
+Resource Pools:
>>> # Create pool for isolated capacity
>>> client = SIEClient("http://gateway:8080")
>>> client.create_pool("eval-bench", {"l4": 2}) # 2 L4 GPUs
@@ -269,8 +268,6 @@ def _handle_oom_retry(
class SIEClient:
"""Client for the Search Inference Engine.
- Per DESIGN.md Section 8.1 and 9.6.
-
Args:
base_url: Base URL of the SIE server (e.g., "http://localhost:8080").
timeout_s: Request timeout in seconds (default: 30.0).
@@ -928,8 +925,6 @@ class SIEClient:
) -> EncodeResult | list[EncodeResult]:
"""Encode items into vector representations.
- Per DESIGN.md Section 8.1.
-
Args:
model: Model name to use for encoding (e.g., "bge-m3").
items: Single Item or list of Items to encode.
@@ -1040,7 +1035,7 @@ class SIEClient:
single_item = not isinstance(items, list)
items_list = [items] if single_item else items
- # Convert images to JPEG bytes for transport (per design.md Section 4.3)
+ # Convert images to JPEG bytes for transport.
# Only copy items that have images — text-only items are passed through directly
items_for_wire = [
convert_item_images({**item}) if "images" in item else item # ty: ignore[invalid-argument-type]
@@ -1437,7 +1432,6 @@ class SIEClient:
if self._api_key:
headers["Authorization"] = f"Bearer {self._api_key}"
- last_error: Exception | None = None
for path in paths:
ws_url = self._ws_url(path)
try:
@@ -1451,7 +1445,6 @@ class SIEClient:
yield data
return
except InvalidStatus as e:
- last_error = e
status = (
getattr(e, "status_code", None)
or getattr(e, "status", None)
@@ -1459,15 +1452,10 @@ class SIEClient:
)
raise RequestError(f"WebSocket connection failed: {status}") from e
except WebSocketException as e:
- last_error = e
raise SIEConnectionError(f"WebSocket error: {e}") from e
except (OSError, json.JSONDecodeError) as e:
- last_error = e
raise SIEConnectionError(f"WebSocket error: {e}") from e
- if last_error:
- raise SIEConnectionError(f"WebSocket connection failed: {last_error}") from last_error
-
def get_capacity(self, *, gpu: str | None = None) -> CapacityInfo:
"""Get current cluster capacity information.
diff --git a/packages/sie_sdk/src/sie_sdk/images.py b/packages/sie_sdk/src/sie_sdk/images.py
index 7a95fd832..71d02eb62 100644
--- a/packages/sie_sdk/src/sie_sdk/images.py
+++ b/packages/sie_sdk/src/sie_sdk/images.py
@@ -1,6 +1,6 @@
"""Image conversion utilities for SIE SDK.
-Per DESIGN.md Section 4.3, images are serialized as JPEG bytes for transport.
+Images are serialized as JPEG bytes for transport.
This module handles conversion from various input formats to JPEG bytes.
Wire format: raw JPEG bytes in msgpack (no base64 encoding).
@@ -20,7 +20,7 @@ if TYPE_CHECKING:
# Type alias for all supported image input formats
ImageLike = Union[Image.Image, "NDArray[Any]", bytes, str, Path]
-# Default JPEG quality (per design.md)
+# Default JPEG quality for image transport.
DEFAULT_JPEG_QUALITY = 95
@@ -31,7 +31,7 @@ def to_jpeg_bytes(
) -> bytes:
"""Convert various image formats to JPEG bytes for wire transport.
- Per DESIGN.md Section 4.3, supports:
+ Supports:
- PIL.Image → JPEG bytes
- np.ndarray (H,W,C) → PIL → JPEG bytes
- bytes (JPEG/PNG) → pass through as-is
@@ -117,7 +117,7 @@ def _pil_to_jpeg_bytes(image: Image.Image, *, quality: int = DEFAULT_JPEG_QUALIT
def convert_item_images(item: dict[str, Any]) -> dict[str, Any]:
"""Convert all images in an item to wire format for transport.
- Per design.md Section 4.3, images are sent as JPEG bytes wrapped in
+ Images are sent as JPEG bytes wrapped in
ImageInput format: {"data": <bytes>, "format": "jpeg"}.
Modifies the item in-place and returns it.
diff --git a/packages/sie_sdk/src/sie_sdk/queue_types.py b/packages/sie_sdk/src/sie_sdk/queue_types.py
index c192a0291..07fc27ed5 100644
--- a/packages/sie_sdk/src/sie_sdk/queue_types.py
+++ b/packages/sie_sdk/src/sie_sdk/queue_types.py
@@ -77,19 +77,19 @@ class WorkItem(_WorkItemRequired, total=False):
labels: list[str] | None
output_schema: dict[str, Any] | None
- # Generate-specific (walking-skeleton wire shape).
+ # Generate-specific wire shape.
# Carries prompt + sampling params for one blocking call to
# ``adapter.generate(...)``. Keys: prompt (str), max_new_tokens (int),
# temperature (float), top_p (float), stop (list[str]).
generate: dict[str, Any] | None
- # M5: W3C Trace Context propagation. Populated by the gateway
+ # W3C Trace Context propagation. Populated by the gateway
# when it has an active span (extracted from the inbound
# ``traceparent`` HTTP header, or rooted at the gateway when
# the client did not send one). Both fields are msgpack-
- # skipped on the wire when ``None``, so a pre-M5 worker
- # decoding a post-M5 envelope just sees its expected key set,
- # and a post-M5 worker decoding a pre-M5 envelope sees both
+ # skipped on the wire when ``None``, so a worker without trace
+ # support sees its expected key set, and a trace-aware worker
+ # decoding an older envelope sees both
# fields default to ``None`` via ``WorkItem.get(...)``.
#
# Privacy: the value is two opaque IDs (trace id + span id)
diff --git a/packages/sie_sdk/src/sie_sdk/scoring.py b/packages/sie_sdk/src/sie_sdk/scoring.py
index af81d5f87..f038e5bf8 100644
--- a/packages/sie_sdk/src/sie_sdk/scoring.py
+++ b/packages/sie_sdk/src/sie_sdk/scoring.py
@@ -3,7 +3,7 @@
Provides MaxSim computation for client-side scoring when query and document
multivectors are already available (e.g., retrieved from a vector database).
-Per DESIGN.md Section 8.4, this enables the "encode once, score many" pattern:
+This enables the "encode once, score many" pattern:
1. Encode documents once and store multivectors in a vector DB
2. At query time, encode query and compute MaxSim locally
3. Avoid re-encoding documents for each query
diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.py
index f6087cb96..f19d4005b 100644
--- a/packages/sie_sdk/src/sie_sdk/types.py
+++ b/packages/sie_sdk/src/sie_sdk/types.py
@@ -3,7 +3,7 @@
These types are lightweight TypedDicts for type hints. No validation is performed
client-side - the server validates all inputs.
-Per DESIGN.md Section 4.1 and 8.2, these types support flexible Python inputs
+These types support flexible Python inputs
(file paths, PIL images, numpy arrays, bytes) which the client converts for transport.
"""
@@ -20,7 +20,7 @@ if TYPE_CHECKING:
from numpy.typing import NDArray
from PIL import Image
-# Output dtype options (per DESIGN.md Section 4.4)
+# Output dtype options.
DType = Literal["float32", "float16", "bfloat16", "int8", "uint8", "binary", "ubinary"]
# Output dtypes we support for casting
@@ -91,7 +91,7 @@ class DocumentInput(TypedDict, total=False):
class Item(TypedDict, total=False):
"""A single item to encode, score, or extract from.
- Per DESIGN.md Section 4.1, items can contain text, images, audio, or video.
+ Items can contain text, images, audio, or video.
Most models operate on text only, but multimodal models can process images.
For simple text encoding, just use {"text": "your text here"}.
@@ -126,10 +126,7 @@ class Item(TypedDict, total=False):
class SparseResult(TypedDict):
- """Sparse vector result with non-zero indices and values.
-
- Per DESIGN.md Section 8.2.
- """
+ """Sparse vector result with non-zero indices and values."""
indices: NDArray[np.int32]
values: NDArray[np.float32]
@@ -147,7 +144,7 @@ class TimingInfo(TypedDict, total=False):
class EncodeResult(TypedDict, total=False):
"""Result of encoding a single item.
- Per DESIGN.md Section 8.2. Contains the item ID (if provided) and one or more
+ Contains the item ID (if provided) and one or more
output representations depending on what was requested.
Attributes:
diff --git a/packages/sie_sdk/tests/client/test_embeddings_error_envelope.py b/packages/sie_sdk/tests/client/test_embeddings_error_envelope.py
index a16bd49cd..6a95c0143 100644
--- a/packages/sie_sdk/tests/client/test_embeddings_error_envelope.py
+++ b/packages/sie_sdk/tests/client/test_embeddings_error_envelope.py
@@ -1,7 +1,7 @@
"""Regression: SIE SDK must parse the OpenAI ``{error:{…}}`` envelope.
-As of roadmap §3 item 1.4, ``/v1/embeddings`` returns the OpenAI-shaped
-error envelope (``{"error": {"message", "type", "param", "code"}}``) on
+``/v1/embeddings`` returns the OpenAI-shaped error envelope
+(``{"error": {"message", "type", "param", "code"}}``) on
*every* error path, not the SIE-native ``{"detail": {"code", "message"}}``.
A SIE SDK user hitting ``/v1/embeddings`` directly must still get a typed
:class:`RequestError` / :class:`ServerError` with the parsed ``code`` and
diff --git a/packages/sie_sdk/tests/test_exceptions.py b/packages/sie_sdk/tests/test_exceptions.py
index 7970a745f..c685b2c6e 100644
--- a/packages/sie_sdk/tests/test_exceptions.py
+++ b/packages/sie_sdk/tests/test_exceptions.py
@@ -6,6 +6,10 @@ import pytest
from sie_sdk.exceptions import GatedModelError
+def _raise_gated(model_id: str = "org/model", original: Exception | None = None) -> None:
+ raise GatedModelError(model_id, original or ValueError("test"))
+
+
class TestGatedModelError:
"""Tests for GatedModelError exception class."""
@@ -67,14 +71,14 @@ class TestGatedModelError:
def test_can_be_caught_as_exception(self) -> None:
"""GatedModelError can be caught as Exception."""
with pytest.raises(Exception, match="Access denied") as exc_info:
- raise GatedModelError("org/model", ValueError("test"))
+ _raise_gated()
assert isinstance(exc_info.value, GatedModelError)
def test_can_be_caught_specifically(self) -> None:
"""GatedModelError can be caught by its specific type."""
with pytest.raises(GatedModelError) as exc_info:
- raise GatedModelError("org/model", ValueError("test"))
+ _raise_gated()
assert exc_info.value.model_id == "org/model"
@@ -102,7 +106,7 @@ class TestGatedModelError:
original = ValueError("HF Hub error")
with pytest.raises(GatedModelError) as exc_info:
- raise GatedModelError("org/model", original)
+ _raise_gated(original=original)
# The original error should be accessible
assert exc_info.value.original_error is original
diff --git a/packages/sie_sdk/tests/test_worker_id_normalization.py b/packages/sie_sdk/tests/test_worker_id_normalization.py
index 2883a9277..098424aaf 100644
--- a/packages/sie_sdk/tests/test_worker_id_normalization.py
+++ b/packages/sie_sdk/tests/test_worker_id_normalization.py
@@ -15,7 +15,7 @@ will silently miss every worker whose raw id contains a newly-changed
character — the pool fallback will eventually catch the work item but the
HRW routing decision is wasted.
-Workstream G-M5.
+This locks the cross-language normalization contract.
"""
from __future__ import annotations
diff --git a/packages/sie_server/Dockerfile.cpu b/packages/sie_server/Dockerfile.cpu
index a9c76e8c9..157e8efa4 100644
--- a/packages/sie_server/Dockerfile.cpu
+++ b/packages/sie_server/Dockerfile.cpu
@@ -8,7 +8,7 @@
ARG BUNDLE=default
# =============================================================================
-# Stage 1: Dependencies (pyproject.toml only, cached across code changes)
+# Dependency image: pyproject-only cache seed
# =============================================================================
FROM python:3.12-slim-bookworm AS deps
@@ -57,9 +57,9 @@ RUN --mount=type=cache,target=/root/.cache/pip \
-e ".[gpu-metrics]"
# =============================================================================
-# Stage 2: Base - source install + shared-venv finalization (no BUNDLE)
+# Shared runtime base: source install and venv finalization
# =============================================================================
-# Bundle-agnostic: all base-stage layers are shared across bundles of this
+# Bundle-agnostic: all base image layers are shared across bundles of this
# platform in local BuildKit cache and in content-addressed registry layers.
FROM deps AS base
@@ -107,7 +107,7 @@ RUN set -eux; \
find /app/.venv -exec touch -h -d @0 {} + 2>/dev/null || true
# =============================================================================
-# Stage 3: Builder - bundle-specific deps
+# Bundle dependency builder: bundle-specific deps
# =============================================================================
FROM base AS builder
@@ -150,7 +150,7 @@ RUN set -eux; \
find /app/bundle-libs -exec touch -h -d @0 {} + 2>/dev/null || true
# =============================================================================
-# Stage 4: Runtime
+# Runtime image
# =============================================================================
FROM python:3.12-slim-bookworm AS runtime
diff --git a/packages/sie_server/Dockerfile.cuda12 b/packages/sie_server/Dockerfile.cuda12
index f9c3befd9..eeeadf2c0 100644
--- a/packages/sie_server/Dockerfile.cuda12
+++ b/packages/sie_server/Dockerfile.cuda12
@@ -1,5 +1,5 @@
# syntax=docker/dockerfile:1
-# SIE Server - CUDA 12.4 Image
+# SIE Server - CUDA 12 Image
# Build from repo root:
# docker build -f packages/sie_server/Dockerfile.cuda12 -t sie-server:cuda12-default .
# docker build -f packages/sie_server/Dockerfile.cuda12 --build-arg BUNDLE=sglang -t sie-server:cuda12-sglang .
@@ -8,7 +8,7 @@ ARG BUNDLE=default
ARG UV_VERSION=0.9.28
# =============================================================================
-# Stage 1: uv + standalone Python 3.12 (no deadsnakes PPA)
+# Dependency image: uv and standalone Python 3.12
# =============================================================================
FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04 AS deps
@@ -59,10 +59,10 @@ RUN --mount=type=cache,target=/root/.cache/pip \
-e ".[gpu-metrics]"
# =============================================================================
-# Stage 2: Base - source install + shared-venv finalization (no BUNDLE)
+# Shared CUDA base: source install and venv finalization
# =============================================================================
# Everything here is bundle-agnostic, so bundle-specific builds of a given
-# platform share every base-stage layer in local BuildKit cache and in
+# platform share every base image layer in local BuildKit cache and in
# content-addressed registry layers.
FROM deps AS base
@@ -126,7 +126,7 @@ RUN set -eux; \
find /app/.venv -exec touch -h -d @0 {} + 2>/dev/null || true
# =============================================================================
-# Stage 3: Builder - bundle-specific deps
+# Bundle dependency builder: bundle-specific deps
# =============================================================================
FROM base AS builder
@@ -173,11 +173,19 @@ RUN set -eux; \
find /app/bundle-libs -exec touch -h -d @0 {} + 2>/dev/null || true
# =============================================================================
-# Stage 4: Runtime
+# Runtime image
# =============================================================================
-# Use base CUDA image (not devel/runtime) — PyTorch wheels bundle CUDA libs,
-# cuDNN ships inside torch. Saves ~2GB vs `runtime` variant.
-FROM nvidia/cuda:12.4.1-base-ubuntu22.04 AS runtime
+# Runtime base selection is bundle-scoped. Most CUDA bundles stay on the
+# smaller CUDA base runtime; SGLang-family bundles need the devel toolkit
+# because flashinfer/tvm_ffi perform runtime JIT through nvcc on first decode.
+FROM nvidia/cuda:12.4.1-base-ubuntu22.04 AS runtime-default
+FROM nvidia/cuda:12.4.1-base-ubuntu22.04 AS runtime-transformers5
+FROM nvidia/cuda:12.9.1-cudnn-devel-ubuntu22.04 AS runtime-sglang
+ENV CUDA_HOME=/usr/local/cuda \
+ LD_LIBRARY_PATH="/usr/local/cuda/lib64:$LD_LIBRARY_PATH"
+FROM runtime-sglang AS runtime-sglang-embedding
+
+FROM runtime-${BUNDLE} AS runtime
ENV DEBIAN_FRONTEND=noninteractive
diff --git a/packages/sie_server/README.md b/packages/sie_server/README.md
index ef3b83bbd..a6945032c 100644
--- a/packages/sie_server/README.md
+++ b/packages/sie_server/README.md
@@ -66,7 +66,7 @@ auto-retries; see `packages/sie_sdk/README.md` for client-side controls.
| Env var | Default | Effect |
|--|--|--|
-| `SIE_GRAMMAR_PREFLIGHT_DEBUG` | unset (off) | Enables the legacy worker-side Outlines preflight compile before each structured-output request. Off by default per ADR-0002 — SGLang is the production grammar authority. Use for diagnosing schema-rejection problems or slow compiles in a controlled environment; not recommended for production traffic. |
+| `SIE_GRAMMAR_PREFLIGHT_DEBUG` | unset (off) | Enables the legacy worker-side Outlines preflight compile before each structured-output request. Off by default because SGLang is the production grammar authority. Use for diagnosing schema-rejection problems or slow compiles in a controlled environment; not recommended for production traffic. |
For nested settings (any field with `__`), the env-var format is
`SIE_<TOP>__<NESTED>=value`. The complete schema is in
diff --git a/packages/sie_server/bundles/default.yaml b/packages/sie_server/bundles/default.yaml
index aff9a639a..8e0baa7f6 100644
--- a/packages/sie_server/bundles/default.yaml
+++ b/packages/sie_server/bundles/default.yaml
@@ -43,6 +43,7 @@ adapters:
- sie_server.adapters.florence2
- sie_server.adapters.docling
- sie_server.adapters.paddleocr_vl
+- sie_server.adapters.mineru_vl
deps:
# Most flash adapters; sentence_transformer needs >=4.57
transformers: '>=4.57,<5'
diff --git a/packages/sie_server/models/Marqo__marqo-fashionSigLIP.yaml b/packages/sie_server/models/Marqo__marqo-fashionSigLIP.yaml
new file mode 100644
index 000000000..c07aefcba
--- /dev/null
+++ b/packages/sie_server/models/Marqo__marqo-fashionSigLIP.yaml
@@ -0,0 +1,28 @@
+sie_id: Marqo/marqo-fashionSigLIP
+hf_id: Marqo/marqo-fashionSigLIP
+inputs:
+ text: true
+ image: true
+ audio: false
+ video: false
+tasks:
+ encode:
+ dense:
+ dim: 768
+ sparse: null
+ multivector: null
+ score: null
+ extract: null
+max_sequence_length: 64
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: float16
+ adapter_path: sie_server.adapters.siglip:SiglipAdapter
+ adapter_options:
+ loadtime:
+ backend: open_clip
+ open_clip_model_id: hf-hub:Marqo/marqo-fashionSigLIP
+ dense_dim: 768
+ runtime:
+ normalize: true
diff --git a/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml b/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml
index 9f936d95e..eb39b309b 100644
--- a/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3-0.6B.yaml
@@ -6,40 +6,39 @@ inputs:
audio: false
video: false
tasks:
- # Tiny generation model used for fast e2e iteration on Modal L4 (walking-skeleton
- # viability bench + validation-harness SIE-only smoke). Loads in ~30s. Quality is
- # bad — this is a transport benchmark target, not a production model.
+ # Small, fast generation model — a viable PROD pick for simple/short-prompt
+ # tasks (cheap + high throughput; weaker on long-context reasoning). Loads in
+ # ~30s. Also doubles as the transport/walking-skeleton benchmark target.
#
- # Context / batch sizes are deliberately small (1024 vs the headroom an
- # L4 could nominally support) so the validation harness can co-resident
- # the worker's SGLang with a second SGLang for the baseline phase on
- # a single 22 GiB card without OOMing. Raise these if you ever run 0.6B
- # alone on a card it doesn't have to share.
+ # ``context_length`` is the standalone PROD serving value (4096): big enough
+ # to fit the full generation benchmark pack (casehold prompts reach ~1.8k
+ # tokens, gpqa ~1.3k) so the model is comparable to the rest of the fleet on
+ # every task, while KV stays trivial at this size (112 KB/token → 4096 ≈
+ # 0.46 GB). The validation/co-residency harness, which packs two SGLang
+ # instances onto a single 22 GiB L4, does NOT depend on this default — it
+ # passes an explicit ``--max-seq-length``/``--context-length`` (see
+ # tools/bench_generation_matrix.py + run_generation_smoke.py) and caps itself
+ # to 1024 for that case.
#
- # Note on the three 1024s below: `context_length`, `max_sequence_length`,
- # and `max_batch_tokens` are NOT redundant — they're three independent
- # knobs (per-request context, SGLang --context-length, batcher cost
- # budget) that just happen to collide here because the model is tiny.
- # See sibling Qwen__Qwen3-4B-Instruct-2507.yaml for the canonical
- # non-collapsed shape.
+ # ``context_length``, ``max_sequence_length``, and ``max_batch_tokens`` are
+ # three independent knobs (per-request context, SGLang --context-length,
+ # batcher cost budget); see sibling Qwen__Qwen3-4B-Instruct-2507.yaml.
generate:
- context_length: 1024
+ context_length: 4096
max_output_tokens: 1024
capabilities:
grammar: []
streaming: true
tools: false
-max_sequence_length: 1024
+max_sequence_length: 4096
# KV-cache memory math (Qwen3-0.6B, bf16):
# layers=28, kv_heads=8, head_dim=128, bytes_per_elem=2
# kv_bytes_per_token = 2 × 28 × 8 × 128 × 2 = 114,688 B ≈ 112 KB
-# The 0.6B is a transport benchmark target — context_length is held at
-# 1024 deliberately (see header comment) so the validation harness can
-# co-resident two SGLang instances on an L4. KV budgets per profile
-# scale with the deployment scenario rather than the GPU ceiling.
+# At ctx=4096 a single request's KV is ~0.46 GB — negligible. The co-residency
+# harness still caps context explicitly when it has to share a card.
profiles:
default:
- max_batch_tokens: 1024
+ max_batch_tokens: 4096
compute_precision: bfloat16
adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter
kv_budget_tokens: 8192
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 6487f8035..3ded160c9 100644
--- a/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3-4B-Instruct-2507.yaml
@@ -66,8 +66,7 @@ max_sequence_length: 32768
# kv_budget_tokens is set to ~40% of theoretical max, matching the L4
# baseline ratio (32768/90000 ≈ 36%). The headroom absorbs batch growth,
# speculative side-cell, grammar/Outlines compile arena, fragmentation.
-# Final empirical validation (concurrency-16 OOM-boundary sweep) is
-# tracked in product/plans/m4-req2-gpu-runbook.md §"#16/#19".
+# Final empirical validation should use concurrency and OOM-boundary sweeps.
profiles:
default:
# max_batch_tokens is a generic engine knob; generation does not batch
@@ -93,7 +92,7 @@ profiles:
top_p: 0.9
stop_tokens:
- "<|im_end|>"
- # M5 audit #16/#19: analytical defaults for a100-40gb / h100. Production
+ # Analytical defaults for a100-40gb / h100. Production
# capacity also grows: with 2-4× the KV budget the context window can be
# widened proportionally so longer-context workloads (RAG with large
# retrieved passages) fit comfortably. ``max_output_tokens`` doubles
diff --git a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml b/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml
index 2e489c7f6..e66535a06 100644
--- a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml
+++ b/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml
@@ -14,10 +14,17 @@ inputs:
tasks:
generate:
# Native context length is 262,144 tokens (YaRN extends to ~1M).
- # Default to 8192 here — H100 80GB can fit larger windows after KV
- # calibration but the conservative cap survives first boot before
- # token_capacity is measured.
- context_length: 8192
+ # Default to 4096 here — this matches the empirically-calibrated
+ # reference point in the profile comments below
+ # (mem_fraction_static=0.93, weight 51.05 GB + kvcache 11.63 GB).
+ # 8192 was the original optimistic default but SGLang's
+ # init_memory_pool refused to fit it inside the conservative
+ # mem_fraction envelope on H100-80GB even when bumped to 0.97 —
+ # NEXTN speculative-decoding draft KV pushes the total past the
+ # available headroom. Raise both context_length AND
+ # mem_fraction_static together if you need longer contexts;
+ # benchmarking and prod requests today fit comfortably in 4096.
+ context_length: 4096
max_output_tokens: 4096
capabilities:
# Same constraint as Qwen3.5-4B: SGLang's outlines_backend does
@@ -47,7 +54,7 @@ tasks:
answer:
type: string
required: [answer]
-max_sequence_length: 8192
+max_sequence_length: 4096
# ── KV-cache math (placeholder, pending Modal calibration) ──
#
# Qwen3.6-27B layer breakdown (per model card / config.json):
@@ -82,29 +89,44 @@ profiles:
# Sizing here at ~1/12 of that capacity to leave room for NEXTN
# draft KV + grammar/Outlines compile arena once spec is re-enabled.
# Re-calibrate after a smoke run on this profile's actual settings.
- kv_budget_tokens: 16384
+ # Halved from 16384 to leave more H100-80GB headroom for the NEXTN
+ # draft activation arena. 8192 KV slots × ~64 KB/token ≈ 0.5 GB —
+ # plenty for the realistic per-request concurrency on this profile.
+ kv_budget_tokens: 8192
adapter_options:
loadtime:
- mem_fraction_static: 0.85
+ # 0.95 paired with ``context_length: 4096`` + the *smaller*
+ # NEXTN draft below (num_steps=2 / num_draft_tokens=2 vs the
+ # 3/4 model-card default). The 0.93+default-draft cell still
+ # OOM'd ``init_memory_pool`` because verification batch grows
+ # with num_steps × num_draft_tokens; halving both shrinks the
+ # activation arena enough to fit.
+ mem_fraction_static: 0.95
served_model_name: Qwen/Qwen3.6-27B
disable_cuda_graph: true
attention_backend: triton
grammar_backend: outlines
reasoning_parser: qwen3
tool_call_parser: qwen3_coder
- # MTP/NEXTN per the Qwen3.x model-card recipe. SGLang implements
- # NEXTN under the EAGLE codepath internally; ``/server_info``
- # reporting ``speculative_algorithm: EAGLE`` is expected.
+ # MTP/NEXTN per the Qwen3.x model-card recipe (SGLang implements
+ # NEXTN under the EAGLE codepath; ``/server_info`` reports
+ # ``speculative_algorithm: EAGLE``). Smaller-draft variant
+ # (num_steps=2 / num_draft_tokens=2 vs the model-card 3/4) so
+ # the verification batch fits inside H100-80GB at ctx=4096 +
+ # mfs=0.95. The 3/4 default reliably OOM'd
+ # ``init_memory_pool`` even at mfs=0.97 — the trade is a
+ # slightly smaller speculative window for the ability to fit at
+ # all. Re-tune (or re-enable 3/4) once FP8 / TP=2 is wired up.
speculative:
enabled: true
algorithm: nextn
- num_steps: 3
+ num_steps: 2
eagle_topk: 1
- num_draft_tokens: 4
- # Required for NEXTN spec decoding to coexist with radix cache
- # on the hybrid Gated-DeltaNet architecture. The adapter also
- # sets SGLANG_ENABLE_SPEC_V2=1 when speculative.enabled — both
- # are required as a pair.
+ num_draft_tokens: 2
+ # ``--mamba-scheduler-strategy extra_buffer`` is the required
+ # pair-flag for NEXTN spec on the hybrid Gated-DeltaNet
+ # architecture. With spec disabled it's also harmless to keep,
+ # so we leave it for when spec is re-enabled.
extra_launch_args:
- "--mamba-scheduler-strategy"
- "extra_buffer"
@@ -129,7 +151,8 @@ profiles:
kv_budget_tokens: 32768
adapter_options:
loadtime:
- mem_fraction_static: 0.85
+ # Same as ``default`` — see that profile's mfs comment.
+ mem_fraction_static: 0.93
served_model_name: Qwen/Qwen3.6-27B
disable_cuda_graph: true
attention_backend: triton
@@ -159,6 +182,95 @@ profiles:
presence_penalty: 1.5
stop_tokens:
- "<|im_end|>"
+ # RTX PRO 6000 (96 GB GDDR7, Blackwell Server Edition, sm_120) profile.
+ # FP8-first for max throughput: ``--quantization fp8`` (SGLang online
+ # dynamic FP8 quant of the BF16 checkpoint) via the ``extra_launch_args``
+ # passthrough — ``compute_precision`` can only express the ``--dtype``
+ # axis (float16/bfloat16/float32), not the orthogonal ``--quantization``
+ # flag, so FP8 rides the same escape hatch already used for the mamba
+ # scheduler. FP8 halves weight memory (~54 → ~27 GB), which frees room
+ # for the *model-card* NEXTN 3/4 draft (num_steps=3 / num_draft_tokens=4)
+ # that OOM'd ``init_memory_pool`` on H100-80GB even at mfs=0.97. The +16 GB
+ # over H100 plus the FP8 weight saving is what makes 3/4 fit here.
+ #
+ # ACCURACY CONTRACT: FP8 is lossy. This profile is validated to within the
+ # Wilson 95% CI of the *BF16* baseline on all four generation tasks (see
+ # docs/adr/0001). If FP8 misses parity after bounded tuning, fall back to
+ # BF16 + NEXTN 3/4 (drop the ``--quantization fp8`` pair below; the 96 GB
+ # still fits the 3/4 draft in BF16). KV cache stays BF16 here — add
+ # ``--kv-cache-dtype fp8_e4m3`` only if memory/throughput needs it AND
+ # accuracy still holds (KV FP8 is usually the first thing to cost accuracy).
+ #
+ # Standalone block (no ``extends``): production ``resolve_profile`` does a
+ # full-replace of ``loadtime`` for extending profiles, so a partial child
+ # would drop inherited launch flags and desync the via-SIE path from the
+ # bare-SGLang bench control.
+ rtx-pro-6000:
+ max_batch_tokens: 32768
+ compute_precision: bfloat16
+ adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter
+ # FP8 weights (~27 GB) + 96 GB total leaves generous KV/draft headroom;
+ # start conservative and raise after the first /get_server_info dump on
+ # the actual RTX-PRO-6000 smoke.
+ kv_budget_tokens: 16384
+ adapter_options:
+ loadtime:
+ # 0.90 is a conservative starting point — FP8 weights free enough
+ # memory that the 3/4 NEXTN verification batch should fit with room
+ # to spare. Iterate upward (smoke ``--mem-fraction-static``) once the
+ # first boot confirms Blackwell sm_120 + FP8 GEMM kernels are present.
+ mem_fraction_static: 0.90
+ served_model_name: Qwen/Qwen3.6-27B
+ disable_cuda_graph: true
+ # triton attention matches the rest of the Qwen3.x family. Blackwell
+ # (sm_120) kernel coverage for triton + FP8 + NEXTN is the first thing
+ # the boot smoke verifies; switch to flashinfer here if triton lacks
+ # sm_120 coverage in the pinned SGLang build.
+ attention_backend: triton
+ grammar_backend: outlines
+ reasoning_parser: qwen3
+ tool_call_parser: qwen3_coder
+ # Model-card NEXTN 3/4 — restored here (vs ``default``'s conservative
+ # 2/2) because FP8 + 96 GB fits the larger verification batch that
+ # OOM'd on H100-80GB.
+ speculative:
+ enabled: true
+ algorithm: nextn
+ num_steps: 3
+ eagle_topk: 1
+ num_draft_tokens: 4
+ # ``--quantization fp8`` rides the passthrough (see header comment).
+ # The mamba-scheduler + overlap pair-flags are the required NEXTN
+ # companions on the hybrid Gated-DeltaNet architecture. List is the
+ # FULL set (production full-replaces ``extra_launch_args``, not merge).
+ extra_launch_args:
+ - "--quantization"
+ - "fp8"
+ - "--mamba-scheduler-strategy"
+ - "extra_buffer"
+ - "--disable-overlap-schedule"
+ runtime:
+ first_chunk_timeout_s: 90
+ inter_chunk_timeout_s: 15
+ overall_timeout_s: 600
+ # Qwen3.6-27B empty-response fix baked in: under greedy/low-temp the
+ # chat template emits EOS as the FIRST token on a large fraction of
+ # prompts (n=50 6000 smoke: casehold 23/50, gpqa 29/50 came back
+ # EMPTY). The floor ``min_new_tokens>=1`` fixes it — validated on the
+ # 6000: min_tokens=10 → 0/50 empty on all four tasks, accuracy within
+ # Wilson 95% CI of the BF16 baseline. ``min_new_tokens`` is the
+ # SGLang-native key; the adapter merges this dict via ``setdefault``,
+ # so a request-supplied ``min_tokens`` still wins. NOTE: this only
+ # takes effect because ``runtime.default_sampling`` is now wired into
+ # the adapter (core/loader.py); before that fix a key here was a
+ # silent no-op and chat clients had to pass ``min_tokens`` themselves.
+ 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/tomoroai__tomoro-colqwen3-embed-4b.yaml b/packages/sie_server/models/TomoroAI__tomoro-colqwen3-embed-4b.yaml
similarity index 100%
rename from packages/sie_server/models/tomoroai__tomoro-colqwen3-embed-4b.yaml
rename to packages/sie_server/models/TomoroAI__tomoro-colqwen3-embed-4b.yaml
diff --git a/packages/sie_server/models/docling.yaml b/packages/sie_server/models/docling.yaml
index 93cea9b87..028129d4e 100644
--- a/packages/sie_server/models/docling.yaml
+++ b/packages/sie_server/models/docling.yaml
@@ -2,7 +2,7 @@ sie_id: docling
package_backed: true
inputs:
text: false
- image: false
+ image: true
audio: false
video: false
document: true
diff --git a/packages/sie_server/models/opendatalab__MinerU2.5-Pro-2604-1.2B.yaml b/packages/sie_server/models/opendatalab__MinerU2.5-Pro-2604-1.2B.yaml
new file mode 100644
index 000000000..ea25c4011
--- /dev/null
+++ b/packages/sie_server/models/opendatalab__MinerU2.5-Pro-2604-1.2B.yaml
@@ -0,0 +1,24 @@
+sie_id: opendatalab/MinerU2.5-Pro-2604-1.2B
+hf_id: opendatalab/MinerU2.5-Pro-2604-1.2B
+hf_revision: d3f5e08d073c21466bbabe21c71bb1e9c2e595da
+inputs:
+ text: false
+ image: true
+ audio: false
+ video: false
+tasks:
+ encode: null
+ score: null
+ extract: {}
+profiles:
+ default:
+ max_batch_tokens: 16384
+ compute_precision: bfloat16
+ adapter_path: sie_server.adapters.mineru_vl:MinerUVLAdapter
+ adapter_options:
+ loadtime:
+ default_task: "[default]"
+ runtime:
+ task: "[default]"
+ max_new_tokens: 4096
+ num_beams: 1
diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.json
index 46845ed11..25abf8fed 100644
--- a/packages/sie_server/openapi.json
+++ b/packages/sie_server/openapi.json
@@ -3,7 +3,7 @@
"info": {
"title": "SIE Server",
"description": "Search Inference Engine - GPU inference server for search workloads",
- "version": "0.4.1"
+ "version": "0.4.2"
},
"paths": {
"/": {
diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.toml
index 48a95e9ef..53ff56ffa 100644
--- a/packages/sie_server/pyproject.toml
+++ b/packages/sie_server/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "sie-server"
-version = "0.4.1"
+version = "0.4.2"
description = "Search Inference Engine - GPU inference server for search workloads"
requires-python = ">=3.12,<3.13"
license = { text = "Apache-2.0" }
@@ -39,7 +39,7 @@ dependencies = [
# SigLIP (Marqo/marqo-ecommerce-embeddings-B native open_clip loader)
"open-clip-torch>=2.24",
# Image processing
- "pillow>=11,<12",
+ "pillow>=12.2.0",
"numpy>=2,<3",
"torchvision>=0.18,<1", # Required by some HF models (e.g., nvidia/llama-nemoretriever)
# Config
@@ -50,8 +50,6 @@ dependencies = [
"packaging>=24,<25",
# Hot-reload
"watchdog>=6,<7",
- # NATS pub/sub for config notifications
- "nats-py>=2.9,<3",
# Observability
"opentelemetry-api>=1.28,<2",
"opentelemetry-sdk>=1.28,<2",
@@ -66,6 +64,11 @@ dependencies = [
"msgspec>=0.20.0",
# Async HTTP client (telemetry sender)
"httpx>=0.28.1",
+ # BLAKE3 used to cross-check the worker-sidecar's `PreparedTokens`
+ # tokenizer_id. Tiny (<200KB, pure-Rust via PyO3), mandatory for
+ # the encode / score fast-path consumer — see
+ # `sie_server.core.preprocessor.text.TextPreprocessor`.
+ "blake3>=0.4,<1",
]
[project.optional-dependencies]
diff --git a/packages/sie_server/scripts/generate_tokenize_fixture.py b/packages/sie_server/scripts/generate_tokenize_fixture.py
new file mode 100644
index 000000000..d05d3c16a
--- /dev/null
+++ b/packages/sie_server/scripts/generate_tokenize_fixture.py
@@ -0,0 +1,203 @@
+#!/usr/bin/env python3
+"""Generate a byte-identity fixture for the Rust tokeniser parity test.
+
+Companion to ``packages/sie_server_sidecar/tests/byte_identity.rs``.
+
+The worker-sidecar can pre-tokenise text on behalf of the Python adapter
+and ship the ids over IPC. Python falls back to its own tokenisation
+whenever the content-hash of the two tokenizers disagrees, but that
+guard is only useful if the two sides produce the SAME output for
+the SAME ``tokenizer.json``.
+
+This script is the ground-truth generator for that check:
+
+ 1. Downloads the target model's ``tokenizer.json`` via
+ ``huggingface_hub`` (uses the standard HF cache).
+ 2. Loads it with ``transformers.AutoTokenizer`` using the exact
+ kwargs our Python adapters use today:
+ ``padding=False, truncation=True, max_length=N``.
+ 3. Runs a curated set of test texts (short, long, multilingual,
+ unicode edge cases) through the tokenizer per-text.
+ 4. Emits a JSON fixture consumed by the Rust test.
+
+Usage:
+
+ uv run --with transformers --with huggingface_hub \\
+ packages/sie_server/scripts/generate_tokenize_fixture.py \\
+ --model Alibaba-NLP/gte-multilingual-base \\
+ --max-seq-len 512 \\
+ --out /tmp/gte_fixture.json
+
+Then:
+
+ SIE_BYTE_IDENTITY_FIXTURE=/tmp/gte_fixture.json \\
+ cargo test --manifest-path packages/sie_server_sidecar/Cargo.toml --test byte_identity -- --nocapture
+
+Intentionally self-contained: the only runtime deps are
+``transformers`` + ``huggingface_hub``; no sie_server imports, so
+the fixture can be regenerated on any machine that can reach HF Hub
+(or has the model cached).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+# Curated text cases. Designed to exercise the corners where
+# tokenizer implementations most often diverge:
+# * plain ASCII (trivial)
+# * leading/trailing whitespace (pre-tokenizer stripping)
+# * Unicode normalisation (combining chars, CJK)
+# * punctuation clusters
+# * very long text that WILL trigger truncation to max_seq_len
+# * empty string (edge case; some tokenizers emit just special tokens)
+DEFAULT_CASES: list[str] = [
+ "hello world",
+ "Hello, World!",
+ " leading and trailing whitespace ",
+ "The quick brown fox jumps over the lazy dog.",
+ "A. B. C. Multiple. Spaces.",
+ # Multilingual — the main reason we use gte-multilingual-base
+ "Bonjour le monde",
+ "你好,世界",
+ "こんにちは世界",
+ "مرحبا بالعالم",
+ "Привет мир",
+ # Unicode combining / normalisation edge cases
+ "café vs cafe\u0301", # NFC vs NFD form of "café"
+ "é\u200bé", # zero-width space between graphemes
+ # Long text — tests truncation behaviour
+ " ".join(["lorem ipsum"] * 300),
+ # Empty string
+ "",
+]
+
+
+def resolve_tokenizer_path(model_id: str) -> str:
+ """Return the absolute filesystem path to ``tokenizer.json`` for
+ ``model_id``, downloading it to the HF cache if necessary.
+ """
+ try:
+ from huggingface_hub import hf_hub_download
+ except ImportError as e: # pragma: no cover
+ print(
+ "huggingface_hub is required; install with "
+ "`pip install huggingface_hub` (or use the `--with` uv invocation "
+ "shown in the module docstring).",
+ file=sys.stderr,
+ )
+ raise SystemExit(2) from e
+
+ path = hf_hub_download(repo_id=model_id, filename="tokenizer.json")
+ return str(Path(path).resolve())
+
+
+def load_tokenizer(model_id: str) -> Any:
+ """Load the HF ``AutoTokenizer`` for ``model_id``. We deliberately
+ call ``AutoTokenizer`` (not ``Tokenizer.from_file``) because that
+ is what every in-tree adapter uses — if the two wrappers differ
+ on any config, the fixture will catch it.
+ """
+ try:
+ from transformers import AutoTokenizer
+ except ImportError as e: # pragma: no cover
+ print(
+ "transformers is required; install with "
+ "`pip install transformers` (or use the `--with` uv invocation "
+ "shown in the module docstring).",
+ file=sys.stderr,
+ )
+ raise SystemExit(2) from e
+
+ return AutoTokenizer.from_pretrained(model_id, use_fast=True)
+
+
+def build_case(tokenizer: Any, text: str, max_seq_len: int) -> dict[str, Any]:
+ """Tokenise ``text`` with the Python-adapter-equivalent kwargs and
+ return a JSON-serialisable case dict.
+ """
+ enc = tokenizer(
+ text,
+ padding=False,
+ truncation=True,
+ max_length=max_seq_len,
+ return_attention_mask=True,
+ return_token_type_ids=None, # let the tokenizer decide
+ )
+ # ``transformers`` returns BatchEncoding-wrapped lists when given
+ # a single string. Convert to plain Python lists for JSON.
+ input_ids = list(enc["input_ids"])
+ attention_mask = list(enc["attention_mask"])
+ # Some tokenizers (XLM-R, most modern multilingual models) don't
+ # emit token_type_ids at all. In that case the key is absent; we
+ # encode that as an empty list in the fixture and the Rust test
+ # treats "empty" as "the Python side didn't emit segment ids".
+ token_type_ids: list[int] = list(enc["token_type_ids"]) if "token_type_ids" in enc else []
+ return {
+ "text": text,
+ "input_ids": input_ids,
+ "attention_mask": attention_mask,
+ "token_type_ids": token_type_ids,
+ }
+
+
+def main() -> None:
+ description = (__doc__ or "").splitlines()[0] if __doc__ else ""
+ parser = argparse.ArgumentParser(description=description)
+ parser.add_argument(
+ "--model",
+ required=True,
+ help="HuggingFace repo id, e.g. 'Alibaba-NLP/gte-multilingual-base'.",
+ )
+ parser.add_argument(
+ "--max-seq-len",
+ type=int,
+ default=512,
+ help="Max sequence length for truncation (must match the Rust side's max_seq_len for the same model).",
+ )
+ parser.add_argument(
+ "--out",
+ type=Path,
+ required=True,
+ help="Where to write the fixture JSON.",
+ )
+ parser.add_argument(
+ "--texts",
+ type=Path,
+ default=None,
+ help="Optional path to a newline-delimited text file of additional "
+ "custom cases. If absent, a curated default set is used.",
+ )
+ args = parser.parse_args()
+
+ texts: list[str] = list(DEFAULT_CASES)
+ if args.texts is not None:
+ extra = args.texts.read_text(encoding="utf-8").splitlines()
+ texts.extend(t for t in extra if t)
+
+ tokenizer_path = resolve_tokenizer_path(args.model)
+ tokenizer = load_tokenizer(args.model)
+
+ cases = [build_case(tokenizer, text, args.max_seq_len) for text in texts]
+
+ fixture = {
+ "model_id": args.model,
+ "tokenizer_path": tokenizer_path,
+ "max_seq_len": args.max_seq_len,
+ "cases": cases,
+ }
+
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps(fixture, ensure_ascii=False, indent=2), encoding="utf-8")
+ print(
+ f"wrote {len(cases)} cases for {args.model} to {args.out} (tokenizer.json = {tokenizer_path})",
+ file=sys.stderr,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/sie_server/src/sie_server/__init__.py b/packages/sie_server/src/sie_server/__init__.py
index 2dc9da718..3f9551855 100644
--- a/packages/sie_server/src/sie_server/__init__.py
+++ b/packages/sie_server/src/sie_server/__init__.py
@@ -1,3 +1,9 @@
"""SIE Server - Search Inference Engine."""
-__version__ = "0.1.0"
+from importlib.metadata import PackageNotFoundError, version
+
+try:
+ __version__ = version("sie_server")
+except PackageNotFoundError:
+ # Package is not installed (e.g. source tree without `pip install -e`).
+ __version__ = "0.0.0+unknown"
diff --git a/packages/sie_server/src/sie_server/_ipc_test_harness.py b/packages/sie_server/src/sie_server/_ipc_test_harness.py
new file mode 100644
index 000000000..e51b5e044
--- /dev/null
+++ b/packages/sie_server/src/sie_server/_ipc_test_harness.py
@@ -0,0 +1,356 @@
+"""Standalone IPC test harness — boots ``IpcServer`` with a stub executor.
+
+This module exists solely for the worker-sidecar's integration smoke test
+(``packages/sie_server_sidecar/tests/integration_smoke.rs``). It is **not**
+used by production code paths and must not import any GPU / torch / model
+dependencies — the whole point is to prove the UDS wire contract without
+needing a real ``sie-server`` with its heavy dependency graph.
+
+Run as::
+
+ python -m sie_server._ipc_test_harness --socket /tmp/ipc.sock --worker-id w1
+
+The process exits on SIGINT / SIGTERM. All stubbed RPCs:
+
+* ``Ping`` — handled by ``IpcServer`` itself.
+* ``EnsureModelReady`` — always returns ``"ready"``.
+* ``ProcessEncodeBatch`` / ``ProcessScoreBatch`` / ``ProcessExtractBatch`` —
+ returns ``publish_and_ack`` for every item with a canned ``result_msgpack``
+ payload that the test can decode and assert on.
+* ``ProcessGenerate`` — when ``--fake-generate-model`` is set, streams
+ ``in_progress`` → ``publish`` → ``ack`` events through the IPC generation
+ protocol without loading a real generation adapter.
+* ``Drain`` — handled by ``IpcServer`` itself.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import logging
+import signal
+from typing import Any, cast
+
+import msgpack
+
+from sie_server.ipc_server import IpcServer
+from sie_server.ipc_types import (
+ BatchOutcome,
+ ItemOutcome,
+ ModelDescriptor,
+ ProcessEncodeBatchRequest,
+ ProcessExtractBatchRequest,
+ ProcessScoreBatchRequest,
+ ReadinessState,
+)
+
+logger = logging.getLogger(__name__)
+
+
+# Fixed canned result the Rust smoke test can pattern-match on.
+_CANNED_RESULT = {"smoke": "ok", "source": "ipc_test_harness"}
+
+
+def _canned_result_bytes() -> bytes:
+ return msgpack.packb(_CANNED_RESULT, use_bin_type=True)
+
+
+class _StubGenerationTasks:
+ def __init__(self, enabled: bool) -> None:
+ self.generate = object() if enabled else None
+
+
+class _StubGenerationConfig:
+ def __init__(self, enabled: bool) -> None:
+ self.tasks = _StubGenerationTasks(enabled)
+
+
+class _StubRegistry:
+ def __init__(
+ self,
+ generation_model: str | None = None,
+ generation_hidden_polls: int = 0,
+ ) -> None:
+ self._generation_model = generation_model
+ self._generation_hidden_polls = generation_hidden_polls
+ self._generation_capability_polls = 0
+
+ def get_configs_snapshot(self) -> dict[str, _StubGenerationConfig]:
+ if self._generation_model is None:
+ return {}
+ self._generation_capability_polls += 1
+ if self._generation_capability_polls <= self._generation_hidden_polls:
+ return {}
+ return {self._generation_model: _StubGenerationConfig(enabled=True)}
+
+
+class _StubExecutor:
+ """Duck-typed replacement for :class:`sie_server.queue_executor.QueueExecutor`.
+
+ We only need the four methods ``IpcServer`` actually calls. The test asserts
+ on the outcome shape, not on any real inference output.
+
+ The optional ``per_request_delay_ms`` knob injects an ``asyncio.sleep`` at
+ the top of every ``process_*_batch`` call. It exists purely so the Rust
+ pool integration test can *observe* concurrency: with fast RPCs the pool
+ returns slots faster than Prometheus can scrape ``ipc_pool_inflight``,
+ making the metric invisible to real-time assertions. A 100ms delay gives
+ the test a comfortable window to scrape ``> 1`` in-flight.
+ """
+
+ def __init__(
+ self,
+ readiness: ReadinessState = "ready",
+ batch_budget: int | None = None,
+ descriptor: ModelDescriptor | None = None,
+ per_request_delay_ms: float = 0.0,
+ generation_model: str | None = None,
+ generation_hidden_polls: int = 0,
+ ) -> None:
+ self._readiness = readiness
+ self._batch_budget = batch_budget
+ self._descriptor = descriptor
+ self._per_request_delay_ms = per_request_delay_ms
+ self.registry = _StubRegistry(generation_model, generation_hidden_polls)
+
+ async def ensure_model_ready(self, model_id: str) -> ReadinessState: # noqa: ARG002
+ return self._readiness
+
+ def get_batch_budget(self, model_id: str) -> int | None: # noqa: ARG002
+ return self._batch_budget
+
+ def get_model_descriptor(self, model_id: str) -> ModelDescriptor | None: # noqa: ARG002
+ return self._descriptor
+
+ async def _maybe_sleep(self) -> None:
+ if self._per_request_delay_ms > 0:
+ await asyncio.sleep(self._per_request_delay_ms / 1000.0)
+
+ async def process_encode_batch(self, req: ProcessEncodeBatchRequest) -> BatchOutcome:
+ await self._maybe_sleep()
+ return _canned_batch_outcome_echoing_prepared_tokens(req.items)
+
+ async def process_score_batch(self, req: ProcessScoreBatchRequest) -> BatchOutcome:
+ await self._maybe_sleep()
+ return _canned_batch_outcome_echoing_prepared_tokens(req.items)
+
+ async def process_extract_batch(self, req: ProcessExtractBatchRequest) -> BatchOutcome:
+ await self._maybe_sleep()
+ return _canned_batch_outcome(req.items)
+
+
+class _FakeGenerateProcessor:
+ def signal_cancel(self, request_id: str) -> bool: # noqa: ARG002
+ return False
+
+ async def process(self, msg: Any, model_id: str) -> None:
+ work_item = msgpack.unpackb(msg.data, raw=False)
+ await msg.in_progress()
+ payload = msgpack.packb(
+ {
+ "smoke": "generate",
+ "source": "ipc_test_harness",
+ "model_id": model_id,
+ "request_id": work_item.get("request_id"),
+ "work_item_id": work_item.get("work_item_id"),
+ },
+ use_bin_type=True,
+ )
+ await msg._sink.publish(work_item["reply_subject"], payload)
+ await msg.ack()
+
+
+def _canned_batch_outcome(items: list[Any]) -> BatchOutcome:
+ payload = _canned_result_bytes()
+ return BatchOutcome(
+ outcomes=[
+ ItemOutcome(
+ work_item_id=item.work_item_id,
+ request_id=item.request_id,
+ item_index=item.item_index,
+ disposition="publish_and_ack",
+ result_msgpack=payload,
+ inference_ms=0.1,
+ tokenization_ms=0.05,
+ postprocessing_ms=0.01,
+ )
+ for item in items
+ ]
+ )
+
+
+def _canned_batch_outcome_echoing_prepared_tokens(items: list[Any]) -> BatchOutcome:
+ """Like :func:`_canned_batch_outcome` but folds each item's
+ ``prepared_tokens`` presence / content into the per-item
+ ``result_msgpack``. The Rust integration smoke test uses this to
+ assert that the Rust tokenise-and-attach hook actually fired
+ for the request without needing to run a real adapter.
+
+ Shape of the echoed result::
+
+ {
+ "smoke": "ok",
+ "source": "ipc_test_harness",
+ "prepared_tokens": {
+ "present": bool,
+ "tokenizer_id": str | None,
+ "input_ids_first_seq": list[int] | None,
+ "max_seq_len": int | None,
+ },
+ }
+ """
+ outcomes: list[ItemOutcome] = []
+ for item in items:
+ pt = getattr(item, "prepared_tokens", None)
+ if pt is not None:
+ pt_echo: dict[str, Any] = {
+ "present": True,
+ "tokenizer_id": pt.tokenizer_id,
+ "input_ids_first_seq": list(pt.input_ids[0]) if pt.input_ids else None,
+ "max_seq_len": int(pt.max_seq_len),
+ }
+ else:
+ pt_echo = {
+ "present": False,
+ "tokenizer_id": None,
+ "input_ids_first_seq": None,
+ "max_seq_len": None,
+ }
+ payload = msgpack.packb({**_CANNED_RESULT, "prepared_tokens": pt_echo}, use_bin_type=True)
+ outcomes.append(
+ ItemOutcome(
+ work_item_id=item.work_item_id,
+ request_id=item.request_id,
+ item_index=item.item_index,
+ disposition="publish_and_ack",
+ result_msgpack=payload,
+ inference_ms=0.1,
+ tokenization_ms=0.05,
+ postprocessing_ms=0.01,
+ )
+ )
+ return BatchOutcome(outcomes=outcomes)
+
+
+async def _main(
+ socket_path: str,
+ worker_id: str,
+ readiness: ReadinessState,
+ per_request_delay_ms: float,
+ descriptor: ModelDescriptor | None,
+ fake_generate_model: str | None,
+ fake_generate_hidden_polls: int,
+) -> None:
+ executor = _StubExecutor(
+ readiness=readiness,
+ descriptor=descriptor,
+ per_request_delay_ms=per_request_delay_ms,
+ generation_model=fake_generate_model,
+ generation_hidden_polls=fake_generate_hidden_polls,
+ )
+ stop = asyncio.Event()
+
+ loop = asyncio.get_running_loop()
+ for sig in (signal.SIGINT, signal.SIGTERM):
+ try:
+ loop.add_signal_handler(sig, stop.set)
+ except NotImplementedError:
+ # Windows / some embedded runtimes
+ pass
+
+ server = IpcServer(socket_path, cast("Any", executor), worker_id=worker_id)
+ if fake_generate_model is not None:
+ server._streaming_processor = _FakeGenerateProcessor()
+
+ async with server:
+ # Ready marker the test can grep for on stdout.
+ print(f"HARNESS_READY socket={socket_path}", flush=True)
+ await stop.wait()
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(prog="sie_server._ipc_test_harness")
+ parser.add_argument("--socket", required=True, help="UDS path to bind")
+ parser.add_argument("--worker-id", default="smoke-worker", help="worker_id to report on Ping")
+ parser.add_argument(
+ "--readiness",
+ default="ready",
+ choices=["ready", "loading_started", "loading_in_progress", "retry_later"],
+ help="Canned readiness state returned for every EnsureModelReady",
+ )
+ parser.add_argument("--log-level", default="INFO")
+ parser.add_argument(
+ "--per-request-delay-ms",
+ type=float,
+ default=0.0,
+ help=(
+ "Inject this many milliseconds of asyncio.sleep at the top of every "
+ "process_*_batch RPC. Used by Rust pool integration tests to make "
+ "concurrent in-flight RPCs observable on `ipc_pool_inflight` / "
+ "`sie_worker_inflight_batches`; set to 0 in production-shaped tests."
+ ),
+ )
+ parser.add_argument(
+ "--tokenizer-path",
+ default=None,
+ help="Optional tokenizer.json path to expose through ModelDescriptor",
+ )
+ parser.add_argument(
+ "--tokenizer-id",
+ default=None,
+ help="Optional tokenizer content hash to expose through ModelDescriptor",
+ )
+ parser.add_argument(
+ "--max-seq-len",
+ type=int,
+ default=None,
+ help="Optional max sequence length to expose through ModelDescriptor",
+ )
+ parser.add_argument(
+ "--fake-generate-model",
+ default=None,
+ help=(
+ "Expose this model as generation-capable and handle ProcessGenerate "
+ "with a fake streaming processor for sidecar smoke tests."
+ ),
+ )
+ parser.add_argument(
+ "--fake-generate-hidden-polls",
+ type=int,
+ default=0,
+ help=(
+ "Return no generation models for this many WorkerCapabilities polls "
+ "before exposing --fake-generate-model. Used to exercise sidecar "
+ "activation after live config reconciliation."
+ ),
+ )
+ args = parser.parse_args()
+
+ logging.basicConfig(
+ level=args.log_level,
+ format="%(asctime)s %(levelname)s %(name)s — %(message)s",
+ )
+
+ descriptor = None
+ if args.tokenizer_path:
+ descriptor = ModelDescriptor(
+ tokenizer_path=args.tokenizer_path,
+ tokenizer_id=args.tokenizer_id,
+ max_seq_len=args.max_seq_len,
+ )
+
+ asyncio.run(
+ _main(
+ args.socket,
+ args.worker_id,
+ args.readiness,
+ args.per_request_delay_ms,
+ descriptor,
+ args.fake_generate_model,
+ args.fake_generate_hidden_polls,
+ )
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/packages/sie_server/src/sie_server/adapter_call_loop.py b/packages/sie_server/src/sie_server/adapter_call_loop.py
new file mode 100644
index 000000000..7dc0788bc
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapter_call_loop.py
@@ -0,0 +1,439 @@
+"""Adapter call loop for the Rust-driven scheduler.
+
+When a request lands on the worker-sidecar path, the worker-sidecar forms
+the batch itself (``sie_server_sidecar::scheduler::Scheduler``) and
+dispatches it over a single :data:`~sie_server.ipc_types.METHOD_RUN_BATCH`
+RPC. This module is the Python receiver for that RPC.
+
+The previous ``SIE_RUST_SCHEDULER_MODELS`` allowlist has been retired:
+routing decisions now live in the gateway's model-config API and pool
+selection. Any model that lands here is running through the worker-sidecar
+scheduler path.
+
+Design rationale — why this isn't just a method on ``QueueExecutor``:
+
+* The existing ``process_encode_batch`` / ``process_score_batch`` /
+ ``process_extract_batch`` methods on ``QueueExecutor`` are the
+ *authoritative* Python path. They stay untouched so direct Python
+ execution and the focused IPC compatibility tests behave
+ exactly as today — zero diff in the hot path.
+* ``adapter_call_loop`` is a **strict subset** of what those three
+ methods do: it accepts an already-formed batch (no batching, no
+ coalesce, no adaptive control — those live in Rust now) and fans
+ each ``RunBatchItem`` into the same per-op handlers the executor
+ already calls. All the adapter-side logic (``handlers.make_config_key``,
+ ``EncodePipeline.run_encode``, ``ModelWorker.submit``, ``_group_by_inference_config``,
+ ``_complete_requests``) is reused verbatim.
+* Keeping the dispatch thin here lets the Rust side own the only
+ behaviourally-novel piece (batch formation + FCFS across LoRAs + PI
+ loop) without duplicating the Python handler vocabulary.
+
+LoRA plumbing (single source of truth for the wire-boundary contract):
+
+* The Rust scheduler hands us **one** ``RunBatchRequest.lora_key`` per
+ batch — items inside the batch are guaranteed homogeneous by the
+ upstream FCFS-across-LoRAs scheduler. We forward that key into each
+ ``EncodeBatchItem.options["lora"]`` / ``ExtractBatchItem.options["lora"]``
+ before fanning out to the per-op handler. From there the existing
+ ``ModelWorker.submit`` path picks it up at lines like
+ ``options.get("lora")`` (``model_worker.py``) and routes the items into
+ the matching per-LoRA ``BatchFormer``, where ``_process_loop`` calls
+ ``self._adapter.set_active_lora(active_lora)`` before the forward
+ pass.
+* Empty / missing ``lora_key`` → no injection → ``options.get("lora")``
+ resolves to ``None`` → base-model batcher. The empty-string-to-``None``
+ coercion is the wire-boundary contract; a future native adapter must
+ apply the same normalisation.
+* Score is base-only — Python's ``ModelWorker.submit_score`` documents
+ this as "Score operations use base model batcher (no LoRA support
+ for reranking)". When ``RunBatch`` arrives with ``op="score"`` and a
+ non-empty ``lora_key`` we **log** and serve the base path rather
+ than fail the batch.
+* Pre-existing ``options["lora"]`` on individual items is **never**
+ silently overwritten — if a caller has already set it (e.g. legacy
+ client code that constructs ``EncodeBatchItem`` directly) and it
+ conflicts with the batch-level ``lora_key``, we log and trust the
+ per-item value. The Rust scheduler never produces this combination
+ today, so the warning surfaces a real protocol bug rather than
+ papering over one.
+
+Fallback contract:
+
+* Unknown ``op`` → typed error per item (``error_code =
+ "run_batch_unknown_op"``). Forward-compat safety: a newer Rust
+ build can ship an op this Python doesn't know, and the operator
+ sees a clean message instead of a crash.
+* Mixed-op batch → wholesale rejection with every outcome tagged
+ ``run_batch_mixed_op``. The Rust scheduler MUST only form
+ homogeneous-op batches; this is defence-in-depth, not an expected
+ code path.
+* Op tag / payload mismatch (e.g. ``op = "encode"`` but
+ ``encode = None``) → per-item ``run_batch_invalid_item``. Keeps
+ one bad item from sinking the whole batch.
+
+Every error path produces a ``publish_error_and_ack`` disposition —
+not a ``nak_retry`` — because the payload is ill-formed at the wire
+level and retrying would deliver the same bad frame. Matches the
+existing behaviour of the per-op handlers when ``msgspec.convert``
+fails.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING, Any
+
+from sie_server.ipc_types import (
+ BatchOutcome,
+ EncodeBatchItem,
+ ExtractBatchItem,
+ ItemOutcome,
+ ProcessEncodeBatchRequest,
+ ProcessExtractBatchRequest,
+ ProcessScoreBatchRequest,
+ RunBatchRequest,
+)
+
+if TYPE_CHECKING:
+ from sie_server.queue_executor import QueueExecutor
+
+logger = logging.getLogger(__name__)
+
+
+# Error codes emitted by this module. Kept as module-level constants
+# so callers (tests, log-greppers, dashboards) can import them without
+# stringly-typed drift. Mirrors the pattern in
+# ``queue_executor._RAW_OUTPUT_ERROR_CODE``.
+RUN_BATCH_EMPTY = "run_batch_empty"
+RUN_BATCH_MIXED_OP = "run_batch_mixed_op"
+RUN_BATCH_UNKNOWN_OP = "run_batch_unknown_op"
+RUN_BATCH_INVALID_ITEM = "run_batch_invalid_item"
+
+
+def _merge_lora_into_options(
+ existing: dict[str, Any] | None,
+ lora_key: str,
+ *,
+ item_id: str,
+ batch_id: int,
+ op: str,
+) -> dict[str, Any] | None:
+ """Return an options dict with ``options["lora"] = lora_key`` set.
+
+ Matches the legacy ``ModelWorker.submit`` contract where the
+ batcher selection is sourced from ``options.get("lora")``. Returns
+ ``existing`` unchanged when ``lora_key`` is empty (the base-model
+ case — leaving ``options["lora"]`` unset rather than setting it to
+ ``None`` keeps the two paths byte-identical).
+
+ Pre-existing per-item ``options["lora"]`` is never silently
+ overwritten: if it conflicts with the batch-level key we log and
+ trust the per-item value. The Rust scheduler never produces this
+ combination today (it partitions by lora_key before forming the
+ batch), so any conflict is a real upstream bug worth a WARN.
+ """
+ if not lora_key:
+ return existing
+
+ if existing is None:
+ return {"lora": lora_key}
+
+ prior = existing.get("lora")
+ if prior is not None and prior != lora_key:
+ logger.warning(
+ "run_batch (%s) item=%r batch_id=%d has options['lora']=%r but "
+ "RunBatchRequest.lora_key=%r — keeping per-item value; the Rust "
+ "scheduler should not produce mixed-LoRA batches",
+ op,
+ item_id,
+ batch_id,
+ prior,
+ lora_key,
+ )
+ return existing
+
+ if prior == lora_key:
+ # Already set to the same value — no copy needed.
+ return existing
+
+ # Avoid mutating the caller's dict. The msgspec deserialisation
+ # produces a fresh dict per call so this copy is cheap (a handful
+ # of items per batch in practice) and keeps the function pure.
+ merged = dict(existing)
+ merged["lora"] = lora_key
+ return merged
+
+
+async def handle_run_batch(
+ executor: QueueExecutor,
+ req: RunBatchRequest,
+) -> BatchOutcome:
+ """Dispatch a Rust-formed batch into the existing per-op handlers.
+
+ Contract:
+ * ``req.items`` must be non-empty and homogeneous in ``op``.
+ * ``req.model_id`` must be a model the executor can serve —
+ the gateway is responsible for only routing models served
+ by this worker image to the worker-sidecar; we don't
+ re-validate here because a model reaching this RPC means
+ the gateway has already decided we can serve it.
+
+ Returns a :class:`BatchOutcome` matching the per-op RPCs' shape
+ so the Rust publisher path is identical regardless of which RPC
+ produced the result (``process_*_batch`` or ``RunBatch``).
+ """
+ if not req.items:
+ logger.warning(
+ "run_batch received empty items list (model=%s, batch_id=%d, lora=%r)",
+ req.model_id,
+ req.batch_id,
+ req.lora_key,
+ )
+ # Empty batch is a protocol violation on the Rust side —
+ # scheduler should never flush zero items. Return an empty
+ # BatchOutcome; the Rust publisher treats this as a no-op.
+ return BatchOutcome(outcomes=[])
+
+ op = req.items[0].op
+ if any(item.op != op for item in req.items):
+ logger.error(
+ "run_batch got mixed-op batch (model=%s, batch_id=%d): "
+ "ops=%s — Rust scheduler MUST emit homogeneous-op batches",
+ req.model_id,
+ req.batch_id,
+ sorted({i.op for i in req.items}),
+ )
+ return _reject_all(req, RUN_BATCH_MIXED_OP, "mixed-op run_batch is not supported")
+
+ if op == "encode":
+ return await _dispatch_encode(executor, req)
+ if op == "score":
+ return await _dispatch_score(executor, req)
+ if op == "extract":
+ return await _dispatch_extract(executor, req)
+
+ logger.error(
+ "run_batch got unknown op=%r (model=%s, batch_id=%d)",
+ op,
+ req.model_id,
+ req.batch_id,
+ )
+ return _reject_all(req, RUN_BATCH_UNKNOWN_OP, f"unknown op {op!r}")
+
+
+# --------------------------------------------------------------------
+# Per-op dispatchers
+# --------------------------------------------------------------------
+#
+# Each dispatcher validates that every RunBatchItem has its matching
+# payload populated, then unwraps into the existing Process*Request
+# type and calls the same method the per-op RPC already uses.
+# Any validation miss on a single item becomes a typed error on that
+# item only — the rest of the batch proceeds.
+
+
+async def _dispatch_encode(
+ executor: QueueExecutor,
+ req: RunBatchRequest,
+) -> BatchOutcome:
+ items: list[EncodeBatchItem] = []
+ invalid: list[ItemOutcome] = []
+ for ri in req.items:
+ if ri.encode is None:
+ invalid.append(
+ _invalid_item_outcome(
+ request_id=ri.request_id,
+ work_item_id=ri.work_item_id,
+ item_index=ri.item_index,
+ reason="op=encode but encode payload missing",
+ )
+ )
+ continue
+ # Plumb RunBatchRequest.lora_key into the per-item options so
+ # ``ModelWorker.submit`` (line ~411 of model_worker.py:
+ # ``options.get("lora")``) routes the item into the matching
+ # per-LoRA batcher and ``_process_loop`` calls
+ # ``set_active_lora(active_lora)`` before the forward pass.
+ merged_options = _merge_lora_into_options(
+ ri.encode.options,
+ req.lora_key,
+ item_id=ri.encode.work_item_id,
+ batch_id=req.batch_id,
+ op="encode",
+ )
+ if merged_options is ri.encode.options:
+ items.append(ri.encode)
+ else:
+ # ``msgspec.Struct.replace``-equivalent: build a new struct
+ # rather than mutating the deserialised one. We only enter
+ # this branch when an injection actually happens, so the
+ # base-LoRA hot path stays allocation-free.
+ items.append(_with_options(ri.encode, merged_options))
+
+ if not items:
+ return BatchOutcome(outcomes=invalid)
+
+ inner = ProcessEncodeBatchRequest(model_id=req.model_id, items=items)
+ outcome = await executor.process_encode_batch(inner)
+ return BatchOutcome(outcomes=[*invalid, *outcome.outcomes])
+
+
+async def _dispatch_score(
+ executor: QueueExecutor,
+ req: RunBatchRequest,
+) -> BatchOutcome:
+ # Score is base-only: ``ModelWorker.submit_score`` always uses
+ # ``self._batchers[None]``. We "downgrade to WARN, serve base" here
+ # so a misrouted batch produces a visible log line rather than a
+ # silent drop or a NAK that confuses retry logic.
+ if req.lora_key:
+ logger.warning(
+ "run_batch op=score for model=%s arrived with lora_key=%r — "
+ "score has no LoRA support (ModelWorker.submit_score), "
+ "serving base weights for batch_id=%d",
+ req.model_id,
+ req.lora_key,
+ req.batch_id,
+ )
+
+ items = []
+ invalid: list[ItemOutcome] = []
+ for ri in req.items:
+ if ri.score is None:
+ invalid.append(
+ _invalid_item_outcome(
+ request_id=ri.request_id,
+ work_item_id=ri.work_item_id,
+ item_index=ri.item_index,
+ reason="op=score but score payload missing",
+ )
+ )
+ continue
+ items.append(ri.score)
+
+ if not items:
+ return BatchOutcome(outcomes=invalid)
+
+ inner = ProcessScoreBatchRequest(model_id=req.model_id, items=items)
+ outcome = await executor.process_score_batch(inner)
+ return BatchOutcome(outcomes=[*invalid, *outcome.outcomes])
+
+
+async def _dispatch_extract(
+ executor: QueueExecutor,
+ req: RunBatchRequest,
+) -> BatchOutcome:
+ items: list[ExtractBatchItem] = []
+ invalid: list[ItemOutcome] = []
+ for ri in req.items:
+ if ri.extract is None:
+ invalid.append(
+ _invalid_item_outcome(
+ request_id=ri.request_id,
+ work_item_id=ri.work_item_id,
+ item_index=ri.item_index,
+ reason="op=extract but extract payload missing",
+ )
+ )
+ continue
+ # Same reasoning as ``_dispatch_encode``: plumb the batch-level
+ # lora_key into ``options["lora"]`` so the legacy
+ # ``ModelWorker.submit_extract`` path picks the right batcher
+ # (model_worker.py line ~464).
+ merged_options = _merge_lora_into_options(
+ ri.extract.options,
+ req.lora_key,
+ item_id=ri.extract.work_item_id,
+ batch_id=req.batch_id,
+ op="extract",
+ )
+ if merged_options is ri.extract.options:
+ items.append(ri.extract)
+ else:
+ items.append(_with_options(ri.extract, merged_options))
+
+ if not items:
+ return BatchOutcome(outcomes=invalid)
+
+ inner = ProcessExtractBatchRequest(model_id=req.model_id, items=items)
+ outcome = await executor.process_extract_batch(inner)
+ return BatchOutcome(outcomes=[*invalid, *outcome.outcomes])
+
+
+def _with_options[OptionsItemT: (EncodeBatchItem, ExtractBatchItem)](
+ item: OptionsItemT,
+ options: dict[str, Any] | None,
+) -> OptionsItemT:
+ """Return a copy of ``item`` with ``options`` replaced.
+
+ Uses ``msgspec.structs.replace`` semantics — preserves every other
+ field byte-for-byte. We avoid mutating the input struct because the
+ deserialised request may be referenced by RPC framing/logging
+ helpers downstream and silent mutation is a debugging hazard.
+
+ Generic over the two item structs that actually carry an
+ ``options`` field so callers preserve their narrowed type
+ (``items.append(_with_options(ri.encode, ...))`` keeps
+ ``list[EncodeBatchItem]``).
+ """
+ import msgspec.structs # noqa: PLC0415 (local import keeps the cold path cold)
+
+ return msgspec.structs.replace(item, options=options)
+
+
+# --------------------------------------------------------------------
+# Error helpers
+# --------------------------------------------------------------------
+
+
+def _reject_all(req: RunBatchRequest, error_code: str, error: str) -> BatchOutcome:
+ """Produce a BatchOutcome that fails every item uniformly.
+
+ Used for batch-level protocol errors (empty, mixed-op, unknown
+ op). Every item's disposition is ``publish_error_and_ack``; the
+ Rust publisher surfaces the error_code on the wire so the SDK
+ sees a structured error rather than a timeout.
+ """
+ outcomes: list[ItemOutcome] = []
+ for idx, ri in enumerate(req.items):
+ work_item_id = ri.work_item_id
+ request_id = ri.request_id
+ item_index = getattr(ri, "item_index", idx)
+ # Pull the id out of whichever payload is populated — we do not know
+ # which, because the whole point of this path is the protocol error.
+ # Prefer the wrapped payload when present so malformed frames still get
+ # useful IDs.
+ payload = ri.encode or ri.score or ri.extract
+ if payload is not None:
+ work_item_id = payload.work_item_id
+ request_id = payload.request_id
+ item_index = payload.item_index
+ outcomes.append(
+ ItemOutcome(
+ work_item_id=work_item_id,
+ request_id=request_id,
+ item_index=item_index,
+ disposition="publish_error_and_ack",
+ error=error,
+ error_code=error_code,
+ )
+ )
+ return BatchOutcome(outcomes=outcomes)
+
+
+def _invalid_item_outcome(
+ *,
+ request_id: str,
+ work_item_id: str,
+ item_index: int,
+ reason: str,
+) -> ItemOutcome:
+ """Single-item error outcome for op-tag / payload mismatches."""
+ return ItemOutcome(
+ work_item_id=work_item_id,
+ request_id=request_id,
+ item_index=item_index,
+ disposition="publish_error_and_ack",
+ error=reason,
+ error_code=RUN_BATCH_INVALID_ITEM,
+ )
diff --git a/packages/sie_server/src/sie_server/adapters/_generation_base.py b/packages/sie_server/src/sie_server/adapters/_generation_base.py
index 208ce8eb5..640388118 100644
--- a/packages/sie_server/src/sie_server/adapters/_generation_base.py
+++ b/packages/sie_server/src/sie_server/adapters/_generation_base.py
@@ -8,10 +8,8 @@ cancellation, and partial-state semantics are not a method bolt-on. The
- async-iterator ``generate(prompt, ...)`` yielding :class:`GenerationChunk`
- worker dispatch on ``isinstance(adapter, GenerationAdapter)``
-The streaming contract replaces the walking-skeleton's blocking shape: concrete adapters yield chunks
-as the upstream engine produces them, with the terminal chunk carrying
-``finish_reason`` and ``usage``. See
-``product/research/generation-primitive-status.md`` (§2 deliverables, §3 measurements).
+Concrete adapters yield chunks as the upstream engine produces them, with the
+terminal chunk carrying ``finish_reason`` and ``usage``.
"""
from __future__ import annotations
diff --git a/packages/sie_server/src/sie_server/adapters/_utils.py b/packages/sie_server/src/sie_server/adapters/_utils.py
index b9488f8af..ff31509f1 100644
--- a/packages/sie_server/src/sie_server/adapters/_utils.py
+++ b/packages/sie_server/src/sie_server/adapters/_utils.py
@@ -114,7 +114,10 @@ def extract_texts(
text = item.text
if template:
- text = template.format(text=text, instruction=instruction or "")
+ kwargs: dict[str, str] = {"text": text}
+ if "{instruction}" in template:
+ kwargs["instruction"] = instruction or ""
+ text = template.format(**kwargs)
elif instruction:
text = f"{instruction} {text}"
diff --git a/packages/sie_server/src/sie_server/adapters/base.py b/packages/sie_server/src/sie_server/adapters/base.py
index 9719bcb54..6166f2e38 100644
--- a/packages/sie_server/src/sie_server/adapters/base.py
+++ b/packages/sie_server/src/sie_server/adapters/base.py
@@ -1,7 +1,4 @@
-"""Base model adapter interface.
-
-See DESIGN.md Section 7.3 for specification.
-"""
+"""Base model adapter interface."""
import logging
from abc import ABC, abstractmethod
@@ -46,7 +43,7 @@ class ModelAdapter(ABC):
Each model adapter wraps a specific model architecture and provides
a consistent interface for loading, inference, and unloading.
- Adapters are resolved in this order (see DESIGN.md Section 7.2):
+ Adapters are resolved in this order:
1. base_model: inherit adapter from another model's config
2. adapter: adapter.py:ClassName (file in model directory)
3. adapter: sie_server.adapters.module:ClassName (built-in adapter)
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 87b1b30f6..84d6dfb63 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
@@ -20,8 +20,6 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-_ERR_CUDA_REQUIRED = "BertFlashCrossEncoder requires CUDA for Flash Attention."
-
class BertFlashCrossEncoderAdapter(FlashBaseAdapter):
"""Cross-encoder adapter with Flash Attention 2 varlen.
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 13c14718a..cc626f0e3 100644
--- a/packages/sie_server/src/sie_server/adapters/clip/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/clip/__init__.py
@@ -3,8 +3,8 @@
This adapter provides support for CLIP and similar image-text models that
produce aligned embeddings for both images and text in a shared vector space.
-Per roadmap Project 10.4, uses transformers CLIPModel with CLIPProcessor
-for Phase 1. Optimization (FA2 varlen for text) deferred to Phase 2.
+Uses transformers CLIPModel with CLIPProcessor. Optimization (FA2 varlen for
+text) remains deferred.
Supports:
- Text-only encoding → dense embeddings
@@ -66,6 +66,7 @@ class CLIPAdapter(BaseAdapter):
compute_precision: ComputePrecision = "float16",
trust_remote_code: bool = False,
max_seq_length: int | None = None,
+ dense_dim: int | None = None,
) -> None:
"""Initialize the adapter.
@@ -75,16 +76,19 @@ 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.
+ dense_dim: Catalog-declared dense embedding dimension. If provided,
+ validated against the loaded model's projection dimension.
"""
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._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 = None
+ self._dense_dim: int | None = dense_dim
def load(self, device: str) -> None:
"""Load the model onto the specified device.
@@ -121,9 +125,18 @@ class CLIPAdapter(BaseAdapter):
self._model.to(device)
self._model.eval()
- # Get embedding dimension from model config
- # CLIP uses projection_dim for the aligned embedding space
- self._dense_dim = self._model.config.projection_dim
+ # CLIP uses projection_dim for the aligned embedding space.
+ self._dense_dim = self._validate_or_set_dense_dim(self._model.config.projection_dim)
+
+ def _validate_or_set_dense_dim(self, observed_dim: int) -> int:
+ """Validate observed CLIP projection width against configured dense_dim."""
+ if self._configured_dense_dim is not None and observed_dim != self._configured_dense_dim:
+ msg = (
+ "CLIP embedding dimension mismatch: "
+ f"configured dense_dim={self._configured_dense_dim}, model projection_dim={observed_dim}"
+ )
+ raise ValueError(msg)
+ return observed_dim
def _resolve_dtype(self) -> torch.dtype:
"""Resolve dtype based on device and config."""
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 02203e3ec..7565e5a03 100644
--- a/packages/sie_server/src/sie_server/adapters/colpali/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/colpali/__init__.py
@@ -10,9 +10,8 @@ ColPali models:
Target model: vidore/colpali-v1.3-hf (PaliGemma-based, 3B params)
-Per roadmap Project 10.5 Phase 1:
- Uses transformers ColPaliForRetrieval + ColPaliProcessor
-- Optimization (FA2 varlen, SGLang) deferred to Phase 2/3
+- Optimization (FA2 varlen, SGLang) remains deferred
See: https://huggingface.co/vidore/colpali-v1.3-hf
"""
@@ -305,16 +304,14 @@ class ColPaliAdapter(BaseAdapter):
if not has_text and not has_images:
raise ValueError(_ERR_NO_INPUT)
- # For queries, prefer text; for documents, prefer images
+ # For queries, prefer text; for documents, prefer images. The top guard
+ # guarantees has_text once we get past has_images.
if is_query and has_text:
return self._encode_text(item.text)
if has_images:
pil_images = self._load_images(item)
return self._encode_images(pil_images)
- if has_text:
- return self._encode_text(item.text)
-
- raise ValueError(_ERR_NO_INPUT)
+ return self._encode_text(item.text)
def _load_images(self, item: Any) -> list[Image.Image]:
"""Load images from item into PIL Images.
@@ -368,13 +365,21 @@ class ColPaliAdapter(BaseAdapter):
# For single image, return [num_patches, 128]
# For multiple images, concatenate patches
if len(images) == 1:
- return embeddings[0].float().cpu().numpy()
+ result = embeddings[0].float().cpu().numpy()
+ else:
+ # Concatenate all image patches
+ all_patches = []
+ for i in range(len(images)):
+ all_patches.append(embeddings[i].float().cpu().numpy())
+ result = np.concatenate(all_patches, axis=0)
+
+ # Free GPU memory from intermediate tensors to prevent OOM on
+ # subsequent batches (L4 22GB GPUs are tight for VLM models).
+ del embeddings, batch
+ if self._device and self._device.startswith("cuda"):
+ torch.cuda.empty_cache()
- # Concatenate all image patches
- all_patches = []
- for i in range(len(images)):
- all_patches.append(embeddings[i].float().cpu().numpy())
- return np.concatenate(all_patches, axis=0)
+ return result
def _encode_text(self, text: str) -> np.ndarray:
"""Encode text query into multi-vector embeddings.
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 d14669788..cecbc45f5 100644
--- a/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py
@@ -302,10 +302,8 @@ class ColQwen2Adapter(BaseAdapter):
return self._encode_text(item.text)
if has_images:
return self._encode_images(self._load_images(item))
- if has_text:
- return self._encode_text(item.text)
-
- raise ValueError(_ERR_NO_INPUT)
+ # The top guard guarantees has_text once we get here.
+ return self._encode_text(item.text)
# ------------------------------------------------------------------
# Image encoding
@@ -393,7 +391,11 @@ class ColQwen2Adapter(BaseAdapter):
results = [embeddings[i].float().cpu().numpy() for i in range(len(images))]
+ # Free GPU memory from intermediate tensors to prevent OOM on
+ # subsequent encode 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
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 4fcff29f9..87cba2d36 100644
--- a/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py
@@ -125,6 +125,25 @@ class ColQwen3Adapter(BaseAdapter):
if isinstance(out_features, int) and out_features > 0:
self._multivector_dim = out_features
+ # FIX[#1055]: propagate the requested attention impl onto the inner VLM.
+ # The model builds ``self.vlm`` via ``AutoModelForImageTextToText.from_config``
+ # with a *fresh* ``Qwen3VLConfig`` that does not inherit the
+ # ``attn_implementation`` passed to ``from_pretrained`` (and its own
+ # ``attn_impl`` constructor hook is never invoked by ``from_pretrained``),
+ # so the inner VLM silently defaults to sdpa. On the sdpa/eager path
+ # Qwen3-VL's vision attention falls back to a per-image Python loop over
+ # ``torch.split`` (one attention call per image per layer), which
+ # serializes the batch and starves the GPU (~27s/image, util ~31%).
+ # Re-dispatching to flash_attention_2 routes the whole batch through the
+ # single cu_seqlens flash-varlen call.
+ self._apply_attn_implementation(attn_impl)
+
+ # FIX[#1055]: replace the vision Conv3d patch-embed with its matmul
+ # equivalent. It dominated the forward at ~169s/6-image batch (99.7% of
+ # the vision tower; the transformer blocks were only ~140ms each) — see
+ # _patch_vision_patch_embed for why.
+ self._patch_vision_patch_embed()
+
def _resolve_dtype(self) -> torch.dtype:
if not self._device or not str(self._device).startswith("cuda"):
return torch.float32
@@ -146,6 +165,59 @@ class ColQwen3Adapter(BaseAdapter):
logger.info("flash_attn not available, using sdpa attention")
return "sdpa"
+ def _apply_attn_implementation(self, attn_impl: str | None) -> None:
+ """Force the requested attention impl onto the inner Qwen3-VL (``self.vlm``).
+
+ Needed because the requested impl does not propagate through the model's
+ ``from_config`` construction. Best-effort: on failure we keep the inner
+ default (sdpa) rather than break loading.
+ """
+ if attn_impl is None or attn_impl == "sdpa":
+ return
+ vlm = getattr(self._model, "vlm", None)
+ if vlm is None or not hasattr(vlm, "set_attn_implementation"):
+ logger.warning("ColQwen3: inner VLM cannot set attn_implementation; keeping default")
+ return
+ try:
+ vlm.set_attn_implementation(attn_impl)
+ logger.info("ColQwen3: set inner-VLM attn_implementation=%s", attn_impl)
+ except Exception: # noqa: BLE001 - best-effort, keep loaded default on failure
+ logger.warning("ColQwen3: could not set inner-VLM attn=%s; keeping default", attn_impl, exc_info=True)
+
+ def _patch_vision_patch_embed(self) -> None:
+ """Rebind the Qwen3-VL vision Conv3d patch-embed to its matmul equivalent.
+
+ ``Qwen3VLVisionPatchEmbed`` projects patches with a ``nn.Conv3d`` whose
+ kernel equals its stride, i.e. a non-overlapping per-patch linear
+ projection. On this GPU the cuDNN Conv3d path for the (~30k-patch,
+ tiny-kernel) shape is pathologically slow — measured at ~169s for a
+ 6-image batch, ~99.7% of the whole vision-tower forward, while the 24
+ transformer blocks took only ~140ms each. Reshaping to ``F.linear`` with
+ the *same weights* is numerically identical but runs as a fast matmul.
+
+ Best-effort: on any structural mismatch we leave the original Conv3d.
+ """
+ try:
+ visual = self._model.vlm.model.visual
+ patch_embed = visual.patch_embed
+ proj = patch_embed.proj
+ if not isinstance(proj, torch.nn.Conv3d):
+ return
+ embed_dim = proj.out_channels
+ in_features = proj.in_channels * proj.kernel_size[0] * proj.kernel_size[1] * proj.kernel_size[2]
+
+ def fast_patch_embed_forward(
+ hidden_states: torch.Tensor, _pe: Any = patch_embed, _embed: int = embed_dim, _in: int = in_features
+ ) -> torch.Tensor:
+ weight = _pe.proj.weight
+ hs = hidden_states.to(weight.dtype).reshape(-1, _in)
+ return F.linear(hs, weight.reshape(_embed, _in), _pe.proj.bias)
+
+ patch_embed.forward = fast_patch_embed_forward
+ logger.info("ColQwen3: replaced vision Conv3d patch-embed with matmul equivalent")
+ except Exception: # noqa: BLE001 - best-effort, keep the original Conv3d on failure
+ logger.warning("ColQwen3: could not rebind vision patch-embed; keeping Conv3d", exc_info=True)
+
# ------------------------------------------------------------------
# Encode
# ------------------------------------------------------------------
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 22815d3d1..77f368d97 100644
--- a/packages/sie_server/src/sie_server/adapters/docling/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/docling/__init__.py
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Any, ClassVar
from sie_server.adapters._base_adapter import BaseAdapter
from sie_server.adapters._spec import AdapterSpec
from sie_server.core.inference_output import ExtractOutput
-from sie_server.types.inputs import is_document_input
+from sie_server.types.inputs import is_document_input, is_image_input
if TYPE_CHECKING:
from sie_server.types.inputs import Item
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
logger = logging.getLogger(__name__)
-_ERR_REQUIRES_DOCUMENT = "Docling requires Item.document with raw bytes"
+_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
# during load() so the first user request doesn't pay the download latency.
@@ -65,7 +65,7 @@ class DoclingAdapter(BaseAdapter):
"""
spec: ClassVar[AdapterSpec] = AdapterSpec(
- inputs=("document",),
+ inputs=("document", "image"),
outputs=("json",),
unload_fields=(),
)
@@ -137,12 +137,23 @@ class DoclingAdapter(BaseAdapter):
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]:
+ # 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.
document = item.document
- if not is_document_input(document):
- return {"error": _ERR_REQUIRES_DOCUMENT}
+ if is_document_input(document):
+ payload = document["data"]
+ format_hint = document.get("format")
+ else:
+ images = item.images or []
+ first_image = images[0] if images else None
+ if not is_image_input(first_image):
+ return {"error": _ERR_REQUIRES_DOCUMENT}
+ payload = first_image["data"]
+ format_hint = first_image.get("format") or "png"
try:
converter = self._get_converter(ocr_enabled=ocr_enabled)
- return self._convert_bytes(converter, document["data"], format_hint=document.get("format"))
+ 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)}
@@ -184,7 +195,7 @@ class DoclingAdapter(BaseAdapter):
from docling.datamodel.base_models import InputFormat # ty: ignore[unresolved-import]
from docling.datamodel.pipeline_options import PdfPipelineOptions # ty: ignore[unresolved-import]
- from docling.document_converter import PdfFormatOption # ty: ignore[unresolved-import]
+ from docling.document_converter import ImageFormatOption, PdfFormatOption # ty: ignore[unresolved-import]
# Pass do_ocr explicitly on both paths. Docling's PdfPipelineOptions defaults
# do_ocr=True, so an unset default would silently OCR every PDF and make the
@@ -193,7 +204,17 @@ class DoclingAdapter(BaseAdapter):
if accelerator_options is not None:
pdf_kwargs["accelerator_options"] = accelerator_options
pdf_opts = PdfPipelineOptions(**pdf_kwargs)
- return DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=pdf_opts)})
+ # Reuse the same PdfPipelineOptions for IMAGE input: Docling's image
+ # pipeline shares the layout/OCR model stack with the PDF pipeline,
+ # and re-using the option object keeps device/ocr settings in lock-step.
+ # ImageFormatOption attaches the ImageDocumentBackend so Docling doesn't
+ # auto-correct + deprecation-warn on every image request.
+ return DocumentConverter(
+ format_options={
+ InputFormat.PDF: PdfFormatOption(pipeline_options=pdf_opts),
+ InputFormat.IMAGE: ImageFormatOption(pipeline_options=pdf_opts),
+ }
+ )
def _build_accelerator_options(self) -> Any:
"""Translate self._device into a Docling AcceleratorOptions, or None."""
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 7590bba13..8678a710f 100644
--- a/packages/sie_server/src/sie_server/adapters/donut/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/donut/__init__.py
@@ -285,8 +285,6 @@ class DonutAdapter(BaseAdapter):
Returns:
ExtractOutput with entities.
"""
- import re
-
from sie_server.core.prepared import DonutPayload, PreparedItem
all_entities = []
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 628ad9dce..20c8d11a2 100644
--- a/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/gliner/__init__.py
@@ -12,8 +12,6 @@ Reference models:
- urchade/gliner_small-v2.1 (English, smaller/faster)
- numind/NuNER_Zero (token-based, requires merge_adjacent_entities=True)
- numind/NuNER_Zero-span (span-based, works without merging)
-
-See DESIGN.md Section 7.6 for adapter specification.
"""
from pathlib import 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 6d22d3350..2b82ee292 100644
--- a/packages/sie_server/src/sie_server/adapters/glirel/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/glirel/__init__.py
@@ -7,8 +7,6 @@ they output (head, relation, tail) triples with confidence scores.
Reference models:
- jackboyla/glirel-large-v0 (zero-shot relation extraction)
- jackboyla/glirel_re_large-v0 (relation-focused variant)
-
-See DESIGN.md Section 7.6 for adapter specification.
"""
from pathlib import Path
@@ -25,7 +23,6 @@ from sie_server.types.responses import Entity, Relation
# Error messages
_ERR_REQUIRES_LABELS = "GLiREL requires labels parameter for relation extraction"
-_ERR_REQUIRES_ENTITIES = "GLiREL requires entities in metadata for relation extraction"
class GLiRELAdapter(BaseAdapter):
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 a97aea477..88eb7c541 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
@@ -3,10 +3,12 @@ from __future__ import annotations
import gc
import io
import logging
+import math
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
import torch
+import torch.nn.functional as F
from sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDims
from sie_server.core.inference_output import EncodeOutput, ExtractOutput
@@ -118,10 +120,113 @@ class GlmOcrAdapter(ModelAdapter):
self._model.to(device) # ty: ignore[invalid-argument-type]
self._model.eval()
+ # The vision tower's patch embedding is a non-overlapping nn.Conv3d
+ # (kernel == stride), i.e. a per-patch linear projection. On CUDA cuDNN
+ # dispatches it as ~one tiny kernel launch per patch (tens of thousands
+ # per page), so the GPU sits idle while a single CPU thread launches
+ # kernels — the dominant cost of every request. Rebind it to the
+ # mathematically identical F.linear (one GEMM) to remove that.
+ self._patch_vision_patch_embed()
+
self._create_preprocessor()
logger.info("GLM-OCR model loaded successfully")
+ def _patch_vision_patch_embed(self) -> None:
+ """Rebind the vision patch-embed Conv to an equivalent F.linear.
+
+ Finds the non-overlapping convolution (``kernel_size == stride``) inside
+ the vision tower and replaces its ``forward`` with the numerically
+ identical matmul. Self-validating: a small synthetic patch batch is run
+ through both the original conv and the matmul at load time, and the fast
+ path is kept only if the outputs match (within bf16 rounding); otherwise
+ a warning is logged and the original conv is left in place. No weights
+ are changed and the check stays off the request path.
+ """
+ if self._model is None:
+ return
+
+ # Non-overlapping convs (kernel == stride) inside the vision tower. The
+ # patch embed is one such conv, but the tower may have others — e.g. a
+ # spatial-merge ``downsample`` Conv2d (also kernel == stride). The patch
+ # embed is the pathological one (~one tiny kernel launch per patch);
+ # disambiguate by input channels: the patch embed consumes raw image
+ # channels (RGB, ≤ 4), while merge/downsample convs consume the hidden dim.
+ convs: list[tuple[str, torch.nn.Conv2d | torch.nn.Conv3d]] = []
+ for name, mod in self._model.named_modules():
+ lname = name.lower()
+ if (
+ isinstance(mod, (torch.nn.Conv2d, torch.nn.Conv3d))
+ and tuple(mod.kernel_size) == tuple(mod.stride)
+ and ("vis" in lname or "patch" in lname or "embed" in lname)
+ ):
+ convs.append((name, mod))
+
+ # Identify the patch embed strictly by structure: it is the only vision
+ # conv that consumes raw image channels (RGB). Any other kernel==stride
+ # conv (e.g. a spatial-merge downsample) consumes the hidden dim. If this
+ # is not unique we do not guess — leave the original conv in place rather
+ # than risk rebinding a module whose runtime input is not per-patch
+ # shaped (fast_forward assumes one flattened patch per row).
+ patch = [c for c in convs if c[1].in_channels <= 4]
+ if len(patch) != 1:
+ logger.warning(
+ "[glm_ocr] patch-embed rebind skipped: expected exactly one RGB-input (in_channels<=4) "
+ "vision conv, found %d among %s",
+ len(patch),
+ [n for n, _ in convs],
+ )
+ return
+
+ name, conv = patch[0]
+ out_ch = conv.out_channels
+ spatial_dims = len(conv.kernel_size)
+ in_features = conv.in_channels * math.prod(conv.kernel_size)
+ weight_2d = conv.weight.reshape(out_ch, in_features) # view; shares storage, no copy
+ bias = conv.bias
+
+ def fast_forward(x: torch.Tensor) -> torch.Tensor:
+ n = x.shape[0]
+ out = F.linear(x.reshape(n, -1).to(weight_2d.dtype), weight_2d, bias)
+ return out.reshape(n, out_ch, *([1] * spatial_dims))
+
+ # Validate equivalence on a small synthetic patch batch at load time
+ # (off the request path) before swapping. The op is mathematically a
+ # matmul over the flattened patch, so any divergence beyond bf16 rounding
+ # means the shape assumption is wrong — keep the original conv if so.
+ with torch.inference_mode():
+ probe = torch.randn(
+ 8, conv.in_channels, *conv.kernel_size, device=conv.weight.device, dtype=conv.weight.dtype
+ )
+ ref = conv(probe).float()
+ got = fast_forward(probe).float().reshape_as(ref)
+ max_abs = (ref - got).abs().max().item()
+ # The conv and the matmul are the same operation, so they differ only by
+ # low-precision (bf16) rounding — small relative to the output scale. A
+ # genuine shape mismatch instead produces differences on the order of the
+ # outputs themselves. Tolerance scaled to the output magnitude separates
+ # the two cleanly without a magic absolute constant.
+ tol = 1e-2 + 0.05 * ref.abs().max().item()
+ if not math.isfinite(max_abs) or max_abs > tol:
+ logger.warning(
+ "[glm_ocr] patch-embed rebind skipped: %s output mismatch (max_abs_diff=%.3e tol=%.3e)",
+ name,
+ max_abs,
+ tol,
+ )
+ return
+
+ conv.forward = fast_forward # ty: ignore[invalid-assignment]
+ logger.info(
+ "[glm_ocr] rebound vision patch-embed %s (%s, kernel=%s) to F.linear (in=%d out=%d, max_abs_diff=%.3e)",
+ name,
+ type(conv).__name__,
+ tuple(conv.kernel_size),
+ in_features,
+ out_ch,
+ max_abs,
+ )
+
def _resolve_dtype(self, device: str) -> torch.dtype:
"""Resolve dtype based on device and config."""
if not device.startswith("cuda"):
diff --git a/packages/sie_server/src/sie_server/adapters/mineru_vl/__init__.py b/packages/sie_server/src/sie_server/adapters/mineru_vl/__init__.py
new file mode 100644
index 000000000..d8371c8ac
--- /dev/null
+++ b/packages/sie_server/src/sie_server/adapters/mineru_vl/__init__.py
@@ -0,0 +1,434 @@
+from __future__ import annotations
+
+import io
+import logging
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, ClassVar
+
+import torch
+
+from sie_server.adapters._base_adapter import BaseAdapter
+from sie_server.adapters._spec import AdapterSpec
+from sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision
+from sie_server.core.inference_output import EncodeOutput, ExtractOutput
+from sie_server.types.inputs import media_bytes
+from sie_server.types.responses import Entity
+
+if TYPE_CHECKING:
+ from sie_server.types.inputs import Item
+
+logger = logging.getLogger(__name__)
+
+_ERR_NO_IMAGES = "MinerUVLAdapter requires image input for extraction"
+_ERR_ENCODE_NOT_SUPPORTED = "MinerUVLAdapter does not support encode(). Use extract() instead."
+_ERR_FP16_UNSUPPORTED = (
+ "MinerU2.5-Pro does not support float16 on CUDA (config pins bfloat16); use bfloat16 or float32."
+)
+
+# Canonical task -> prompt mapping from upstream mineru_vl_utils.mineru_client.
+# Bracketed task names (``[default]``, ``[layout]``) mirror the upstream
+# convention — preserve them verbatim. Leading newline in the prompt strings
+# is intentional (MinerU's prompts start with "\n"); do NOT strip it. Keep in
+# sync with preprocessor/vision.py::_MINERU_VL_TASK_PROMPTS.
+_TASK_PROMPTS: dict[str, str] = {
+ "[default]": "\nText Recognition:",
+ "table": "\nTable Recognition:",
+ "equation": "\nFormula Recognition:",
+ "image": "\nImage Analysis:",
+ "chart": "\nImage Analysis:",
+ "[layout]": "\nLayout Detection:",
+}
+_VALID_TASKS: tuple[str, ...] = tuple(_TASK_PROMPTS)
+_DEFAULT_TASK = "[default]"
+
+# HF-applicable subset of mineru_vl_utils' DEFAULT_SAMPLING_PARAMS.
+# ``presence_penalty`` and ``frequency_penalty`` from MinerU's defaults are
+# vLLM-only knobs — HF's ``generate`` silently drops them. Greedy decoding
+# (``do_sample=False``) is MinerU's production setting; ``repetition_penalty``
+# reproduces MinerU's transformers-backend recipe. ``no_repeat_ngram_size`` is
+# applied via a fast logits processor (see ``_ngram_logits_processor``).
+_NO_REPEAT_NGRAM_SIZE = 100
+_MINERU_GENERATE_KWARGS: dict[str, Any] = {
+ "do_sample": False,
+ "repetition_penalty": 1.0,
+}
+
+
+class _IncrementalNoRepeatNGramLogitsProcessor:
+ """Bit-identical, O(ngram_size)-per-step drop-in for HF's ``NoRepeatNGramLogitsProcessor``.
+
+ HF's stock processor rebuilds the entire n-gram table and does a full
+ GPU->CPU ``.tolist()`` of the growing sequence on *every* decode step —
+ O(L^2) pure-Python work plus one host sync per token. On MinerU's dense
+ pages that reach the 4096-token cap this single-threaded loop pegs one CPU
+ core and starves the GPU (measured ~20% util, ``load``~=1.0). This version
+ keeps the table incrementally: each step it adds only the single n-gram
+ completed by the previous token and syncs only that token, so per-step cost
+ is O(ngram_size) instead of O(sequence_length * ngram_size). It produces
+ identical bans (verified in tests) — at ngram_size=100 the guard still
+ fires only on a verbatim 100-token repeat (the runaway-loop case).
+
+ Stateful, hence single-sequence / greedy only: beam search reorders
+ hypotheses between steps and would invalidate the cached table, so the
+ adapter only wires this in for ``num_beams == 1`` and keeps HF's stateless
+ processor otherwise. Construct a fresh instance per ``generate`` call.
+ """
+
+ def __init__(self, ngram_size: int) -> None:
+ self._n = ngram_size
+ self._tokens: list[int] = []
+ self._ngrams: dict[tuple[int, ...], list[int]] = {}
+ self._seen_len = 0
+
+ def __call__(self, input_ids: torch.Tensor, scores: torch.Tensor) -> torch.Tensor:
+ n = self._n
+ cur_len = input_ids.shape[-1]
+ if self._seen_len == 0:
+ # First call: ingest the whole prompt prefix once (O(prefix)).
+ self._tokens = input_ids[0].tolist()
+ for end in range(n - 1, len(self._tokens)):
+ self._ngrams.setdefault(tuple(self._tokens[end - n + 1 : end]), []).append(self._tokens[end])
+ else:
+ # Later calls: append only tokens added since the last step
+ # (normally exactly one) and extend the table incrementally.
+ for tok in input_ids[0, self._seen_len :].tolist():
+ self._tokens.append(tok)
+ if len(self._tokens) >= n:
+ self._ngrams.setdefault(tuple(self._tokens[-n:-1]), []).append(self._tokens[-1])
+ self._seen_len = cur_len
+
+ if cur_len + 1 < n:
+ return scores
+ banned = self._ngrams.get(tuple(self._tokens[cur_len - n + 1 : cur_len]))
+ if not banned:
+ return scores
+ scores_processed = scores.clone()
+ scores_processed[0, banned] = -float("inf")
+ return scores_processed
+
+
+def _ngram_logits_processor(num_beams: int) -> dict[str, Any]:
+ """No-repeat-ngram generate kwargs, fast path for greedy decoding.
+
+ ``num_beams == 1`` (MinerU's production setting) uses the incremental
+ processor; beam search keeps HF's stateless ``no_repeat_ngram_size`` kwarg
+ because the incremental table is invalidated by beam reordering.
+ """
+ if num_beams == 1:
+ from transformers import LogitsProcessorList
+
+ return {
+ "logits_processor": LogitsProcessorList([_IncrementalNoRepeatNGramLogitsProcessor(_NO_REPEAT_NGRAM_SIZE)])
+ }
+ return {"no_repeat_ngram_size": _NO_REPEAT_NGRAM_SIZE}
+
+
+class MinerUVLAdapter(BaseAdapter):
+ """Adapter for opendatalab/MinerU2.5-Pro-2604-1.2B document OCR VLM.
+
+ MinerU2.5-Pro-2604-1.2B is a 1.2B-param Qwen2-VL-based document parser
+ (Apache-2.0). Architecture: 32-layer ViT (embed 1280, patch 14, spatial
+ merge 2) over a 24-layer Qwen2 decoder (hidden 896, GQA 14/2, vocab
+ 151936, mRoPE). OmniDocBench v1.6 Overall 95.75 — best of the
+ fast-tier open-weight document VLMs.
+
+ Uses upstream ``Qwen2VLForConditionalGeneration`` — no
+ ``trust_remote_code``, no custom modeling code. ``bfloat16`` on CUDA
+ (per ``config.json``; fp16 is unsupported), ``float32`` on CPU/MPS for
+ smoke testing only.
+
+ Supports six task modes via the ``task`` runtime option:
+ ``[default]`` (text recognition), ``table``, ``equation``, ``image``,
+ ``chart``, ``[layout]``. Bracketed task names mirror upstream's
+ convention. Each call returns a single ``Entity`` whose ``label`` is
+ ``mineru_<task-without-brackets>`` (e.g. ``mineru_text``,
+ ``mineru_table``, ``mineru_layout``).
+ """
+
+ spec: ClassVar[AdapterSpec] = AdapterSpec(
+ inputs=("image",),
+ outputs=("json",),
+ unload_fields=("_model", "_processor", "_preprocessor"),
+ default_preprocessor="image",
+ )
+
+ def __init__(
+ self,
+ model_name_or_path: str | Path,
+ *,
+ compute_precision: ComputePrecision = "bfloat16",
+ revision: str | None = None,
+ default_task: str = _DEFAULT_TASK,
+ max_new_tokens: int = 4096,
+ num_beams: int = 1,
+ attn_implementation: str = "sdpa",
+ **kwargs: Any,
+ ) -> None:
+ del kwargs # Accept + discard loader extras (normalize, max_seq_length, etc.)
+ if default_task not in _VALID_TASKS:
+ msg = f"default_task {default_task!r} must be one of {_VALID_TASKS}"
+ raise ValueError(msg)
+ self._model_name_or_path = str(model_name_or_path)
+ self._compute_precision = compute_precision
+ self._revision = revision
+ self._default_task = default_task
+ self._max_new_tokens = max_new_tokens
+ self._num_beams = num_beams
+ self._attn_implementation = attn_implementation
+
+ self._model: Any = None
+ self._processor: Any = None
+ self._preprocessor: Any = None
+ self._device: str | None = None
+
+ def load(self, device: str) -> None:
+ # Use upstream Qwen2VLForConditionalGeneration directly. MinerU ships
+ # no custom modeling code, so no trust_remote_code and no
+ # create_causal_mask shim are needed (compare PaddleOCR-VL).
+ from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
+
+ self._device = device
+ dtype = self._resolve_dtype_for(device)
+
+ shared_kwargs: dict[str, Any] = {}
+ if self._revision is not None:
+ shared_kwargs["revision"] = self._revision
+
+ logger.info(
+ "Loading MinerU2.5-Pro model %s on device=%s dtype=%s revision=%s attn=%s",
+ self._model_name_or_path,
+ device,
+ dtype,
+ self._revision,
+ self._attn_implementation,
+ )
+
+ self._processor = AutoProcessor.from_pretrained(
+ self._model_name_or_path,
+ use_fast=True,
+ **shared_kwargs,
+ )
+ self._model = Qwen2VLForConditionalGeneration.from_pretrained(
+ self._model_name_or_path,
+ dtype=dtype,
+ attn_implementation=self._attn_implementation,
+ **shared_kwargs,
+ )
+ self._model.to(device) # ty: ignore[invalid-argument-type]
+ self._model.eval()
+
+ self._create_preprocessor()
+ logger.info("MinerU2.5-Pro model loaded successfully")
+
+ def _resolve_dtype_for(self, device: str) -> torch.dtype:
+ if not device.startswith("cuda"):
+ return torch.float32
+ if self._compute_precision == "float16":
+ raise ValueError(_ERR_FP16_UNSUPPORTED)
+ dtype_map = {"bfloat16": torch.bfloat16, "float32": torch.float32}
+ dtype = dtype_map.get(self._compute_precision)
+ if dtype is None:
+ msg = f"Unsupported compute_precision: {self._compute_precision!r}. Use 'bfloat16' or 'float32'."
+ raise ValueError(msg)
+ return dtype
+
+ def _create_preprocessor(self) -> None:
+ from sie_server.core.preprocessor.vision import MinerUVLPreprocessor
+
+ self._preprocessor = MinerUVLPreprocessor(
+ processor=self._processor,
+ model_name=self._model_name_or_path,
+ default_task=self._default_task,
+ )
+
+ def get_preprocessor(self) -> Any | None:
+ return self._preprocessor
+
+ def encode(
+ self,
+ items: list[Item],
+ output_types: list[str],
+ *,
+ instruction: str | None = None,
+ is_query: bool = False,
+ prepared_items: list[Any] | None = None,
+ options: dict[str, Any] | None = None,
+ ) -> EncodeOutput:
+ raise NotImplementedError(_ERR_ENCODE_NOT_SUPPORTED)
+
+ def extract(
+ self,
+ items: list[Item],
+ *,
+ labels: list[str] | None = None,
+ output_schema: dict[str, Any] | None = None,
+ instruction: str | None = None,
+ options: dict[str, Any] | None = None,
+ prepared_items: list[Any] | None = None,
+ ) -> ExtractOutput:
+ self._check_loaded()
+ if self._processor is None:
+ raise RuntimeError(ERR_NOT_LOADED)
+
+ options = options or {}
+ task = options.get("task", self._default_task)
+ if task not in _VALID_TASKS:
+ msg = f"task {task!r} must be one of {_VALID_TASKS}"
+ raise ValueError(msg)
+ max_new_tokens = options.get("max_new_tokens", self._max_new_tokens)
+ num_beams = options.get("num_beams", self._num_beams)
+
+ if prepared_items is not None and len(prepared_items) > 0:
+ if len(prepared_items) != len(items):
+ msg = f"prepared_items length ({len(prepared_items)}) must match items length ({len(items)})"
+ raise ValueError(msg)
+ return self._extract_preprocessed(
+ items=items,
+ prepared_items=prepared_items,
+ task=task,
+ instruction=instruction,
+ max_new_tokens=max_new_tokens,
+ num_beams=num_beams,
+ )
+
+ all_entities = []
+ for item in items:
+ entities = self._extract_single(
+ item,
+ task=task,
+ instruction=instruction,
+ max_new_tokens=max_new_tokens,
+ num_beams=num_beams,
+ )
+ all_entities.append(entities)
+ return ExtractOutput(entities=all_entities)
+
+ def _extract_preprocessed(
+ self,
+ items: list[Item],
+ prepared_items: list[Any],
+ *,
+ task: str,
+ instruction: str | None,
+ max_new_tokens: int,
+ num_beams: int,
+ ) -> ExtractOutput:
+ from sie_server.core.prepared import MinerUVLPayload, PreparedItem
+
+ all_entities = []
+ for i, prepared in enumerate(prepared_items):
+ payload = prepared.payload if isinstance(prepared, PreparedItem) else getattr(prepared, "payload", prepared)
+ if not isinstance(payload, MinerUVLPayload):
+ all_entities.append(
+ self._extract_single(
+ items[i],
+ task=task,
+ instruction=instruction,
+ max_new_tokens=max_new_tokens,
+ num_beams=num_beams,
+ )
+ )
+ continue
+
+ pixel_values = payload.pixel_values.to(device=self._device, dtype=self._model.dtype)
+ input_ids = payload.input_ids.unsqueeze(0).to(self._device)
+ attention_mask = payload.attention_mask.unsqueeze(0).to(self._device)
+ image_grid_thw = payload.image_grid_thw.to(self._device)
+ prompt_len = input_ids.shape[1]
+
+ with torch.inference_mode():
+ output_ids = self._model.generate(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ pixel_values=pixel_values,
+ image_grid_thw=image_grid_thw,
+ max_new_tokens=max_new_tokens,
+ num_beams=num_beams,
+ use_cache=True,
+ **_MINERU_GENERATE_KWARGS,
+ **_ngram_logits_processor(num_beams),
+ )
+
+ generated_ids = output_ids[0, prompt_len:]
+ generated_text = self._processor.decode(generated_ids, skip_special_tokens=True)
+ all_entities.append(self._convert_output(generated_text, task))
+ return ExtractOutput(entities=all_entities)
+
+ def _extract_single(
+ self,
+ item: Item,
+ *,
+ task: str,
+ instruction: str | None,
+ max_new_tokens: int,
+ num_beams: int,
+ ) -> list[Entity]:
+ from PIL import Image as PILImage
+
+ images = item.images
+ if not images:
+ raise ValueError(_ERR_NO_IMAGES)
+
+ img_bytes = media_bytes(images[0], kind="image")
+ pil_img = PILImage.open(io.BytesIO(img_bytes))
+ if pil_img.mode != "RGB":
+ pil_img = pil_img.convert("RGB")
+
+ messages = self._build_messages(task=task, instruction=instruction)
+ text = self._processor.apply_chat_template(
+ messages,
+ add_generation_prompt=True,
+ tokenize=False,
+ )
+
+ inputs = self._processor(
+ text=text,
+ images=[pil_img],
+ return_tensors="pt",
+ )
+ inputs = {
+ k: v.to(device=self._device, dtype=self._model.dtype) if v.is_floating_point() else v.to(self._device)
+ for k, v in inputs.items()
+ }
+ prompt_len = inputs["input_ids"].shape[1]
+
+ with torch.inference_mode():
+ output_ids = self._model.generate(
+ **inputs,
+ max_new_tokens=max_new_tokens,
+ num_beams=num_beams,
+ use_cache=True,
+ **_MINERU_GENERATE_KWARGS,
+ **_ngram_logits_processor(num_beams),
+ )
+
+ generated_ids = output_ids[0, prompt_len:]
+ generated_text = self._processor.decode(generated_ids, skip_special_tokens=True)
+ return self._convert_output(generated_text, task)
+
+ def _build_messages(self, *, task: str, instruction: str | None) -> list[dict[str, Any]]:
+ prompt_text = instruction or _TASK_PROMPTS[task]
+ return [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image"},
+ {"type": "text", "text": prompt_text},
+ ],
+ }
+ ]
+
+ @staticmethod
+ def _convert_output(text: str, task: str) -> list[Entity]:
+ """Wrap generated text in a single-entity list labelled ``mineru_<task>``.
+
+ Bracketed task names ``[default]``/``[layout]`` map to bracket-free
+ labels ``mineru_text``/``mineru_layout``; all other task names pass
+ through unchanged (``mineru_table``, ``mineru_equation``,
+ ``mineru_image``, ``mineru_chart``). Downstream JSON parsing for
+ ``[layout]`` (bbox-annotated output) is deferred — consumers can
+ post-process.
+ """
+ label_suffix_map = {"[default]": "text", "[layout]": "layout"}
+ label_suffix = label_suffix_map.get(task, task)
+ return [Entity(text=text.strip(), label=f"mineru_{label_suffix}", score=1.0)]
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 95abdaa03..8879d459d 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
@@ -14,7 +14,6 @@ Key features:
License: NVIDIA Non-Commercial (note in model config)
-Per roadmap Project 10.5 Phase 1c:
- Full conformance with SIE preprocessor infrastructure
- Uses NemoColEmbedPreprocessor for image preprocessing
- Calls model.forward() directly instead of forward_passages()
@@ -174,6 +173,23 @@ class NemoColEmbedAdapter(BaseAdapter):
if isinstance(embedding_dim, int) and embedding_dim > 0:
self._multivector_dim = embedding_dim
+ # FIX[#1055]: ensure the requested attention impl actually reaches the
+ # inner Qwen3-VL backbone (v2). On the sdpa fallback Qwen3-VL's vision
+ # attention runs a per-image Python loop over torch.split that
+ # serializes the batch (see ColQwen3). Safe no-op when flash already
+ # propagated, or for the v1 SigLIP+Llama path.
+ if attn_impl is not None and attn_impl != "sdpa" and hasattr(self._model, "set_attn_implementation"):
+ try:
+ self._model.set_attn_implementation(attn_impl)
+ except Exception: # noqa: BLE001 - best-effort, keep loaded default on failure
+ logger.warning("NemoColEmbed: could not set attn=%s; keeping default", attn_impl, exc_info=True)
+
+ # FIX[#1055]: replace the Qwen3-VL vision Conv3d patch-embed with its
+ # matmul equivalent (same weights). The non-overlapping Conv3d hits a
+ # pathologically slow cuDNN path on this GPU; for the sibling ColQwen3 it
+ # was ~99.7% of the vision-tower forward. No-op for the v1 SigLIP path.
+ self._patch_vision_patch_embed()
+
# Create preprocessor only when the model exposes v1-style attrs (image_size,
# num_image_token). v2 (Qwen3-VL) does not, and the SigLIP+Llama-keyed
# NemoColEmbedPreprocessor does not apply.
@@ -182,6 +198,38 @@ class NemoColEmbedAdapter(BaseAdapter):
else:
logger.info("Skipping NemoColEmbedPreprocessor — model lacks v1 attrs (likely v2 backbone).")
+ def _patch_vision_patch_embed(self) -> None:
+ """Rebind the Qwen3-VL vision Conv3d patch-embed to its matmul equivalent.
+
+ The non-overlapping Conv3d patch projection (kernel == stride) hits a
+ pathologically slow cuDNN path on this GPU; for the sibling ColQwen3 it
+ was ~99.7% of the vision-tower forward. Reshaping to ``F.linear`` with the
+ same weights is numerically identical but runs as a fast matmul. Locates
+ the vision tower under the v2 (Qwen3-VL) backbone; no-op for the v1 path.
+ """
+ from torch.nn import functional
+
+ try:
+ visual = getattr(getattr(self._model, "model", None), "visual", None)
+ patch_embed = getattr(visual, "patch_embed", None)
+ proj = getattr(patch_embed, "proj", None)
+ if not isinstance(proj, torch.nn.Conv3d):
+ return
+ embed_dim = proj.out_channels
+ in_features = proj.in_channels * proj.kernel_size[0] * proj.kernel_size[1] * proj.kernel_size[2]
+
+ def fast_patch_embed_forward(
+ hidden_states: torch.Tensor, _pe: Any = patch_embed, _embed: int = embed_dim, _in: int = in_features
+ ) -> torch.Tensor:
+ weight = _pe.proj.weight
+ hs = hidden_states.to(weight.dtype).reshape(-1, _in)
+ return functional.linear(hs, weight.reshape(_embed, _in), _pe.proj.bias)
+
+ patch_embed.forward = fast_patch_embed_forward # ty: ignore[invalid-assignment]
+ logger.info("NemoColEmbed: replaced vision Conv3d patch-embed with matmul equivalent")
+ except Exception: # noqa: BLE001 - best-effort, keep the original Conv3d on failure
+ logger.warning("NemoColEmbed: could not rebind vision patch-embed; keeping Conv3d", exc_info=True)
+
def _load_v1_dynamic(self, device: str, dtype: torch.dtype) -> Any:
"""Load v1 (SigLIP+Llama) via the explicit dynamic-module path.
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 80ce68a22..6ed644fc5 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
@@ -10,8 +10,6 @@ Usage:
self._model = AutoModel.from_pretrained(...)
# Store base model reference for LoRA wrapping
self._base_model = self._model
-
-See DESIGN.md Section 7.3 for the LoRA architecture specification.
"""
from __future__ import annotations
diff --git a/packages/sie_server/src/sie_server/adapters/pytorch_embedding/__init__.py b/packages/sie_server/src/sie_server/adapters/pytorch_embedding/__init__.py
index d7073b7da..742235fa9 100644
--- a/packages/sie_server/src/sie_server/adapters/pytorch_embedding/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/pytorch_embedding/__init__.py
@@ -8,7 +8,7 @@ Supports:
- Encoder-based models (when using CLS or mean pooling)
- Configurable attention: SDPA (default) or Flash Attention 2
-Performance notes (see DESIGN.md Section 6.3):
+Performance notes:
- SDPA is 20-25% faster for sequences <512 tokens
- FA2 is faster for sequences >512 tokens
- Default is SDPA since standard retrieval workloads have short texts
@@ -97,6 +97,7 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):
default_instruction: str | None = None,
forward_kwargs: dict[str, Any] | None = None,
uses_legacy_transformers_cache: bool = False,
+ dense_dim: int | None = None,
) -> None:
r"""Initialize the adapter.
@@ -131,6 +132,8 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):
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).
+ dense_dim: Catalog-declared dense embedding dimension. If provided,
+ validated against the loaded model's hidden size.
"""
self._model_name_or_path = str(model_name_or_path)
self._pooling = pooling
@@ -145,11 +148,12 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):
self._default_instruction = default_instruction
self._forward_kwargs = forward_kwargs or {}
self._uses_legacy_transformers_cache = uses_legacy_transformers_cache
+ self._configured_dense_dim = dense_dim
self._model: PreTrainedModel | None = None
self._tokenizer: PreTrainedTokenizerFast | None = None
self._device: str | None = None
- self._dense_dim: int | None = None
+ self._dense_dim: int | None = dense_dim
def load(self, device: str) -> None:
"""Load the model onto the specified device.
@@ -204,8 +208,17 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):
self._model.to(device)
self._model.eval()
- # Get embedding dimension from model config
- self._dense_dim = self._model.config.hidden_size
+ self._dense_dim = self._validate_or_set_dense_dim(self._model.config.hidden_size)
+
+ def _validate_or_set_dense_dim(self, observed_dim: int) -> int:
+ """Validate observed model width against configured dense_dim."""
+ if self._configured_dense_dim is not None and observed_dim != self._configured_dense_dim:
+ msg = (
+ "PyTorch embedding dimension mismatch: "
+ f"configured dense_dim={self._configured_dense_dim}, model hidden_size={observed_dim}"
+ )
+ raise ValueError(msg)
+ return observed_dim
def _resolve_dtype_and_attn(self, device: str) -> tuple[torch.dtype, str]:
"""Resolve dtype and attention implementation based on device and config.
diff --git a/packages/sie_server/src/sie_server/adapters/sglang/_server.py b/packages/sie_server/src/sie_server/adapters/sglang/_server.py
index c48281f05..29e6e8f2c 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/_server.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/_server.py
@@ -170,6 +170,7 @@ def wait_for_server(
if response.status_code == 200:
return True
except requests.RequestException:
+ # Health endpoint not up yet — keep polling until timeout.
pass
time.sleep(HEALTH_CHECK_INTERVAL_S)
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 c5492c85c..1e99cdddb 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py
@@ -12,8 +12,6 @@ Target models:
Implementation: Uses SGLang's HTTP server mode (subprocess) rather than the
Engine API to avoid event loop conflicts with uvicorn/uvloop.
-
-See DESIGN.md Section 6.2 for backend selection rationale.
"""
from __future__ import annotations
@@ -204,7 +202,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):
if self._pooling_method:
cmd.extend(["--pooling-method", self._pooling_method])
- # LoRA configuration (see DESIGN.md Section 3.7)
+ # LoRA configuration for the SGLang server.
if self._lora_paths:
cmd.append("--enable-lora")
lora_path_str = ",".join(f"{name}={path}" for name, path in self._lora_paths.items())
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 ceccaae2c..46902d6d0 100644
--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py
+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py
@@ -173,8 +173,8 @@ class SGLangGenerationAdapter(GenerationAdapter):
# ``--tool-call-parser`` (e.g. ``qwen3_coder`` for Qwen3.5).
# Set ``None`` to omit the flag.
self._tool_call_parser = tool_call_parser
- # M4 req2 Proj 5 — generic speculative-decoding surface.
- # Accepts ``{enabled, algorithm, num_steps?, eagle_topk?,
+ # Generic speculative-decoding surface accepts
+ # ``{enabled, algorithm, num_steps?, eagle_topk?,
# num_draft_tokens?, draft_model?}``; translated by
# ``_speculative_launch_args`` into SGLang CLI flags. Default-on
# for Qwen3.5-4B (NEXTN/MTP trained in); intentionally off for
@@ -196,8 +196,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
# ``unload()``. A single shared client lets concurrent requests
# multiplex over a connection pool instead of paying per-request
# TCP setup. Measured impact at c=16 on A100: ~20% TTFT improvement
- # vs the previous "new AsyncClient per request" implementation
- # (see ``product/research/generation-primitive-status.md`` §3.4).
+ # vs the previous "new AsyncClient per request" implementation.
self._http_client: httpx.AsyncClient | None = None
# Two locks for the lazy ``_http_client``:
#
@@ -732,6 +731,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
presence_penalty: float | None = None,
top_k: int | None = None,
repetition_penalty: float | None = None,
+ min_new_tokens: int | None = None,
grammar: GrammarSpec | None = None,
seed: int | None = None,
logit_bias: dict[str, float] | None = None,
@@ -756,6 +756,12 @@ class SGLangGenerationAdapter(GenerationAdapter):
sampling_params["top_k"] = top_k
if repetition_penalty is not None:
sampling_params["repetition_penalty"] = repetition_penalty
+ # SGLang ``sampling_params["min_new_tokens"]`` — minimum tokens
+ # before stop. Plumbed end-to-end from the gateway's chat
+ # ``min_tokens`` knob (workaround for Qwen3.6's first-token-EOS
+ # bug under greedy decode).
+ if min_new_tokens is not None:
+ sampling_params["min_new_tokens"] = min_new_tokens
# SGLang accepts both penalty knobs natively under
# ``sampling_params`` with the same names OpenAI uses. Pass them
# through only when the gateway provided a value so model
@@ -992,7 +998,7 @@ class SGLangGenerationAdapter(GenerationAdapter):
prompt_tokens = meta["prompt_tokens"]
if isinstance(meta.get("completion_tokens"), int):
total_completion += meta["completion_tokens"]
- # Per-candidate logprobs (M4): only emit when the request
+ # Per-candidate logprobs: only emit when the request
# asked for them. ``return_logprob`` is also set for
# ``best_of`` ranking; do NOT surface the ranking-only
# logprobs to the client — that would make ``logprobs:
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 48fe6552f..9b5754cb8 100644
--- a/packages/sie_server/src/sie_server/adapters/siglip/__init__.py
+++ b/packages/sie_server/src/sie_server/adapters/siglip/__init__.py
@@ -3,9 +3,9 @@
This adapter provides support for SigLIP (Sigmoid Loss for Language Image Pre-training)
models that produce aligned embeddings for both images and text in a shared vector space.
-Per roadmap Project 10.4, uses transformers SiglipModel with SiglipProcessor
-for Phase 1. SigLIP differs from CLIP in using sigmoid loss instead of softmax
-and not having a separate projection_dim - it uses hidden_size directly.
+Uses transformers SiglipModel with SiglipProcessor. SigLIP differs from CLIP in
+using sigmoid loss instead of softmax and not having a separate projection_dim -
+it uses hidden_size directly.
Supports two backends:
diff --git a/packages/sie_server/src/sie_server/api/encode.py b/packages/sie_server/src/sie_server/api/encode.py
index 20381ac72..046e0f449 100644
--- a/packages/sie_server/src/sie_server/api/encode.py
+++ b/packages/sie_server/src/sie_server/api/encode.py
@@ -39,7 +39,7 @@ def _format_dense(
) -> DenseVector:
"""Format a dense embedding for response.
- Per DESIGN.md 13.2: Keep numpy arrays, don't convert to list.
+ Keep numpy arrays for msgpack serialization; do not convert to lists.
Quantization is now done by QuantizePostprocessor before this is called.
"""
# For binary (packed uint8), dims represents the original dimension
@@ -67,7 +67,7 @@ def _format_sparse(
) -> SparseVector:
"""Format a sparse embedding for response.
- Per DESIGN.md 13.2: Keep numpy arrays, don't convert to list.
+ Keep numpy arrays for msgpack serialization; do not convert to lists.
Quantization is now done by QuantizePostprocessor before this is called.
Note: Sparse vectors only support float32 and float16 dtypes.
@@ -98,7 +98,7 @@ def _format_multivector(
) -> MultiVector:
"""Format a multivector embedding for response.
- Per DESIGN.md 13.2: Keep numpy arrays, don't convert to list.
+ Keep numpy arrays for msgpack serialization; do not convert to lists.
Quantization is now done by QuantizePostprocessor before this is called.
Note: Quantization is applied per-token. ColBERTv2 uses 2-bit quantization
diff --git a/packages/sie_server/src/sie_server/api/extract.py b/packages/sie_server/src/sie_server/api/extract.py
index dc409beba..b05f7b3aa 100644
--- a/packages/sie_server/src/sie_server/api/extract.py
+++ b/packages/sie_server/src/sie_server/api/extract.py
@@ -103,9 +103,16 @@ async def _extract_via_worker(
except (AttributeError, TypeError):
pass
- if use_preprocessor:
- if preprocessor_registry is None:
- raise RuntimeError("Preprocessor registry is not available")
+ if use_preprocessor and preprocessor_registry is not None:
+ has_images = any(item.images for item in items)
+ try:
+ has_text_preprocessor = preprocessor_registry.has_preprocessor(model, "text") is True
+ except (AttributeError, TypeError):
+ has_text_preprocessor = False
+ if not has_images and not has_text_preprocessor:
+ msg = f"Model '{model}' requires image input for extraction"
+ raise ValueError(msg)
+
# Vision model: use PreprocessorRegistry for CPU preprocessing in thread pool
# This uses the shared preprocessing thread pool for better resource utilization
# Pass instruction and task for models like Florence-2 that need them in the prompt
diff --git a/packages/sie_server/src/sie_server/api/health.py b/packages/sie_server/src/sie_server/api/health.py
index 7f566a44f..41137ec7b 100644
--- a/packages/sie_server/src/sie_server/api/health.py
+++ b/packages/sie_server/src/sie_server/api/health.py
@@ -4,8 +4,6 @@ Provides Kubernetes-compatible probes:
- /healthz: Startup/liveness probe - is the process alive? (CPU only, cheap)
- /livez: GPU-aware liveness probe - can the device still run kernels?
- /readyz: Readiness probe - is the server ready to accept traffic right now?
-
-See DESIGN.md Section 3.1 for specification.
"""
from fastapi import APIRouter, Response
diff --git a/packages/sie_server/src/sie_server/api/helpers.py b/packages/sie_server/src/sie_server/api/helpers.py
index 358e64472..80aaaff3c 100644
--- a/packages/sie_server/src/sie_server/api/helpers.py
+++ b/packages/sie_server/src/sie_server/api/helpers.py
@@ -170,7 +170,7 @@ class ContentNegotiator:
def wants_msgpack(accept: str | None) -> bool:
"""Check if client prefers msgpack based on Accept header.
- Default to msgpack if no preference specified (per DESIGN.md).
+ Default to msgpack if no preference is specified.
"""
if not accept:
return True # Default to msgpack
diff --git a/packages/sie_server/src/sie_server/api/openai_compat.py b/packages/sie_server/src/sie_server/api/openai_compat.py
index ec44e505d..6859e377d 100644
--- a/packages/sie_server/src/sie_server/api/openai_compat.py
+++ b/packages/sie_server/src/sie_server/api/openai_compat.py
@@ -8,7 +8,7 @@ class out of the box:
embeddings = OpenAIEmbeddings(base_url="http://localhost:8080/v1")
-Per roadmap Project 11.0: OpenAI-Compatible API.
+This module implements the OpenAI-compatible embeddings API surface.
"""
from __future__ import annotations
diff --git a/packages/sie_server/src/sie_server/api/serialization.py b/packages/sie_server/src/sie_server/api/serialization.py
index 0ed5d9973..83d4c007f 100644
--- a/packages/sie_server/src/sie_server/api/serialization.py
+++ b/packages/sie_server/src/sie_server/api/serialization.py
@@ -3,7 +3,7 @@
Provides msgpack serialization with native numpy support for efficient wire format.
Falls back to JSON for debugging when Accept header requests it.
-Per DESIGN.md Section 5.9:
+Serialization behavior:
- Use msgpack with msgpack-numpy for arrays (not list comprehensions)
- Single call serialization, no Python loops
"""
diff --git a/packages/sie_server/src/sie_server/api/ws.py b/packages/sie_server/src/sie_server/api/ws.py
index 3954cfe65..16bd4569b 100644
--- a/packages/sie_server/src/sie_server/api/ws.py
+++ b/packages/sie_server/src/sie_server/api/ws.py
@@ -7,8 +7,9 @@ import json
import logging
import os
import time
+import weakref
from pathlib import Path
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Protocol
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from sie_sdk.types import (
@@ -28,7 +29,14 @@ from sie_server.observability.prometheus import collect_prometheus_metrics
if TYPE_CHECKING:
from sie_server.core.registry import ModelRegistry
- from sie_server.nats_pull_loop import NatsPullLoop
+
+
+class StatusPullLoop(Protocol):
+ worker_id: str
+
+ def update_saturation(self) -> bool:
+ raise NotImplementedError
+
logger = logging.getLogger(__name__)
@@ -171,8 +179,8 @@ def _compute_bundle_config_hash(registry: ModelRegistry, bundle_id: str) -> str:
# Deterministic serialization matching gateway's compute_bundle_config_hash:
# both sides hash [{"sie_id": name, "profiles": [{name, config}]}]
- # where config contains routable fields (adapter_path, max_batch_tokens, etc.).
- _hash_fields = ("adapter_path", "max_batch_tokens", "compute_precision", "adapter_options")
+ # where config contains routable fields: adapter_path, max_batch_tokens,
+ # compute_precision, adapter_options.
items = []
for config in sorted(configs.values(), key=lambda c: c.sie_id):
profiles_for_hash = []
@@ -203,8 +211,12 @@ def _compute_bundle_config_hash(registry: ModelRegistry, bundle_id: str) -> str:
# Cache of bundle config hashes. Populated by _compute_bundle_config_hash
-# and invalidated when the registry is mutated.
-_bundle_config_hash_cache: dict[str, tuple[int, str]] = {}
+# and invalidated when the corresponding registry is mutated. The cache is
+# scoped per registry so test/sidecar registry instances with the same version
+# cannot reuse each other's bundle hash.
+_bundle_config_hash_cache: weakref.WeakKeyDictionary[ModelRegistry, dict[str, tuple[int, str]]] = (
+ weakref.WeakKeyDictionary()
+)
def compute_bundle_config_hash_cached(registry: ModelRegistry, bundle_id: str) -> str:
@@ -213,17 +225,21 @@ def compute_bundle_config_hash_cached(registry: ModelRegistry, bundle_id: str) -
Uses the registry's config version (mutation counter) to detect staleness.
"""
version = getattr(registry, "_config_version", 0)
- cached = _bundle_config_hash_cache.get(bundle_id)
+ registry_cache = _bundle_config_hash_cache.get(registry)
+ if registry_cache is None:
+ registry_cache = {}
+ _bundle_config_hash_cache[registry] = registry_cache
+ cached = registry_cache.get(bundle_id)
if cached is not None and cached[0] == version:
return cached[1]
result = _compute_bundle_config_hash(registry, bundle_id)
- _bundle_config_hash_cache[bundle_id] = (version, result)
+ registry_cache[bundle_id] = (version, result)
return result
async def build_status_message(
registry: ModelRegistry,
- pull_loop: NatsPullLoop | None = None,
+ pull_loop: StatusPullLoop | None = None,
) -> WorkerStatusMessage:
"""Build the complete status message.
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 ac531746b..8e975841b 100644
--- a/packages/sie_server/src/sie_server/app/app_factory.py
+++ b/packages/sie_server/src/sie_server/app/app_factory.py
@@ -6,7 +6,6 @@ from contextlib import asynccontextmanager
from typing import Any
import torch
-import yaml
from fastapi import FastAPI
from sie_server.api.encode import router as encode_router
@@ -23,34 +22,24 @@ from sie_server.api.ws import init_server_start_time
from sie_server.api.ws import router as ws_router
from sie_server.app.app_state_config import AppStateConfig
from sie_server.config.engine import EngineConfig
-from sie_server.config.model import ModelConfig, ProfileConfig, Tasks
from sie_server.core.memory import MemoryConfig
-from sie_server.core.readiness import mark_not_ready, mark_ready
+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.shutdown import ShutdownMiddleware, ShutdownState, setup_signal_handlers
-from sie_server.nats_pull_loop import NatsPullLoop
-from sie_server.nats_subscriber import NatsSubscriber
+from sie_server.ipc_server import IpcServer
from sie_server.observability.gpu import _init_nvml, shutdown_nvml
from sie_server.observability.telemetry import telemetry_sender
from sie_server.observability.tracing import setup_tracing
+from sie_server.queue_executor import QueueExecutor
logger = logging.getLogger(__name__)
-def _resolved_pool_name() -> str | None:
- """Resolve the worker's pool identity from the environment.
-
- Returns the ``SIE_POOL`` value (with ``"_default"`` fallback) when
- cluster-queue routing is active, else ``None`` for the local
- single-process serving path which has no pool semantics.
-
- Shared by :meth:`AppFactory._registry_lifecycle` (registry
- pool-isolation validator) and :meth:`AppFactory._nats_pull_loop`
- (NATS pull loop) so the two cannot drift.
- """
- if os.environ.get("SIE_CLUSTER_ROUTING") != "queue":
- return None
- return os.environ.get("SIE_POOL", "_default")
+def _env_flag(name: str, default: bool = False) -> bool:
+ raw = os.environ.get(name)
+ if raw is None:
+ return default
+ return raw.strip().lower() not in {"", "0", "false", "no", "off"}
@asynccontextmanager
@@ -90,16 +79,28 @@ class AppFactory:
# Setup OpenTelemetry tracing (no-op if SIE_TRACING_ENABLED is not set)
setup_tracing(app)
- # Register routers
+ # Queue is the only supported routing mode: the worker-sidecar
+ # drives NATS and talks to Python over UDS IPC. We still mount
+ # the HTTP routers for /healthz, /readyz, /metrics (K8s probes
+ # and Prometheus), the landing page, and /ws/status — which is
+ # the gateway's worker-registration channel: the gateway dials
+ # `ws://<pod>/ws/status` to learn pool_name, bundle,
+ # machine_profile, and readiness. The inference endpoints
+ # (/encode, /score, /extract, /generate, /models, /v1/embeddings) are
+ # historically reachable on the pod's HTTP port but are not a
+ # production ingress — the Rust gateway is queue-only and
+ # publishes to JetStream, not HTTP. They stay mounted so local
+ # SIEClient-based checks and the existing test surface keep
+ # working; no traffic reaches them in a real cluster.
app.include_router(root_router)
app.include_router(health_router)
+ app.include_router(metrics_router)
+ app.include_router(ws_router)
app.include_router(encode_router)
app.include_router(extract_router)
app.include_router(generate_router)
app.include_router(score_router)
app.include_router(models_router)
- app.include_router(metrics_router)
- app.include_router(ws_router)
app.include_router(openai_router) # OpenAI-compatible /v1/embeddings
setup_custom_openapi_schema(app)
@@ -126,23 +127,12 @@ class AppFactory:
_timed_stage("nvml", cls._nvml()),
_timed_stage("telemetry", telemetry_sender()),
_timed_stage("model_registry", cls._model_registry(config)) as registry,
- _timed_stage("nats_subscriber", cls._nats_subscriber(registry)) as nats_sub,
- _timed_stage("nats_pull_loop", cls._nats_pull_loop(registry, nats_sub)) as pull_loop,
- # Optional NATS health publisher. Off by default; flip
- # SIE_HEALTH_NATS=1 to surface `saturated` (and the rest of the
- # WorkerStatusMessage) over `sie.health.{worker_id}` in addition
- # to the WS path. Started *after* the pull loop because it
- # snapshots `pull_loop.update_saturation()` on every tick.
- _timed_stage(
- "nats_health_publisher",
- cls._nats_health_publisher(registry, nats_sub, pull_loop),
- ),
+ _timed_stage("ipc_server", cls._ipc_server(registry)) as ipc_server,
_timed_stage("graceful_shutdown", cls._graceful_shutdown(shutdown_state)),
_timed_stage("readiness", cls._readiness_handling()),
):
app.state.registry = registry
- app.state.nats_subscriber = nats_sub
- app.state.nats_pull_loop = pull_loop
+ app.state.ipc_server = ipc_server
yield
return lifespan
@@ -162,18 +152,12 @@ class AppFactory:
models_dir = config.models_dir or str(engine_config.models_dir)
- # Pass the worker's pool identity into the registry so
- # the pool-isolation validator can reject mixed gen/non-gen pools
- # at config-load time. Only set when SIE_CLUSTER_ROUTING=queue so
- # local single-process serving (which has no pool semantics) keeps
- # working without the check.
registry = ModelRegistry(
models_dir=models_dir,
model_filter=config.model_filter,
memory_config=memory_config,
device=config.device,
engine_config=engine_config,
- pool_name=_resolved_pool_name(),
)
try:
# Start background services (memory monitor, idle evictor, hot reload).
@@ -197,177 +181,41 @@ class AppFactory:
@classmethod
@asynccontextmanager
- async def _nats_subscriber(cls, registry: ModelRegistry) -> AsyncGenerator[NatsSubscriber | None, None]:
- """For optional NATS subscriber lifecycle.
-
- Only starts if SIE_NATS_URL is set. Connection failures are non-fatal —
- the server starts normally without NATS.
- """
- nats_url = os.environ.get("SIE_NATS_URL")
- if not nats_url:
- yield None
- return
-
- async def on_model_config(model_id: str, config_yaml: str) -> None:
- try:
- raw = yaml.safe_load(config_yaml)
- if not isinstance(raw, dict):
- logger.warning("NATS config for '%s' is not a dict, ignoring", model_id)
- return
-
- # Try full ModelConfig parsing (works for complete configs with tasks, hf_id, etc.)
- try:
- model_config = ModelConfig(**raw)
- registry.add_config(model_config)
- logger.info("Added full model config from NATS: %s", model_config.sie_id)
- return
- except Exception: # noqa: BLE001 — fallback to lightweight path
- logger.debug("Full ModelConfig parse failed for '%s', trying minimal path", model_id)
-
- # Fallback: minimal config from Config API (sie_id + profiles only).
- # Create a stub ModelConfig with required fields filled in from the profile.
- sie_id = raw.get("sie_id", model_id)
- profiles_raw = raw.get("profiles", {})
- if not profiles_raw:
- logger.warning("NATS config for '%s' has no profiles, ignoring", model_id)
- return
-
- # Fallback to sie_id as hf_id (satisfies ModelConfig validator)
-
- # Build a minimal valid ModelConfig
- profiles = {}
- for pname, pdata in profiles_raw.items():
- profiles[pname] = ProfileConfig(
- adapter_path=pdata.get("adapter_path"),
- max_batch_tokens=pdata.get("max_batch_tokens"),
- extends=pdata.get("extends"),
- )
-
- # Build a stub ModelConfig for profile/hash tracking.
- # This config may not be loadable — it's used to register the model
- # in the registry so the config hash updates and routing can reference it.
- # Actual model loading will use the full config pushed by the adapter.
- model_config = ModelConfig(
- sie_id=sie_id,
- hf_id=raw.get("hf_id", sie_id),
- tasks=Tasks(),
- profiles=profiles,
- )
- registry.add_config(model_config)
- logger.info("Added minimal model config from NATS: %s", sie_id)
-
- except Exception:
- logger.exception("Failed to apply NATS config for model '%s'", model_id)
-
- subscriber = NatsSubscriber(nats_url=nats_url, on_model_config=on_model_config)
- await subscriber.start()
- try:
- yield subscriber
- finally:
- await subscriber.stop()
-
- @classmethod
- @asynccontextmanager
- async def _nats_pull_loop(
- cls, registry: ModelRegistry, nats_subscriber: NatsSubscriber | None
- ) -> AsyncGenerator[NatsPullLoop | None, None]:
- """For optional NATS pull loop lifecycle.
-
- Only starts when SIE_CLUSTER_ROUTING=queue and a NATS connection exists.
- """
- if os.environ.get("SIE_CLUSTER_ROUTING") != "queue":
- yield None
- return
-
- if nats_subscriber is None:
- raise RuntimeError("SIE_CLUSTER_ROUTING=queue but no NATS subscriber available — cannot start pull loop")
-
- nc = nats_subscriber.nc
- if nc is None:
- raise RuntimeError("SIE_CLUSTER_ROUTING=queue but NATS connection is None — cannot start pull loop")
- js = nc.jetstream()
- bundle_id = os.environ.get("SIE_BUNDLE", "default")
- # Share resolution with the registry's pool isolation
- # validator. ``_resolved_pool_name`` returns ``None`` outside
- # ``SIE_CLUSTER_ROUTING=queue``, but we still need a pool string
- # for the pull-loop subject naming inside this branch (we already
- # know cluster routing is queue — this lifecycle only fires then).
- pool_name = _resolved_pool_name() or os.environ.get("SIE_POOL", "_default")
- payload_store_url = os.environ.get("SIE_PAYLOAD_STORE_URL")
-
- pull_loop = NatsPullLoop(
- nc=nc,
- js=js,
- registry=registry,
- bundle_id=bundle_id,
- pool_name=pool_name,
- payload_store_url=payload_store_url,
- )
- await pull_loop.start()
-
- # Register pull loop reconnect handler via NatsSubscriber's public API.
- # This is invoked by the NATS client's reconnected_cb chain, ensuring
- # pull subscriptions are re-created after NATS reconnect.
- nats_subscriber.add_reconnect_handler(pull_loop.handle_reconnect)
-
- try:
- yield pull_loop
- finally:
- await pull_loop.stop()
-
- @classmethod
- @asynccontextmanager
- async def _nats_health_publisher(
- cls,
- registry: ModelRegistry,
- nats_subscriber: NatsSubscriber | None,
- pull_loop: NatsPullLoop | None,
- ) -> AsyncGenerator[object | None, None]:
- """Optional periodic ``sie.health.{worker_id}`` publisher.
-
- Opt-in via ``SIE_HEALTH_NATS=1``. Disabled by default because
- the WebSocket ``/ws/status`` path is still the canonical
- transport; the NATS path is parallel and runs at the same
- cadence so the gateway sees consistent state from either
- side. Requires the NATS connection from the subscriber and
- the pull loop (for saturation). Gracefully no-ops if either
- is missing.
+ async def _ipc_server(cls, registry: ModelRegistry) -> AsyncGenerator[IpcServer, None]:
+ """IPC server lifecycle for the sidecar path.
+
+ The worker-sidecar drives NATS and talks to Python over a
+ UDS msgpack RPC. This context manager binds the socket, exposes
+ the :class:`QueueExecutor`, and can wire the sidecar heartbeat into
+ ``/readyz`` so a dead sidecar flips the pod unready.
+
+ The IPC server starts unconditionally so the same image can serve
+ direct HTTP and sidecar-driven queue deployments. Readiness only
+ depends on the Rust heartbeat when ``SIE_IPC_REQUIRE_HEARTBEAT`` is
+ truthy; Helm sets that env var when the worker-sidecar is present.
"""
- from sie_server.health.nats_publisher import NatsHealthPublisher, is_enabled # noqa: PLC0415
-
- if not is_enabled():
- yield None
- return
- nats_url = os.environ.get("SIE_NATS_URL")
- if not nats_url or nats_subscriber is None or pull_loop is None:
- logger.info(
- "SIE_HEALTH_NATS=1 but prerequisites missing (url=%s, subscriber=%s, pull_loop=%s); "
- "skipping NATS health publisher",
- bool(nats_url),
- nats_subscriber is not None,
- pull_loop is not None,
- )
- yield None
- return
-
- # Build a closure that the publisher polls once per interval.
- # We pull `pull_loop` directly so the `saturated` field is in
- # lockstep with the gate state machine.
- from sie_server.api.ws import build_status_message # noqa: PLC0415
-
- async def _snapshot() -> Any:
- return await build_status_message(registry, pull_loop=pull_loop)
-
- publisher = NatsHealthPublisher(
- nats_url=nats_url,
- worker_id=pull_loop.worker_id,
- build_status=_snapshot,
+ socket_path = os.environ.get("SIE_IPC_SOCKET_PATH", "/tmp/sie-ipc.sock") # noqa: S108
+ stale_after_ms = float(os.environ.get("SIE_IPC_STALE_AFTER_MS", "10000"))
+ worker_id = os.environ.get("SIE_WORKER_ID") or os.environ.get("HOSTNAME", "worker-unknown")
+ require_heartbeat = _env_flag("SIE_IPC_REQUIRE_HEARTBEAT")
+
+ executor = QueueExecutor(registry)
+ server = IpcServer(
+ socket_path,
+ executor,
+ worker_id=worker_id,
+ stale_after_ms=stale_after_ms,
)
- await publisher.start()
+ await server.start()
+ if require_heartbeat:
+ register_liveness_probe(server.is_heartbeat_fresh)
+ else:
+ register_liveness_probe(None)
try:
- yield publisher
+ yield server
finally:
- await publisher.stop()
+ register_liveness_probe(None)
+ await server.stop()
@classmethod
@asynccontextmanager
diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.py
index e1fc3a445..08f291482 100644
--- a/packages/sie_server/src/sie_server/cli.py
+++ b/packages/sie_server/src/sie_server/cli.py
@@ -282,6 +282,26 @@ def serve(
typer.echo(f"Available models: {', '.join(sorted(all_configs.keys())[:10])}...", err=True)
raise typer.Exit(1)
+ # Augment the filter with explicitly-allowed extra model ids (opt-in via
+ # ``SIE_EXTRA_MODELS``). A bundle's filter is built by scanning model YAML
+ # files, so it only contains *base* ids — it can't see profile-variant ids
+ # like ``Qwen/Qwen3.6-27B:rtx-pro-6000`` that the loader expands at runtime.
+ # A worker that serves a base model's adapter can also serve that model's
+ # profile variants (same adapter, same weights, different launch flags), so
+ # allow naming them here. Validated against the variant-expanded config set.
+ # The advertised bundle (``SIE_BUNDLE`` below) is unchanged, so gateway
+ # routing by adapter→bundle still resolves these variants to this worker.
+ extra_models_env = os.environ.get("SIE_EXTRA_MODELS")
+ if extra_models_env and model_filter is not None:
+ extras = [m.strip() for m in extra_models_env.split(",") if m.strip()]
+ all_configs = load_model_configs(models_dir_resolved)
+ unknown_extra = [m for m in extras if m not in all_configs]
+ if unknown_extra:
+ typer.echo(f"Error: SIE_EXTRA_MODELS unknown model(s): {', '.join(unknown_extra)}", err=True)
+ raise typer.Exit(1)
+ model_filter = sorted(set(model_filter) | set(extras))
+ typer.echo(f"Extra models added to filter: {', '.join(extras)}")
+
os.environ["SIE_INSTRUMENTATION"] = "true" if instrumentation else "false"
if bundle:
os.environ["SIE_BUNDLE"] = bundle
diff --git a/packages/sie_server/src/sie_server/config/engine.py b/packages/sie_server/src/sie_server/config/engine.py
index ba5647231..311ca4ffc 100644
--- a/packages/sie_server/src/sie_server/config/engine.py
+++ b/packages/sie_server/src/sie_server/config/engine.py
@@ -2,8 +2,6 @@
Defines the EngineConfig Pydantic model that controls server-wide settings
like batching, memory management, and performance tuning.
-
-See DESIGN.md Section 10.1 for full specification.
"""
import os
@@ -68,8 +66,18 @@ class AdaptiveBatchingConfig(BaseModel):
] = 500.0
min_wait_ms: Annotated[
float,
- Field(ge=0.1, description="Minimum batch wait time in milliseconds"),
- ] = 1.0
+ Field(
+ ge=0.1,
+ description=(
+ "Floor for the adaptive first-request timeout. Not a "
+ "mandatory wait — under load the batcher yields on "
+ "full/coalesce far earlier, so raising this has no "
+ "steady-state latency cost. Keeping it well above zero "
+ "prevents GPU-batch shredding when the PI controller "
+ "briefly wants to flush on every submit."
+ ),
+ ),
+ ] = 15.0
max_wait_ms: Annotated[
float,
Field(ge=1, description="Maximum batch wait time in milliseconds"),
@@ -95,6 +103,36 @@ class AdaptiveBatchingConfig(BaseModel):
Field(ge=1, description="Batches between controller updates"),
] = 10
+ # -- Starvation detector / deadlock recovery ---------------------------
+ # See ``AdaptiveBatchingParams`` in core/worker/types.py for the full
+ # rationale. TL;DR: the PI loop can get stuck in a "batch-of-1"
+ # attractor when both knobs bottom out; these fields arm an escape.
+ starvation_recovery_enabled: Annotated[
+ bool,
+ Field(description="Enable self-heal when both knobs sit at their floors."),
+ ] = True
+ starvation_window: Annotated[
+ int,
+ Field(
+ ge=1,
+ description=(
+ "Consecutive tiny batches at the floor before declaring "
+ "deadlock. Should be long enough to absorb genuine idle "
+ "tails, short enough to recover within a few seconds."
+ ),
+ ),
+ ] = 20
+ starvation_batch_size: Annotated[
+ int,
+ Field(
+ ge=1,
+ description=(
+ "Batch sizes at or below this count toward the starvation "
+ "streak. 1 = only single-item GPU forwards are pathological."
+ ),
+ ),
+ ] = 1
+
@model_validator(mode="after")
def validate_invariants(self) -> "AdaptiveBatchingConfig":
"""Check cross-field invariants."""
@@ -223,8 +261,43 @@ class EngineConfig(BaseSettings):
] = 64
max_batch_wait_ms: Annotated[
float,
- Field(description="Maximum milliseconds to wait for batch to fill"),
- ] = 10.0
+ Field(
+ description=(
+ "Initial value for the adaptive first-request timeout. "
+ "The PI controller moves this between "
+ "adaptive_batching.min_wait_ms and max_wait_ms at runtime, "
+ "so the practical effect of this knob is bounded by those."
+ ),
+ ),
+ ] = 15.0
+ coalesce_ms: Annotated[
+ float,
+ Field(
+ ge=0.0,
+ description=(
+ "Ceiling for the idle-coalesce window. When items stop "
+ "arriving for this long, the batcher yields whatever it "
+ "has accumulated. Tune to the typical inter-arrival "
+ "jitter of upstream IPC bursts so a full sidecar batch "
+ "lands in one GPU forward instead of being shredded. "
+ "Effective window is capped by ``coalesce_ratio * "
+ "max_batch_wait_ms``."
+ ),
+ ),
+ ] = 15.0
+ coalesce_ratio: Annotated[
+ float,
+ Field(
+ ge=0.0,
+ le=1.0,
+ description=(
+ "Coalesce window as a fraction of the current "
+ "max_batch_wait_ms. Keeps the coalesce window "
+ "proportional as the PI controller moves the wait "
+ "timeout."
+ ),
+ ),
+ ] = 0.5
max_concurrent_requests: Annotated[
int,
Field(description="Maximum concurrent requests (queue size)"),
diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.py
index 2ebd49fe5..c3c2aca66 100644
--- a/packages/sie_server/src/sie_server/config/model.py
+++ b/packages/sie_server/src/sie_server/config/model.py
@@ -266,6 +266,7 @@ _DEFAULT_GPU_MEMORY_GB = 24.0
# fallback comes from).
_GPU_MEMORY_GB_BY_PROFILE_HINT: tuple[tuple[str, float], ...] = (
("h200", 141.0),
+ ("rtx-pro-6000", 96.0), # RTX PRO 6000 Blackwell Server Edition (96 GB GDDR7)
("h100", 80.0),
("a100-80", 80.0),
("a100-40", 40.0),
@@ -355,8 +356,7 @@ def _maybe_warn_oversubscribed_budget(
f"kv_bytes_per_token≈{kv_bytes_per_token}, "
f"assumed_gpu_memory_gb={gpu_memory_gb}). "
"Operators can override — this is a warning, not an error. "
- "See product/plans/m4-req2-generate-issues/"
- "10-validation-and-calibration.md for calibrated values."
+ "Use measured workload and GPU data to calibrate this value."
)
warnings.warn(msg, UserWarning, stacklevel=2)
logger.warning(
@@ -476,18 +476,14 @@ class ModelConfig(BaseModel):
msg = (
f"Profile '{name}' on a generation model "
f"('{self.sie_id}') is missing 'kv_budget_tokens'. "
- "This is the per-worker KV-cache admission budget; "
- "see product/plans/m4-req2-generate-issues/"
- "10-validation-and-calibration.md for the calibrated value."
+ "This is the per-worker KV-cache admission budget."
)
raise ValueError(msg)
if not isinstance(effective_budget, int) or effective_budget <= 0:
msg = (
f"Profile '{name}' on a generation model "
f"('{self.sie_id}'): 'kv_budget_tokens' must be a "
- f"positive int, got {effective_budget!r}. "
- "See product/plans/m4-req2-generate-issues/"
- "10-validation-and-calibration.md for calibration guidance."
+ f"positive int, got {effective_budget!r}."
)
raise ValueError(msg)
diff --git a/packages/sie_server/src/sie_server/core/adaptive_batching.py b/packages/sie_server/src/sie_server/core/adaptive_batching.py
index 024a6a7d8..6a28d6fe5 100644
--- a/packages/sie_server/src/sie_server/core/adaptive_batching.py
+++ b/packages/sie_server/src/sie_server/core/adaptive_batching.py
@@ -111,6 +111,8 @@ class AdaptiveBatchState:
headroom_ms: float | None
fill_ratio: float | None
integral: float
+ starvation_streak: int = 0
+ starvation_resets: int = 0
@dataclass(slots=True)
@@ -146,6 +148,25 @@ class AdaptiveBatchController:
the current limit). This prevents wasteful increases when batches
aren't filling. No integral term needed — the gating condition
acts as a form of conditional integration.
+
+ Starvation recovery (deadlock escape hatch):
+ The PI loop has a pathological attractor when observed p50 stays
+ above target for long enough to push both wait and cost to the
+ floor. At the floor, every batch holds a single item; the single
+ item has high p50 (dominated by one-item forward-pass + queue);
+ headroom stays negative; the loop keeps both knobs pinned — it
+ cannot raise wait (headroom < 0) and cannot raise cost
+ (``headroom_frac × cost_gain < 0``). To escape, we track a streak
+ of "batch produced at floor with size ≤ threshold". If the streak
+ exceeds ``starvation_window`` AND both knobs are at their floors,
+ we declare deadlock and hard-reset to a conservative recovery
+ point half-way between floor and initial values. The integrator
+ and ``last_step_time`` are also cleared so the next few samples
+ come from a clean state.
+
+ The counter only increments when ``step()`` is called with a
+ non-None ``batch_size`` — i.e. real traffic is flowing. Idle
+ worker loops don't trip it.
"""
# Latency target — None means auto-calibrate from inference latency
@@ -156,11 +177,19 @@ class AdaptiveBatchController:
min_target_p50_ms: float = 5.0
max_target_p50_ms: float = 500.0
- # Wait time bounds
+ # Wait time bounds. These are the PID-controller's internal default
+ # clamps; production deployments construct ``AdaptiveBatchController``
+ # explicitly from ``sie_server.config.engine.AdaptiveBatchingConfig``.
min_wait_ms: float = 1.0
max_wait_ms: float = 50.0
- # Batch cost bounds (token limit)
+ # Batch cost bounds (token limit). These in-module defaults exist so
+ # the controller is constructible without arguments for tests; real
+ # deployments compute ``min_batch_cost`` from the model's
+ # ``max_batch_tokens`` (see ``ModelWorker.__init__``) so the floor
+ # scales with the model budget — a flat 256 is too low for anything
+ # but the smallest models and lets the cost knob collapse to a
+ # single-item batch under sustained negative-headroom load.
min_batch_cost: int = 256
max_batch_cost: int = 65536
@@ -171,6 +200,17 @@ class AdaptiveBatchController:
update_interval: int = 10
fill_ratio_threshold: float = 0.7
+ # Starvation detection / deadlock recovery
+ starvation_recovery_enabled: bool = True
+ starvation_window: int = 20
+ starvation_batch_size: int = 1
+
+ # Initial values used as recovery anchors (captured in __post_init__
+ # from the _current_* fields so operator-provided startup values are
+ # honoured rather than being replaced with hard-coded defaults).
+ _initial_wait_ms: float = 0.0
+ _initial_batch_cost: int = 0
+
# Current state
_current_wait_ms: float = 10.0
_current_batch_cost: int = 16384
@@ -186,11 +226,21 @@ class AdaptiveBatchController:
_integral_max: float = 20.0
_last_step_time: float | None = None
+ # Starvation tracking (runtime)
+ _starvation_streak: int = 0
+ _starvation_resets: int = 0
+
def __post_init__(self) -> None:
if self.target_p50_ms is None:
self._auto_calibrate = True
else:
self._calibrated = True
+ # Snapshot the operator-provided start values so ``reset()`` and
+ # starvation recovery can return to whatever the worker was
+ # configured with (e.g. from helm values) rather than this
+ # module's historic defaults.
+ self._initial_wait_ms = self._current_wait_ms
+ self._initial_batch_cost = self._current_batch_cost
def record_inference_sample(self, inference_ms: float) -> None:
"""Record an inference-only latency sample for auto-calibration.
@@ -208,6 +258,7 @@ class AdaptiveBatchController:
self,
observed_p50_ms: float | None,
fill_ratio: float | None,
+ batch_size: int | None = None,
) -> tuple[float, int]:
"""Advance the controller and return (new_wait_ms, new_batch_cost).
@@ -215,10 +266,22 @@ class AdaptiveBatchController:
observed_p50_ms: Current rolling p50 latency (total_ms), or None
if not enough samples yet.
fill_ratio: Mean batch fill ratio (0.0–1.0), or None.
+ batch_size: Size of the batch that triggered this step. Used by
+ the starvation detector to count consecutive tiny batches at
+ the floor. ``None`` (the default, for backward compatibility
+ with callers that don't track per-batch size) disables the
+ starvation counter — the loop still runs but can never
+ trigger recovery.
Returns:
Tuple of (max_batch_wait_ms, max_batch_cost).
"""
+ # Starvation tracking runs on every call (not every update_interval)
+ # but only counts while both knobs are pinned at the floor. Tiny
+ # batches before the floor are normal control-loop evidence, not a
+ # deadlock signal.
+ self._update_starvation_tracker(batch_size, pinned_at_floor=self._is_pinned_at_floor())
+
self._steps_since_update += 1
if self._steps_since_update < self.update_interval:
return self._current_wait_ms, self._current_batch_cost
@@ -251,6 +314,13 @@ class AdaptiveBatchController:
if observed_p50_ms is None or self.target_p50_ms is None:
return self._current_wait_ms, self._current_batch_cost
+ # --- Starvation recovery (before running the PI loop). ---
+ # If we trip this, skip the PI update this step — the recovery
+ # already set the knobs. The PI loop will resume next step with a
+ # cleared integrator and fresh latency samples.
+ if self._maybe_recover_from_starvation():
+ return self._current_wait_ms, self._current_batch_cost
+
target = self.target_p50_ms
headroom_ms = target - observed_p50_ms
headroom_frac = headroom_ms / target # normalized (-inf, 1)
@@ -290,13 +360,36 @@ class AdaptiveBatchController:
self._current_wait_ms = _clamp(new_wait, self.min_wait_ms, self.max_wait_ms)
# --- Knob 2: batch cost (proportional-only, gated on fill ratio) ---
+ # Symmetric anti-windup: don't push the cost further into saturation
+ # in the direction the error wants. Without this guard, once p50
+ # exceeds target the loop shrinks cost from initial all the way to
+ # ``min_batch_cost`` (since fill_ratio rises to ~1.0 as batches
+ # collapse — tiny batches always fill their tiny budget). That's the
+ # mechanism behind the queue-mode regression guarded by
+ # packages/sie_server_sidecar/docs/architecture-guide.md.
+ #
+ # The anti-windup only stops further shrinking once at the floor,
+ # it doesn't stop the collapse itself — that's why callers are
+ # expected to set ``min_batch_cost`` to a value large enough to
+ # keep GPU forwards amortized (see ModelWorker.__init__ which
+ # anchors it at ``max_batch_tokens // 4``). A flat floor of 256
+ # is too low for any non-trivial model.
if fill_ratio is not None and fill_ratio >= self.fill_ratio_threshold:
- cost_adjustment = self._current_batch_cost * headroom_frac * self.cost_gain
- new_cost = self._current_batch_cost + cost_adjustment
- self._current_batch_cost = int(_clamp(new_cost, self.min_batch_cost, self.max_batch_cost))
+ cost_at_max = self._current_batch_cost >= self.max_batch_cost
+ cost_at_min = self._current_batch_cost <= self.min_batch_cost
+ can_adjust_cost = True
+ if cost_at_max and headroom_ms > 0:
+ can_adjust_cost = False
+ if cost_at_min and headroom_ms < 0:
+ can_adjust_cost = False
+ if can_adjust_cost:
+ cost_adjustment = self._current_batch_cost * headroom_frac * self.cost_gain
+ new_cost = self._current_batch_cost + cost_adjustment
+ self._current_batch_cost = int(_clamp(new_cost, self.min_batch_cost, self.max_batch_cost))
logger.debug(
- "Adaptive batch: p50=%.1fms (target=%.1f), headroom=%.1fms, integral=%.2f, fill=%.2f, wait=%.1fms, cost=%d",
+ "Adaptive batch: p50=%.1fms (target=%.1f), headroom=%.1fms, integral=%.2f, "
+ "fill=%.2f, wait=%.1fms, cost=%d, starvation_streak=%d",
observed_p50_ms,
target,
headroom_ms,
@@ -304,10 +397,94 @@ class AdaptiveBatchController:
fill_ratio or 0.0,
self._current_wait_ms,
self._current_batch_cost,
+ self._starvation_streak,
)
return self._current_wait_ms, self._current_batch_cost
+ # ------------------------------------------------------------------
+ # Starvation detector helpers
+ # ------------------------------------------------------------------
+
+ def _is_pinned_at_floor(self) -> bool:
+ return self._current_wait_ms <= self.min_wait_ms and self._current_batch_cost <= self.min_batch_cost
+
+ def _update_starvation_tracker(self, batch_size: int | None, *, pinned_at_floor: bool) -> None:
+ """Advance the consecutive-tiny-batches counter.
+
+ The streak resets whenever we see a batch larger than the
+ ``starvation_batch_size`` threshold — a single healthy batch is
+ enough evidence that the loop is not deadlocked, regardless of
+ what the PI math is about to do this step.
+
+ ``batch_size is None`` means starvation detection is disabled
+ for this step, so clear any stale streak before the recovery
+ check runs.
+ """
+ if batch_size is None:
+ self._starvation_streak = 0
+ return
+ if not pinned_at_floor:
+ self._starvation_streak = 0
+ return
+ if batch_size > self.starvation_batch_size:
+ self._starvation_streak = 0
+ else:
+ self._starvation_streak += 1
+
+ def _maybe_recover_from_starvation(self) -> bool:
+ """If deadlock is detected, reset knobs and return True.
+
+ Deadlock = consecutive tiny batches + both knobs already pinned
+ at their floors. Once tripped, we jump to a conservative midway
+ point (half of initial) — aggressive enough to pull a few items
+ per batch (which re-establishes a healthy p50 signal) but not so
+ aggressive that we re-overshoot SLO immediately.
+
+ Integrator, last-step-time and the streak counter are all
+ cleared; the next iteration effectively starts the PI loop from
+ scratch using fresh samples.
+ """
+ if not self.starvation_recovery_enabled:
+ return False
+ if self._starvation_streak < self.starvation_window:
+ return False
+ if not self._is_pinned_at_floor():
+ return False
+
+ recovery_wait = _clamp(
+ (self.min_wait_ms + self._initial_wait_ms) / 2,
+ self.min_wait_ms,
+ self.max_wait_ms,
+ )
+ recovery_cost = int(
+ _clamp(
+ max(self._initial_batch_cost // 2, self.min_batch_cost * 4),
+ self.min_batch_cost,
+ self.max_batch_cost,
+ )
+ )
+
+ logger.warning(
+ "Adaptive batch: starvation recovery triggered after %d consecutive "
+ "batches with size <= %d at the floor (wait=%.1fms, cost=%d). "
+ "Resetting to wait=%.1fms, cost=%d.",
+ self._starvation_streak,
+ self.starvation_batch_size,
+ self._current_wait_ms,
+ self._current_batch_cost,
+ recovery_wait,
+ recovery_cost,
+ )
+
+ self._current_wait_ms = recovery_wait
+ self._current_batch_cost = recovery_cost
+ self._integral = 0.0
+ self._last_step_time = None
+ self._starvation_streak = 0
+ self._starvation_resets += 1
+ return True
+
@property
def current_wait_ms(self) -> float:
return self._current_wait_ms
@@ -320,6 +497,14 @@ class AdaptiveBatchController:
def calibrated(self) -> bool:
return self._calibrated
+ @property
+ def starvation_streak(self) -> int:
+ return self._starvation_streak
+
+ @property
+ def starvation_resets(self) -> int:
+ return self._starvation_resets
+
def snapshot(
self,
observed_p50_ms: float | None = None,
@@ -340,20 +525,30 @@ class AdaptiveBatchController:
headroom_ms=headroom,
fill_ratio=fill_ratio,
integral=self._integral,
+ starvation_streak=self._starvation_streak,
+ starvation_resets=self._starvation_resets,
)
def reset(self) -> None:
- """Reset the controller to its initial state."""
- self._current_wait_ms = _clamp(10.0, self.min_wait_ms, self.max_wait_ms)
- self._current_batch_cost = int(_clamp(16384, self.min_batch_cost, self.max_batch_cost))
+ """Reset the controller to the operator-provided initial state.
+
+ ``_initial_wait_ms`` / ``_initial_batch_cost`` are captured in
+ ``__post_init__`` so this restores whatever the worker was
+ configured with at startup, not the module's legacy defaults.
+ """
+ self._current_wait_ms = _clamp(self._initial_wait_ms, self.min_wait_ms, self.max_wait_ms)
+ self._current_batch_cost = int(_clamp(self._initial_batch_cost, self.min_batch_cost, self.max_batch_cost))
self._steps_since_update = 0
self._integral = 0.0
self._last_step_time = None
+ self._starvation_streak = 0
if self._auto_calibrate:
self._calibrated = False
self.target_p50_ms = None
self._inference_tracker.reset()
- # If target was explicit, _calibrated stays True
+ # If target was explicit, _calibrated stays True.
+ # ``_starvation_resets`` is a monotonic counter and deliberately not
+ # cleared — it's an operational signal exposed via Prometheus.
# Keep backward compat alias
diff --git a/packages/sie_server/src/sie_server/core/batcher.py b/packages/sie_server/src/sie_server/core/batcher.py
index f75e64eab..8abe3048e 100644
--- a/packages/sie_server/src/sie_server/core/batcher.py
+++ b/packages/sie_server/src/sie_server/core/batcher.py
@@ -1,7 +1,7 @@
"""Batch formation for dynamic batching.
Accumulates requests until batch limits are reached, then returns a batch
-ready for inference. See DESIGN.md Section 5.1.
+ready for inference.
Batch formation loop:
1. Wait for first request
@@ -127,11 +127,11 @@ class BatchConfig:
self,
max_batch_cost: int = 16384,
max_batch_requests: int = 64,
- max_batch_wait_ms: float = 10.0,
+ max_batch_wait_ms: float = 15.0,
*,
max_batch_tokens: int | None = None, # Backward compatibility alias
- coalesce_ms: float = 2.0,
- coalesce_ratio: float = 0.2,
+ coalesce_ms: float = 15.0,
+ coalesce_ratio: float = 0.5,
) -> None:
"""Initialize batch configuration.
@@ -143,12 +143,15 @@ class BatchConfig:
coalesce_ms: Idle coalescing window ceiling. If no new items arrive
within this period, yield the batch even if max_batch_wait_ms
hasn't expired. The actual coalescing window may be smaller;
- see effective_coalesce_ms.
+ see effective_coalesce_ms. Set around the expected inter-arrival
+ jitter of upstream IPC bursts so a whole burst lands in one
+ GPU batch — too small shreds IPC batches of 64 into 2–3
+ under-filled GPU forwards.
coalesce_ratio: Coalesce window as a fraction of max_batch_wait_ms.
The effective coalesce window is
``min(coalesce_ms, max_batch_wait_ms * coalesce_ratio)``.
This keeps coalesce proportional when the adaptive controller
- changes max_batch_wait_ms. Default 0.2 (20%).
+ changes max_batch_wait_ms. Default 0.5 (50%).
"""
# Allow max_batch_tokens as an alias for max_batch_cost
if max_batch_tokens is not None:
diff --git a/packages/sie_server/src/sie_server/core/deps.py b/packages/sie_server/src/sie_server/core/deps.py
index 7ec2f3df0..14b6b2832 100644
--- a/packages/sie_server/src/sie_server/core/deps.py
+++ b/packages/sie_server/src/sie_server/core/deps.py
@@ -2,12 +2,11 @@ from __future__ import annotations
import logging
import re
-import sys
from dataclasses import dataclass
from pathlib import Path
import yaml
-from sie_sdk.bundle_utils import find_bundle_for_models, match_bundle_models
+from sie_sdk.bundle_utils import match_bundle_models
logger = logging.getLogger(__name__)
@@ -185,46 +184,3 @@ def collect_bundle_deps(
conflicts=[],
models=model_names,
)
-
-
-def resolve_bundle_deps_cli(
- bundle_name: str | None,
- model_names: list[str] | None,
- bundles_dir: Path,
- models_dir: Path,
-) -> int:
- """CLI entry point for resolving bundle dependencies.
-
- Prints requirements to stdout (one per line) or errors to stderr.
-
- Args:
- bundle_name: Name of the bundle to resolve.
- model_names: Alternative: explicit list of model names (finds matching bundle).
- bundles_dir: Path to the bundles directory.
- models_dir: Path to the models directory.
-
- Returns:
- Exit code (0 for success, 1 for conflicts/errors).
- """
- if bundle_name:
- result = collect_bundle_deps(bundle_name, bundles_dir, models_dir)
- elif model_names:
- # Find the best matching bundle for these models
- matched = find_bundle_for_models(model_names, bundles_dir, models_dir)
- if not matched:
- print(f"No bundle found covering models: {', '.join(model_names)}", file=sys.stderr)
- return 1
- result = collect_bundle_deps(matched, bundles_dir, models_dir)
- else:
- return 1
-
- if result.conflicts:
- for conflict in result.conflicts:
- print(conflict, file=sys.stderr)
- return 1
-
- # Print requirements to stdout for shell scripts to consume
- for req in result.requirements:
- print(req)
-
- return 0
diff --git a/packages/sie_server/src/sie_server/core/disk_cache.py b/packages/sie_server/src/sie_server/core/disk_cache.py
index 03200d093..6e45dd552 100644
--- a/packages/sie_server/src/sie_server/core/disk_cache.py
+++ b/packages/sie_server/src/sie_server/core/disk_cache.py
@@ -5,7 +5,7 @@ Uses huggingface_hub's scan_cache_dir() for inspection and
delete_revisions() for eviction. LRU ordering is based on
blob_last_accessed timestamps.
-Per DESIGN.md Section 5.4 (extended to disk):
+Disk cache eviction behavior:
- Reactive LRU eviction when disk pressure exceeds threshold
- Check disk usage before downloading new models
- Evict least-recently-accessed models to make space
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 879875cdb..690a50359 100644
--- a/packages/sie_server/src/sie_server/core/encode_pipeline.py
+++ b/packages/sie_server/src/sie_server/core/encode_pipeline.py
@@ -1,13 +1,20 @@
+from __future__ import annotations
+
import asyncio
-from typing import Any, cast
+from typing import TYPE_CHECKING, Any, cast
from sie_server.core.inference_output import EncodeOutput
from sie_server.core.prepared import ImagePayload, PreparedBatch, PreparedItem
+from sie_server.core.preprocessor.text import TextPreprocessor
from sie_server.core.registry import ModelRegistry
from sie_server.core.timing import RequestTiming
from sie_server.core.worker.handlers.encode import EncodeHandler
from sie_server.types.inputs import Item
+if TYPE_CHECKING:
+ from sie_server.core.preprocessor_registry import PreprocessorRegistry
+ from sie_server.ipc_types import PreparedTokens
+
class EncodePipeline:
@classmethod
@@ -21,14 +28,29 @@ class EncodePipeline:
config: Any,
is_query: bool,
options: dict[str, Any],
+ prepared_tokens_per_item: list[PreparedTokens | None] | None = None,
) -> tuple[list[dict[str, Any]], RequestTiming]:
"""Main entry point: preprocess then execute encoding.
This is the unified encode path that handles text, image, and direct modes.
+
+ ``prepared_tokens_per_item`` is the worker-sidecar's fast-path
+ token payload, aligned 1:1 with ``items``. When supplied,
+ the text preprocessor skips its own tokenisation iff the
+ tokenizer_id matches (see ``TextPreprocessor.try_prepare_from_prepared_tokens``).
+ Absent / mismatched → Python tokenises exactly like today.
"""
timing = RequestTiming()
- prepared_batch = await cls._prepare_batch(registry, model, items, config, is_query, timing)
+ prepared_batch = await cls._prepare_batch(
+ registry,
+ model,
+ items,
+ config,
+ is_query,
+ timing,
+ prepared_tokens_per_item=prepared_tokens_per_item,
+ )
if prepared_batch is not None:
# Batched worker path
@@ -77,10 +99,18 @@ class EncodePipeline:
config: Any,
is_query: bool,
timing: RequestTiming,
+ *,
+ prepared_tokens_per_item: list[PreparedTokens | None] | None = None,
) -> PreparedBatch | None:
"""Run CPU preprocessing (tokenization/image processing) if a preprocessor exists.
Returns None if no preprocessor is registered (direct adapter call path).
+
+ When ``prepared_tokens_per_item`` is supplied, the text path tries the
+ Rust-tokenise fast path first via
+ ``TextPreprocessor.try_prepare_from_prepared_tokens``; any rejection
+ (mismatch, missing, drift, etc.) transparently falls back to the
+ Python tokenizer so correctness is never at risk.
"""
preprocessor_registry = registry.preprocessor_registry
has_image_input = config.inputs is not None and config.inputs.image
@@ -90,6 +120,19 @@ class EncodePipeline:
# Text-only path: use text preprocessor
if preprocessor_registry.has_preprocessor(model, "text") and all_items_have_text and not any_items_have_images:
timing.start_tokenization()
+ # Try the Rust-tokenise fast path first. Only the in-tree
+ # `TextPreprocessor` implements it; other preprocessors
+ # (e.g. `CharCountPreprocessor` for library-wrapped
+ # adapters) return None and we fall through to the
+ # normal path.
+ if prepared_tokens_per_item is not None:
+ fast_path = await cls._try_fast_path(
+ preprocessor_registry, model, items, prepared_tokens_per_item, config=config
+ )
+ if fast_path is not None:
+ timing.end_tokenization()
+ return fast_path
+
prepared_batch = await preprocessor_registry.prepare(model, items, config, is_query=is_query)
timing.end_tokenization()
return prepared_batch
@@ -118,3 +161,28 @@ class EncodePipeline:
# No preprocessor available - return None to signal direct adapter call
return None
+
+ @classmethod
+ async def _try_fast_path(
+ cls,
+ preprocessor_registry: PreprocessorRegistry,
+ model: str,
+ items: list[Item],
+ prepared_tokens_per_item: list[PreparedTokens | None],
+ *,
+ config: Any,
+ ) -> PreparedBatch | None:
+ """Attempt the Rust-tokenise fast path. Returns ``None`` if the
+ preprocessor for ``model`` isn't a plain ``TextPreprocessor``
+ (e.g. ``CharCountPreprocessor`` for library-wrapped adapters),
+ or if the fast path rejects the batch for any reason.
+
+ Runs synchronously — the fast path is pure Python list
+ manipulation, no tokenizer call. Skipping the ``to_thread``
+ hop saves ~1.5 ms of scheduling overhead for the common case
+ where every item hits the fast path.
+ """
+ preprocessor = preprocessor_registry.get_preprocessor(model, "text")
+ if not isinstance(preprocessor, TextPreprocessor):
+ return None
+ return preprocessor.try_prepare_from_prepared_tokens(items, prepared_tokens_per_item, config=config)
diff --git a/packages/sie_server/src/sie_server/core/extract_cost.py b/packages/sie_server/src/sie_server/core/extract_cost.py
index 5d166f07e..66e177f6b 100644
--- a/packages/sie_server/src/sie_server/core/extract_cost.py
+++ b/packages/sie_server/src/sie_server/core/extract_cost.py
@@ -13,8 +13,7 @@ into one forward pass. Two distinct adapter shapes feed this:
output side, so the batcher over-packs and the GPU stalls or
OOMs. This is the bug behind issue #33.
-The fix (M4 req2 Proj 2 / coordination contract — "same fix is
-referenced by #33"): callers operating on decoder-OCR adapters pass
+The fix: callers operating on decoder-OCR adapters pass
``decoder_max_output_tokens`` so the cost reflects the worst-case
KV growth during decode. Encoder-only callers pass nothing — default
zero preserves the existing behaviour exactly.
diff --git a/packages/sie_server/src/sie_server/core/hot_reload.py b/packages/sie_server/src/sie_server/core/hot_reload.py
index de7354805..6f1c905e0 100644
--- a/packages/sie_server/src/sie_server/core/hot_reload.py
+++ b/packages/sie_server/src/sie_server/core/hot_reload.py
@@ -7,8 +7,6 @@ configurations change. Handles the full lifecycle:
3. Unload model and clear module cache
4. Load new adapter
5. Resume serving
-
-See DESIGN.md Section 7.4.
"""
from __future__ import annotations
diff --git a/packages/sie_server/src/sie_server/core/inference.py b/packages/sie_server/src/sie_server/core/inference.py
index 0c1508132..c421469bf 100644
--- a/packages/sie_server/src/sie_server/core/inference.py
+++ b/packages/sie_server/src/sie_server/core/inference.py
@@ -1,6 +1,6 @@
"""Inference optimization utilities.
-Handles compute precision and attention backend configuration per DESIGN.md Section 6.3-6.4.
+Handles compute precision and attention backend configuration.
Compute precision pipeline:
- Weights on disk (FP32/BF16) → Load/Cast to GPU → Compute (FP16/BF16/FP32) → Output
@@ -164,7 +164,7 @@ def resolve_attention_backend(
Handles "auto" selection and validates compatibility with precision and device.
- Per DESIGN.md: Flash Attention 2 requires FP16 or BF16 and CUDA device.
+ Flash Attention 2 requires FP16 or BF16 and a CUDA device.
Args:
requested: Requested backend from config.
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 910c5c390..f3ea60908 100644
--- a/packages/sie_server/src/sie_server/core/inference_output.py
+++ b/packages/sie_server/src/sie_server/core/inference_output.py
@@ -1,8 +1,5 @@
"""Typed output types for standardized batched inference results.
-See DESIGN.md Section 7.3 for specification.
-See product/roadmap.md Project 10.12 for design rationale.
-
Three separate output types for three operations:
- EncodeOutput: from adapter.encode() - embeddings (dense/sparse/multivector)
- ScoreOutput: from adapter.score_pairs() - reranking scores
diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.py
index 78150e351..0337f9a99 100644
--- a/packages/sie_server/src/sie_server/core/loader.py
+++ b/packages/sie_server/src/sie_server/core/loader.py
@@ -291,6 +291,27 @@ def load_adapter(
# If signature inspection fails, avoid passing unsupported kwargs
pass
+ # Wire the profile's ``runtime.default_sampling`` into the adapter when its
+ # constructor accepts it. These defaults live under ``adapter_options.runtime``
+ # (not ``loadtime``) and were previously dropped entirely — so a profile's
+ # ``default_sampling`` silently no-op'd (e.g. a ``min_new_tokens`` floor for
+ # the Qwen3.6 stop-token-as-first-token bug never reached SGLang). The adapter
+ # merges this dict with ``setdefault`` semantics, so request-supplied sampling
+ # values still win; this only fills params the caller omitted, which is the
+ # documented intent of a ``default_sampling`` block. Guarded by signature
+ # inspection so adapters that don't accept the kwarg are unaffected.
+ if "default_sampling" not in adapter_kwargs:
+ try:
+ signature = inspect.signature(adapter_class.__init__)
+ default_sampling = dict(config.resolve_profile("default").runtime).get("default_sampling")
+ if "default_sampling" in signature.parameters and default_sampling:
+ adapter_kwargs["default_sampling"] = default_sampling
+ except (TypeError, ValueError):
+ logger.debug(
+ "Could not inspect adapter constructor for default_sampling support; skipping default_sampling wiring.",
+ exc_info=True,
+ )
+
# Instantiate adapter using factory method for device-aware selection
# All adapters inherit create_for_device() from ModelAdapter base class
adapter = adapter_class.create_for_device(device=device, **adapter_kwargs)
diff --git a/packages/sie_server/src/sie_server/core/memory.py b/packages/sie_server/src/sie_server/core/memory.py
index 85f37440d..7291342bc 100644
--- a/packages/sie_server/src/sie_server/core/memory.py
+++ b/packages/sie_server/src/sie_server/core/memory.py
@@ -2,7 +2,7 @@
Device-agnostic memory monitoring and LRU tracking for CUDA, MPS, and CPU.
-Per DESIGN.md Section 5.4:
+Memory management behavior:
- Reactive LRU eviction without static VRAM budgets
- Try to load model → If OOM, evict LRU model and retry
- After each batch, check memory usage; evict if above threshold
@@ -462,7 +462,7 @@ class MemoryManager:
async def check_memory_pressure(self) -> list[str]:
"""Check memory pressure and return models that should be evicted.
- Async wrapper for use in async request handlers (per DESIGN.md).
+ Async wrapper for use in async request handlers.
The underlying check is fast and non-blocking.
Returns:
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 217247768..063d2f391 100644
--- a/packages/sie_server/src/sie_server/core/model_loader.py
+++ b/packages/sie_server/src/sie_server/core/model_loader.py
@@ -138,6 +138,8 @@ class ModelLoader:
attention_backend: AttentionBackend = "auto",
max_batch_requests: int | None = None,
max_batch_wait_ms: float | None = None,
+ coalesce_ms: float | None = None,
+ coalesce_ratio: float | None = None,
max_queue_size: int | None = None,
instrumentation: bool = False,
max_loras_per_model: int = DEFAULT_MAX_LORAS,
@@ -162,6 +164,8 @@ class ModelLoader:
self._attention_backend = attention_backend
self._max_batch_requests = max_batch_requests
self._max_batch_wait_ms = max_batch_wait_ms
+ self._coalesce_ms = coalesce_ms
+ self._coalesce_ratio = coalesce_ratio
self._max_queue_size = max_queue_size
self._instrumentation = instrumentation
self._max_loras_per_model = max_loras_per_model
@@ -570,7 +574,7 @@ class ModelLoader:
self._preprocessor_registry.register_image(name, preprocessor)
logger.info("Registered image preprocessor for model '%s'", name)
- # Register postprocessors if adapter provides them (Phase 5)
+ # Register postprocessors if adapter provides them.
if hasattr(adapter, "get_postprocessors"):
postprocessors = adapter.get_postprocessors()
if postprocessors:
@@ -594,6 +598,8 @@ class ModelLoader:
max_batch_tokens=resolved.max_batch_tokens,
max_batch_requests=self._max_batch_requests or WorkerConfig().max_batch_requests,
max_batch_wait_ms=self._max_batch_wait_ms or WorkerConfig().max_batch_wait_ms,
+ coalesce_ms=self._coalesce_ms if self._coalesce_ms is not None else WorkerConfig().coalesce_ms,
+ coalesce_ratio=self._coalesce_ratio if self._coalesce_ratio is not None else WorkerConfig().coalesce_ratio,
max_queue_size=self._max_queue_size or WorkerConfig().max_queue_size,
instrumentation=self._instrumentation,
adaptive_batching=adaptive_params,
diff --git a/packages/sie_server/src/sie_server/core/pool_isolation.py b/packages/sie_server/src/sie_server/core/pool_isolation.py
index e0fba1b12..5aaebbbef 100644
--- a/packages/sie_server/src/sie_server/core/pool_isolation.py
+++ b/packages/sie_server/src/sie_server/core/pool_isolation.py
@@ -7,8 +7,7 @@ cross-worker pool registry. The validator fires when configs are added
to a worker's :class:`ModelRegistry` (i.e. at startup config-load and
at hot-reload time).
-Rationale (per source spec for the admission-control rollout): mixed-pool fairness across
-request shapes is an explicit M5+ concern. For the current horizon
+Rationale: mixed-pool fairness across request shapes is a separate concern. For the current horizon
the simpler invariant — a single pool holds a single task class — is
what the gateway's routing and the worker's batch-shape assumptions
already assume. Reject loudly at config load so operators see the
@@ -190,8 +189,6 @@ def validate_no_legacy_scalar_lora_id(
f"adapter_options.runtime, which is not supported on the "
f"generation primitive. Multi-LoRA generation is shipped via "
f"``adapter_options.loadtime.lora_paths`` (list of adapter ids); "
- f"migrate to that form, or remove the ``lora_id`` entry. See "
- f"product/research/generation-primitive-status.md "
- f"(§4.8 pool isolation, §5/§6.2 LoRA on generation)."
+ f"migrate to that form, or remove the ``lora_id`` entry."
)
raise LegacyScalarLoraIdError(msg)
diff --git a/packages/sie_server/src/sie_server/core/postprocessor.py b/packages/sie_server/src/sie_server/core/postprocessor.py
index f4d6920ec..abcc345bc 100644
--- a/packages/sie_server/src/sie_server/core/postprocessor.py
+++ b/packages/sie_server/src/sie_server/core/postprocessor.py
@@ -1,8 +1,5 @@
"""Postprocessor protocol and implementations for output type coercion.
-See DESIGN.md Section 7.3.2 for specification.
-See product/roadmap.md Project 10.12 for design rationale.
-
Postprocessors transform EncodeOutput in-place to add/convert output types:
- MuveraPostprocessor: multivector -> dense (for ColBERT/ColPali)
- Future: Int8Postprocessor, BinaryPostprocessor for quantization
diff --git a/packages/sie_server/src/sie_server/core/postprocessor_registry.py b/packages/sie_server/src/sie_server/core/postprocessor_registry.py
index 348697763..fe52a0fed 100644
--- a/packages/sie_server/src/sie_server/core/postprocessor_registry.py
+++ b/packages/sie_server/src/sie_server/core/postprocessor_registry.py
@@ -3,8 +3,8 @@
This module manages postprocessors for loaded models and provides
async postprocessing that runs in a shared thread pool.
-Postprocessors are triggered explicitly via runtime options (not inferred
-from output types). See DESIGN.md Section 7.3.2.
+Postprocessors are triggered explicitly via runtime options, not inferred
+from output types.
Example:
# Register when model loads
diff --git a/packages/sie_server/src/sie_server/core/prepared.py b/packages/sie_server/src/sie_server/core/prepared.py
index 1a897fe53..bda815bed 100644
--- a/packages/sie_server/src/sie_server/core/prepared.py
+++ b/packages/sie_server/src/sie_server/core/prepared.py
@@ -4,7 +4,7 @@ This module defines the core abstractions for preprocessing items before
batching and inference. These types generalize TokenizedItem to support
text, images, audio, and mixed-modality inputs.
-See roadmap.md Project 10.4 Phase 2 for design details.
+Prepared batches carry modality-specific payloads through the batching layer.
"""
from __future__ import annotations
@@ -300,6 +300,26 @@ class PaddleOCRVLPayload(Payload):
PaddleOCRVLPreparedItem = PreparedItem[PaddleOCRVLPayload]
+@dataclass(slots=True)
+class MinerUVLPayload(Payload):
+ """Preprocessed MinerU2.5-Pro input ready for extraction.
+
+ MinerU2.5-Pro-2604-1.2B is a Qwen2-VL document parser. The processor
+ (Qwen2VLProcessor with Qwen2VLImageProcessorFast) tokenizes a Qwen2-VL
+ chat-template prompt and emits ``image_grid_thw`` alongside
+ ``pixel_values`` for native-resolution patch packing.
+ """
+
+ pixel_values: Any # torch.Tensor
+ input_ids: Any # torch.Tensor [seq_len]
+ attention_mask: Any # torch.Tensor [seq_len]
+ image_grid_thw: Any # torch.Tensor [1, 3] — (temporal, height, width) grid
+ original_size: tuple[int, int]
+
+
+MinerUVLPreparedItem = PreparedItem[MinerUVLPayload]
+
+
@dataclass(slots=True)
class GlmOcrPayload(Payload):
"""Preprocessed GLM-OCR input ready for extraction.
diff --git a/packages/sie_server/src/sie_server/core/preprocessor/__init__.py b/packages/sie_server/src/sie_server/core/preprocessor/__init__.py
index f548fcd06..0ff13b3c5 100644
--- a/packages/sie_server/src/sie_server/core/preprocessor/__init__.py
+++ b/packages/sie_server/src/sie_server/core/preprocessor/__init__.py
@@ -3,8 +3,6 @@
This module defines the Preprocessor protocol and concrete implementations
for text (tokenization) and images (PIL -> processor -> tensor).
-See roadmap.md Project 10.4 Phase 2 for design details.
-
Performance optimizations:
- Parallel image processing with ThreadPoolExecutor (GIL released during I/O)
- pillow-simd detection for 4-6x faster image resizing (if installed)
diff --git a/packages/sie_server/src/sie_server/core/preprocessor/base.py b/packages/sie_server/src/sie_server/core/preprocessor/base.py
index 2cc2347a2..791a7c915 100644
--- a/packages/sie_server/src/sie_server/core/preprocessor/base.py
+++ b/packages/sie_server/src/sie_server/core/preprocessor/base.py
@@ -3,7 +3,7 @@
This module defines the Preprocessor protocol that all modality-specific
preprocessors must implement, plus shared infrastructure for image processing.
-See roadmap.md Project 10.4 Phase 2 for design details.
+Preprocessors convert request items into payloads ready for batching.
"""
from __future__ import annotations
diff --git a/packages/sie_server/src/sie_server/core/preprocessor/text.py b/packages/sie_server/src/sie_server/core/preprocessor/text.py
index c9f14e3b2..9cc9f734a 100644
--- a/packages/sie_server/src/sie_server/core/preprocessor/text.py
+++ b/packages/sie_server/src/sie_server/core/preprocessor/text.py
@@ -7,6 +7,7 @@ This module contains preprocessors for text modality:
from __future__ import annotations
+import logging
from typing import TYPE_CHECKING, Any
from sie_server.core.prepared import PreparedBatch, PreparedItem, TextPayload
@@ -15,8 +16,11 @@ if TYPE_CHECKING:
from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast
from sie_server.config.model import ModelConfig
+ from sie_server.ipc_types import PreparedTokens
from sie_server.types.inputs import Item
+logger = logging.getLogger(__name__)
+
class TextPreprocessor:
"""Preprocessor for text tokenization.
@@ -38,6 +42,229 @@ class TextPreprocessor:
"""
self._tokenizer = tokenizer
self._model_name = model_name
+ # Cached cross-language content hash of this tokenizer. Used
+ # by `try_prepare_from_prepared_tokens` to decide whether
+ # Rust-side pre-tokenised inputs can be trusted without
+ # re-running Python tokenisation. Lazily computed — Rust-fast
+ # models pay it once at adapter load; others never do.
+ self._tokenizer_id: str | None = None
+
+ @property
+ def tokenizer_id(self) -> str | None:
+ """Return the BLAKE3 content hash of this tokenizer, matching
+ what the worker-sidecar emits in ``PreparedTokens.tokenizer_id``.
+
+ Returns ``None`` when the tokenizer is not a HuggingFace fast
+ tokenizer (slow tokenizers don't expose a canonical JSON
+ serialisation and therefore cannot participate in the Rust
+ fast-path).
+
+ Hash is computed on first access and cached thereafter.
+ """
+ if self._tokenizer_id is not None:
+ return self._tokenizer_id
+
+ # Fast tokenizers expose `.backend_tokenizer` → the underlying
+ # Rust `tokenizers::Tokenizer`. Slow tokenizers don't, and
+ # will return None (which the caller interprets as "this
+ # model cannot fast-path — always tokenise in Python").
+ backend = getattr(self._tokenizer, "backend_tokenizer", None)
+ if backend is None:
+ return None
+
+ try:
+ import blake3
+
+ canonical = backend.to_str(pretty=False).encode("utf-8")
+ self._tokenizer_id = blake3.blake3(canonical).hexdigest()[:32]
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "tokenizer_id: failed to compute hash for %s; fast-path disabled",
+ self._model_name,
+ exc_info=True,
+ )
+ return None
+
+ return self._tokenizer_id
+
+ def try_prepare_from_prepared_tokens(
+ self,
+ items: list[Item],
+ prepared_tokens_per_item: list[PreparedTokens | None],
+ *,
+ config: ModelConfig,
+ ) -> PreparedBatch[TextPayload] | None:
+ """Fast-path builder: assemble a ``PreparedBatch`` directly from
+ Rust-supplied ``PreparedTokens`` without re-tokenising.
+
+ Returns ``None`` when the fast path is not viable for the
+ batch — in which case the caller must call ``prepare()`` as
+ usual.
+
+ Per-item hybrid acceptance (v2 of this gate):
+
+ * Items whose ``pt`` is present and passes all in-item checks
+ (``tokenizer_id`` match, 1 sequence, correct shape, zero
+ ``token_type_ids``, ``max_seq_len`` within model cap) build
+ their ``TextPayload`` directly from the Rust bytes.
+ * Items whose ``pt`` is ``None`` (Rust deliberately skipped
+ them — empty text, multimodal fields, instruction/is_query
+ subgroup, ...) are tokenised in Python via ``prepare()`` on
+ the subset, then spliced back in the original order. Every
+ item ends up with a valid ``TextPayload``; the adapter sees
+ a homogeneous batch and does a single forward pass.
+
+ Whole-batch fallback (return ``None``) is reserved for signals
+ that correctness of *other* items in the batch is suspect:
+
+ * Length mismatch between ``items`` and ``prepared_tokens_per_item``.
+ * ``tokenizer_id`` disagrees with this preprocessor's hash —
+ indicates a drift between what Rust loaded and what Python
+ loaded (different revisions, different ``tokenizer_config``
+ overrides, ...). Safer to re-tokenise everything under the
+ Python policy.
+ * A ``prepared_tokens`` whose sequence was truncated to a
+ larger ``max_seq_len`` than this model's
+ ``config.max_sequence_length`` — staying on the Python path
+ lets the config-level truncation apply consistently.
+ * Malformed wire shape (``len(input_ids) != 1`` or explicit
+ ``attention_mask`` width does not match ``input_ids``).
+ """
+ if not items:
+ return PreparedBatch(items=[], total_cost=0, modality="text")
+
+ if len(prepared_tokens_per_item) != len(items):
+ logger.debug(
+ "rust-tokenize fast-path: prepared_tokens length mismatch (%d vs %d items); falling back",
+ len(prepared_tokens_per_item),
+ len(items),
+ )
+ return None
+
+ my_id = self.tokenizer_id
+ if my_id is None:
+ return None
+
+ model_max_seq = getattr(config, "max_sequence_length", None)
+
+ # Classify each item into fast (Rust bytes usable) or slow
+ # (Python tokeniser needed). Drift / malformed signals on any
+ # item collapse the whole batch to slow via an early return.
+ fast_payloads: dict[int, TextPayload] = {}
+ slow_indices: list[int] = []
+ for i, pt in enumerate(prepared_tokens_per_item):
+ if pt is None:
+ slow_indices.append(i)
+ continue
+ if pt.tokenizer_id != my_id:
+ # Tokenizer drift on any item = batch-wide fallback.
+ # Silent at debug to avoid flooding during rolling
+ # deploys where Rust and Python legitimately disagree
+ # for a few minutes.
+ logger.debug(
+ "rust-tokenize fast-path: tokenizer_id mismatch for %s (python=%s, rust=%s); falling back",
+ self._model_name,
+ my_id,
+ pt.tokenizer_id,
+ )
+ return None
+ if len(pt.input_ids) != 1:
+ logger.debug(
+ "rust-tokenize fast-path: item %d has %d sequences, expected 1; falling back",
+ i,
+ len(pt.input_ids),
+ )
+ return None
+ if model_max_seq is not None and pt.max_seq_len > model_max_seq:
+ logger.debug(
+ "rust-tokenize fast-path: item %d truncated at %d > model cap %d; falling back",
+ i,
+ pt.max_seq_len,
+ model_max_seq,
+ )
+ return None
+ # Non-zero segment ids are a per-item concern: the sidecar's
+ # text payload can't ferry them, so this item falls
+ # back to Python (which regenerates the correct segment
+ # synthesis the adapter expects). Other items in the
+ # batch can still use the fast path.
+ if pt.token_type_ids and any(any(t != 0 for t in row) for row in pt.token_type_ids):
+ logger.debug(
+ "rust-tokenize fast-path: non-zero token_type_ids on item %d; tokenising in Python",
+ i,
+ )
+ slow_indices.append(i)
+ continue
+
+ input_ids = list(pt.input_ids[0])
+ # Rust elides `attention_mask` entirely when it would be
+ # all-ones (the no-padding case); rebuild the default.
+ if pt.attention_mask:
+ mask_shape_mismatch = len(pt.attention_mask) != len(pt.input_ids) or len(pt.attention_mask[0]) != len(
+ input_ids
+ )
+ if mask_shape_mismatch:
+ logger.debug(
+ "rust-tokenize fast-path: item %d has malformed attention_mask shape; falling back",
+ i,
+ )
+ return None
+ attention_mask = list(pt.attention_mask[0])
+ else:
+ attention_mask = [1] * len(input_ids)
+
+ fast_payloads[i] = TextPayload(input_ids=input_ids, attention_mask=attention_mask)
+
+ # If no item hit the fast path, let the caller's normal
+ # ``prepare()`` run — spawning a second tokeniser call for
+ # an all-slow batch would just be overhead.
+ if not fast_payloads:
+ return None
+
+ # Hybrid path: tokenise the slow subset in Python and splice
+ # back. A synchronous call is fine — we're already inside the
+ # tokenisation phase of ``_prepare_batch``.
+ slow_payload_by_original_index: dict[int, TextPayload] = {}
+ if slow_indices:
+ slow_items = [items[i] for i in slow_indices]
+ try:
+ slow_batch = self.prepare(slow_items, config=config)
+ except Exception: # noqa: BLE001
+ # Bail to whole-batch fallback if the slow subset
+ # blows up — the caller's ``prepare()`` will retry
+ # with the full item list and a uniform error path.
+ logger.warning(
+ "rust-tokenize fast-path: hybrid slow-subset tokenise failed for %s; falling back whole batch",
+ self._model_name,
+ exc_info=True,
+ )
+ return None
+ for prep_item in slow_batch.items:
+ original_index = slow_indices[prep_item.original_index]
+ slow_payload_by_original_index[original_index] = prep_item.payload
+
+ # Assemble in original ``items`` order so downstream
+ # ``original_index`` invariants are preserved (used by the
+ # encode pipeline to route outputs back to request items).
+ prepared_items: list[PreparedItem[TextPayload]] = []
+ total_cost = 0
+ for i in range(len(items)):
+ payload = fast_payloads.get(i) or slow_payload_by_original_index.get(i)
+ if payload is None:
+ # Defensive: every index must be covered by exactly
+ # one of the two sources. If this branch ever fires
+ # it means the classification logic above diverged
+ # from the merge logic here.
+ logger.warning(
+ "rust-tokenize fast-path: item %d has no payload after hybrid merge; falling back",
+ i,
+ )
+ return None
+ cost = len(payload.input_ids)
+ prepared_items.append(PreparedItem(payload=payload, cost=cost, original_index=i))
+ total_cost += cost
+
+ return PreparedBatch(items=prepared_items, total_cost=total_cost, modality="text")
@property
def modality(self) -> str:
@@ -59,16 +286,16 @@ class TextPreprocessor:
items: Items with text field.
config: Model config with max_sequence_length.
is_query: Whether items are queries (True) or documents (False).
- Currently unused - will be used for query-specific tokenization
- in Phase 4 (e.g., ColBERT query expansion, instruction prefixes).
+ Currently unused; reserved for query-specific tokenization
+ such as ColBERT query expansion or instruction prefixes.
instruction: Optional instruction (unused for text preprocessing).
task: Optional task token (unused for text preprocessing).
Returns:
PreparedBatch with TextPayload items.
"""
- # Note: is_query available for future query-specific tokenization
- _ = is_query # Unused for now, will be used in Phase 4
+ # Note: is_query is reserved for future query-specific tokenization.
+ _ = is_query
del instruction, task # Unused - only needed for vision models
# Extract texts
diff --git a/packages/sie_server/src/sie_server/core/preprocessor/vision.py b/packages/sie_server/src/sie_server/core/preprocessor/vision.py
index 7024766cd..ac5d25915 100644
--- a/packages/sie_server/src/sie_server/core/preprocessor/vision.py
+++ b/packages/sie_server/src/sie_server/core/preprocessor/vision.py
@@ -19,6 +19,7 @@ from sie_server.core.prepared import (
Florence2Payload,
GlmOcrPayload,
LightOnOCRPayload,
+ MinerUVLPayload,
NemoColEmbedPayload,
PaddleOCRVLPayload,
PreparedBatch,
@@ -1488,3 +1489,177 @@ class PaddleOCRVLPreprocessor:
"attention_mask": p.payload.attention_mask.unsqueeze(0).to(device),
"image_grid_thw": p.payload.image_grid_thw.to(device),
}
+
+
+# Canonical task -> prompt mapping from upstream mineru_vl_utils.mineru_client
+# (``DEFAULT_PROMPTS``). Bracketed task names (``[default]``, ``[layout]``)
+# mirror upstream's convention. The leading newline is intentional — preserve
+# verbatim. Keep in sync with ``adapters/mineru_vl/__init__.py::_TASK_PROMPTS``.
+_MINERU_VL_TASK_PROMPTS: dict[str, str] = {
+ "[default]": "\nText Recognition:",
+ "table": "\nTable Recognition:",
+ "equation": "\nFormula Recognition:",
+ "image": "\nImage Analysis:",
+ "chart": "\nImage Analysis:",
+ "[layout]": "\nLayout Detection:",
+}
+
+
+class MinerUVLPreprocessor:
+ """Preprocessor for MinerU2.5-Pro-2604-1.2B document OCR VLM.
+
+ Builds a Qwen2-VL chat-template prompt keyed by task ([default]/table/
+ equation/image/chart/[layout]) and runs the HuggingFace processor
+ (Qwen2VLProcessor + Qwen2VLImageProcessorFast) to produce pixel_values,
+ input_ids, attention_mask, and image_grid_thw.
+
+ Thread-safe: PIL and HuggingFace processors handle concurrent calls.
+ """
+
+ def __init__(
+ self,
+ processor: Any,
+ model_name: str,
+ *,
+ default_task: str = "[default]",
+ ) -> None:
+ if default_task not in _MINERU_VL_TASK_PROMPTS:
+ msg = f"default_task {default_task!r} must be one of {tuple(_MINERU_VL_TASK_PROMPTS)}"
+ raise ValueError(msg)
+ self._processor = processor
+ self._model_name = model_name
+ self._default_task = default_task
+
+ @property
+ def modality(self) -> str:
+ return "image"
+
+ def _task_prompt(self, task: str | None, instruction: str | None) -> str:
+ """Resolve the text prompt for the user message.
+
+ Instruction overrides the task-based prompt when provided.
+ """
+ if instruction:
+ return instruction
+ resolved_task = task or self._default_task
+ return _MINERU_VL_TASK_PROMPTS.get(resolved_task, _MINERU_VL_TASK_PROMPTS[self._default_task])
+
+ def _build_messages(self, prompt_text: str) -> list[dict[str, Any]]:
+ return [
+ {
+ "role": "user",
+ "content": [
+ {"type": "image"},
+ {"type": "text", "text": prompt_text},
+ ],
+ }
+ ]
+
+ def _process_single_image(
+ self,
+ item: Item,
+ index: int,
+ text: str,
+ ) -> PreparedItem[MinerUVLPayload] | None:
+ from PIL import Image as PILImage
+
+ if not item.images:
+ logger.warning("MinerUVLPreprocessor: item %d has no images", index)
+ return None
+
+ img_input = item.images[0]
+ pil_img = PILImage.open(io.BytesIO(media_bytes(img_input, kind="image")))
+ original_size = (pil_img.width, pil_img.height)
+
+ if pil_img.mode != "RGB":
+ pil_img = pil_img.convert("RGB")
+
+ inputs = self._processor(
+ text=text,
+ images=[pil_img],
+ return_tensors="pt",
+ )
+
+ payload = MinerUVLPayload(
+ pixel_values=inputs["pixel_values"],
+ input_ids=inputs["input_ids"].squeeze(0),
+ attention_mask=inputs["attention_mask"].squeeze(0),
+ image_grid_thw=inputs["image_grid_thw"],
+ original_size=original_size,
+ )
+ return PreparedItem(payload=payload, cost=1, original_index=index)
+
+ def prepare(
+ self,
+ items: list[Item],
+ *,
+ config: ModelConfig,
+ is_query: bool = False,
+ instruction: str | None = None,
+ task: str | None = None,
+ ) -> PreparedBatch[MinerUVLPayload]:
+ prompt_text = self._task_prompt(task, instruction)
+ messages = self._build_messages(prompt_text)
+ text = self._processor.apply_chat_template(
+ messages,
+ add_generation_prompt=True,
+ tokenize=False,
+ )
+
+ if len(items) == 1:
+ result = self._process_single_image(items[0], 0, text)
+ if result is None:
+ return PreparedBatch(items=[], total_cost=0, modality="image")
+ return PreparedBatch(items=[result], total_cost=1, modality="image")
+
+ executor = get_image_executor()
+ futures = [executor.submit(self._process_single_image, item, i, text) for i, item in enumerate(items)]
+
+ prepared_items: list[PreparedItem[MinerUVLPayload]] = []
+ for future in futures:
+ result = future.result()
+ if result is not None:
+ prepared_items.append(result)
+
+ return PreparedBatch(
+ items=prepared_items,
+ total_cost=len(prepared_items),
+ modality="image",
+ )
+
+ def collate(
+ self,
+ prepared: list[PreparedItem[MinerUVLPayload]],
+ *,
+ device: str,
+ dtype: Any = None,
+ ) -> dict[str, Any]:
+ """Collate items into batched tensors.
+
+ MinerU2.5-Pro processes one image at a time (variable-size inputs via
+ Qwen2-VL native-resolution patch packing); batching multiple images
+ requires careful grid handling that the model's own path does not
+ expose. This collate emits the first item's tensors, matching
+ PaddleOCR-VL / LightOnOCR.
+ """
+ import torch
+
+ if not prepared:
+ return {
+ "pixel_values": torch.tensor([]),
+ "input_ids": torch.tensor([]),
+ "attention_mask": torch.tensor([]),
+ "image_grid_thw": torch.tensor([]),
+ }
+
+ p = prepared[0]
+ pixel_values = p.payload.pixel_values
+ if dtype is not None:
+ pixel_values = pixel_values.to(dtype=dtype)
+
+ return {
+ "pixel_values": pixel_values.to(device),
+ "input_ids": p.payload.input_ids.unsqueeze(0).to(device),
+ "attention_mask": p.payload.attention_mask.unsqueeze(0).to(device),
+ "image_grid_thw": p.payload.image_grid_thw.to(device),
+ }
diff --git a/packages/sie_server/src/sie_server/core/preprocessor_registry.py b/packages/sie_server/src/sie_server/core/preprocessor_registry.py
index ae7d651ce..b5ddae534 100644
--- a/packages/sie_server/src/sie_server/core/preprocessor_registry.py
+++ b/packages/sie_server/src/sie_server/core/preprocessor_registry.py
@@ -4,7 +4,8 @@ This module manages preprocessors for all loaded models and provides
async preprocessing that runs in a thread pool to avoid blocking
the event loop.
-See roadmap.md Project 10.4 Phase 2 for design details.
+Adapters provide preprocessors at model-load time; this registry dispatches
+items to the registered modality implementation.
"""
from __future__ import annotations
diff --git a/packages/sie_server/src/sie_server/core/readiness.py b/packages/sie_server/src/sie_server/core/readiness.py
index 6ba6b5326..f937cf988 100644
--- a/packages/sie_server/src/sie_server/core/readiness.py
+++ b/packages/sie_server/src/sie_server/core/readiness.py
@@ -7,29 +7,41 @@ This module provides a single source of truth for worker readiness, used by:
The gateway only routes requests to workers that report ready=True.
This prevents routing to workers that are still starting up.
+The worker's queue path is driven by the worker-sidecar over UDS IPC.
+Startup readiness and normal unloading flow through
+``mark_ready``/``mark_not_ready``. Sidecar deployments can additionally
+gate readiness on the sidecar's heartbeat being fresh via
+``register_liveness_probe``; direct HTTP/local deployments can leave that
+probe unset.
+
Usage:
from sie_server.core.readiness import is_ready, mark_ready, mark_not_ready
- # In lifespan:
mark_ready() # After startup completes
yield
mark_not_ready() # During shutdown
"""
import logging
+from collections.abc import Callable
logger = logging.getLogger(__name__)
_ready = False
+_liveness_probe: Callable[[], bool] | None = None
def is_ready() -> bool:
"""Check if worker is ready to accept traffic.
Returns:
- True if the worker has completed startup and can handle requests.
+ True if the worker has completed startup, has not shut down, and any
+ registered external liveness probe (e.g., worker-sidecar heartbeat)
+ still reports healthy.
"""
- return _ready
+ if not _ready:
+ return False
+ return not (_liveness_probe is not None and not _liveness_probe())
def mark_ready() -> None:
@@ -50,3 +62,14 @@ def mark_not_ready() -> None:
global _ready
logger.info("Worker shutting down, no longer accepting traffic")
_ready = False
+
+
+def register_liveness_probe(probe: Callable[[], bool] | None) -> None:
+ """Register (or clear) an external liveness check.
+
+ When set, ``is_ready()`` returns ``False`` whenever ``probe()`` returns
+ ``False``, even if the worker is otherwise marked ready. Passing ``None``
+ clears the probe — used during shutdown to avoid dangling references.
+ """
+ global _liveness_probe
+ _liveness_probe = probe
diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.py
index af4b14aa1..7af06fa9d 100644
--- a/packages/sie_server/src/sie_server/core/registry.py
+++ b/packages/sie_server/src/sie_server/core/registry.py
@@ -186,6 +186,14 @@ class ModelRegistry:
integral_gain=ab.integral_gain,
window_size=ab.window_size,
update_interval=ab.update_interval,
+ # Starvation detector lives on the runtime params struct so
+ # it is configurable per-deployment without touching code.
+ # Engine-level defaults (see AdaptiveBatchingConfig) are
+ # tuned for production; tests override via direct
+ # AdaptiveBatchingParams construction.
+ starvation_recovery_enabled=ab.starvation_recovery_enabled,
+ starvation_window=ab.starvation_window,
+ starvation_batch_size=ab.starvation_batch_size,
)
# Build OOM recovery config from the engine config (if present).
@@ -201,6 +209,8 @@ class ModelRegistry:
attention_backend=engine_config.attention_backend if engine_config else "auto",
max_batch_requests=engine_config.max_batch_requests if engine_config else None,
max_batch_wait_ms=engine_config.max_batch_wait_ms if engine_config else None,
+ coalesce_ms=engine_config.coalesce_ms if engine_config else None,
+ coalesce_ratio=engine_config.coalesce_ratio if engine_config else None,
max_queue_size=engine_config.max_concurrent_requests if engine_config else None,
instrumentation=engine_config.instrumentation if engine_config else False,
max_loras_per_model=engine_config.max_loras_per_model if engine_config else DEFAULT_MAX_LORAS,
@@ -1599,8 +1609,6 @@ class ModelRegistry:
model: Model name.
lora: LoRA adapter name/path.
"""
- import asyncio
-
loop = asyncio.get_running_loop()
try:
@@ -1648,8 +1656,6 @@ class ModelRegistry:
model: Model name.
lora: LoRA adapter name/path.
"""
- import asyncio
-
loop = asyncio.get_running_loop()
try:
diff --git a/packages/sie_server/src/sie_server/core/timing.py b/packages/sie_server/src/sie_server/core/timing.py
index dd5c9ce13..36a896413 100644
--- a/packages/sie_server/src/sie_server/core/timing.py
+++ b/packages/sie_server/src/sie_server/core/timing.py
@@ -1,6 +1,6 @@
"""Request timing utilities.
-Tracks latency breakdown for encode requests per DESIGN.md Section 5.7.
+Tracks latency breakdown for encode requests.
Timing headers:
- X-Queue-Time: Time waiting in queue (ms)
diff --git a/packages/sie_server/src/sie_server/core/tokenizer.py b/packages/sie_server/src/sie_server/core/tokenizer.py
index 163e10512..73fd2adfe 100644
--- a/packages/sie_server/src/sie_server/core/tokenizer.py
+++ b/packages/sie_server/src/sie_server/core/tokenizer.py
@@ -1,10 +1,4 @@
-"""Tokenization utilities.
-
-Contains load_tokenizer() for loading HuggingFace tokenizers.
-For preprocessing types, see the prepared module (PreparedItem, TextPayload, etc.).
-
-See DESIGN.md Section 5.2.
-"""
+"""Tokenization utilities."""
from __future__ import annotations
@@ -24,17 +18,7 @@ def load_tokenizer(
*,
trust_remote_code: bool = False,
) -> PreTrainedTokenizer | PreTrainedTokenizerFast:
- """Load a tokenizer from a model path or HuggingFace ID.
-
- Attempts to load the fast (Rust) tokenizer first, falls back to Python.
-
- Args:
- model_path: Local path or HuggingFace model ID.
- trust_remote_code: Whether to trust remote code in the tokenizer.
-
- Returns:
- Loaded tokenizer instance.
- """
+ """Load a HuggingFace tokenizer from a local path or model id."""
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
diff --git a/packages/sie_server/src/sie_server/core/worker/__init__.py b/packages/sie_server/src/sie_server/core/worker/__init__.py
index c03670a6a..55f7475d6 100644
--- a/packages/sie_server/src/sie_server/core/worker/__init__.py
+++ b/packages/sie_server/src/sie_server/core/worker/__init__.py
@@ -10,8 +10,6 @@ Architecture:
- ModelWorker: Manages lifecycle, batching, FCFS scheduling, stats
- OperationHandler: Abstract interface for operation-specific logic
- EncodeHandler, ExtractHandler, ScoreHandler: Concrete implementations
-
-See DESIGN.md Section 5.3.
"""
from sie_server.core.worker.handlers import (
diff --git a/packages/sie_server/src/sie_server/core/worker/model_worker.py b/packages/sie_server/src/sie_server/core/worker/model_worker.py
index 3ee02867f..d54cf7a5a 100644
--- a/packages/sie_server/src/sie_server/core/worker/model_worker.py
+++ b/packages/sie_server/src/sie_server/core/worker/model_worker.py
@@ -6,8 +6,6 @@ The ModelWorker manages a single model's inference pipeline:
3. Runs inference on batches via operation handlers
4. Fans out results to waiting futures
-See DESIGN.md Section 5.3.
-
Architecture:
- ModelWorker: Manages lifecycle, batching, FCFS scheduling, stats
- OperationHandler: Abstract interface for operation-specific logic
@@ -45,7 +43,7 @@ from sie_server.core.worker.types import (
)
try:
- from prometheus_client import Gauge, Histogram
+ from prometheus_client import Counter, Gauge, Histogram
GPU_BATCH_ITEMS = Histogram(
"sie_gpu_batch_items",
@@ -90,6 +88,40 @@ try:
["model"],
buckets=[0.01, 0.05, 0.1, 0.2, 0.3, 0.5, 0.7, 0.9, 1.0],
)
+ ADAPTIVE_STARVATION_STREAK = Gauge(
+ "sie_adaptive_starvation_streak",
+ "Current consecutive-tiny-batch streak tracked by the adaptive controller",
+ ["model"],
+ )
+ ADAPTIVE_STARVATION_RESETS = Counter(
+ "sie_adaptive_starvation_resets_total",
+ "Total number of starvation-triggered controller resets",
+ ["model"],
+ )
+ # Queue-depth visibility for the Python-side adaptive batcher.
+ #
+ # Counterpart to the Rust-side `sie_worker_ipc_mux_inflight` gauge:
+ # together they bracket the path between Rust dispatch and the GPU.
+ # A regression where Rust caching/multiplexing removes its own
+ # back-pressure shows up here as a wider distribution of items
+ # waiting at dispatch time, even though the GPU sees the same
+ # batch size and total throughput. This is the metric to watch
+ # when tuning `SIE_IPC_MUX_MAX_INFLIGHT_PER_POD` — a healthy cap
+ # keeps the histogram concentrated near 0–1 batches deep.
+ MODEL_LOOP_PENDING_AT_DISPATCH = Histogram(
+ "sie_model_loop_pending_at_dispatch",
+ "Total items pending across all LoRA batchers at the moment a "
+ "batch is dispatched to the model adapter (i.e. queue depth "
+ "observed by the model loop, NOT including the items being "
+ "dispatched).",
+ ["model"],
+ buckets=[0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024],
+ )
+ MODEL_LOOP_PENDING_GAUGE = Gauge(
+ "sie_model_loop_pending",
+ "Current items pending across all LoRA batchers; sampled at every model-loop iteration.",
+ ["model"],
+ )
_HAS_BATCH_METRICS = True
except ImportError:
_HAS_BATCH_METRICS = False
@@ -158,6 +190,23 @@ class ModelWorker:
self._postprocessor_registry = postprocessor_registry
self._registry_callbacks = registry_callbacks
+ # Pass-through mode: skip BatchFormer / FCFS / adaptive batching;
+ # every ``submit*`` becomes one GPU forward pass. Env var wins so we
+ # can flip it without redeploying with a new WorkerConfig. See the
+ # comment on ``WorkerConfig.passthrough_mode`` for the rationale and
+ # the cluster-wide alignment with the worker-sidecar's owner role.
+ env_passthrough = os.environ.get("SIE_WORKER_PASSTHROUGH", "").lower() in ("1", "true", "yes")
+ self._passthrough_mode = self._config.passthrough_mode or env_passthrough
+ # Async lock so concurrent passthrough submits serialise across the
+ # ``set_active_lora -> _process_batch`` pair. The single-thread
+ # inference executor would already serialise the GPU calls, but the
+ # adapter's active-LoRA state lives on the asyncio thread and would
+ # race otherwise (lora_A set, lora_B set, A's inference runs with B
+ # active). Held only for the synchronous ``set_active_lora`` and the
+ # ``await _process_batch`` body — the executor handoff itself does
+ # NOT extend this lock further than needed.
+ self._passthrough_lock = asyncio.Lock()
+
# Initialize operation handlers (dependency injection point)
if handlers is not None:
self._handlers: dict[str, OperationHandler[Any]] = handlers
@@ -173,12 +222,19 @@ class ModelWorker:
max_batch_tokens=self._config.max_batch_tokens,
max_batch_requests=self._config.max_batch_requests,
max_batch_wait_ms=self._config.max_batch_wait_ms,
+ coalesce_ms=self._config.coalesce_ms,
+ coalesce_ratio=self._config.coalesce_ratio,
)
# Per-LoRA batchers: None = base model, "lora-name" = specific LoRA
- # Each LoRA gets its own batcher for FCFS fairness
+ # Each LoRA gets its own batcher for FCFS fairness. In passthrough
+ # mode the dict stays empty — the dispatcher path bypasses these
+ # entirely and the GPU batch is the IPC frame as it arrived. We
+ # still keep the field for shape-compat with code that reads
+ # ``self._batchers`` (e.g. shutdown, instrumentation).
self._batchers: dict[str | None, BatchFormer[HasCost, RequestMetadata]] = {}
- self._batchers[None] = BatchFormer(self._batch_config) # Base model batcher
+ if not self._passthrough_mode:
+ self._batchers[None] = BatchFormer(self._batch_config) # Base model batcher
# Thread pool for running inference (doesn't block event loop)
self._inference_executor = ThreadPoolExecutor(
@@ -186,13 +242,34 @@ class ModelWorker:
thread_name_prefix="inference",
)
- # Adaptive batching controller (optional, off by default)
+ # Adaptive batching controller (optional, off by default).
+ # Forced off in passthrough mode: there's no ``_process_loop`` to
+ # observe batch fill / latency feedback, and the sidecar runs its
+ # own adaptive batcher one IPC hop upstream. Competing controllers
+ # can make batch-size feedback oscillate.
ab = self._config.adaptive_batching
- if ab.enabled:
+ if ab.enabled and not self._passthrough_mode:
self._latency_tracker: LatencyTracker | None = LatencyTracker(
window_size=ab.window_size,
)
self._efficiency_tracker: BatchEfficiencyTracker | None = BatchEfficiencyTracker()
+ # min_batch_cost is a *floor* on how small the cost knob can get,
+ # not a ceiling. The old value of min(256, max_batch_tokens) was
+ # effectively always 256, which lets the PI loop shrink each
+ # batch down to a single item whenever p50 stays above target —
+ # and under scale-out load (queue latency >> target) p50 *always*
+ # stays above target, so cost collapses to 256 and the GPU runs
+ # 1-item forwards at ~30k tok/s/pod. Instead, anchor the floor
+ # to a quarter of max_batch_tokens so even a fully-collapsed
+ # knob still packs ~10 items per forward on the default gte
+ # (16384 / 4 = 4096 tokens ≈ 10 items of ~400 tokens each).
+ # For tiny max_batch_tokens (<1024), keep the legacy 256 floor
+ # so adapters with genuinely small budgets aren't forced above
+ # their configured ceiling. See
+ # packages/sie_server_sidecar/docs/architecture-guide.md for
+ # the related queue-mode regression guard.
+ cost_floor = max(256, self._config.max_batch_tokens // 4)
+ cost_floor = min(cost_floor, self._config.max_batch_tokens)
self._adaptive_controller: AdaptiveBatchController | None = AdaptiveBatchController(
target_p50_ms=ab.target_p50_ms,
calibration_multiplier=ab.calibration_multiplier,
@@ -200,14 +277,15 @@ class ModelWorker:
max_target_p50_ms=ab.max_target_p50_ms,
min_wait_ms=ab.min_wait_ms,
max_wait_ms=ab.max_wait_ms,
- min_batch_cost=min(256, self._config.max_batch_tokens),
- max_batch_cost=max(
- min(256, self._config.max_batch_tokens), self._config.max_batch_tokens * 4
- ), # allow up to 4x growth
+ min_batch_cost=cost_floor,
+ max_batch_cost=max(cost_floor, self._config.max_batch_tokens * 4),
gain=ab.gain,
integral_gain=ab.integral_gain,
cost_gain=ab.gain * 0.5, # cost knob is more conservative
update_interval=ab.update_interval,
+ starvation_recovery_enabled=ab.starvation_recovery_enabled,
+ starvation_window=ab.starvation_window,
+ starvation_batch_size=ab.starvation_batch_size,
_current_wait_ms=self._config.max_batch_wait_ms,
_current_batch_cost=self._config.max_batch_tokens,
)
@@ -294,6 +372,18 @@ class ModelWorker:
logger.info("ModelWorker instrumentation enabled")
self._running = True
+ # Passthrough mode owns its own dispatch path inside ``submit*`` —
+ # no background loop, no FCFS scheduling, no adaptive controller.
+ # We still flip ``_running`` so the existing ``stop()`` path works
+ # and ``_check_queue_capacity`` accepts work.
+ if self._passthrough_mode:
+ logger.info(
+ "ModelWorker started (passthrough mode: no internal batcher / "
+ "no _process_loop / no adaptive controller — every submit() is "
+ "one GPU forward pass)"
+ )
+ return
+
self._process_task = asyncio.create_task(
self._process_loop(),
name="model-worker-process",
@@ -533,6 +623,12 @@ class ModelWorker:
if not self._running:
msg = "ModelWorker is not running"
raise RuntimeError(msg)
+ # In passthrough mode there is no queue to fill — every submit
+ # runs synchronously to GPU under the passthrough lock, so back-
+ # pressure happens at the lock acquisition rather than via a
+ # depth check. The worker-sidecar enforces the per-pod inflight cap.
+ if self._passthrough_mode:
+ return
max_queue = self._config.max_queue_size
if max_queue > 0:
current_pending = self.pending_count
@@ -575,10 +671,54 @@ class ModelWorker:
Returns:
The future from metadata that will resolve to WorkerResult.
"""
+ if self._passthrough_mode:
+ return await self._submit_passthrough(prepared_items, metadata, lora)
+
batcher = self._get_batcher(lora)
await batcher.submit_many([(item, metadata) for item in prepared_items])
return metadata.future
+ async def _submit_passthrough(
+ self,
+ prepared_items: Sequence[HasCost],
+ metadata: RequestMetadata,
+ lora: str | None,
+ ) -> asyncio.Future[WorkerResult]:
+ """Run the IPC frame as exactly one GPU forward pass.
+
+ Builds a synthetic ``FormattedBatch`` directly from ``prepared_items``
+ — bypassing the BatchFormer / FCFS / adaptive controller entirely
+ — and dispatches it through the existing ``_process_batch`` path so
+ operation handlers, postprocessors and timing instrumentation all
+ keep working unchanged.
+
+ Concurrency: held under ``_passthrough_lock`` so concurrent submits
+ to different LoRAs cannot interleave the (``set_active_lora`` →
+ ``_process_batch``) pair, which otherwise races on the adapter's
+ active-LoRA state. The single-thread inference executor would
+ already serialise the GPU work — the lock specifically protects
+ the LoRA-set-then-forward atomicity.
+ """
+ # Cost is a sequence-of-protocol read, no I/O — safe outside the lock.
+ items_list = list(prepared_items)
+ total_cost = sum(item.cost for item in items_list)
+ # ``_process_batch`` keys metadata identity by ``id(metadata)`` so a
+ # single shared metadata reference (one per request, N items) is
+ # fine; the existing ``_complete_requests`` only fires the future
+ # once all items have results regardless of how many slots share it.
+ metadata_per_item: list[RequestMetadata] = [metadata] * len(items_list)
+ synthetic_batch: FormattedBatch[HasCost, RequestMetadata] = FormattedBatch(
+ items=items_list,
+ metadata=metadata_per_item,
+ total_cost=total_cost,
+ )
+
+ async with self._passthrough_lock:
+ self._adapter.set_active_lora(lora)
+ await self._process_batch(synthetic_batch)
+
+ return metadata.future
+
# =========================================================================
# Batch Processing
# =========================================================================
@@ -658,6 +798,16 @@ class ModelWorker:
batch_wait_ms = (time.monotonic() - batch_wait_start) * 1000
+ # Queue-depth observation. Captured AFTER the batch is
+ # pulled so it reflects items still waiting once we
+ # commit to dispatching this batch — that's the figure
+ # we want when reasoning about Rust-side back-pressure.
+ if _HAS_BATCH_METRICS:
+ pending_after_pull = sum(b.pending_count for b in self._batchers.values())
+ _label_name = self._model_name or "unknown"
+ MODEL_LOOP_PENDING_AT_DISPATCH.labels(model=_label_name).observe(pending_after_pull)
+ MODEL_LOOP_PENDING_GAUGE.labels(model=_label_name).set(pending_after_pull)
+
# Set active LoRA before processing batch
# This allows adapters to switch to the correct LoRA adapter
self._adapter.set_active_lora(active_lora)
@@ -730,7 +880,8 @@ class ModelWorker:
if self._adaptive_controller is not None and self._latency_tracker is not None:
observed_p50 = self._latency_tracker.p50()
fill_ratio = self._efficiency_tracker.mean_fill_ratio() if self._efficiency_tracker else None
- new_wait, new_cost = self._adaptive_controller.step(observed_p50, fill_ratio)
+ prev_resets = self._adaptive_controller.starvation_resets
+ new_wait, new_cost = self._adaptive_controller.step(observed_p50, fill_ratio, batch_size=batch.size)
self._batch_config.max_batch_wait_ms = new_wait
self._batch_config.max_batch_cost = new_cost
@@ -745,6 +896,10 @@ class ModelWorker:
ADAPTIVE_HEADROOM.labels(model=_label).set(target - observed_p50)
if fill_ratio is not None:
ADAPTIVE_FILL_RATIO.labels(model=_label).set(fill_ratio)
+ ADAPTIVE_STARVATION_STREAK.labels(model=_label).set(self._adaptive_controller.starvation_streak)
+ reset_delta = self._adaptive_controller.starvation_resets - prev_resets
+ if reset_delta > 0:
+ ADAPTIVE_STARVATION_RESETS.labels(model=_label).inc(reset_delta)
# Log every 10 batches at INFO level for visibility
if self._stats.batches_processed % 10 == 0:
diff --git a/packages/sie_server/src/sie_server/core/worker/types.py b/packages/sie_server/src/sie_server/core/worker/types.py
index e5a500980..61a0ecead 100644
--- a/packages/sie_server/src/sie_server/core/worker/types.py
+++ b/packages/sie_server/src/sie_server/core/worker/types.py
@@ -98,12 +98,37 @@ class AdaptiveBatchingParams:
calibration_multiplier: float = 1.5
min_target_p50_ms: float = 5.0
max_target_p50_ms: float = 500.0
- min_wait_ms: float = 1.0
+ # min_wait_ms is the floor the PI controller can shrink the first-request
+ # timeout to. It is *not* a mandatory wait — under load the batcher fills
+ # (or the coalesce window fires) well before this timeout trips, so
+ # raising it has no latency cost in steady state. The floor exists
+ # purely to keep the batcher from collapsing to a "flush on every
+ # submit" mode under oscillating headroom, which would shred GPU
+ # batch sizes from 64 down to single-digits.
+ min_wait_ms: float = 15.0
max_wait_ms: float = 50.0
gain: float = 0.3
integral_gain: float = 0.05
window_size: int = 200
update_interval: int = 10
+ # -- Starvation detection / deadlock recovery ----------------------------
+ # The PI loop can deadlock in a "batch-of-1" attractor: once observed p50
+ # exceeds the auto-calibrated target, the controller shrinks wait to the
+ # floor and cost to the floor, which collapses GPU batches to 1 item,
+ # which raises p50 further, which keeps the controller pinned at the
+ # floor. Headroom stays negative indefinitely and there is no recovery
+ # path. These knobs arm a self-healing escape hatch. Set
+ # ``starvation_recovery_enabled=False`` to disable (e.g. for synthetic
+ # tests that want bare PI behaviour).
+ starvation_recovery_enabled: bool = True
+ # How many consecutive batches of ``size <= starvation_batch_size`` at
+ # the floor before declaring deadlock. Must be large enough to absorb
+ # genuine idle-tail batches where the next burst's first batch is
+ # naturally tiny, small enough to recover within a few seconds of load.
+ starvation_window: int = 20
+ # Treat any batch with ``size <= this`` as contributing to the starvation
+ # counter. 1 by default — only "forward pass of a single item" counts.
+ starvation_batch_size: int = 1
@dataclass
@@ -112,13 +137,33 @@ class WorkerConfig:
max_batch_tokens: int = 16384
max_batch_requests: int = 256
- max_batch_wait_ms: float = 10.0
+ max_batch_wait_ms: float = 15.0
+ # Coalescing window: yield the current batch if no new items have been
+ # submitted within this ceiling (capped by ``coalesce_ratio *
+ # max_batch_wait_ms``). The default targets typical IPC burst jitter
+ # so a worker-sidecar batch of ~64 items lands in a single GPU forward
+ # instead of being shredded into several half-full ones.
+ coalesce_ms: float = 15.0
+ coalesce_ratio: float = 0.5
max_queue_size: int = 1000 # Maximum pending items in queue (0 = unlimited)
instrumentation: bool = False
adaptive_batching: AdaptiveBatchingParams = field(default_factory=AdaptiveBatchingParams)
# Reactive OOM recovery applied inside `_process_batch`. When disabled,
# OOM exceptions propagate as before (legacy behaviour).
oom_recovery: OomRecoveryConfig = field(default_factory=OomRecoveryConfig)
+ # When ``True`` the ModelWorker bypasses its internal BatchFormer /
+ # per-LoRA queues / adaptive controller / FCFS process loop, and instead
+ # treats every ``submit*`` call as a fully-formed GPU batch — exactly the
+ # frame that arrived over IPC from the worker-sidecar. Used when the
+ # sidecar already owns batch formation
+ # (its own adaptive batcher) and re-running the batcher here only adds
+ # queue depth and competing controllers (the "dual batching" pathology).
+ # The Python tokenizer / templating / output framing all stay alive as
+ # fallback for items that arrive without ``prepared_tokens``.
+ #
+ # The env var ``SIE_WORKER_PASSTHROUGH=1`` overrides this at construction
+ # time so we can A/B without redeploying with a different config.
+ passthrough_mode: bool = False
@dataclass
diff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.py
new file mode 100644
index 000000000..2390cab23
--- /dev/null
+++ b/packages/sie_server/src/sie_server/ipc_server.py
@@ -0,0 +1,679 @@
+from __future__ import annotations
+
+import asyncio
+import contextvars
+import logging
+import os
+import struct
+import time
+from pathlib import Path
+from types import TracebackType
+from typing import Any, Self
+
+import msgpack
+
+from sie_server.adapter_call_loop import handle_run_batch
+from sie_server.ipc_types import (
+ IPC_VERSION,
+ METHOD_APPLY_MODEL_CONFIG,
+ METHOD_DRAIN,
+ METHOD_ENSURE_MODEL_READY,
+ METHOD_PING,
+ METHOD_PROCESS_ENCODE_BATCH,
+ METHOD_PROCESS_EXTRACT_BATCH,
+ METHOD_PROCESS_GENERATE,
+ METHOD_PROCESS_SCORE_BATCH,
+ METHOD_RUN_BATCH,
+ METHOD_SIGNAL_GENERATE_CANCEL,
+ METHOD_WORKER_CAPABILITIES,
+ ApplyModelConfigRequest,
+ ApplyModelConfigResponse,
+ BatchOutcome,
+ DrainResponse,
+ EnsureModelReadyRequest,
+ EnsureModelReadyResponse,
+ GenerateEvent,
+ PingRequest,
+ PingResponse,
+ ProcessEncodeBatchRequest,
+ ProcessExtractBatchRequest,
+ ProcessGenerateRequest,
+ ProcessScoreBatchRequest,
+ ResponseEnvelope,
+ RunBatchRequest,
+ SignalGenerateCancelRequest,
+ SignalGenerateCancelResponse,
+ WorkerCapabilitiesRequest,
+ WorkerCapabilitiesResponse,
+)
+from sie_server.processors.admission import resolve_admission_enabled
+from sie_server.queue_executor import QueueExecutor
+
+logger = logging.getLogger(__name__)
+
+
+# Frame layout: [4-byte big-endian unsigned length][msgpack body]
+_LEN_STRUCT = struct.Struct("!I")
+_LEN_BYTES = _LEN_STRUCT.size
+
+# Upper bound on a single request/response frame body. 32 MiB is enough for
+# any decoded WorkItem batch we would send in-band — large payloads arrive
+# via the payload store, not via IPC.
+_MAX_FRAME_BYTES = 32 * 1024 * 1024
+
+_GENERATE_SINK: contextvars.ContextVar[_IpcGenerateSink | None] = contextvars.ContextVar(
+ "sie_generate_ipc_sink",
+ default=None,
+)
+
+
+class IpcServerError(Exception):
+ """Raised for protocol-level IPC failures (framing, encoding)."""
+
+
+class _IpcGenerateSink:
+ """Serializes generation events back to the Rust sidecar over one IPC stream."""
+
+ def __init__(self, server: IpcServer, writer: asyncio.StreamWriter, request_id: str) -> None:
+ self._server = server
+ self._writer = writer
+ self._request_id = request_id
+ self._lock = asyncio.Lock()
+
+ async def send(self, event: GenerateEvent) -> None:
+ envelope = ResponseEnvelope(
+ version=IPC_VERSION,
+ request_id=self._request_id,
+ ok=True,
+ body=_to_builtins(event),
+ )
+ payload = msgpack.packb(_envelope_to_dict(envelope), use_bin_type=True)
+ async with self._lock:
+ await self._server._write_frame(self._writer, payload)
+
+ async def publish(self, reply_subject: str, payload: bytes) -> None:
+ await self.send(
+ GenerateEvent(
+ kind="publish",
+ reply_subject=reply_subject,
+ payload=payload,
+ )
+ )
+
+
+class _IpcGenerateNatsShim:
+ """NATS-like publisher used by ``StreamingProcessor`` in sidecar mode.
+
+ The sidecar owns the real NATS client. Python still owns generation
+ adapter execution and chunk encoding, so ``publish`` emits a typed IPC
+ event and the Rust sidecar publishes the bytes to the gateway inbox.
+ """
+
+ async def publish(self, reply_subject: str, payload: bytes) -> None:
+ sink = _GENERATE_SINK.get()
+ if sink is None:
+ raise RuntimeError("ProcessGenerate publish called without an active IPC sink")
+ await sink.publish(reply_subject, payload)
+
+
+class _IpcGenerateMessage:
+ """Minimal JetStream-message facade for ``StreamingProcessor``.
+
+ Python decides *what* settlement it wants; the Rust sidecar performs
+ the actual JetStream ACK/NAK/progress on the consumed message.
+ """
+
+ def __init__(self, sink: _IpcGenerateSink, data: bytes) -> None:
+ self.data = data
+ self._sink = sink
+
+ async def ack(self) -> None:
+ await self._sink.send(GenerateEvent(kind="ack"))
+
+ async def nak(self, delay: float | None = None) -> None:
+ delay_ms: int | None = None
+ if delay is not None:
+ delay_ms = max(0, int(delay * 1000))
+ await self._sink.send(GenerateEvent(kind="nak", delay_ms=delay_ms))
+
+ async def in_progress(self) -> None:
+ await self._sink.send(GenerateEvent(kind="in_progress"))
+
+
+class IpcServer:
+ """UDS msgpack RPC server fronting the QueueExecutor.
+
+ Framing:
+ [4-byte BE length][msgpack RequestEnvelope] -> [4-byte BE length][msgpack ResponseEnvelope]
+
+ Lifecycle:
+ async with IpcServer(path, executor) as server:
+ await server.wait_closed()
+
+ At most one Rust client is expected per worker pod, but the server accepts
+ multiple concurrent connections so that restarting the worker-sidecar does
+ not leave stale connections.
+ """
+
+ def __init__(
+ self,
+ socket_path: str | os.PathLike[str],
+ executor: QueueExecutor,
+ *,
+ worker_id: str,
+ stale_after_ms: float = 10_000.0,
+ bundle_id: str | None = None,
+ ) -> None:
+ self._socket_path = Path(socket_path)
+ self._executor = executor
+ self._worker_id = worker_id
+ self._stale_after_ms = stale_after_ms
+ self._bundle_id = bundle_id or os.environ.get("SIE_BUNDLE", "")
+
+ self._server: asyncio.AbstractServer | None = None
+ self._connections: set[asyncio.Task[None]] = set()
+ self._inflight: set[asyncio.Task[None]] = set()
+
+ self._last_ping_monotonic: float | None = None
+ self._drain_event = asyncio.Event()
+ # Populated by the Rust caller on Drain via `deadline_ms`. Left as
+ # `None` until then, in which case `stop()` falls back to its
+ # caller-supplied default. Enforced in `stop()`.
+ self._drain_deadline_s: float | None = None
+ self._streaming_processor: Any | None = None
+ self._streaming_processor_lock = asyncio.Lock()
+ self._generation_prewarmed = False
+
+ # -- Public surface ----------------------------------------------------
+
+ @property
+ def socket_path(self) -> Path:
+ return self._socket_path
+
+ def is_heartbeat_fresh(self, *, now_monotonic: float | None = None) -> bool:
+ """Return True iff the Rust side has pinged within ``stale_after_ms``.
+
+ Used by readiness: a stale heartbeat means the worker-sidecar is dead
+ or wedged, and the pod should fail ``/readyz`` so Kubernetes reroutes.
+ """
+ if self._last_ping_monotonic is None:
+ return False
+ if now_monotonic is None:
+ now_monotonic = time.monotonic()
+ elapsed_ms = (now_monotonic - self._last_ping_monotonic) * 1000
+ return elapsed_ms <= self._stale_after_ms
+
+ @property
+ def last_ping_monotonic(self) -> float | None:
+ return self._last_ping_monotonic
+
+ async def start(self) -> None:
+ """Bind the UDS and begin serving. Unlinks any stale socket file first."""
+ if self._socket_path.exists():
+ try:
+ self._socket_path.unlink()
+ except OSError:
+ logger.warning("Could not unlink existing socket at %s", self._socket_path)
+
+ self._socket_path.parent.mkdir(parents=True, exist_ok=True)
+ self._server = await asyncio.start_unix_server(
+ self._handle_connection,
+ path=str(self._socket_path),
+ )
+ try:
+ self._socket_path.chmod(0o600)
+ except OSError:
+ logger.debug("Could not chmod socket at %s", self._socket_path)
+ logger.info("IPC server listening on %s", self._socket_path)
+
+ async def stop(self, *, drain_timeout_s: float = 25.0) -> None:
+ """Stop accepting new connections and drain in-flight requests."""
+ self._drain_event.set()
+
+ if self._server is not None:
+ self._server.close()
+ try:
+ await asyncio.wait_for(self._server.wait_closed(), timeout=5.0)
+ except TimeoutError:
+ logger.warning("IPC server wait_closed timed out")
+
+ if self._inflight:
+ # Prefer the Rust-supplied deadline when it is tighter than the
+ # caller's default — the worker-sidecar sizes it from its own
+ # shutdown budget so exceeding it guarantees a SIGKILL mid-IPC.
+ effective_timeout = drain_timeout_s
+ if self._drain_deadline_s is not None:
+ effective_timeout = min(effective_timeout, self._drain_deadline_s)
+ logger.info(
+ "IPC server draining %d in-flight requests (timeout=%.1fs)",
+ len(self._inflight),
+ effective_timeout,
+ )
+ try:
+ await asyncio.wait_for(
+ asyncio.gather(*self._inflight, return_exceptions=True),
+ timeout=effective_timeout,
+ )
+ except TimeoutError:
+ logger.warning("IPC drain timed out after %.1fs — cancelling", effective_timeout)
+ for t in self._inflight:
+ t.cancel()
+
+ for t in self._connections:
+ t.cancel()
+
+ try:
+ if self._socket_path.exists():
+ self._socket_path.unlink()
+ except OSError:
+ logger.debug("Could not unlink socket at %s on shutdown", self._socket_path)
+
+ async def __aenter__(self) -> Self:
+ await self.start()
+ return self
+
+ async def __aexit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc: BaseException | None,
+ tb: TracebackType | None,
+ ) -> None:
+ await self.stop()
+
+ # -- Connection / framing ----------------------------------------------
+
+ async def _handle_connection(
+ self,
+ reader: asyncio.StreamReader,
+ writer: asyncio.StreamWriter,
+ ) -> None:
+ task = asyncio.current_task()
+ if task is not None:
+ self._connections.add(task)
+ task.add_done_callback(self._connections.discard)
+
+ peer = writer.get_extra_info("peername") or "unknown"
+ logger.info("IPC connection accepted from %s", peer)
+
+ try:
+ while True:
+ frame = await self._read_frame(reader)
+ if frame is None:
+ return
+ await self._dispatch_frame(frame, writer)
+ except asyncio.CancelledError:
+ raise
+ except IpcServerError as e:
+ logger.warning("IPC protocol error: %s — closing connection", e)
+ except Exception:
+ logger.exception("IPC connection crashed")
+ finally:
+ try:
+ writer.close()
+ await writer.wait_closed()
+ except Exception: # noqa: BLE001
+ logger.debug("Error closing IPC writer", exc_info=True)
+
+ async def _read_frame(self, reader: asyncio.StreamReader) -> bytes | None:
+ """Read one length-prefixed frame. Returns None on clean EOF."""
+ try:
+ header = await reader.readexactly(_LEN_BYTES)
+ except asyncio.IncompleteReadError as e:
+ if not e.partial:
+ return None
+ raise IpcServerError("truncated frame header") from e
+
+ (length,) = _LEN_STRUCT.unpack(header)
+ if length == 0:
+ return b""
+ if length > _MAX_FRAME_BYTES:
+ raise IpcServerError(f"frame too large: {length} > {_MAX_FRAME_BYTES}")
+
+ try:
+ return await reader.readexactly(length)
+ except asyncio.IncompleteReadError as e:
+ raise IpcServerError("truncated frame body") from e
+
+ async def _write_frame(self, writer: asyncio.StreamWriter, payload: bytes) -> None:
+ writer.write(_LEN_STRUCT.pack(len(payload)) + payload)
+ await writer.drain()
+
+ # -- Dispatch ----------------------------------------------------------
+
+ async def _dispatch_frame(self, frame: bytes, writer: asyncio.StreamWriter) -> None:
+ try:
+ raw = msgpack.unpackb(frame, raw=False)
+ except Exception as e:
+ raise IpcServerError(f"malformed msgpack: {e}") from e
+
+ if not isinstance(raw, dict):
+ raise IpcServerError("envelope must be a map")
+
+ version = raw.get("version")
+ if version != IPC_VERSION:
+ await self._send_error(writer, raw.get("request_id", ""), f"unsupported version {version}")
+ return
+
+ method = raw.get("method")
+ request_id = raw.get("request_id", "")
+ body = raw.get("body") or {}
+ if not isinstance(method, str) or not isinstance(request_id, str) or not isinstance(body, dict):
+ await self._send_error(writer, request_id, "envelope missing fields")
+ return
+
+ # Process methods (encode/score/extract) are dispatched in background
+ # tasks so the Rust client can fire up to N in parallel if it ever
+ # does. Ping/EnsureModelReady/Drain run inline — they are cheap.
+ if method in (
+ METHOD_PROCESS_ENCODE_BATCH,
+ METHOD_PROCESS_SCORE_BATCH,
+ METHOD_PROCESS_EXTRACT_BATCH,
+ METHOD_RUN_BATCH,
+ METHOD_PROCESS_GENERATE,
+ ):
+ if self._drain_event.is_set():
+ await self._send_error(writer, request_id, "draining")
+ return
+ task = asyncio.create_task(self._run_method_task(method, request_id, body, writer))
+ self._inflight.add(task)
+ task.add_done_callback(self._inflight.discard)
+ return
+
+ await self._run_method(method, request_id, body, writer)
+
+ async def _run_method_task(
+ self,
+ method: str,
+ request_id: str,
+ body: dict[str, Any],
+ writer: asyncio.StreamWriter,
+ ) -> None:
+ try:
+ await self._run_method(method, request_id, body, writer)
+ except Exception:
+ logger.exception("IPC method %s crashed", method)
+
+ async def _run_method(
+ self,
+ method: str,
+ request_id: str,
+ body: dict[str, Any],
+ writer: asyncio.StreamWriter,
+ ) -> None:
+ import msgspec # noqa: PLC0415
+
+ try:
+ if method == METHOD_PROCESS_GENERATE:
+ await self._handle_process_generate(
+ msgspec.convert(body, ProcessGenerateRequest),
+ request_id=request_id,
+ writer=writer,
+ )
+ return
+ if method == METHOD_PING:
+ resp_body = await self._handle_ping(msgspec.convert(body, PingRequest))
+ elif method == METHOD_ENSURE_MODEL_READY:
+ resp_body = await self._handle_ensure_ready(msgspec.convert(body, EnsureModelReadyRequest))
+ elif method == METHOD_WORKER_CAPABILITIES:
+ resp_body = self._handle_worker_capabilities(msgspec.convert(body, WorkerCapabilitiesRequest))
+ elif method == METHOD_PROCESS_ENCODE_BATCH:
+ resp_body = await self._handle_process_encode(msgspec.convert(body, ProcessEncodeBatchRequest))
+ elif method == METHOD_PROCESS_SCORE_BATCH:
+ resp_body = await self._handle_process_score(msgspec.convert(body, ProcessScoreBatchRequest))
+ elif method == METHOD_PROCESS_EXTRACT_BATCH:
+ resp_body = await self._handle_process_extract(msgspec.convert(body, ProcessExtractBatchRequest))
+ elif method == METHOD_RUN_BATCH:
+ # Rust scheduler drove the batch formation; we just fan
+ # the items into the existing
+ # per-op handlers. See adapter_call_loop.py for the
+ # full fallback matrix.
+ resp_body = await self._handle_run_batch(msgspec.convert(body, RunBatchRequest))
+ elif method == METHOD_APPLY_MODEL_CONFIG:
+ resp_body = self._handle_apply_model_config(msgspec.convert(body, ApplyModelConfigRequest))
+ elif method == METHOD_SIGNAL_GENERATE_CANCEL:
+ resp_body = await self._handle_signal_generate_cancel(
+ msgspec.convert(body, SignalGenerateCancelRequest)
+ )
+ elif method == METHOD_DRAIN:
+ # The Rust caller may pass `deadline_ms` to indicate how
+ # long it is willing to wait before SIGTERM. We don't
+ # block here (that would hold the IPC response), but we
+ # record the deadline so `stop()` can cap its in-flight
+ # drain instead of using the hard-coded default.
+ #
+ # Repeated Drain calls (e.g. a retry after a transient
+ # IPC glitch) must tighten, never loosen, the effective
+ # shutdown budget — the worker-sidecar's own budget is the
+ # wall-clock floor. `bool` is also an `int`, so reject
+ # it explicitly or `deadline_ms=True` would set a
+ # 1ms timeout.
+ deadline_ms = body.get("deadline_ms")
+ if not isinstance(deadline_ms, bool) and isinstance(deadline_ms, (int, float)) and deadline_ms > 0:
+ new_deadline_s = float(deadline_ms) / 1000.0
+ if self._drain_deadline_s is None:
+ self._drain_deadline_s = new_deadline_s
+ else:
+ self._drain_deadline_s = min(self._drain_deadline_s, new_deadline_s)
+ self._drain_event.set()
+ resp_body = DrainResponse(acknowledged=True)
+ else:
+ await self._send_error(writer, request_id, f"unknown method {method}")
+ return
+ except msgspec.ValidationError as e:
+ await self._send_error(writer, request_id, f"bad body for {method}: {e}")
+ return
+ except Exception as e:
+ logger.exception("IPC method %s failed", method)
+ await self._send_error(writer, request_id, f"{type(e).__name__}: {e}")
+ return
+
+ envelope = ResponseEnvelope(
+ version=IPC_VERSION,
+ request_id=request_id,
+ ok=True,
+ body=_to_builtins(resp_body),
+ )
+ await self._write_frame(writer, msgpack.packb(_envelope_to_dict(envelope), use_bin_type=True))
+
+ # -- Handlers ----------------------------------------------------------
+
+ async def _handle_ping(self, req: PingRequest) -> PingResponse:
+ self._last_ping_monotonic = time.monotonic()
+ bundle_config_hash = ""
+ if self._bundle_id:
+ try:
+ bundle_config_hash = self._executor.compute_bundle_config_hash(self._bundle_id)
+ except Exception: # noqa: BLE001
+ logger.debug("Could not compute bundle_config_hash for ping", exc_info=True)
+ return PingResponse(
+ timestamp_ms=req.timestamp_ms,
+ worker_id=self._worker_id,
+ bundle_config_hash=bundle_config_hash,
+ )
+
+ async def _handle_ensure_ready(self, req: EnsureModelReadyRequest) -> EnsureModelReadyResponse:
+ state = await self._executor.ensure_model_ready(req.model_id)
+ # Only populate batch_budget + descriptor on the "ready" path — the
+ # worker isn't guaranteed to exist in other states and the Rust
+ # side will re-query after the NAK delay anyway.
+ batch_budget: int | None = None
+ descriptor = None
+ if state == "ready":
+ batch_budget = self._executor.get_batch_budget(req.model_id)
+ descriptor = self._executor.get_model_descriptor(req.model_id)
+ return EnsureModelReadyResponse(
+ state=state,
+ batch_budget=batch_budget,
+ descriptor=descriptor,
+ )
+
+ async def _handle_process_encode(self, req: ProcessEncodeBatchRequest) -> BatchOutcome:
+ return await self._executor.process_encode_batch(req)
+
+ async def _handle_process_score(self, req: ProcessScoreBatchRequest) -> BatchOutcome:
+ return await self._executor.process_score_batch(req)
+
+ async def _handle_process_extract(self, req: ProcessExtractBatchRequest) -> BatchOutcome:
+ return await self._executor.process_extract_batch(req)
+
+ async def _handle_run_batch(self, req: RunBatchRequest) -> BatchOutcome:
+ return await handle_run_batch(self._executor, req)
+
+ def _handle_apply_model_config(self, req: ApplyModelConfigRequest) -> ApplyModelConfigResponse:
+ return self._executor.apply_model_config(req)
+
+ def _handle_worker_capabilities(self, _req: WorkerCapabilitiesRequest) -> WorkerCapabilitiesResponse:
+ generation_models: list[str] = []
+ try:
+ configs = self._executor.registry.get_configs_snapshot()
+ except Exception: # noqa: BLE001
+ logger.debug("Could not snapshot configs for worker capabilities", exc_info=True)
+ return WorkerCapabilitiesResponse()
+
+ for model_id, config in configs.items():
+ try:
+ if config.tasks.generate is not None:
+ generation_models.append(model_id)
+ except Exception: # noqa: BLE001
+ logger.debug("Could not inspect generation task for %s", model_id, exc_info=True)
+
+ generation_models.sort()
+ return WorkerCapabilitiesResponse(
+ has_generation_models=bool(generation_models),
+ generation_models=generation_models,
+ )
+
+ async def _handle_signal_generate_cancel(
+ self,
+ req: SignalGenerateCancelRequest,
+ ) -> SignalGenerateCancelResponse:
+ if not req.request_id:
+ return SignalGenerateCancelResponse(matched=False)
+ processor = await self._get_streaming_processor()
+ return SignalGenerateCancelResponse(matched=bool(processor.signal_cancel(req.request_id)))
+
+ async def _handle_process_generate(
+ self,
+ req: ProcessGenerateRequest,
+ *,
+ request_id: str,
+ writer: asyncio.StreamWriter,
+ ) -> None:
+ processor = await self._get_streaming_processor()
+ sink = _IpcGenerateSink(self, writer, request_id)
+ msg = _IpcGenerateMessage(sink, req.work_item_msgpack)
+ token = _GENERATE_SINK.set(sink)
+ try:
+ await processor.process(msg, req.model_id)
+ await sink.send(GenerateEvent(kind="done"))
+ finally:
+ _GENERATE_SINK.reset(token)
+
+ async def _get_streaming_processor(self) -> Any:
+ if self._streaming_processor is not None:
+ return self._streaming_processor
+ async with self._streaming_processor_lock:
+ if self._streaming_processor is not None:
+ return self._streaming_processor
+
+ from sie_server.processors.streaming import StreamingProcessor # noqa: PLC0415
+
+ processor = StreamingProcessor(
+ nc=_IpcGenerateNatsShim(), # type: ignore[arg-type]
+ registry=self._executor.registry,
+ worker_id=self._worker_id,
+ admission_resolver=self._resolve_generation_admission,
+ )
+ self._streaming_processor = processor
+ await self._prewarm_generation_grammars(processor)
+ return processor
+
+ def _resolve_generation_admission(self, model_id: str) -> tuple[int | None, bool | None]:
+ try:
+ config = self._executor.registry.get_config(model_id)
+ except KeyError:
+ return None, None
+ try:
+ if config.tasks.generate is None:
+ return None, None
+ resolved = config.resolve_profile("default")
+ except Exception: # noqa: BLE001
+ logger.debug("Could not resolve generation admission config for %s", model_id, exc_info=True)
+ return None, None
+
+ budget = resolved.kv_budget_tokens
+ if not isinstance(budget, int) or budget <= 0:
+ budget = None
+ profile_admission = resolved.admission_enabled
+ if not isinstance(profile_admission, bool):
+ profile_admission = None
+ return budget, resolve_admission_enabled(profile_admission=profile_admission)
+
+ async def _prewarm_generation_grammars(self, processor: Any) -> None:
+ if self._generation_prewarmed:
+ return
+ self._generation_prewarmed = True
+ try:
+ configs = self._executor.registry.get_configs_snapshot()
+ except Exception: # noqa: BLE001
+ logger.debug("Could not snapshot configs for generation grammar prewarm", exc_info=True)
+ return
+ for model_id, config in configs.items():
+ try:
+ if config.tasks.generate is None:
+ continue
+ await processor.prewarm_grammars_for_model(model_id)
+ except Exception: # noqa: BLE001
+ logger.warning("Generation grammar prewarm failed for %s", model_id, exc_info=True)
+
+ # -- Error helper ------------------------------------------------------
+
+ async def _send_error(self, writer: asyncio.StreamWriter, request_id: str, message: str) -> None:
+ """Send a ``ok=False`` error response.
+
+ The Rust client surfaces these as ``IpcError::Server(...)`` and
+ treats them as logical (non-transport) failures, so no reconnect
+ or retry is attempted.
+ """
+ envelope = ResponseEnvelope(
+ version=IPC_VERSION,
+ request_id=request_id,
+ ok=False,
+ body=None,
+ error=message,
+ )
+ await self._write_frame(writer, msgpack.packb(_envelope_to_dict(envelope), use_bin_type=True))
+
+
+# ---------------------------------------------------------------------------
+# msgspec → plain dict helpers for msgpack wire format
+# ---------------------------------------------------------------------------
+#
+# We don't use ``msgspec.msgpack.encode`` directly because the Rust side
+# expects unadorned msgpack (no ``msgspec`` tag field on nested structs), so
+# we convert via ``msgspec.to_builtins`` first.
+
+
+def _to_builtins(obj: Any) -> Any:
+ """Convert a msgspec Struct tree to plain builtins for msgpack.
+
+ ``builtin_types=(bytes,)`` is critical: by default ``to_builtins`` base64-
+ encodes ``bytes`` to ``str`` for JSON compatibility, but our wire format
+ is msgpack (binary-native) and the Rust side must see ``result_msgpack``
+ as raw bytes, not a base64 string.
+ """
+ import msgspec # noqa: PLC0415
+
+ if obj is None:
+ return None
+ return msgspec.to_builtins(obj, builtin_types=(bytes,))
+
+
+def _envelope_to_dict(envelope: ResponseEnvelope) -> dict[str, Any]:
+ return {
+ "version": envelope.version,
+ "request_id": envelope.request_id,
+ "ok": envelope.ok,
+ "body": envelope.body,
+ "error": envelope.error,
+ }
diff --git a/packages/sie_server/src/sie_server/ipc_types.py b/packages/sie_server/src/sie_server/ipc_types.py
new file mode 100644
index 000000000..c2c33d615
--- /dev/null
+++ b/packages/sie_server/src/sie_server/ipc_types.py
@@ -0,0 +1,514 @@
+from __future__ import annotations
+
+from typing import Any, Literal
+
+import msgspec
+
+# -----------------------------------------------------------------------------
+# Envelope
+# -----------------------------------------------------------------------------
+
+IPC_VERSION: int = 1
+
+
+# Incoming request frames are parsed directly as dicts in
+# ``ipc_server._dispatch_frame`` — a typed ``RequestEnvelope`` struct
+# sits in the Rust client (see ``sie_server_sidecar::ipc_types``) but was
+# unused on the Python side. Responses DO use a typed struct, below.
+
+
+class ResponseEnvelope(msgspec.Struct, tag_field="kind", tag="response"):
+ version: int
+ request_id: str
+ ok: bool
+ body: dict[str, Any] | None = None
+ error: str | None = None
+
+
+# -----------------------------------------------------------------------------
+# Methods
+# -----------------------------------------------------------------------------
+
+METHOD_PING = "Ping"
+METHOD_ENSURE_MODEL_READY = "EnsureModelReady"
+METHOD_PROCESS_ENCODE_BATCH = "ProcessEncodeBatch"
+METHOD_PROCESS_SCORE_BATCH = "ProcessScoreBatch"
+METHOD_PROCESS_EXTRACT_BATCH = "ProcessExtractBatch"
+METHOD_PROCESS_GENERATE = "ProcessGenerate"
+METHOD_WORKER_CAPABILITIES = "WorkerCapabilities"
+METHOD_SIGNAL_GENERATE_CANCEL = "SignalGenerateCancel"
+# RPC that accepts a whole pre-formed batch (single-op, mixed items)
+# and returns ``BatchOutcome`` unchanged.
+# Coexists with the per-op Process* RPCs: the current sie-server-sidecar image
+# uses ``RunBatch`` exclusively, while the per-op RPCs stay in the wire
+# contract for focused IPC parity tests and Python-framed callers.
+# Direct ``sie-server`` HTTP execution does not use this IPC boundary.
+METHOD_RUN_BATCH = "RunBatch"
+METHOD_APPLY_MODEL_CONFIG = "ApplyModelConfig"
+METHOD_DRAIN = "Drain"
+
+
+# -----------------------------------------------------------------------------
+# Ping
+# -----------------------------------------------------------------------------
+
+
+class PingRequest(msgspec.Struct):
+ timestamp_ms: float
+
+
+class PingResponse(msgspec.Struct):
+ timestamp_ms: float
+ worker_id: str
+ bundle_config_hash: str = ""
+
+
+# -----------------------------------------------------------------------------
+# EnsureModelReady
+# -----------------------------------------------------------------------------
+
+ReadinessState = Literal["ready", "loading_started", "loading_in_progress", "retry_later"]
+
+
+class EnsureModelReadyRequest(msgspec.Struct):
+ model_id: str
+
+
+# ---------------------------------------------------------------------------
+# Model descriptor
+# ---------------------------------------------------------------------------
+#
+# Carried on ``EnsureModelReadyResponse`` to let the worker-sidecar discover
+# per-model capabilities at runtime instead of from startup env vars. Every
+# field is optional/defaulted because capabilities are model-dependent. See
+# ``packages/sie_server_sidecar/docs/architecture-guide.md`` for the contract.
+
+
+class ModelDescriptor(msgspec.Struct):
+ # Absolute path to ``tokenizer.json`` on a filesystem the sidecar can
+ # read (single-container deploy: HF cache or any sidecar-readable path;
+ # split-container: shared ``emptyDir``). ``None`` → adapter has not
+ # materialised its tokeniser to a sidecar-visible path; the sidecar
+ # skips Rust-side tokenisation for this model and Python tokenises.
+ tokenizer_path: str | None = None
+ # BLAKE3 (truncated to 32 hex chars) of the canonical tokenizer JSON.
+ # Lets the sidecar verify byte-identity with the adapter's loaded
+ # tokeniser before enabling the fast path.
+ tokenizer_id: str | None = None
+ # Per-model truncation cap. ``None`` falls back to the registry's
+ # ``DEFAULT_MAX_SEQ_LEN`` on the Rust side.
+ max_seq_len: int | None = None
+ # Output keys the adapter knows how to emit (``"dense"``, ``"sparse"``,
+ # ``"multivector"``, ``"score"``). Informational; per-request shape
+ # checks in ``queue_executor._maybe_*_raw_output`` are still the
+ # authoritative gate for whether a given request is framed in Rust.
+ output_types: list[str] = msgspec.field(default_factory=list)
+ # True iff this adapter has implemented the ``RunBatch`` IPC method.
+ # False for adapters still on the per-op ``Process*Batch`` RPCs.
+ supports_run_batch: bool = False
+ # Model-default ``query_template`` (per-adapter ctor arg, sourced
+ # from the model YAML). Used by the sidecar to apply asymmetric-
+ # retrieval prompts in Rust before tokenisation when an item
+ # arrives with ``is_query=True``, matching the precedence in
+ # ``_utils.extract_texts`` (template > bare instruction >
+ # passthrough). ``None`` keeps the legacy behaviour: Python applies
+ # templates and the sidecar either skips ``prepared_tokens`` for
+ # the item or matches the unaltered text.
+ #
+ # Per-request ``options.query_template`` still wins; this is only
+ # the model-default fallback. Wire format is the raw Python
+ # ``str.format``-style template (e.g. ``"query: {text}"`` or
+ # ``"Instruct: {instruction}\nQuery: {text}"``).
+ default_query_template: str | None = None
+ # Model-default ``doc_template`` (per-adapter ctor arg). Same wire
+ # contract as ``default_query_template`` but selected when
+ # ``is_query=False``.
+ default_doc_template: str | None = None
+
+
+class EnsureModelReadyResponse(msgspec.Struct):
+ state: ReadinessState
+ # Per-model batch budget for fair dispatch. The worker-sidecar uses this to
+ # cap how many messages for this model it dispatches to the Python side
+ # in a single batch (excess are NAK'd for redelivery, possibly to another
+ # worker).
+ #
+ # ``None`` when the model is not yet loaded (state != "ready") — the
+ # caller should NAK the group and re-query later.
+ batch_budget: int | None = None
+ # Model descriptor. Populated by Python adapters that expose a
+ # HF fast tokeniser + structured ``output_types``; ``None`` for non-text /
+ # image / audio adapters that do not emit it.
+ descriptor: ModelDescriptor | None = None
+
+
+# -----------------------------------------------------------------------------
+# ApplyModelConfig
+# -----------------------------------------------------------------------------
+
+
+class ApplyModelConfigRequest(msgspec.Struct):
+ bundle_id: str
+ model_id: str
+ epoch: int
+ bundle_config_hash: str
+ model_config: str
+ profiles_added: list[str] = msgspec.field(default_factory=list)
+
+
+class ApplyModelConfigResponse(msgspec.Struct):
+ applied: bool
+ bundle_config_hash: str
+ config_version: int = 0
+
+
+# -----------------------------------------------------------------------------
+# ProcessGenerate — streaming generation over IPC
+# -----------------------------------------------------------------------------
+
+GenerateEventKind = Literal["publish", "ack", "nak", "in_progress", "done"]
+
+
+class ProcessGenerateRequest(msgspec.Struct):
+ model_id: str
+ work_item_msgpack: bytes
+
+
+class GenerateEvent(msgspec.Struct):
+ kind: GenerateEventKind
+ reply_subject: str = ""
+ payload: bytes = b""
+ delay_ms: int | None = None
+ error: str | None = None
+
+
+class WorkerCapabilitiesRequest(msgspec.Struct):
+ pass
+
+
+class WorkerCapabilitiesResponse(msgspec.Struct):
+ has_generation_models: bool = False
+ generation_models: list[str] = msgspec.field(default_factory=list)
+
+
+class SignalGenerateCancelRequest(msgspec.Struct):
+ request_id: str
+
+
+class SignalGenerateCancelResponse(msgspec.Struct):
+ matched: bool = False
+
+
+# -----------------------------------------------------------------------------
+# PreparedTokens — Rust-side fast-path tokenisation
+# -----------------------------------------------------------------------------
+#
+# When the worker-sidecar has learned a tokenizer for the target model
+# from ``ModelDescriptor``, it pre-tokenises ``item.text`` and attaches the
+# ragged, unpadded token arrays here. The Python adapter's fast-path uses
+# them verbatim iff ``tokenizer_id`` matches the BLAKE3 content hash of its
+# own ``tokenizer.json`` bytes; otherwise it falls back to
+# ``TextPreprocessor.prepare()`` exactly like today.
+#
+# ``prepared_tokens`` is optional because the worker-sidecar only attaches it
+# when tokenizer materialization and hashing succeed; otherwise Python tokenises.
+#
+# Wire-size policy notes (mirror ``dispatcher.rs::rag_to_wire``):
+# * ``attention_mask`` can be empty → Python rebuilds it as all-ones
+# per sequence (safe because all sequences are truncated at
+# ``max_seq_len`` and contain no padding).
+# * ``token_type_ids`` can be empty → Python treats that as "all
+# zeros" (the BERT convention for single-segment text), which
+# matches what every in-tree adapter currently synthesises.
+
+
+class PreparedTokens(msgspec.Struct):
+ # Ragged batch: outer = batch size, inner = this sequence's length.
+ # Already truncated to ``max_seq_len`` on the Rust side; NOT padded.
+ input_ids: list[list[int]]
+ # Stable content hash of ``tokenizer.json`` bytes (BLAKE3, first
+ # 32 hex chars). Python compares against its own loaded-tokenizer
+ # hash; on mismatch, Python re-tokenises and ``prepared_tokens``
+ # is discarded.
+ tokenizer_id: str
+ attention_mask: list[list[int]] = msgspec.field(default_factory=list)
+ token_type_ids: list[list[int]] = msgspec.field(default_factory=list)
+ # The ``max_length`` Rust applied when truncating. Python uses
+ # this only for drift detection — not for re-truncation.
+ max_seq_len: int = 0
+
+
+# -----------------------------------------------------------------------------
+# ProcessEncodeBatch
+# -----------------------------------------------------------------------------
+
+
+class EncodeBatchItem(msgspec.Struct):
+ work_item_id: str
+ request_id: str
+ item_index: int
+ total_items: int
+ timestamp: float
+ # Resolved payload: either the inline item dict or the payload_ref-resolved dict.
+ item: dict[str, Any]
+ # Sub-grouping keys. Items that share the same tuple of
+ # (output_types, instruction, is_query, options) can be run as a
+ # single EncodePipeline call.
+ output_types: list[str] | None = None
+ instruction: str | None = None
+ is_query: bool = False
+ options: dict[str, Any] | None = None
+ profile_id: str | None = None
+ bundle_config_hash: str | None = None
+ payload_fetch_ms: float = 0.0
+ # Optional pre-tokenised payload populated by the worker-sidecar
+ # (see ``PreparedTokens`` above). When present and the tokenizer
+ # id matches, the Python adapter skips its own tokenisation.
+ prepared_tokens: PreparedTokens | None = None
+
+
+class ProcessEncodeBatchRequest(msgspec.Struct):
+ model_id: str
+ items: list[EncodeBatchItem]
+
+
+# -----------------------------------------------------------------------------
+# ProcessScoreBatch
+# -----------------------------------------------------------------------------
+
+
+class ScoreBatchItem(msgspec.Struct):
+ work_item_id: str
+ request_id: str
+ item_index: int
+ total_items: int
+ timestamp: float
+ query_item: dict[str, Any]
+ score_items: list[dict[str, Any]]
+ instruction: str | None = None
+ options: dict[str, Any] | None = None
+ profile_id: str | None = None
+ payload_fetch_ms: float = 0.0
+ # Rust-side fast-path tokenisation. Wire layout matches the Rust
+ # dispatcher: ``input_ids[0]`` is the query, ``input_ids[1..]`` are
+ # the N score docs in the same order as ``score_items``.
+ prepared_tokens: PreparedTokens | None = None
+
+
+class ProcessScoreBatchRequest(msgspec.Struct):
+ model_id: str
+ items: list[ScoreBatchItem]
+
+
+# -----------------------------------------------------------------------------
+# ProcessExtractBatch
+# -----------------------------------------------------------------------------
+
+
+class ExtractBatchItem(msgspec.Struct):
+ work_item_id: str
+ request_id: str
+ item_index: int
+ total_items: int
+ timestamp: float
+ item: dict[str, Any]
+ labels: list[str] | None = None
+ output_schema: dict[str, Any] | None = None
+ instruction: str | None = None
+ options: dict[str, Any] | None = None
+ profile_id: str | None = None
+ bundle_config_hash: str | None = None
+ payload_fetch_ms: float = 0.0
+
+
+class ProcessExtractBatchRequest(msgspec.Struct):
+ model_id: str
+ items: list[ExtractBatchItem]
+
+
+# -----------------------------------------------------------------------------
+# Batch outcome — returned by all ProcessXxxBatch RPCs
+# -----------------------------------------------------------------------------
+
+Disposition = Literal["publish_and_ack", "publish_error_and_ack", "nak_retry"]
+
+
+# -----------------------------------------------------------------------------
+# RawOutput — Rust-side result framing fast-path
+# -----------------------------------------------------------------------------
+#
+# Mirrors ``sie_server_sidecar::ipc_types::RawOutput``. When the Python
+# adapter emits one of these typed shapes, Rust owns final wire framing
+# instead of Python packing the final ``msgpack`` envelope itself.
+#
+# Wire contract (non-destructive, additive):
+# * ``raw_output`` defaults to ``None`` on ``ItemOutcome``.
+# * Every inner variant is ``Optional``; new variants (sparse,
+# multivector, extract JSON, ...) are added as further
+# ``Optional`` fields without breaking clients.
+# * When ``raw_output`` is set, ``result_msgpack`` MUST be empty —
+# the Rust side treats a populated ``result_msgpack`` as
+# authoritative (rolling-deploy safety, see
+# ``publisher::shape_raw_output_for_wire``).
+# * On any shape error the Rust publisher converts the outcome to
+# ``publish_error_and_ack`` with ``error_code = "raw_output_shape_error"``.
+# We never silently drop a request.
+
+
+class DenseOutput(msgspec.Struct):
+ # Flat ``[dim]`` float32 embedding for a single encode item.
+ # ``len(values) == dim`` is enforced by the Rust shaper.
+ values: list[float]
+ dim: int
+ # If True, the Rust shaper L2-normalises ``values`` before
+ # packing. For v1 the Python adapter continues to normalise
+ # itself and sets this to False; kept on the wire so a later
+ # stage can delegate the step without a schema bump.
+ normalize: bool = False
+
+
+class ScoreOutputRaw(msgspec.Struct):
+ # Parallel lists in input order; the Rust shaper sorts desc by
+ # ``scores[i]`` (stable tie-break) and assigns ``rank = 0..``.
+ scores: list[float]
+ item_ids: list[str]
+
+
+class SparseOutput(msgspec.Struct):
+ # Parallel non-zero ``(indices, values)`` pair for one encode
+ # item. Mirrors the adapter-side ``SparseVector`` exactly
+ # (``np.int32`` indices, ``np.float32`` values), which every
+ # in-tree sparse encoder already produces.
+ #
+ # Invariants enforced by the Rust shaper:
+ # * ``len(indices) == len(values)``
+ # * indices fit in int32 (adapter convention)
+ # Violations surface as ``raw_output_shape_error`` on the wire.
+ indices: list[int]
+ values: list[float]
+ # ``None`` → packed as msgpack ``nil`` to match the legacy
+ # ``{"dims": None, ...}`` convention for vocab-less sparse.
+ dims: int | None = None
+
+
+class MultivectorOutput(msgspec.Struct):
+ # Flattened ``[num_tokens, token_dims]`` float32 matrix in C
+ # (row-major) order — same byte order as ``arr.tobytes()`` on a
+ # contiguous ndarray. The Rust shaper rebuilds the 2-D shape.
+ #
+ # Float32 is the supported Rust-framed path; ``float16`` and the
+ # bit-packed binary variant (``shape[1] < token_dims``) stay on the legacy
+ # Python-framed path via the ``_maybe_multivector_raw_output``
+ # gate in ``queue_executor``.
+ values: list[float]
+ num_tokens: int
+ token_dims: int
+
+
+class RawOutput(msgspec.Struct):
+ # At most one variant is populated per outcome — the Python
+ # safety gates (``_maybe_*_raw_output``) mint a ``RawOutput``
+ # with exactly the one field that matched a fast-path-eligible
+ # adapter output. All-None is treated as a typed error
+ # (``raw_output_shape_error``) by the Rust publisher — a
+ # rolling-deploy forward-compat guard against a future variant
+ # the current Rust build doesn't know.
+ dense: DenseOutput | None = None
+ score: ScoreOutputRaw | None = None
+ sparse: SparseOutput | None = None
+ multivector: MultivectorOutput | None = None
+
+
+# -----------------------------------------------------------------------------
+# ItemOutcome / BatchOutcome
+# -----------------------------------------------------------------------------
+
+
+class ItemOutcome(msgspec.Struct):
+ work_item_id: str
+ request_id: str
+ item_index: int
+ disposition: Disposition
+ nak_delay_ms: int | None = None
+ # Opaque msgpack bytes (what the SDK expects as WorkResult.result_msgpack).
+ # The executor produces this using the same path as the current pull loop.
+ result_msgpack: bytes | None = None
+ error: str | None = None
+ error_code: str | None = None
+ inference_ms: float | None = None
+ tokenization_ms: float | None = None
+ postprocessing_ms: float | None = None
+ # Typed raw inference output. When set, ``result_msgpack`` MUST be
+ # empty and the Rust publisher produces the final wire bytes. See
+ # ``RawOutput`` above for the fallback matrix.
+ raw_output: RawOutput | None = None
+
+
+class BatchOutcome(msgspec.Struct):
+ outcomes: list[ItemOutcome]
+
+
+# -----------------------------------------------------------------------------
+# RunBatch
+# -----------------------------------------------------------------------------
+#
+# Mirrors ``sie_server_sidecar::ipc_types::{RunBatchRequest, RunBatchItem}``.
+# See the Rust definitions for the design rationale; this file is the
+# decode side.
+#
+# Invariants enforced by ``adapter_call_loop.handle_run_batch``:
+# * ``items`` is non-empty.
+# * Every item's ``op`` discriminator matches exactly one populated
+# optional field (encode / score / extract) and all other optional
+# fields are ``None``.
+# * All items in a single request share the same ``op`` — the
+# Rust scheduler only flushes one op per batch; a mixed-op
+# request is an invariant violation and is rejected with
+# ``error_code = "run_batch_mixed_op"``.
+#
+# Unknown ``op`` values surface as ``error_code = "run_batch_unknown_op"``
+# (forward-compat: a newer Rust scheduler could ship an op this Python
+# doesn't understand, and we want the operator to see a clean error
+# rather than a confusing traceback).
+
+RunBatchOp = Literal["encode", "score", "extract"]
+
+
+class RunBatchItem(msgspec.Struct):
+ op: RunBatchOp
+ # Identity copied from the wrapped per-op item. Redundant on the
+ # happy path, but needed for deterministic per-item errors if a
+ # malformed frame omits the wrapped encode / score / extract
+ # payload.
+ work_item_id: str = ""
+ request_id: str = ""
+ item_index: int = 0
+ encode: EncodeBatchItem | None = None
+ score: ScoreBatchItem | None = None
+ extract: ExtractBatchItem | None = None
+
+
+class RunBatchRequest(msgspec.Struct):
+ model_id: str
+ # Rust-assigned batch id (u64 on the wire; int here).
+ batch_id: int
+ # Empty string means base model (no LoRA).
+ lora_key: str
+ # Sum of per-item costs, as computed by the Rust scheduler.
+ total_cost: int
+ items: list[RunBatchItem]
+
+
+# -----------------------------------------------------------------------------
+# Drain
+# -----------------------------------------------------------------------------
+
+
+# DrainRequest only exists over the wire; the Python server reads the
+# `deadline_ms` field out of the incoming dict directly (see
+# ``ipc_server._handle_drain``). A typed struct parallel lives in the
+# Rust client.
+
+
+class DrainResponse(msgspec.Struct):
+ acknowledged: bool = True
diff --git a/packages/sie_server/src/sie_server/nats_pull_loop.py b/packages/sie_server/src/sie_server/nats_pull_loop.py
deleted file mode 100644
index d4b7ce4f2..000000000
--- a/packages/sie_server/src/sie_server/nats_pull_loop.py
+++ /dev/null
@@ -1,2532 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import concurrent.futures
-import contextlib
-import logging
-import os
-import threading
-import time
-import uuid
-from collections.abc import AsyncIterator, Awaitable, Mapping
-from pathlib import Path
-from typing import Any
-
-import msgpack
-import msgpack_numpy
-import nats
-import nats.errors
-import nats.js.errors
-from nats.aio.client import Client as NATSClient
-from nats.js import JetStreamContext
-from nats.js.api import (
- AckPolicy,
- ConsumerConfig,
- DiscardPolicy,
- RetentionPolicy,
- StorageType,
- StreamConfig,
-)
-from sie_sdk import SIEAsyncClient, SIEError
-from sie_sdk.queue_types import (
- WORK_SUBJECT_PREFIX,
- WorkItem,
- WorkResult,
- denormalize_model_id,
- normalize_worker_id,
- work_consumer_name,
- work_pool_stream_name,
- work_pool_stream_subjects,
- work_stream_name,
- work_worker_consumer_name,
- work_worker_stream_name,
- work_worker_stream_subjects,
-)
-
-from sie_server.core.adaptive_batching import LatencyTracker
-from sie_server.core.extract_cost import build_extract_prepared_items
-from sie_server.core.inference_output import ScoreOutput
-from sie_server.core.oom import is_oom_error
-from sie_server.core.prepared import ScorePreparedItem
-from sie_server.core.registry import ModelRegistry
-from sie_server.core.timing import RequestTiming
-from sie_server.core.worker.handlers.extract import ExtractHandler
-from sie_server.processors.work_class_scheduler import (
- EMBEDDING_CLASS,
- GENERATION_CLASS,
- FairnessConfig,
- WorkClassConfig,
- WorkClassScheduler,
- classify_work_class,
-)
-from sie_server.types.inputs import InvalidMediaError, Item
-from sie_server.types.responses import ErrorCode
-
-msgpack_numpy.patch()
-
-logger = logging.getLogger(__name__)
-
-# Default ACK wait in seconds — nats.py converts to nanoseconds internally.
-_ACK_WAIT_S = 30
-
-# Streaming-generation ack_wait: long generations would exceed the 30s
-# default. Use 5 minutes for pools that host any generation model; the
-# worker emits ``msg.in_progress()`` between chunks to refresh the timer
-# for genuinely slow decodes.
-_ACK_WAIT_S_GENERATION = 300
-
-# Default batch budget — controls how many NATS messages a single fetch()
-# returns. This is the primary driver of GPU batch size in queue mode:
-# the pull loop groups fetched messages by model and dispatches them as a
-# single GPU forward pass. Configurable via SIE_NATS_FETCH_BUDGET.
-_DEFAULT_BATCH_BUDGET = int(os.environ.get("SIE_NATS_FETCH_BUDGET", "64"))
-
-# Maximum concurrent batch-processing tasks to avoid ACK timeout storms.
-_MAX_CONCURRENT_BATCHES = 4
-
-# TTL (seconds) for caching the bundle config hash.
-_CONFIG_HASH_CACHE_TTL_S = 5.0
-
-# Interval (seconds) between retries for models whose initial subscription failed.
-_FAILED_MODEL_RETRY_INTERVAL = 30.0
-
-# Pool admission defaults. When SIE_GATEWAY_URL is unset the gate is disabled
-# for local/single-worker compatibility.
-_POOL_ADMISSION_CHECK_INTERVAL_S = float(os.environ.get("SIE_POOL_ADMISSION_CHECK_INTERVAL_S", "5.0"))
-_POOL_ADMISSION_PAUSE_S = float(os.environ.get("SIE_POOL_ADMISSION_PAUSE_S", "1.0"))
-_POOL_ADMISSION_STALE_AFTER_S = float(os.environ.get("SIE_POOL_ADMISSION_STALE_AFTER_S", "30.0"))
-
-# Graceful drain timeout (seconds) — matches _ACK_WAIT_S so in-flight batches
-# have time to finish and ACK before the pull loop shuts down.
-_DRAIN_TIMEOUT_S = 30.0
-
-# NAK delay (seconds) for items targeting unloaded models.
-# JetStream redelivers after this delay, giving time for loading to complete.
-# Configurable via SIE_NAK_DELAY_S; with max_deliver=20, the default gives
-# ~100s total retry budget — enough for cold model downloads.
-_NAK_DELAY_S = float(os.environ.get("SIE_NAK_DELAY_S", "5.0"))
-
-# NAK delay for items that hit OOM (RESOURCE_EXHAUSTED) on this worker.
-# Slightly longer than the default to give the OOMed worker time to drain
-# its in-flight requests (and for any sibling worker to pick up the NAKed
-# item via JetStream redelivery). The delay is intentionally NOT zero —
-# instant redelivery would just reroute the same item back to the still-
-# pressured worker. Tunable via SIE_OOM_NAK_DELAY_S.
-_OOM_NAK_DELAY_S = float(os.environ.get("SIE_OOM_NAK_DELAY_S", "10.0"))
-
-# Maximum delivery attempts before a message is sent to the DLQ.
-# Configurable via SIE_MAX_DELIVER; must be high enough to cover model load
-# times (10-60s+ for cold HuggingFace downloads).
-_MAX_DELIVER = int(os.environ.get("SIE_MAX_DELIVER", "20"))
-
-_MIN_SUBJECT_PARTS = 4 # sie.work.{model}.{pool}
-
-# Dynamic fetch timeout bounds. With the pool-level stream design (single
-# subscription per pool), idle polling cost is just one NATS fetch RPC per
-# cycle — much lower than the old O(N-models) design. The max can be kept
-# very tight to minimise head-of-line delay at low concurrency.
-#
-# At 1ms minimum, the worker checks for new messages every 1ms when busy.
-# At 20ms maximum, the worst-case idle delay is 20ms (avg ~10ms).
-# This translates to ~50 idle polls/sec to NATS — negligible load.
-_MIN_FETCH_TIMEOUT_S = 0.001 # 1ms — near-instant when messages flow
-_MAX_FETCH_TIMEOUT_S = 0.02 # 20ms — tight idle delay
-_BACKOFF_GROWTH = 2.0 # 1ms → 2ms → 4ms → 8ms → 16ms → 20ms (5 steps)
-
-# Thrashing detection: if a model is background-loaded this many times
-# within this window, log a warning suggesting separate bundles.
-_THRASH_WINDOW_S = 300.0 # 5 minutes
-_THRASH_THRESHOLD = 4 # 4 loads in 5 minutes = thrashing
-
-# Max age (seconds) for messages in the pool-level stream.
-# Configurable via SIE_STREAM_MAX_AGE_S to give headroom for slow model loads.
-_DEFAULT_STREAM_MAX_AGE_S = int(os.environ.get("SIE_STREAM_MAX_AGE_S", "120"))
-
-# Thread pool for S3 payload fetches — avoids exhausting the default
-# asyncio thread pool when fetching many large payloads concurrently.
-_PAYLOAD_THREAD_POOL = concurrent.futures.ThreadPoolExecutor(max_workers=16, thread_name_prefix="payload-fetch")
-
-
-def _env_bool(name: str, default: bool) -> bool:
- raw = os.environ.get(name)
- if raw is None:
- return default
- return raw.strip().lower() not in {"0", "false", "no", "off"}
-
-
-def _normalize_pool_name(name: str | None) -> str:
- value = (name or "").strip().lower()
- if value in {"", "_default"}:
- return "default"
- return value
-
-
-def _first_csv_token(value: str | None) -> str | None:
- if not value:
- return None
- for token in value.split(","):
- token = token.strip()
- if token:
- return token
- return None
-
-
-def _lookup_case_insensitive(mapping: Mapping[str, Any], key: str) -> Any:
- key_lower = key.lower()
- for candidate, value in mapping.items():
- if candidate.lower() == key_lower:
- return value
- return None
-
-
-class _PoolAdmissionGate:
- """Decides whether this worker may pull from its configured queue pool."""
-
- def __init__(
- self,
- *,
- pool_name: str,
- worker_id: str,
- machine_profile: str,
- gateway_url: str | None,
- api_key: str | None,
- check_interval_s: float = _POOL_ADMISSION_CHECK_INTERVAL_S,
- pause_s: float = _POOL_ADMISSION_PAUSE_S,
- stale_after_s: float = _POOL_ADMISSION_STALE_AFTER_S,
- client: Any | None = None,
- ) -> None:
- self._pool_name = pool_name
- self._worker_id = worker_id
- self._machine_profile = machine_profile
- self._gateway_url = (gateway_url or "").strip()
- self._check_interval_s = check_interval_s
- self.pause_s = pause_s
- self._stale_after_s = stale_after_s
- self._client = client
- self._owns_client = client is None
- self._enabled = bool(self._gateway_url)
- self._last_check_at = 0.0
- self._last_success_at = 0.0
- self._admitted = _normalize_pool_name(pool_name) == "default"
- self._last_reason = "initial"
-
- if self._enabled and self._client is None:
- self._client = SIEAsyncClient(self._gateway_url, timeout_s=5.0, api_key=api_key or None)
-
- async def close(self) -> None:
- if self._owns_client and self._client is not None:
- await self._client.close()
-
- async def admitted(self) -> bool:
- if not self._enabled or self._client is None:
- return True
-
- now = time.monotonic()
- if now - self._last_check_at < self._check_interval_s:
- return self._admitted
-
- self._last_check_at = now
- try:
- pool = await self._client.get_pool(self._pool_name)
- except SIEError as exc:
- return self._handle_error(now, str(exc))
- except Exception as exc: # noqa: BLE001
- return self._handle_error(now, str(exc))
-
- self._last_success_at = now
- admitted, reason = self._decide(pool)
- self._set_admitted(admitted, reason)
- return self._admitted
-
- def _handle_error(self, now: float, error: str) -> bool:
- if self._last_success_at and now - self._last_success_at <= self._stale_after_s:
- return self._admitted
-
- # Keep the default pool available during gateway/status glitches. Named
- # pools fail closed because their caps are isolation contracts.
- fail_open = _normalize_pool_name(self._pool_name) == "default"
- self._set_admitted(fail_open, f"status_error:{error[:120]}")
- return self._admitted
-
- def _decide(self, pool: Mapping[str, Any] | None) -> tuple[bool, str]:
- if pool is None:
- is_default = _normalize_pool_name(self._pool_name) == "default"
- return is_default, "pool_missing"
-
- spec_raw = pool.get("spec", {})
- spec = spec_raw if isinstance(spec_raw, Mapping) else {}
- caps = spec.get("gpu_caps") or {}
- if not isinstance(caps, dict) or not caps:
- return True, "uncapped"
-
- cap = _lookup_case_insensitive(caps, self._machine_profile) if self._machine_profile else None
- if cap is None:
- return True, "profile_uncapped"
- try:
- if int(cap) <= 0:
- return False, "cap_exhausted"
- except (TypeError, ValueError):
- return False, "malformed_gpu_cap"
-
- status_raw = pool.get("status", {})
- status = status_raw if isinstance(status_raw, Mapping) else {}
- assigned = status.get("assigned_workers", [])
- if not isinstance(assigned, list):
- return False, "malformed_assigned_workers"
-
- for worker in assigned:
- if isinstance(worker, dict) and worker.get("name") == self._worker_id:
- return True, "assigned"
- return False, "not_assigned"
-
- def _set_admitted(self, admitted: bool, reason: str) -> None:
- if admitted == self._admitted and reason == self._last_reason:
- return
- self._admitted = admitted
- self._last_reason = reason
- logger.info(
- "Pool admission %s (pool=%s, worker=%s, machine_profile=%s, reason=%s)",
- "granted" if admitted else "paused",
- self._pool_name,
- self._worker_id,
- self._machine_profile,
- reason,
- )
-
-
-# Map numpy dtype to the wire-format dtype string expected by the SDK.
-_NP_DTYPE_MAP = {"float32": "float32", "float16": "float16", "int8": "int8", "uint8": "binary"}
-
-
-def _wrap_encode_output(output: dict, config: Any) -> dict:
- """Wrap raw numpy arrays from ``EncodeHandler.format_output`` into the
- ``DenseVector``/``SparseVector`` wire format that the SDK expects.
-
- The HTTP path does this via ``encode.py:_build_response_items`` + Pydantic
- ``EncodeResult``. In the queue path the worker must produce the same shape
- *before* msgpack-serializing, because the gateway embeds the blob as-is.
- """
- import numpy as np # noqa: PLC0415
-
- wrapped = dict(output)
-
- if "dense" in wrapped and isinstance(wrapped["dense"], np.ndarray):
- arr = wrapped["dense"]
- encode_task = getattr(config, "tasks", None)
- encode_task = getattr(encode_task, "encode", None)
- dense_cfg = getattr(encode_task, "dense", None) if encode_task else None
- dense_dim = dense_cfg.dim if dense_cfg else None
-
- is_binary = arr.dtype == np.uint8 and dense_dim and arr.shape[0] < dense_dim
- dims = dense_dim if dense_dim is not None else arr.shape[0]
- dtype = "binary" if is_binary else _NP_DTYPE_MAP.get(str(arr.dtype), "float32")
-
- wrapped["dense"] = {"dims": int(dims), "dtype": dtype, "values": arr}
-
- if "sparse" in wrapped and isinstance(wrapped["sparse"], dict):
- # sparse already comes as {"indices": ndarray, "values": ndarray}
- pass
-
- if "multivector" in wrapped and isinstance(wrapped["multivector"], np.ndarray):
- arr = wrapped["multivector"]
- wrapped["multivector"] = {"values": arr}
-
- return wrapped
-
-
-# ---------------------------------------------------------------------------
-# Metrics (optional — gracefully degrade if prometheus_client not installed)
-# ---------------------------------------------------------------------------
-
-try:
- from prometheus_client import Counter, Histogram
-
- PULL_ITEMS_FETCHED = Histogram(
- "sie_pull_loop_items_fetched",
- "Number of items fetched per pull cycle",
- ["model"],
- buckets=[1, 2, 4, 8, 16, 32, 64, 128, 256],
- )
- PULL_BATCH_PROCESS_SECONDS = Histogram(
- "sie_pull_loop_batch_process_seconds",
- "Time to process a pulled batch (seconds)",
- ["model", "operation"],
- buckets=[0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
- )
- PULL_QUEUE_WAIT_SECONDS = Histogram(
- "sie_pull_loop_queue_wait_seconds",
- "Time items waited in NATS queue before being pulled (seconds)",
- ["model"],
- buckets=[0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0],
- )
- PULL_CONFIG_HASH_MISMATCHES = Counter(
- "sie_pull_loop_config_hash_mismatches_total",
- "Config hash mismatches detected (log-only, items still processed)",
- ["model"],
- )
- PULL_NAK_UNLOADED = Counter(
- "sie_pull_loop_nak_unloaded_total",
- "Work items NAKed because the target model is not loaded",
- ["model"],
- )
- PULL_MODEL_LOADS = Counter(
- "sie_pull_loop_model_loads_total",
- "Background model loads triggered by demand",
- ["model"],
- )
- PULL_GENERATE_DISPATCH_ERRORS = Counter(
- "sie_pull_loop_generate_dispatch_errors_total",
- "Unhandled exceptions escaping StreamingProcessor.process (message NAK'd)",
- ["model"],
- )
- _HAS_METRICS = True
-except ImportError:
- _HAS_METRICS = False
-
-
-# ---------------------------------------------------------------------------
-# Minimal payload store (read-only) — self-contained to avoid cross-package
-# imports from the config service or gateway.
-# ---------------------------------------------------------------------------
-
-
-class _PayloadStore:
- """Read-only payload fetcher (local filesystem or S3)."""
-
- async def get(self, key: str) -> bytes:
- raise NotImplementedError
-
-
-class _LocalPayloadStore(_PayloadStore):
- def __init__(self, base_dir: str) -> None:
- self._base_dir = Path(base_dir)
-
- def _safe_path(self, key: str) -> Path:
- """Resolve key to a path inside base_dir, rejecting traversal."""
- target = (self._base_dir / key).resolve()
- base = self._base_dir.resolve()
- try:
- target.relative_to(base)
- except ValueError:
- raise ValueError(f"Path traversal detected: {key}") from None
- return target
-
- async def get(self, key: str) -> bytes:
- path = self._safe_path(key)
- loop = asyncio.get_running_loop()
- try:
- return await loop.run_in_executor(_PAYLOAD_THREAD_POOL, path.read_bytes)
- except FileNotFoundError:
- raise KeyError(f"Payload not found: {key}") from None
-
-
-class _S3PayloadStore(_PayloadStore):
- def __init__(self, bucket: str, prefix: str = "payloads") -> None:
- self._bucket = bucket
- self._prefix = prefix
- self._client: object | None = None
- self._client_lock = threading.Lock()
-
- def _get_client(self) -> object:
- """Get or create a cached boto3 S3 client (thread-safe)."""
- if self._client is None:
- with self._client_lock:
- if self._client is None:
- import boto3 # noqa: PLC0415
-
- self._client = boto3.client("s3")
- return self._client
-
- async def get(self, key: str) -> bytes:
- full_key = f"{self._prefix}/{key}" if self._prefix else key
-
- def _fetch() -> bytes:
- client = self._get_client()
- response = client.get_object(Bucket=self._bucket, Key=full_key) # type: ignore
- body = response["Body"]
- try:
- return body.read()
- finally:
- body.close()
-
- try:
- loop = asyncio.get_running_loop()
- return await loop.run_in_executor(_PAYLOAD_THREAD_POOL, _fetch)
- except KeyError:
- raise
- except Exception as e:
- import botocore.exceptions # noqa: PLC0415 — optional dep, lazy import
-
- if isinstance(e, botocore.exceptions.ClientError):
- error_code = e.response.get("Error", {}).get("Code", "")
- if error_code in ("NoSuchKey", "404"):
- raise KeyError(f"Payload not found: {key}") from e
- raise
-
-
-class _GCSPayloadStore(_PayloadStore):
- """Read-only GCS payload store for the worker pull loop."""
-
- def __init__(self, bucket: str, prefix: str) -> None:
- self._bucket_name = bucket
- self._prefix = prefix
- self._client: Any = None
-
- def _get_bucket(self) -> Any:
- if self._client is None:
- try:
- from google.cloud import storage # noqa: PLC0415
- except ImportError:
- raise ImportError(
- "google-cloud-storage is required for GCS payload stores. Install the google-cloud-storage package"
- ) from None
- client = storage.Client()
- self._client = client.bucket(self._bucket_name)
- return self._client
-
- async def get(self, key: str) -> bytes:
- bucket = self._get_bucket()
- full_key = f"{self._prefix}/{key}" if self._prefix else key
- blob = bucket.blob(full_key)
- try:
- data: bytes = await asyncio.to_thread(blob.download_as_bytes)
- return data
- except Exception as e:
- _not_found = None
- with contextlib.suppress(ImportError):
- from google.api_core.exceptions import NotFound # noqa: PLC0415
-
- _not_found = NotFound
- if _not_found is not None and isinstance(e, _not_found):
- raise KeyError(f"Payload not found: {key}") from e
- raise
-
-
-def _create_payload_store(url: str | None) -> _PayloadStore | None:
- """Create a read-only payload store from a URL."""
- if not url:
- return None
- if url.startswith("s3://"):
- parts = url[5:].split("/", 1)
- bucket = parts[0]
- prefix = parts[1] if len(parts) > 1 else "payloads"
- return _S3PayloadStore(bucket=bucket, prefix=prefix)
- if url.startswith("gs://"):
- parts = url[5:].split("/", 1)
- bucket = parts[0]
- prefix = parts[1] if len(parts) > 1 else "payloads"
- return _GCSPayloadStore(bucket=bucket, prefix=prefix)
- if "://" in url:
- raise ValueError(
- f"Unsupported payload store URL scheme: {url!r}. "
- "Supported: 's3://bucket/prefix', 'gs://bucket/prefix', or a local filesystem path."
- )
- return _LocalPayloadStore(base_dir=url)
-
-
-def _resolve_generation_admission(registry: ModelRegistry, model_id: str) -> tuple[int | None, bool | None]:
- """Resolve generation admission settings for the model being processed."""
- try:
- config = registry.get_config(model_id)
- except KeyError:
- return None, None
- if config.tasks.generate is None:
- return None, None
- try:
- resolved = config.resolve_profile("default")
- except Exception: # noqa: BLE001
- logger.debug(
- "Failed to resolve 'default' profile for admission lookup on %s",
- config.sie_id,
- exc_info=True,
- )
- return None, None
- return resolved.kv_budget_tokens, resolved.admission_enabled
-
-
-def _fairness_config_from_env() -> FairnessConfig | None:
- """Build the opt-in pool-fairness config from env, or ``None`` (default).
-
- Off unless ``SIE_POOL_FAIRNESS_ENABLED`` is truthy. When on, the generation
- and embedding work classes share ``SIE_POOL_FAIRNESS_TOTAL_SLOTS`` by weight,
- with a reserved ``min_slots`` floor per class so embedding/score are not
- starved under generation saturation. Returns ``None`` (scheduler off →
- dispatch byte-identical to today) unless explicitly enabled, so this is a
- zero-impact default. A misconfiguration is logged and disables the scheduler
- rather than crashing the worker.
- """
- if os.environ.get("SIE_POOL_FAIRNESS_ENABLED", "").strip().lower() not in ("1", "true", "yes", "on"):
- return None
-
- def _int(name: str, default: int) -> int:
- try:
- return int(os.environ[name])
- except (KeyError, ValueError):
- return default
-
- def _float(name: str, default: float) -> float:
- try:
- return float(os.environ[name])
- except (KeyError, ValueError):
- return default
-
- cfg = FairnessConfig(
- total_slots=_int("SIE_POOL_FAIRNESS_TOTAL_SLOTS", 8),
- classes={
- GENERATION_CLASS: WorkClassConfig(
- weight=_float("SIE_POOL_FAIRNESS_GEN_WEIGHT", 1.0),
- min_slots=_int("SIE_POOL_FAIRNESS_GEN_MIN_SLOTS", 0),
- ),
- EMBEDDING_CLASS: WorkClassConfig(
- weight=_float("SIE_POOL_FAIRNESS_EMB_WEIGHT", 1.0),
- min_slots=_int("SIE_POOL_FAIRNESS_EMB_MIN_SLOTS", 1),
- ),
- },
- )
- try:
- cfg.validate()
- except ValueError as exc:
- logger.error("Invalid SIE_POOL_FAIRNESS_* config (%s); disabling fairness scheduler", exc)
- return None
- return cfg
-
-
-class NatsPullLoop:
- """Pull work items from NATS JetStream and feed to ModelWorker.
-
- One pull loop per worker process. The loop round-robins across models
- in the worker's bundle, pulling items from each model's JetStream
- subject and submitting them to the appropriate ModelWorker.
- """
-
- def __init__(
- self,
- nc: NATSClient,
- js: JetStreamContext,
- registry: ModelRegistry,
- bundle_id: str,
- pool_name: str,
- payload_store_url: str | None = None,
- ) -> None:
- self._nc = nc
- self._js = js
- self._registry = registry
- self._bundle_id = bundle_id
- self._pool_name = pool_name
- self._payload_store_url = payload_store_url
- self._subscriptions: dict[str, Any] = {} # model_id → PullSubscription
- self._running = False
- self._pull_task: asyncio.Task[None] | None = None
- # Parallel pull task for the per-worker direct-dispatch
- # subscription. ``None`` until ``start()`` creates it; left
- # ``None`` on direct-dispatch boot failures so the pool path keeps
- # working.
- self._worker_pull_task: asyncio.Task[None] | None = None
- self._worker_sub: Any | None = None
- self._hosts_generation_model: bool | None = None
- self._in_flight_tasks: set[asyncio.Task[None]] = set()
- # Outstanding generation streams, tracked separately from the
- # GPU-batch ``_in_flight_tasks``. Generation is decoupled from
- # ``_batch_sem`` (see :meth:`_process_generate_items`): each stream
- # runs as its own task so it does NOT hold a GPU-batch slot for its
- # whole lifetime — that capped generation at ``_MAX_CONCURRENT_BATCHES``
- # and starved direct-dispatch. Concurrency is instead bounded by the
- # KV-budget admission gate inside :class:`StreamingProcessor`. We
- # keep strong refs here so the loop doesn't GC a stream mid-flight
- # and so :meth:`stop` can drain them gracefully.
- self._in_flight_generate_tasks: set[asyncio.Task[None]] = set()
- self._payload_store: _PayloadStore | None = None
- # Stable worker identity. Priority order:
- # 1. SIE_WORKER_ID — explicit operator override; survives pod restarts.
- # 2. HOSTNAME — set by K8s (per-pod), reasonable for cluster deployments.
- # 3. POD_NAME — secondary K8s fallback if HOSTNAME is masked.
- # 4. uuid4 hex — last-resort for local dev so multi-process runs don't
- # collide on the durable consumer name ``gen-{worker_id}``.
- # Previous default was a bare ``"worker"`` literal which broke local
- # parallelism by sharing the same JetStream durable across processes.
- #
- # The resolved value is then normalized via ``normalize_worker_id``
- # (mirrors the gateway's ``normalize_model_id`` in
- # ``packages/sie_gateway/src/queue/publisher.rs``) before any subject
- # is composed. Kubernetes pod hostnames embed ``.`` which is the NATS
- # subject separator; without normalization here the gateway publishes
- # to ``sie.work.{model}.{pool}.{normalized}`` while the worker would
- # bind its stream to ``sie.work.*.{pool}.{raw-with-dots}`` and
- # direct-dispatch would silently miss until the pool-fallback fires
- # (workstream G-M5).
- _worker_id_raw = (
- os.environ.get("SIE_WORKER_ID")
- or os.environ.get("HOSTNAME")
- or os.environ.get("POD_NAME")
- or uuid.uuid4().hex
- )
- try:
- self._worker_id = normalize_worker_id(_worker_id_raw)
- except ValueError:
- # All four sources empty/whitespace is extremely unlikely
- # (uuid4().hex is non-empty by construction) but if a future
- # change broke that invariant we want a deterministic fallback
- # rather than silently substituting "worker" — that constant
- # collides durable consumers across processes.
- logger.error(
- "nats_pull_loop: resolved worker_id %r is empty after "
- "normalization; falling back to fresh uuid4 to avoid "
- "durable-consumer collisions",
- _worker_id_raw,
- )
- self._worker_id = normalize_worker_id(uuid.uuid4().hex)
- # Keep the pre-normalization form for log messages where the raw
- # hostname is more recognizable to operators. Subject construction
- # MUST use ``self._worker_id`` (the normalized form) so the gateway
- # and worker agree on the wire.
- self._worker_id_raw = _worker_id_raw
- if self._worker_id == _worker_id_raw:
- logger.info("nats_pull_loop resolved worker_id=%s", self._worker_id)
- else:
- logger.info(
- "nats_pull_loop resolved worker_id=%s (normalized from %r)",
- self._worker_id,
- _worker_id_raw,
- )
- # Saturation gate. Driven from in-flight task count vs
- # the aggregate ``max_batch_requests``. Read by ``api/ws.py``
- # (via ``app.state.nats_pull_loop``) and the optional NATS
- # health publisher.
- from sie_server.health.saturation import SaturationGate # noqa: PLC0415
-
- self._saturation_gate = SaturationGate()
- self._machine_profile = os.environ.get("SIE_MACHINE_PROFILE") or os.environ.get("SIE_GPU_TYPE", "")
- gateway_url = os.environ.get("SIE_GATEWAY_URL", "") if _env_bool("SIE_POOL_ADMISSION_ENABLED", True) else ""
- self._admission_gate = _PoolAdmissionGate(
- pool_name=self._pool_name,
- worker_id=self._worker_id,
- machine_profile=self._machine_profile,
- gateway_url=gateway_url,
- api_key=_first_csv_token(os.environ.get("SIE_GATEWAY_API_KEY") or os.environ.get("SIE_AUTH_TOKEN")),
- )
- self._failed_models: set[str] = set()
- self._config_hash_cache: str | None = None
- self._config_hash_cache_time: float = 0.0
- self._batch_sem = asyncio.Semaphore(_MAX_CONCURRENT_BATCHES)
-
- # Opt-in mixed-pool fairness: when ``SIE_POOL_FAIRNESS_ENABLED`` is set,
- # dispatch is gated by a weighted-fair-queue scheduler with per-class
- # ``min_slots`` floors (generation vs embedding/score/extract), so a
- # saturated generation stream cannot starve embeddings on a shared pool.
- # ``None`` (default) → unchanged dispatch.
- _fairness_cfg = _fairness_config_from_env()
- self._scheduler: WorkClassScheduler | None = (
- WorkClassScheduler(_fairness_cfg) if _fairness_cfg is not None else None
- )
- if self._scheduler is not None:
- logger.info("nats_pull_loop: work-class fairness scheduler enabled (%s)", _fairness_cfg)
-
- # Reactive model loading state
- self._loading_models: set[str] = set() # Models currently being loaded
- self._load_tasks: dict[str, asyncio.Task[None]] = {} # model → background load task
- self._load_history: list[tuple[str, float]] = [] # (model_id, timestamp) for thrash detection
-
- # Adaptive fetch timeout: tracks queue-path latency (time from
- # gateway publish to result publish) and adjusts fetch_timeout to
- # balance item accumulation (throughput) vs head-of-line delay.
- # When latency is under the target, the timeout can increase to
- # allow more items to accumulate → larger GPU batches. When over
- # the target, the timeout shrinks for faster pickup.
- self._queue_latency_tracker = LatencyTracker(window_size=200, min_samples=10)
-
- # ``MessageProcessor`` seam. The existing batch path
- # (encode/score/extract) is not yet flipped through this protocol;
- # only generation work items are dispatched here.
- from sie_server.processors.admission import resolve_admission_enabled # noqa: PLC0415
- from sie_server.processors.streaming import StreamingProcessor # noqa: PLC0415
-
- def resolve_effective_admission(model_id: str) -> tuple[int | None, bool | None]:
- kv_budget_tokens, profile_admission = _resolve_generation_admission(self._registry, model_id)
- return kv_budget_tokens, resolve_admission_enabled(profile_admission=profile_admission)
-
- self._streaming_processor = StreamingProcessor(
- nc=self._nc,
- registry=self._registry,
- worker_id=self._worker_id,
- admission_resolver=resolve_effective_admission,
- )
- # Cancel subscription (cluster-scope ``cancel.>``). Created
- # lazily in :meth:`start`; ``None`` until then so :meth:`stop`
- # tolerates an early shutdown.
- self._cancel_sub: Any | None = None
- self._pool_sub: Any | None = None
-
- async def start(self) -> None:
- """Start the pull loop.
-
- Creates a single multiplexed JetStream consumer for the worker's
- pool and begins pulling work items for all models.
- """
- self._running = True
- self._payload_store = _create_payload_store(self._payload_store_url)
-
- # Migrate: remove legacy per-model streams that overlap with the
- # new pool-level stream subjects. ``add_stream`` will reject the
- # pool stream if any per-model stream has an overlapping subject.
- await self._migrate_per_model_streams()
-
- self._refresh_generation_pool_flag()
-
- # Create the single pool-level stream + consumer
- await self._ensure_pool_subscription()
-
- if self._pool_hosts_generation_model():
- # Per-worker direct-dispatch stream + consumer. The
- # pool stream's wildcard ``sie.work.*.{pool}`` captures exactly
- # 3 subject tokens after the prefix; the per-worker subject has
- # 4 tokens (``…{pool}.{worker_id}``) so it cannot overlap. Both
- # subscriptions feed the same ``_process_messages`` path.
- # Failure here is non-fatal — workers without a per-worker
- # subscription degrade to the pool-fallback path (the gateway
- # already handles "no eligible worker" by publishing to the
- # pool subject).
- try:
- await self._ensure_per_worker_subscription()
- except Exception:
- logger.exception("Failed to create per-worker subscription (continuing with pool-only delivery)")
-
- # Subscribe (cluster-scope) to cancel.> on core NATS so
- # the StreamingProcessor can react to client disconnect cancels.
- # request_id uniqueness is the filter; router_id is informational.
- await self._ensure_cancel_subscription()
- else:
- logger.info("Skipping generation direct-dispatch subscriptions for non-generation pool %s", self._pool_name)
-
- # Grammar prewarm. Compile each model's
- # ``tasks.generate.prewarm_grammars`` ahead of request traffic so
- # the cold-start TTFT for those schemas excludes Outlines
- # compile cost. Runs before ``_pull_task`` starts so the cache
- # is hot by the time the first work item arrives. Non-generation
- # models are skipped via :func:`is_generation_model`. Per-entry
- # failures are absorbed inside the processor and surfaced via
- # ``sie_worker_grammar_prewarm_total{outcome="failed"}``.
- await self._prewarm_grammars()
-
- # Start the main pull loop
- self._pull_task = asyncio.create_task(self._run())
- # Parallel pull task draining the per-worker stream.
- # Spawned only if the per-worker subscription was created.
- if self._worker_sub is not None:
- self._worker_pull_task = asyncio.create_task(self._run_worker_pull())
- logger.info(
- "NatsPullLoop started (bundle=%s, pool=%s, models=%d, stream=%s)",
- self._bundle_id,
- self._pool_name,
- len(self._registry.model_names),
- work_pool_stream_name(self._pool_name),
- )
-
- async def stop(self) -> None:
- """Stop the pull loop gracefully.
-
- Cancels the pull task and waits for in-flight processing to complete.
- """
- self._running = False
-
- # Cancel the main pull loop
- if self._pull_task is not None:
- self._pull_task.cancel()
- try:
- await self._pull_task
- except asyncio.CancelledError:
- pass
- self._pull_task = None
-
- if self._worker_pull_task is not None:
- self._worker_pull_task.cancel()
- with contextlib.suppress(asyncio.CancelledError):
- await self._worker_pull_task
- self._worker_pull_task = None
-
- # Wait for in-flight tasks to complete (graceful drain).
- # Do NOT cancel — let current batches finish, ACK, and drain cleanly.
- # Items processed during drain are ACKed normally; no GPU work wasted.
- #
- # ``_in_flight_generate_tasks`` is drained alongside the GPU-batch
- # ``_in_flight_tasks``: generation streams run as independent tasks
- # (decoupled from ``_batch_sem`` — see ``_process_generate_items``)
- # so they would otherwise not be awaited here, dropping in-flight
- # generations on shutdown. Draining both with the same timeout +
- # cancel-on-overrun policy keeps the graceful-shutdown contract.
- drain_tasks = self._in_flight_tasks | self._in_flight_generate_tasks
- if drain_tasks:
- logger.info(
- "Draining %d in-flight task(s) (%d batch, %d generation)",
- len(drain_tasks),
- len(self._in_flight_tasks),
- len(self._in_flight_generate_tasks),
- )
- _done, pending = await asyncio.wait(drain_tasks, timeout=_DRAIN_TIMEOUT_S)
- if pending:
- logger.warning("Drain timeout: %d tasks still pending, cancelling", len(pending))
- for task in pending:
- task.cancel()
- await asyncio.gather(*pending, return_exceptions=True)
- self._in_flight_tasks.clear()
- self._in_flight_generate_tasks.clear()
-
- # Drain the fairness scheduler (no-op when disabled): pulling has
- # stopped and in-flight work is settled above, so all slots are
- # released and this returns promptly.
- if self._scheduler is not None:
- with contextlib.suppress(Exception):
- await asyncio.wait_for(self._scheduler.drain(), timeout=5.0)
-
- # Cancel background model load tasks
- for load_task in self._load_tasks.values():
- load_task.cancel()
- if self._load_tasks:
- await asyncio.gather(*self._load_tasks.values(), return_exceptions=True)
- self._load_tasks.clear()
- self._loading_models.clear()
-
- for sub in self._subscriptions.values():
- try:
- await sub.unsubscribe()
- except Exception: # noqa: BLE001
- logger.debug("Failed to unsubscribe during shutdown")
- self._subscriptions.clear()
-
- if self._pool_sub is not None:
- try:
- await self._pool_sub.unsubscribe()
- except Exception: # noqa: BLE001
- logger.debug("Failed to unsubscribe pool sub during shutdown")
- self._pool_sub = None
- await self._admission_gate.close()
-
- # Tear down the per-worker subscription.
- if self._worker_sub is not None:
- try:
- await self._worker_sub.unsubscribe()
- except Exception: # noqa: BLE001
- logger.debug("Failed to unsubscribe per-worker sub during shutdown")
- self._worker_sub = None
-
- if hasattr(self, "_cancel_sub") and self._cancel_sub is not None:
- try:
- await self._cancel_sub.unsubscribe()
- except Exception: # noqa: BLE001
- logger.debug("Failed to unsubscribe cancel sub during shutdown")
- self._cancel_sub = None
-
- logger.info("NatsPullLoop stopped")
-
- async def handle_reconnect(self) -> None:
- """Re-create pull subscriptions after NATS reconnect.
-
- After a NATS server restart, existing subscriptions may be invalid.
- This clears them and re-creates consumers for all known models.
- """
- # Unsubscribe stale subscriptions (best-effort)
- for sub in self._subscriptions.values():
- try:
- await sub.unsubscribe()
- except Exception: # noqa: BLE001
- logger.debug("Failed to unsubscribe during reconnect")
- self._subscriptions.clear()
-
- # Unsubscribe stale pool subscription (best-effort)
- if self._pool_sub is not None:
- try:
- await self._pool_sub.unsubscribe()
- except Exception: # noqa: BLE001
- logger.debug("Failed to unsubscribe old pool sub during reconnect")
- self._pool_sub = None
-
- if self._worker_pull_task is not None:
- self._worker_pull_task.cancel()
- with contextlib.suppress(asyncio.CancelledError):
- await self._worker_pull_task
- self._worker_pull_task = None
-
- # Also drop the per-worker subscription so the next
- # `_ensure_per_worker_subscription` call re-binds against the
- # new connection.
- if self._worker_sub is not None:
- try:
- await self._worker_sub.unsubscribe()
- except Exception: # noqa: BLE001
- logger.debug("Failed to unsubscribe old per-worker sub during reconnect")
- self._worker_sub = None
-
- self._refresh_generation_pool_flag()
-
- # Re-create the pool subscription
- await self._ensure_pool_subscription()
- if self._pool_hosts_generation_model():
- # Re-create the per-worker subscription (best-effort).
- try:
- await self._ensure_per_worker_subscription()
- except Exception: # noqa: BLE001
- logger.warning("Failed to re-create per-worker subscription on reconnect", exc_info=True)
- else:
- logger.info("Reconnect kept non-generation pool %s on pool-only delivery", self._pool_name)
-
- # Re-spawn the parallel pull task if needed.
- if (
- self._running
- and self._worker_sub is not None
- and (self._worker_pull_task is None or self._worker_pull_task.done())
- ):
- self._worker_pull_task = asyncio.create_task(self._run_worker_pull())
- logger.info("NatsPullLoop reconnected — re-created pool subscription")
-
- async def add_model(self, model_id: str) -> None:
- """Refresh transport wiring after a model is hot-added.
-
- The pool subscription already covers all encode / score /
- extract models. If the added model is the first generation
- model in this worker pool, create the per-worker
- direct-dispatch subscription now so hot reload preserves the
- same generation path as cold start.
- """
- if not self._running:
- return
-
- was_generation_pool = self._pool_hosts_generation_model()
- if not self._refresh_generation_pool_flag():
- return
-
- if self._worker_sub is None:
- try:
- await self._ensure_per_worker_subscription()
- except Exception:
- logger.exception(
- "Failed to create per-worker subscription after adding model %s (continuing with pool-only delivery)",
- model_id,
- )
-
- if not was_generation_pool:
- await self._rebind_pool_subscription(reason=f"first generation model added: {model_id}")
-
- if self._cancel_sub is None:
- await self._ensure_cancel_subscription()
-
- if self._worker_sub is not None and (self._worker_pull_task is None or self._worker_pull_task.done()):
- self._worker_pull_task = asyncio.create_task(self._run_worker_pull())
-
- # -- Pool-level multiplexed stream/consumer --------------------------------
-
- async def _migrate_per_model_streams(self) -> None:
- """Delete legacy per-model streams that overlap with the pool stream.
-
- The old design created ``WORK_{model_id}`` streams per model.
- The new pool-level stream ``WORK_POOL_{pool}`` uses ``sie.work.*.{pool}``
- which overlaps. NATS rejects streams with overlapping subjects, so we
- must clean up old streams before creating the pool stream.
- """
- model_ids = list(self._registry.model_names)
- deleted = 0
- for model_id in model_ids:
- stream_name = work_stream_name(model_id)
- try:
- await self._js.delete_stream(stream_name)
- deleted += 1
- except Exception: # noqa: BLE001, S110
- pass # Stream may not exist — that's fine
- if deleted:
- logger.info("Migrated: deleted %d legacy per-model streams", deleted)
-
- async def _ensure_pool_subscription(self) -> None:
- """Create the single pool-level stream and pull consumer.
-
- One stream captures ``sie.work.*.{pool}`` (all models for this pool).
- One durable consumer pulls from it. This replaces the old O(N-models)
- per-model subscription loop with a single fetch point.
- """
- stream_name = work_pool_stream_name(self._pool_name)
- subjects = work_pool_stream_subjects(self._pool_name)
- consumer_name = work_consumer_name(self._bundle_id, self._pool_name)
-
- config = StreamConfig(
- name=stream_name,
- subjects=subjects,
- retention=RetentionPolicy.WORK_QUEUE,
- max_age=_DEFAULT_STREAM_MAX_AGE_S,
- max_msgs=100_000,
- storage=StorageType.MEMORY,
- num_replicas=1,
- discard=DiscardPolicy.NEW,
- )
-
- try:
- await self._js.add_stream(config)
- logger.info(
- "Pool stream created/verified: %s (subjects=%s, max_age=%ds)",
- stream_name,
- subjects,
- _DEFAULT_STREAM_MAX_AGE_S,
- )
- except Exception:
- logger.exception("Failed to create pool stream: %s", stream_name)
- raise
-
- # Filter subject: all models for this pool
- filter_subject = f"{WORK_SUBJECT_PREFIX}.*.{self._pool_name}"
-
- # §4.4: extend ack_wait to 5 min if any model in this
- # pool declares a generate task. Per §4.3 generation pools are
- # isolated from embed/extract pools, so this is per-pool.
- ack_wait_s = _ACK_WAIT_S_GENERATION if self._pool_hosts_generation_model() else _ACK_WAIT_S
-
- consumer_config = ConsumerConfig(
- durable_name=consumer_name,
- filter_subject=filter_subject,
- ack_policy=AckPolicy.EXPLICIT,
- ack_wait=ack_wait_s,
- max_deliver=_MAX_DELIVER,
- max_ack_pending=1000,
- )
-
- try:
- sub = await self._js.pull_subscribe(
- subject=filter_subject,
- durable=consumer_name,
- stream=stream_name,
- config=consumer_config,
- )
- except nats.js.errors.BadRequestError:
- logger.warning(
- "Consumer %s config mismatch (likely max_deliver upgrade), recreating",
- consumer_name,
- )
- await self._js.delete_consumer(stream_name, consumer_name)
- sub = await self._js.pull_subscribe(
- subject=filter_subject,
- durable=consumer_name,
- stream=stream_name,
- config=consumer_config,
- )
- except Exception:
- logger.exception("Failed to create pool consumer: %s", consumer_name)
- raise
-
- self._pool_sub = sub
- logger.info(
- "Pool consumer created: %s on stream %s (filter=%s)",
- consumer_name,
- stream_name,
- filter_subject,
- )
-
- async def _rebind_pool_subscription(self, *, reason: str) -> None:
- """Recreate the pool consumer when generation settings change."""
- if self._pool_sub is not None:
- try:
- await self._pool_sub.unsubscribe()
- except Exception: # noqa: BLE001
- logger.debug("Failed to unsubscribe old pool sub during rebind")
- self._pool_sub = None
-
- await self._ensure_pool_subscription()
- logger.info("Pool consumer re-bound (%s)", reason)
-
- async def _ensure_per_worker_subscription(self) -> None:
- """Create the per-worker direct-dispatch stream and pull consumer.
-
- Subject pattern: ``sie.work.*.{pool}.{worker_id}`` — one
- additional token beyond the pool stream's three-token
- wildcard, so the two streams cannot double-deliver. Durable
- consumer name ``gen-{worker_id}`` per the routing spec; the
- worker_id must be stable across boots to avoid orphan
- durables (see ``NatsPullLoop.__init__`` for the resolution
- priority).
- """
- stream_name = work_worker_stream_name(self._worker_id)
- subjects = work_worker_stream_subjects(self._pool_name, self._worker_id)
- consumer_name = work_worker_consumer_name(self._worker_id)
- filter_subject = subjects[0]
-
- # Same retention/storage settings as the pool stream — the
- # per-worker stream sits on the same JetStream cluster and
- # carries the same item shape; only the addressing differs.
- config = StreamConfig(
- name=stream_name,
- subjects=subjects,
- retention=RetentionPolicy.WORK_QUEUE,
- max_age=_DEFAULT_STREAM_MAX_AGE_S,
- max_msgs=100_000,
- storage=StorageType.MEMORY,
- num_replicas=1,
- discard=DiscardPolicy.NEW,
- )
-
- try:
- await self._js.add_stream(config)
- logger.info(
- "Per-worker stream created/verified: %s (subjects=%s)",
- stream_name,
- subjects,
- )
- except Exception:
- logger.exception("Failed to create per-worker stream: %s", stream_name)
- raise
-
- ack_wait_s = _ACK_WAIT_S_GENERATION if self._pool_hosts_generation_model() else _ACK_WAIT_S
- consumer_config = ConsumerConfig(
- durable_name=consumer_name,
- filter_subject=filter_subject,
- ack_policy=AckPolicy.EXPLICIT,
- ack_wait=ack_wait_s,
- max_deliver=_MAX_DELIVER,
- max_ack_pending=1000,
- )
-
- try:
- sub = await self._js.pull_subscribe(
- subject=filter_subject,
- durable=consumer_name,
- stream=stream_name,
- config=consumer_config,
- )
- except nats.js.errors.BadRequestError:
- logger.warning(
- "Per-worker consumer %s config mismatch, recreating",
- consumer_name,
- )
- await self._js.delete_consumer(stream_name, consumer_name)
- sub = await self._js.pull_subscribe(
- subject=filter_subject,
- durable=consumer_name,
- stream=stream_name,
- config=consumer_config,
- )
- except Exception:
- logger.exception("Failed to create per-worker consumer: %s", consumer_name)
- raise
-
- self._worker_sub = sub
- logger.info(
- "Per-worker consumer created: %s on stream %s (filter=%s)",
- consumer_name,
- stream_name,
- filter_subject,
- )
-
- def _refresh_generation_pool_flag(self) -> bool:
- self._hosts_generation_model = self._detect_pool_hosts_generation_model()
- return self._hosts_generation_model
-
- def _pool_hosts_generation_model(self) -> bool:
- """Return whether this pool hosts generation models.
-
- The answer is cached because status heartbeats call the saturation
- path frequently. Startup, reconnect, and hot-add refresh the flag
- so normal status updates stay O(1) with respect to model count.
- """
- if self._hosts_generation_model is None:
- return self._refresh_generation_pool_flag()
- return self._hosts_generation_model
-
- def _detect_pool_hosts_generation_model(self) -> bool:
- """Detect whether any model in this pool declares a generate task.
-
- Used to pick the worker transport and the appropriate JetStream
- ``ack_wait`` (§4.4: long generations would exceed the default 30s
- window).
- """
- for model_id in self._registry.model_names:
- try:
- config = self._registry.get_config(model_id)
- except KeyError:
- continue
- tasks = getattr(config, "tasks", None)
- if tasks is not None and getattr(tasks, "generate", None) is not None:
- return True
- return False
-
- async def _prewarm_grammars(self) -> None:
- """Prewarm grammar caches for every generation model in the registry.
-
- Iterates the worker's loaded configs and invokes
- :meth:`StreamingProcessor.prewarm_grammars_for_model` on each
- generation config (the
- :func:`~sie_server.core.pool_isolation.is_generation_model` gate
- excludes encode/score/extract). Failures inside the processor
- are absorbed and surfaced via metrics; this loop never raises.
-
- Sequential rather than parallel because (a) prewarm is a one-shot
- boot-time operation, (b) the dedicated grammar executor only has
- 4 threads anyway, and (c) sequential keeps log lines clean for
- operators watching boot.
- """
- from sie_server.core.pool_isolation import is_generation_model # noqa: PLC0415
-
- for model_id in self._registry.model_names:
- try:
- config = self._registry.get_config(model_id)
- except KeyError:
- # Model removed between iteration start and lookup
- # (hot-reload race). Skip silently — the next reload
- # will re-attempt.
- continue
- if not is_generation_model(config):
- continue
- await self._streaming_processor.prewarm_grammars_for_model(model_id)
-
- async def _ensure_cancel_subscription(self) -> None:
- """Subscribe (core NATS) to ``cancel.>`` for streaming-generation cancels.
-
- The cancel path uses cluster-scope subscription with in-process
- request_id filtering: every worker hears every cancel signal but
- only acts on those whose request_id is currently in flight on
- this worker (via :meth:`StreamingProcessor.signal_cancel`).
-
- request_ids are globally unique UUIDs so the cluster-scope
- approach is correct without router_id discrimination. Spurious
- signals for someone else's request_id are dropped cheaply
- (DashMap lookup).
- """
- # Expected ``cancel.{router_id}.{request_id}`` → 3 tokens after split.
- _CANCEL_SUBJECT_TOKENS = 3
-
- async def _on_cancel(msg: Any) -> None:
- try:
- # We take the last token (everything after the second
- # dot) as the request_id and let the streaming processor
- # decide whether to act on it.
- subject = msg.subject
- parts = subject.split(".", 2)
- if len(parts) < _CANCEL_SUBJECT_TOKENS:
- return
- request_id = parts[2]
- matched = self._streaming_processor.signal_cancel(request_id)
- if matched:
- logger.info("Generation cancel signalled for %s", request_id)
- except Exception: # noqa: BLE001
- logger.debug("Failed to process cancel message", exc_info=True)
-
- try:
- self._cancel_sub = await self._nc.subscribe("cancel.>", cb=_on_cancel)
- logger.info("Subscribed to cancel.> for generation cancellation signals")
- except Exception: # noqa: BLE001
- logger.warning("Failed to subscribe to cancel.> — cancellation disabled", exc_info=True)
- self._cancel_sub = None
-
- def _get_batch_budget(self, model_id: str) -> int:
- """Get the batch budget for a model from its BatchConfig.
-
- Accesses ModelWorker._batch_config (private) — falls back to
- _DEFAULT_BATCH_BUDGET if unavailable.
- """
- try:
- worker = self._registry.get_worker(model_id)
- if worker is not None and hasattr(worker, "_batch_config"):
- return worker._batch_config.max_batch_requests
- except (KeyError, AttributeError):
- pass
- return _DEFAULT_BATCH_BUDGET
-
- @property
- def worker_id(self) -> str:
- """Stable worker identity used for the per-worker NATS subject
- and the JetStream durable consumer name. See ``__init__`` for
- the resolution order.
- """
- return self._worker_id
-
- def in_flight_count(self) -> int:
- """Current in-flight count for the pool's transport class.
-
- Generation pools count streaming requests; non-generation pools
- count fetched queue batches. Keeping those signals separate is
- important: the generation rollout added direct-dispatch state,
- but encode / score / extract still rely on the shared pool queue
- and must not report zero in-flight work just because no
- generation stream is active.
- """
- if self._pool_hosts_generation_model():
- return self._streaming_processor.in_flight_count()
- return len(self._in_flight_tasks)
-
- def aggregate_max_batch_requests(self) -> int:
- """Aggregate batch capacity across loaded models.
-
- The routing rollout uses ``in_flight / aggregate_max_batch_requests`` as
- the saturation fraction. We take the minimum across loaded
- models because the GPU batch is model-specific and the
- smallest capacity is the binding constraint — mirroring
- ``api.ws.build_status_message``.
- """
- # Snapshot `_loaded` to dodge `RuntimeError` from concurrent
- # mutation; same approach as `build_status_message`.
- loaded_snapshot = list(getattr(self._registry, "_loaded", {}).values())
- budgets = [
- w._batch_config.max_batch_requests
- for w in (lm.worker for lm in loaded_snapshot)
- if w is not None and hasattr(w, "_batch_config")
- ]
- if budgets:
- return min(budgets)
- return _DEFAULT_BATCH_BUDGET
-
- def update_saturation(self) -> bool:
- """Recompute the saturation flag from the current in-flight
- count and aggregate capacity, returning the new latched value.
-
- Idempotent. Callers (the WS status builder, the optional NATS
- health publisher, and the per-worker subscription gate) drive
- this on every status emission so the gate sees a steady
- stream of observations under load.
-
- Admission-control rollout: generation pools prefer the KV-budget
- signal (``kv_reserved / kv_budget``) regardless of whether
- admission is actually enabled — the budget is the right
- denominator for a generation worker's saturation, and the
- reserve counter is live whenever the streaming processor is
- wired in. Non-gen pools (no budget configured) fall back to the
- original ``in_flight / max_batch_requests`` fraction.
- """
- budget = self._effective_kv_budget()
- if budget is not None and budget > 0:
- return self._saturation_gate.update(
- in_flight=self._streaming_processor.kv_reserved_tokens(),
- capacity=budget,
- )
- return self._saturation_gate.update(
- in_flight=self.in_flight_count(),
- capacity=self.aggregate_max_batch_requests(),
- )
-
- def _effective_kv_budget(self) -> int | None:
- """Worker-wide KV budget for the saturation gate.
-
- The streaming processor resolves admission budgets *per request* and
- is never seeded with a worker-wide value, so its
- ``kv_budget_tokens`` property is ``None`` in production — which left
- the KV-budget saturation signal dead and silently falling back to
- the request-count fraction. Derive the budget here instead: the
- explicit processor override if one was injected, else the minimum
- ``kv_budget_tokens`` across loaded generation models (the binding
- constraint, mirroring :meth:`aggregate_max_batch_requests`). Returns
- ``None`` when no loaded generation model declares a budget, so
- non-generation pools keep using the request-count fraction.
- """
- explicit = self._streaming_processor.kv_budget_tokens
- if explicit is not None and explicit > 0:
- return explicit
- budgets: list[int] = []
- for model_id in self._registry.loaded_model_names:
- budget, _ = _resolve_generation_admission(self._registry, model_id)
- if budget is not None and budget > 0:
- budgets.append(budget)
- return min(budgets) if budgets else None
-
- @property
- def saturated(self) -> bool:
- """Latched saturation flag, without recomputing. Use
- :meth:`update_saturation` to refresh.
- """
- return self._saturation_gate.saturated
-
- def _check_config_hash(self, model_id: str, wi: WorkItem) -> bool:
- """Log-only soft check of bundle_config_hash — always returns True.
-
- Compares the hash from the work item against the local config.
- Mismatches are logged but do not reject the item, because hash
- computation differs between gateway and worker registries.
- """
- expected_hash = wi.get("bundle_config_hash")
- if not expected_hash:
- return True # No hash set — backward compatible
-
- # Use cached hash (recompute every _CONFIG_HASH_CACHE_TTL_S seconds)
- now = time.monotonic()
- if self._config_hash_cache is None or (now - self._config_hash_cache_time) > _CONFIG_HASH_CACHE_TTL_S:
- try:
- from sie_server.api.ws import _compute_bundle_config_hash # noqa: PLC0415
-
- self._config_hash_cache = _compute_bundle_config_hash(self._registry, self._bundle_id)
- self._config_hash_cache_time = now
- except Exception: # noqa: BLE001
- logger.debug("Could not compute config hash for validation", exc_info=True)
- return True
-
- if self._config_hash_cache and self._config_hash_cache != expected_hash:
- # Log-only: hash computation differs between gateway and worker
- # registries (different model filtering). Allow processing to
- # proceed — the hash is a soft check, not a hard gate. Still
- # record the mismatch on the dedicated counter so operators can
- # see drift even though items are not rejected.
- if _HAS_METRICS:
- PULL_CONFIG_HASH_MISMATCHES.labels(model=model_id).inc()
- logger.debug(
- "Config hash mismatch for %s (gateway=%s, worker=%s) — processing anyway",
- wi.get("work_item_id"),
- expected_hash[:8],
- self._config_hash_cache[:8],
- )
-
- return True
-
- def _extract_model_id(self, msg: Any) -> str | None:
- """Extract model_id from the NATS message subject.
-
- Subject format: ``sie.work.{normalized_model_id}.{pool_name}``
- We reverse the normalization to recover the original model_id.
- """
- subject = msg.subject # e.g., "sie.work.BAAI__bge-m3.l4"
- parts = subject.split(".")
- if len(parts) < _MIN_SUBJECT_PARTS:
- return None
- normalized = parts[2] # e.g., "BAAI__bge-m3"
- return denormalize_model_id(normalized)
-
- def _adaptive_fetch_timeout(self, current: float) -> float:
- """Adjust fetch timeout based on observed queue-path latency.
-
- Under load, when latency is below the target SLO, increase the
- timeout to allow more items to accumulate in the queue → bigger
- GPU batches → better throughput. When over SLO, decrease for
- faster pickup → lower latency at the cost of smaller batches.
-
- At idle (not enough samples), fall back to the static adaptive
- backoff (caller handles that case).
- """
- observed = self._queue_latency_tracker.p50()
- if observed is None:
- return _MIN_FETCH_TIMEOUT_S # Not enough samples — reset to minimum
-
- # Target: 50ms by default (matches EngineConfig default).
- # In production, this should be configurable per pool.
- target = float(os.environ.get("SIE_ADAPTIVE_TARGET_P50_MS", "50"))
-
- headroom_ms = target - observed
- gain = 0.2 # Conservative gain for fetch timeout
-
- # Convert headroom to a timeout adjustment:
- # +headroom → increase timeout (we can afford to wait → bigger batches)
- # -headroom → decrease timeout (over SLO → pick up faster)
- adjustment_s = headroom_ms * gain / 1000.0 # ms → seconds
- new_timeout = current + adjustment_s
- return max(_MIN_FETCH_TIMEOUT_S, min(_MAX_FETCH_TIMEOUT_S, new_timeout))
-
- async def _run(self) -> None:
- """Main pull loop — single-consumer multiplexed design.
-
- Pulls from the single pool-level consumer, groups messages by
- model_id (extracted from the NATS subject), and dispatches
- per-model batches for processing with fair scheduling.
-
- This eliminates the O(N-models) sequential scan of the old design.
- One ``fetch()`` call replaces 83+ per-model fetches.
-
- **Fair dispatch:** When a batch contains multiple models, each
- model's messages are capped at the model's batch budget. Excess
- messages are NAK'd for redelivery, preventing a hot model from
- monopolising the GPU.
-
- **Adaptive fetch timeout:** When the latency tracker has enough
- samples, the fetch timeout is adjusted based on observed p50 vs
- the target SLO. Under load with headroom, the timeout grows to
- allow item accumulation (throughput). Over SLO, it shrinks.
- At idle, static backoff applies (1ms → 20ms).
- """
- fetch_timeout = _MIN_FETCH_TIMEOUT_S
-
- while self._running:
- # Check completed background load tasks
- self._reap_load_tasks()
-
- if not await self._admission_gate.admitted():
- fetch_timeout = _MIN_FETCH_TIMEOUT_S
- await asyncio.sleep(self._admission_gate.pause_s)
- continue
-
- pool_sub = self._pool_sub
- if pool_sub is None:
- fetch_timeout = _MIN_FETCH_TIMEOUT_S
- await asyncio.sleep(fetch_timeout)
- continue
-
- try:
- messages = await pool_sub.fetch(batch=_DEFAULT_BATCH_BUDGET, timeout=fetch_timeout)
- except nats.errors.TimeoutError:
- # No items — back off
- fetch_timeout = min(fetch_timeout * _BACKOFF_GROWTH, _MAX_FETCH_TIMEOUT_S)
- continue
- except Exception: # noqa: BLE001
- logger.warning("Pool pull error", exc_info=True)
- fetch_timeout = min(fetch_timeout * _BACKOFF_GROWTH, _MAX_FETCH_TIMEOUT_S)
- await asyncio.sleep(fetch_timeout)
- continue
-
- if not messages:
- fetch_timeout = min(fetch_timeout * _BACKOFF_GROWTH, _MAX_FETCH_TIMEOUT_S)
- continue
-
- # Adjust fetch timeout — use adaptive controller if we have
- # enough latency samples, otherwise reset to minimum.
- fetch_timeout = self._adaptive_fetch_timeout(fetch_timeout)
-
- await self._dispatch_batch(messages)
-
- async def _dispatch_batch(self, messages: list[Any]) -> None:
- """Group a fetched batch by model_id and dispatch via
- :meth:`_process_messages`.
-
- Shared by the pool pull loop (:meth:`_run`) and the
- per-worker pull loop (:meth:`_run_worker_pull`). Behaviour
- identical to the original inline body: model-not-loaded
- triggers a NAK + background load; over-budget batches NAK the
- overflow for re-delivery; the per-batch GPU dispatch is
- serialised through ``_batch_sem``.
- """
- # Group messages by model_id (extracted from subject)
- model_groups: dict[str, list[Any]] = {}
- for msg in messages:
- model_id = self._extract_model_id(msg)
- if model_id is None:
- logger.warning("Could not extract model_id from subject: %s", msg.subject)
- try:
- await msg.nak()
- except Exception: # noqa: BLE001, S110
- pass
- continue
- model_groups.setdefault(model_id, []).append(msg)
-
- # Fair dispatch: round-robin across models, capping per-model batch
- for model_id, model_msgs in model_groups.items():
- # Skip models currently loading — NAK for redelivery
- if model_id in self._loading_models:
- for m in model_msgs:
- try:
- await m.nak(delay=_NAK_DELAY_S)
- except Exception: # noqa: BLE001, S110
- pass
- continue
-
- # Check if model is loaded
- if not self._registry.is_loaded(model_id):
- await self._handle_unloaded_model(model_id, model_msgs)
- continue
-
- # Apply per-model batch cap for fairness. If more messages
- # arrived than the model's batch budget, NAK the excess so
- # they are redelivered (possibly to another worker).
- budget = self._get_batch_budget(model_id)
- dispatch_msgs = model_msgs[:budget]
- overflow = model_msgs[budget:]
- for m in overflow:
- try:
- await m.nak(delay=0.1) # fast redeliver
- except Exception: # noqa: BLE001, S110
- pass
-
- if _HAS_METRICS:
- PULL_ITEMS_FETCHED.labels(model=model_id).observe(len(dispatch_msgs))
-
- # Limit concurrent batch processing
- await self._batch_sem.acquire()
-
- async def _guarded_process(msgs: list[Any], mdl: str) -> None:
- try:
- await self._process_messages(mdl, msgs)
- finally:
- self._batch_sem.release()
-
- task = asyncio.create_task(_guarded_process(dispatch_msgs, model_id))
- self._in_flight_tasks.add(task)
- task.add_done_callback(self._in_flight_tasks.discard)
-
- async def _run_worker_pull(self) -> None:
- """Parallel pull loop for the per-worker direct-dispatch stream.
-
- Identical batching/dispatch semantics to :meth:`_run`, but
- sources messages from :attr:`_worker_sub` (filter
- ``sie.work.*.{pool}.{worker_id}``). Both loops share
- ``_batch_sem`` so the worker's GPU is the global concurrency
- limit, not "GPU × 2".
- """
- worker_sub = self._worker_sub
- if worker_sub is None:
- logger.debug("Per-worker pull loop requested without a subscription; exiting")
- return
-
- fetch_timeout = _MIN_FETCH_TIMEOUT_S
- while self._running:
- try:
- messages = await worker_sub.fetch(batch=_DEFAULT_BATCH_BUDGET, timeout=fetch_timeout)
- except nats.errors.TimeoutError:
- fetch_timeout = min(fetch_timeout * _BACKOFF_GROWTH, _MAX_FETCH_TIMEOUT_S)
- continue
- except Exception: # noqa: BLE001
- logger.warning("Per-worker pull error", exc_info=True)
- fetch_timeout = min(fetch_timeout * _BACKOFF_GROWTH, _MAX_FETCH_TIMEOUT_S)
- await asyncio.sleep(fetch_timeout)
- continue
-
- if not messages:
- fetch_timeout = min(fetch_timeout * _BACKOFF_GROWTH, _MAX_FETCH_TIMEOUT_S)
- continue
-
- fetch_timeout = self._adaptive_fetch_timeout(fetch_timeout)
- await self._dispatch_batch(messages)
-
- def _reap_load_tasks(self) -> None:
- """Check completed background load tasks and clean up state."""
- for model_id in list(self._load_tasks):
- task = self._load_tasks[model_id]
- if not task.done():
- continue
-
- self._loading_models.discard(model_id)
- del self._load_tasks[model_id]
-
- try:
- exc = task.exception()
- except asyncio.CancelledError:
- logger.debug("Background model load cancelled for %s", model_id)
- continue
- if exc is not None:
- logger.warning("Background model load failed for %s: %s", model_id, exc)
- else:
- logger.info("Model %s loaded via background demand, now pulling", model_id)
-
- async def _handle_unloaded_model(self, model_id: str, messages: list[Any]) -> None:
- """Handle items pulled for a model that isn't loaded yet.
-
- NAKs all items with a delay so JetStream redelivers them after
- the model has had time to load. Triggers a background load if
- one isn't already in progress.
-
- Uses a longer NAK delay when a load is already in progress to
- conserve the delivery budget (max_deliver) for slow model loads.
- """
- already_loading = model_id in self._loading_models
- nak_delay = _NAK_DELAY_S * 2 if already_loading else _NAK_DELAY_S
-
- for msg in messages:
- try:
- await msg.nak(delay=nak_delay)
- except Exception: # noqa: BLE001
- logger.debug("Failed to NAK message for unloaded model %s", model_id)
-
- if _HAS_METRICS:
- PULL_NAK_UNLOADED.labels(model=model_id).inc(len(messages))
-
- logger.info(
- "NAKed %d items for unloaded model %s (redeliver in %.0fs, loading=%s)",
- len(messages),
- model_id,
- nak_delay,
- already_loading,
- )
-
- # Trigger background load if not already in progress
- if model_id not in self._loading_models:
- self._check_thrashing(model_id)
- self._loading_models.add(model_id)
- load_task = asyncio.create_task(self._background_load_model(model_id))
- self._load_tasks[model_id] = load_task
-
- if _HAS_METRICS:
- PULL_MODEL_LOADS.labels(model=model_id).inc()
-
- logger.info("Triggered background load for model %s", model_id)
-
- async def _background_load_model(self, model_id: str) -> None:
- """Load a model in the background without blocking the pull loop.
-
- ``registry.load_async()`` serializes loads via an internal lock,
- runs the actual GPU loading in a thread pool, and may evict LRU
- models to free memory. If the evicted model was being served,
- the pull loop will discover ``is_loaded() == False`` on the next
- iteration and NAK its items — no race condition.
- """
- try:
- device = self._registry.device
- await self._registry.load_async(model_id, device)
- self._load_history.append((model_id, time.monotonic()))
- except Exception:
- logger.warning("Background load failed for model %s", model_id, exc_info=True)
- self._loading_models.discard(model_id)
- raise
-
- def _check_thrashing(self, model_id: str) -> None:
- """Detect and warn about model load/evict thrashing.
-
- If any model has been background-loaded ``_THRASH_THRESHOLD`` or
- more times within ``_THRASH_WINDOW_S``, log a warning. This
- indicates the GPU cannot hold all in-demand models simultaneously
- and the operator should use separate bundles or add GPU capacity.
- """
- now = time.monotonic()
- cutoff = now - _THRASH_WINDOW_S
-
- # Prune old entries
- self._load_history = [(m, t) for m, t in self._load_history if t > cutoff]
-
- # Count recent loads for this model
- recent = sum(1 for m, _ in self._load_history if m == model_id)
- if recent >= _THRASH_THRESHOLD:
- logger.warning(
- "Model thrashing detected: %s loaded %d times in the last %.0fs. "
- "GPU memory cannot hold all in-demand models simultaneously. "
- "Consider using separate bundles per model or adding GPU capacity.",
- model_id,
- recent,
- _THRASH_WINDOW_S,
- )
-
- async def _process_messages(self, model_id: str, messages: list[Any]) -> None:
- """Process a batch of pulled NATS messages for a model.
-
- Groups encode/extract items into batches for optimal GPU utilization.
- Score items are submitted concurrently for cross-request batching.
- """
- work_items: list[tuple[WorkItem, Any]] = [] # (work_item, nats_msg)
-
- for msg in messages:
- try:
- wi: WorkItem = msgpack.unpackb(msg.data, raw=False)
- # Validate reply_subject to prevent injection attacks.
- # Only accept subjects under the _INBOX prefix.
- reply_subj = wi.get("reply_subject", "")
- if reply_subj and not reply_subj.startswith("_INBOX."):
- logger.warning(
- "Rejecting work item with suspicious reply_subject=%r "
- "model_id=%r bundle_id=%r request_id=%r subject=%r",
- reply_subj[:60],
- wi.get("model_id"),
- wi.get("bundle_id"),
- wi.get("request_id"),
- getattr(msg, "subject", None),
- )
- await msg.ack() # Consume to prevent redelivery
- continue
- work_items.append((wi, msg))
- except Exception: # noqa: BLE001
- logger.warning("Failed to deserialize work item", exc_info=True)
- await msg.nak()
-
- if not work_items:
- return
-
- # Record queue wait times
- if _HAS_METRICS:
- for wi, _ in work_items:
- queue_wait_s = time.time() - wi.get("timestamp", time.time())
- if queue_wait_s > 0:
- PULL_QUEUE_WAIT_SECONDS.labels(model=model_id).observe(queue_wait_s)
-
- # Validate bundle_config_hash — log-only soft check (never NAKs)
- for wi, _ in work_items:
- self._check_config_hash(model_id, wi)
- valid_items = work_items
-
- if not valid_items:
- return
-
- # Group by operation for batch processing. Generate items go through
- # the ``MessageProcessor`` seam (one task per message) — they don't
- # batch on the GPU side (SGLang does continuous batching internally)
- # and they hold a worker slot for longer than embedding/extract.
- encode_items: list[tuple[WorkItem, Any]] = []
- score_items: list[tuple[WorkItem, Any]] = []
- extract_items: list[tuple[WorkItem, Any]] = []
- generate_items: list[tuple[WorkItem, Any]] = []
-
- for wi, msg in valid_items:
- op = wi.get("operation", "encode")
- if op == "encode":
- encode_items.append((wi, msg))
- elif op == "score":
- score_items.append((wi, msg))
- elif op == "extract":
- extract_items.append((wi, msg))
- elif op == "generate":
- generate_items.append((wi, msg))
- else:
- logger.warning("Unknown operation %s for %s", op, wi.get("work_item_id"))
- await self._publish_error(wi, "unknown_operation", f"Unknown operation: {op}")
- await msg.ack()
-
- # Process batches concurrently
- tasks: list[Any] = []
- if encode_items:
- tasks.append(self._run_in_class_slot("encode", self._process_encode_batch(model_id, encode_items)))
- if score_items:
- # Score items submitted concurrently for BatchFormer cross-request batching
- tasks.append(self._run_in_class_slot("score", self._process_score_batch(model_id, score_items)))
- if extract_items:
- tasks.append(self._run_in_class_slot("extract", self._process_extract_batch(model_id, extract_items)))
- if generate_items:
- # Generation slots are acquired per-stream inside
- # ``_guarded_generate_process`` (each stream is its own task), not
- # here — the batch only *dispatches* generate streams.
- tasks.append(self._process_generate_items(model_id, generate_items))
-
- await asyncio.gather(*tasks)
-
- async def _process_generate_items(self, model_id: str, items_msgs: list[tuple[WorkItem, Any]]) -> None:
- """Dispatch generate work items through the StreamingProcessor seam.
-
- One concurrent task per message: generation is intentionally
- unbatched at this layer (SGLang batches internally).
-
- H2 fix — decouple generation from ``_batch_sem``. Previously this
- method ``await``ed the streams to completion, which (because the
- caller holds ``_batch_sem`` for the whole ``_process_messages``
- body) pinned a GPU-batch slot for each stream's entire lifetime.
- With ``_MAX_CONCURRENT_BATCHES=4`` that capped the worker at 4
- concurrent generations regardless of how much KV budget was free,
- and starved the per-worker direct-dispatch path of slots.
-
- Instead each stream is launched as an independent tracked task and
- this method returns immediately. ``_batch_sem`` is therefore
- released once the batch is *dispatched* (when ``_process_messages``
- returns), NOT when the streams finish. Generation concurrency is
- bounded by the KV-budget admission gate inside
- :class:`StreamingProcessor` (``_try_reserve`` /
- ``reason="kv_budget"`` NAK), which is the intended backpressure.
-
- Safety: ``StreamingProcessor.process`` owns its whole lifecycle —
- per-message JetStream ``in_progress()`` heartbeats, terminal
- publish, and ACK/NAK all happen inside it. So a fire-and-forget
- task does not drop acks or heartbeats. The embedding / score /
- extract paths are untouched (they still run synchronously under
- ``_batch_sem`` because they DO contend for the GPU as a batch).
- Tasks are tracked in ``_in_flight_generate_tasks`` for graceful
- drain on :meth:`stop`.
-
- BUG 3 — guarded dispatch. ``process`` only catches the
- ``msgpack.unpackb`` decode; ANY other exception (model load race,
- publish failure, a bug) escapes the fire-and-forget task. Without a
- guard that left the JetStream message unsettled (→ redelivery storm
- + KV-budget leak via the Bug 2/7 path) AND surfaced as an
- unobserved-task-exception. Wrap the coroutine so an unexpected
- exception is logged with context, counted, and NAKs the message for
- redelivery — mirroring the batch path's ``_guarded_process`` spirit.
- """
- for _, msg in items_msgs:
- task = asyncio.create_task(self._guarded_generate_process(msg, model_id))
- self._in_flight_generate_tasks.add(task)
- task.add_done_callback(self._in_flight_generate_tasks.discard)
-
- @contextlib.asynccontextmanager
- async def _class_slot(self, op: str) -> AsyncIterator[None]:
- """Hold a work-class scheduler slot for the wrapped work, when the
- opt-in fairness scheduler is enabled; a no-op pass-through otherwise.
-
- One slot == one in-flight unit of GPU work (a generation stream or a
- batch). The slot is released on exit (including on exception) by the
- scheduler's lease, so a crash never leaks a slot.
- """
- if self._scheduler is None:
- yield
- return
- async with self._scheduler.lease(classify_work_class(op)):
- yield
-
- async def _run_in_class_slot(self, op: str, coro: Awaitable[None]) -> None:
- """Await ``coro`` while holding its work-class slot (no-op when the
- fairness scheduler is disabled).
- """
- async with self._class_slot(op):
- await coro
-
- async def _guarded_generate_process(self, msg: Any, model_id: str) -> None:
- """Run ``StreamingProcessor.process`` with a top-level exception guard.
-
- ``process`` settles the message itself on every *expected* path. This
- guard is the safety net for the *unexpected*: it ensures an escaped
- exception is observed (logged + metric) and the message is NAK'd for
- redelivery rather than left in-flight forever (BUG 3).
- """
- try:
- async with self._class_slot("generate"):
- await self._streaming_processor.process(msg, model_id)
- except Exception:
- logger.exception(
- "Unhandled exception in StreamingProcessor.process for model %s; NAKing for redelivery",
- model_id,
- )
- if _HAS_METRICS:
- PULL_GENERATE_DISPATCH_ERRORS.labels(model=model_id).inc()
- try:
- await msg.nak(delay=_NAK_DELAY_S)
- except Exception: # noqa: BLE001
- logger.debug("Failed to NAK generate msg after unhandled process exception")
-
- async def _process_encode_batch(self, model_id: str, items_msgs: list[tuple[WorkItem, Any]]) -> None:
- """Process a batch of encode work items through EncodePipeline."""
- from sie_server.core.encode_pipeline import EncodePipeline # noqa: PLC0415
-
- batch_start = time.monotonic()
-
- # Resolve all item payloads (with fetch timing)
- resolved: list[tuple[WorkItem, Any, Item, float]] = [] # (..., payload_fetch_ms)
- for wi, msg in items_msgs:
- fetch_start = time.monotonic()
- item = await self._resolve_item(wi)
- fetch_ms = (time.monotonic() - fetch_start) * 1000 if wi.get("payload_ref") else 0.0
- if item is None:
- await self._publish_error(wi, "payload_error", "Failed to resolve item payload")
- await msg.ack()
- continue
- resolved.append((wi, msg, item, fetch_ms))
-
- if not resolved:
- return
-
- try:
- config = self._registry.get_config(model_id)
- except KeyError:
- # Model config not found or model evicted mid-batch — NAK for redelivery.
- # Another worker (or this one after re-loading) will process them.
- for wi, msg, _, _fm in resolved:
- try:
- await msg.nak(delay=_NAK_DELAY_S)
- except Exception: # noqa: BLE001
- logger.debug("Failed to NAK message for evicted model %s", model_id)
- return
-
- # Group items by encode params to handle heterogeneous batches.
- # Items from different API requests may have different output_types,
- # instruction, is_query, or options — these cannot be mixed in a
- # single EncodePipeline.run_encode() call.
- groups: dict[tuple, list[tuple[WorkItem, Any, Item, float]]] = {}
- for wi, msg, item, fetch_ms in resolved:
- output_types = tuple(wi.get("output_types") or ["dense"])
- instruction = wi.get("instruction")
- is_query = wi.get("is_query", False)
- # options dict is not hashable — use sorted tuple of items
- options = wi.get("options") or {}
- options_key = msgpack.packb(options, use_bin_type=True) if options else b""
- key = (output_types, instruction, is_query, options_key)
- groups.setdefault(key, []).append((wi, msg, item, fetch_ms))
-
- # Process each sub-batch
- for (output_types_t, instruction, is_query, options_key), group in groups.items():
- output_types = list(output_types_t)
- options = msgpack.unpackb(options_key, raw=False) if options_key else {}
- all_items = [item for _, _, item, _ in group]
- queue_times = [(time.time() - wi.get("timestamp", time.time())) * 1000 for wi, _, _, _ in group]
- fetch_times = [fm for _, _, _, fm in group]
-
- try:
- formatted_outputs, timing = await EncodePipeline.run_encode(
- registry=self._registry,
- model=model_id,
- items=all_items,
- output_types=output_types,
- instruction=instruction,
- config=config,
- is_query=is_query,
- options=options,
- )
-
- for idx, (wi, msg, _, _fm) in enumerate(group):
- output = formatted_outputs[idx] if idx < len(formatted_outputs) else {}
- # Wrap raw numpy arrays in the DenseVector/SparseVector wire
- # format that the SDK client expects:
- # dense → {"dims": N, "dtype": str, "values": ndarray}
- # sparse → {"indices": ndarray, "values": ndarray}
- # This matches ``encode.py:_build_response_items`` on the HTTP path.
- output = _wrap_encode_output(output, config)
- result_data = msgpack.packb(output, use_bin_type=True)
- reply_subject = wi.get("reply_subject", "")
- if reply_subject:
- result: WorkResult = {
- "work_item_id": wi.get("work_item_id", ""),
- "request_id": wi.get("request_id", ""),
- "item_index": wi.get("item_index", 0),
- "success": True,
- "result_msgpack": result_data,
- "queue_ms": queue_times[idx],
- "processing_ms": 0.0,
- "worker_id": self._worker_id,
- }
- if timing.inference_ms is not None:
- result["inference_ms"] = timing.inference_ms
- if timing.tokenization_ms > 0:
- result["tokenization_ms"] = timing.tokenization_ms
- if timing.postprocessing_ms > 0:
- result["postprocessing_ms"] = timing.postprocessing_ms
- result["payload_fetch_ms"] = fetch_times[idx]
- result_bytes = msgpack.packb(result, use_bin_type=True)
- try:
- await self._nc.publish(reply_subject, result_bytes)
- except Exception: # noqa: BLE001
- logger.warning("Failed to publish result for %s", wi.get("work_item_id"), exc_info=True)
- continue # Don't ACK — let JetStream redeliver
-
- # Feed adaptive latency tracker: total queue-path
- # latency = queue wait + inference + postprocessing.
- total_ms = queue_times[idx] + (timing.inference_ms or 0) + timing.postprocessing_ms
- self._queue_latency_tracker.record(total_ms)
-
- await msg.ack()
-
- except asyncio.CancelledError:
- # Worker was evicted (model unloaded) mid-batch — NAK for redelivery
- logger.info("Encode batch cancelled (model %s likely evicted) — NAKing items", model_id)
- for wi, msg, _, _fm in group:
- try:
- await msg.nak(delay=_NAK_DELAY_S)
- except Exception: # noqa: BLE001
- logger.debug("Failed to NAK message for evicted model %s", model_id)
- except Exception as e: # noqa: BLE001
- code, msg_text = self._classify_inference_exception(e)
- logger.warning(
- "Encode sub-batch failed for model %s (code=%s): %s",
- model_id,
- code,
- e,
- )
- # For non-retryable codes: publish the error result to the
- # gateway's reply subject and ACK the JetStream message —
- # redelivering would just reproduce the same failure.
- #
- # For RESOURCE_EXHAUSTED: skip ``_publish_error`` and only
- # NAK so JetStream can redeliver the work item to a sibling
- # worker (or this worker after memory clears). Publishing
- # the error here would fill the gateway's per-item slot and
- # complete the request immediately, dropping the redelivered
- # work on arrival (the gateway's inbox handler discards
- # replies whose ``request_id`` is no longer pending). The
- # caller still sees a 503 RESOURCE_EXHAUSTED — the gateway
- # synthesises one from result-await timeouts — and the SDK
- # auto-retries; the NAK simply gives non-retrying clients
- # (``max_oom_retries=0``) a real second attempt instead of
- # the wasted compute the previous "publish + NAK"
- # combination produced.
- is_resource_exhausted = code == ErrorCode.RESOURCE_EXHAUSTED.value
- for wi, msg, _, _fm in group:
- if not is_resource_exhausted:
- await self._publish_error(wi, code, msg_text)
- await self._ack_or_nak_after_error(msg, code)
-
- if _HAS_METRICS:
- elapsed = time.monotonic() - batch_start
- PULL_BATCH_PROCESS_SECONDS.labels(model=model_id, operation="encode").observe(elapsed)
-
- async def _process_score_batch(self, model_id: str, items_msgs: list[tuple[WorkItem, Any]]) -> None:
- """Process score items concurrently for BatchFormer cross-request batching."""
- batch_start = time.monotonic()
-
- async def _process_one(wi: WorkItem, msg: Any) -> None:
- try:
- await self._process_single_score(model_id, wi, msg)
- except Exception: # noqa: BLE001
- logger.warning("Score failed for %s", wi.get("work_item_id"), exc_info=True)
- try:
- await self._publish_error(wi, "internal_error", "Unexpected processing failure")
- except Exception: # noqa: BLE001
- logger.debug("Failed to publish error result for %s", wi.get("work_item_id"))
- try:
- await msg.ack()
- except Exception: # noqa: BLE001
- logger.debug("Failed to ACK message for %s", wi.get("work_item_id"))
-
- await asyncio.gather(*(_process_one(wi, msg) for wi, msg in items_msgs))
-
- if _HAS_METRICS:
- elapsed = time.monotonic() - batch_start
- PULL_BATCH_PROCESS_SECONDS.labels(model=model_id, operation="score").observe(elapsed)
-
- async def _process_extract_batch(self, model_id: str, items_msgs: list[tuple[WorkItem, Any]]) -> None:
- """Process extract items individually but concurrently."""
- batch_start = time.monotonic()
-
- # Extract items go through worker.submit_extract individually
- # but concurrent submission lets BatchFormer batch them
- async def _process_one(wi: WorkItem, msg: Any) -> None:
- try:
- fetch_start = time.monotonic()
- item = await self._resolve_item(wi)
- fetch_ms = (time.monotonic() - fetch_start) * 1000 if wi.get("payload_ref") else 0.0
- if item is None:
- await self._publish_error(wi, "payload_error", "Failed to resolve item payload")
- await msg.ack()
- return
- await self._process_single_extract(model_id, wi, msg, item, fetch_ms)
- except Exception: # noqa: BLE001
- logger.warning("Extract failed for %s", wi.get("work_item_id"), exc_info=True)
- try:
- await self._publish_error(wi, "internal_error", "Unexpected processing failure")
- except Exception: # noqa: BLE001
- logger.debug("Failed to publish error result for %s", wi.get("work_item_id"))
- try:
- await msg.ack()
- except Exception: # noqa: BLE001
- logger.debug("Failed to ACK message for %s", wi.get("work_item_id"))
-
- await asyncio.gather(*(_process_one(wi, msg) for wi, msg in items_msgs))
-
- if _HAS_METRICS:
- elapsed = time.monotonic() - batch_start
- PULL_BATCH_PROCESS_SECONDS.labels(model=model_id, operation="extract").observe(elapsed)
-
- async def _process_single_score(
- self,
- model_id: str,
- wi: WorkItem,
- msg: Any,
- ) -> None:
- """Run the score pipeline for a single item, ACK, and publish result."""
- queue_ms = (time.time() - wi.get("timestamp", time.time())) * 1000
-
- # Start the model worker (lazy loading)
- try:
- worker = await self._registry.start_worker(model_id)
- except (KeyError, RuntimeError) as e:
- logger.info("Model %s not available for score: %s — NAKing", model_id, e)
- await msg.nak(delay=_NAK_DELAY_S)
- return
-
- query = wi.get("query_item")
- items = wi.get("score_items")
-
- # Resolve offloaded score payload
- payload_fetch_ms = 0.0
- if query is None and wi.get("query_payload_ref"):
- ref_key: str = wi["query_payload_ref"] # type: ignore
- fetch_start = time.monotonic()
- payload_data = await self._fetch_payload(ref_key)
- payload_fetch_ms = (time.monotonic() - fetch_start) * 1000
- if payload_data:
- decoded = msgpack.unpackb(payload_data, raw=False)
- query = decoded.get("query")
- items = decoded.get("items")
-
- if query is None or items is None:
- await self._publish_error(wi, "payload_error", "Missing query or items for score")
- await msg.ack()
- return
-
- query_item = self._dict_to_item(query) if isinstance(query, dict) else query
- score_items = [self._dict_to_item(it) if isinstance(it, dict) else it for it in items]
-
- instruction = wi.get("instruction")
- options = wi.get("options") or {}
-
- try:
- timing = RequestTiming()
-
- # Build prepared items with cost (query + doc char count)
- query_text = query_item.text
- query_len = len(query_text) if query_text else 0
- timing.start_tokenization()
- prepared_items = []
- for i, it in enumerate(score_items):
- item_text = it.text
- doc_len = len(item_text) if item_text else 0
- prepared_items.append(ScorePreparedItem(cost=query_len + doc_len, original_index=i))
- timing.end_tokenization()
-
- # Submit to worker and await result
- future = await worker.submit_score(
- prepared_items=prepared_items,
- query=query_item,
- items=score_items,
- instruction=instruction,
- options=options,
- timing=timing,
- )
- worker_result = await future
-
- # Extract scores and build ranked ScoreEntry list.
- # The gateway wraps this in {"model": ..., "items": <blob>}, so
- # result_data must be the scores list, not a full ScoreResponse.
- score_output: ScoreOutput = worker_result.output # type: ignore
- raw_scores = [float(score_output.scores[i]) for i in range(score_output.batch_size)]
-
- scored_items = []
- for i, sc in enumerate(raw_scores):
- item_id = score_items[i].id if score_items[i].id is not None else f"item-{i}"
- scored_items.append((item_id, sc))
- scored_items.sort(key=lambda x: x[1], reverse=True)
-
- score_entries = [
- {"item_id": item_id, "score": sc, "rank": rank} for rank, (item_id, sc) in enumerate(scored_items)
- ]
- result_data = msgpack.packb(score_entries, use_bin_type=True)
- inference_ms = timing.inference_ms
- except Exception as e: # noqa: BLE001
- code, msg_text = self._classify_inference_exception(e)
- logger.warning(
- "Score failed for %s (code=%s): %s",
- wi.get("work_item_id"),
- code,
- e,
- )
- # See ``_process_encode_group`` for the rationale: for
- # ``RESOURCE_EXHAUSTED`` we skip ``_publish_error`` and only NAK so
- # JetStream can redeliver to a sibling worker, leaving the
- # gateway's per-item slot free for the retry.
- if code != ErrorCode.RESOURCE_EXHAUSTED.value:
- await self._publish_error(wi, code, msg_text)
- await self._ack_or_nak_after_error(msg, code)
- return
-
- # Publish result
- reply_subject = wi.get("reply_subject", "")
- if reply_subject and result_data is not None:
- result: WorkResult = {
- "work_item_id": wi.get("work_item_id", ""),
- "request_id": wi.get("request_id", ""),
- "item_index": wi.get("item_index", 0),
- "success": True,
- "result_msgpack": result_data,
- "queue_ms": queue_ms,
- "processing_ms": 0.0,
- "worker_id": self._worker_id,
- }
- if inference_ms is not None:
- result["inference_ms"] = inference_ms
- if timing.tokenization_ms > 0:
- result["tokenization_ms"] = timing.tokenization_ms
- if timing.postprocessing_ms > 0:
- result["postprocessing_ms"] = timing.postprocessing_ms
- if payload_fetch_ms > 0:
- result["payload_fetch_ms"] = payload_fetch_ms
- result_bytes = msgpack.packb(result, use_bin_type=True)
- try:
- await self._nc.publish(reply_subject, result_bytes)
- except Exception: # noqa: BLE001
- logger.warning("Failed to publish result for %s", wi.get("work_item_id"), exc_info=True)
- return # Don't ACK — let JetStream redeliver
-
- await msg.ack()
-
- async def _process_single_extract(
- self,
- model_id: str,
- wi: WorkItem,
- msg: Any,
- item: Item,
- payload_fetch_ms: float = 0.0,
- ) -> None:
- """Run the extract pipeline for a single item, ACK, and publish result."""
- queue_ms = (time.time() - wi.get("timestamp", time.time())) * 1000
-
- # Start the model worker (lazy loading)
- try:
- worker = await self._registry.start_worker(model_id)
- except (KeyError, RuntimeError) as e:
- logger.info("Model %s not available for extract: %s — NAKing", model_id, e)
- await msg.nak(delay=_NAK_DELAY_S)
- return
-
- labels = wi.get("labels")
- output_schema = wi.get("output_schema")
- instruction = wi.get("instruction")
- options = wi.get("options") or {}
-
- try:
- timing = RequestTiming()
-
- # Build prepared items with cost (character count for text, byte size for documents)
- timing.start_tokenization()
- prepared_items = build_extract_prepared_items([item])
- timing.end_tokenization()
-
- # Submit to worker and await result
- future = await worker.submit_extract(
- prepared_items=prepared_items,
- items=[item],
- labels=labels,
- output_schema=output_schema,
- instruction=instruction,
- options=options,
- timing=timing,
- )
- worker_result = await future
-
- # Format output using ExtractHandler (matches api/extract.py)
- extraction_results = ExtractHandler.format_output(worker_result.output) # type: ignore
- result_data = msgpack.packb(extraction_results[0] if extraction_results else {}, use_bin_type=True)
- inference_ms = timing.inference_ms
- except Exception as e: # noqa: BLE001
- code, msg_text = self._classify_inference_exception(e)
- logger.warning(
- "Extract failed for %s (code=%s): %s",
- wi.get("work_item_id"),
- code,
- e,
- )
- # See ``_process_encode_group`` for the rationale: for
- # ``RESOURCE_EXHAUSTED`` we skip ``_publish_error`` and only NAK so
- # JetStream can redeliver to a sibling worker, leaving the
- # gateway's per-item slot free for the retry.
- if code != ErrorCode.RESOURCE_EXHAUSTED.value:
- await self._publish_error(wi, code, msg_text)
- await self._ack_or_nak_after_error(msg, code)
- return
-
- # Publish result
- reply_subject = wi.get("reply_subject", "")
- if reply_subject and result_data is not None:
- result: WorkResult = {
- "work_item_id": wi.get("work_item_id", ""),
- "request_id": wi.get("request_id", ""),
- "item_index": wi.get("item_index", 0),
- "success": True,
- "result_msgpack": result_data,
- "queue_ms": queue_ms,
- "processing_ms": 0.0,
- "worker_id": self._worker_id,
- }
- if inference_ms is not None:
- result["inference_ms"] = inference_ms
- if timing.tokenization_ms > 0:
- result["tokenization_ms"] = timing.tokenization_ms
- if timing.postprocessing_ms > 0:
- result["postprocessing_ms"] = timing.postprocessing_ms
- if payload_fetch_ms > 0:
- result["payload_fetch_ms"] = payload_fetch_ms
- result_bytes = msgpack.packb(result, use_bin_type=True)
- try:
- await self._nc.publish(reply_subject, result_bytes)
- except Exception: # noqa: BLE001
- logger.warning("Failed to publish result for %s", wi.get("work_item_id"), exc_info=True)
- return # Don't ACK — let JetStream redeliver
-
- await msg.ack()
-
- async def _resolve_item(self, wi: WorkItem) -> Item | None:
- """Resolve a work item's payload (inline or from payload store)."""
- item_data = wi.get("item")
- if item_data is not None:
- if isinstance(item_data, dict):
- return self._dict_to_item(item_data)
- return item_data
-
- # Fetch from payload store
- payload_ref = wi.get("payload_ref")
- if payload_ref:
- payload_bytes = await self._fetch_payload(payload_ref)
- if payload_bytes:
- item_dict = msgpack.unpackb(payload_bytes, raw=False)
- return self._dict_to_item(item_dict)
-
- return None
-
- @staticmethod
- def _dict_to_item(d: dict) -> Item:
- """Convert a dict (from SDK wire format) to an Item.
-
- The SDK sends ``content`` while the server ``Item`` struct expects
- ``text``. Map the field and drop any other unknown keys so that the
- ``Item`` constructor doesn't raise.
- """
- if "content" in d and "text" not in d:
- d = {**d, "text": d.pop("content")}
- known = set(Item.__struct_fields__)
- return Item(**{k: v for k, v in d.items() if k in known})
-
- async def _fetch_payload(self, ref_key: str) -> bytes | None:
- """Fetch payload from the cached payload store."""
- if self._payload_store is None:
- logger.warning("Payload ref %s but no payload store configured", ref_key)
- return None
-
- try:
- return await self._payload_store.get(ref_key)
- except KeyError:
- logger.warning("Payload not found: %s", ref_key)
- return None
-
- async def _ack_or_nak_after_error(self, msg: Any, code: str) -> None:
- """Decide ACK vs NAK after a failed inference handler.
-
- Retryable codes (currently just ``RESOURCE_EXHAUSTED``) are NAKed
- with a delay so JetStream redelivers the work item — potentially
- to a sibling worker, or to this worker after its memory pressure
- clears. This means a client without SDK auto-retry (or with
- ``max_oom_retries=0``) still gets the work executed eventually,
- instead of silently losing it.
-
- Non-retryable codes (the legacy ``"inference_error"`` literal,
- ``"unknown_operation"``, ``"payload_error"``, ``"internal_error"``)
- are ACKed: redelivering them would just reproduce the same failure.
-
- Behaviour on delivery-status failures:
- - ACK exceptions are swallowed at debug level — the error response
- has already been published, and JetStream's ack-wait will
- eventually redeliver, which is harmless for non-retryable
- failures (the redelivered request will fail the same way and
- ACK again).
- - NAK exceptions on the ``RESOURCE_EXHAUSTED`` path are
- *deliberately not* followed by an ACK fallback. Falling through
- to ACK would silently drop the work item — JetStream would
- consider it delivered and never retry — which is exactly the
- opposite of the retryable contract. Instead, we log the NAK
- failure and return without ACKing, leaving the message unacked
- so JetStream redelivers it after ``ack_wait`` expires.
- """
- if code == ErrorCode.RESOURCE_EXHAUSTED.value:
- try:
- await msg.nak(delay=_OOM_NAK_DELAY_S)
- except Exception: # noqa: BLE001
- # Do NOT fall through to ACK — that would silently drop
- # the work item. Leave it unacked; JetStream will
- # redeliver after ack_wait expires.
- logger.warning(
- "Failed to NAK RESOURCE_EXHAUSTED message; leaving unacked for JetStream redelivery",
- exc_info=True,
- )
- return
- try:
- await msg.ack()
- except Exception: # noqa: BLE001
- logger.debug("Failed to ACK message after error", exc_info=True)
-
- @staticmethod
- def _classify_inference_exception(exc: BaseException) -> tuple[str, str]:
- """Map an inference-path exception to ``(error_code, error_msg)``.
-
- Used by the queue (NATS) path's catch-all error handler so the
- gateway — which translates ``WorkResult.error_code`` into HTTP
- responses — can emit the same retryable contract the HTTP path
- emits via ``InferenceErrorHandler``.
-
- Currently distinguishes:
- - OOM (any flavour, including ``ResourceExhaustedError``) →
- ``RESOURCE_EXHAUSTED`` (gateway maps to 503 + Retry-After,
- SDK auto-retries).
- - Malformed media input (``InvalidMediaError``, e.g. an un-decoded
- base64 ``str`` reaching a preprocessor/adapter) → ``INVALID_INPUT``
- (gateway maps to 400; the caller's payload is wrong, not retryable).
- - Everything else → the legacy ``"inference_error"`` literal so
- existing dashboards / alerts keep working.
-
- Note the case mismatch: ``"inference_error"`` (lowercase) is the
- wire value the queue path has used historically; ``ErrorCode``
- enum values are uppercase. Aligning the legacy literal is out of
- scope here — see follow-up work.
- """
- if is_oom_error(exc):
- return ErrorCode.RESOURCE_EXHAUSTED.value, str(exc)
- if isinstance(exc, InvalidMediaError):
- return ErrorCode.INVALID_INPUT.value, str(exc)
- return "inference_error", str(exc)
-
- async def _publish_error(self, wi: WorkItem, error_code: str, error_msg: str) -> None:
- """Publish an error result to the reply subject."""
- reply_subject = wi.get("reply_subject", "")
- if not reply_subject:
- return
-
- result: WorkResult = {
- "work_item_id": wi.get("work_item_id", ""),
- "request_id": wi.get("request_id", ""),
- "item_index": wi.get("item_index", 0),
- "success": False,
- "error": error_msg,
- "error_code": error_code,
- "worker_id": self._worker_id,
- }
- result_bytes = msgpack.packb(result, use_bin_type=True)
- try:
- await self._nc.publish(reply_subject, result_bytes)
- except Exception: # noqa: BLE001
- logger.warning("Failed to publish error result for %s", wi.get("work_item_id"))
diff --git a/packages/sie_server/src/sie_server/nats_subscriber.py b/packages/sie_server/src/sie_server/nats_subscriber.py
deleted file mode 100644
index 9079f94e3..000000000
--- a/packages/sie_server/src/sie_server/nats_subscriber.py
+++ /dev/null
@@ -1,231 +0,0 @@
-from __future__ import annotations
-
-import json
-import logging
-import os
-from collections.abc import Awaitable, Callable
-from typing import Any
-
-import nats
-
-logger = logging.getLogger(__name__)
-
-_BUNDLE_SUBJECT = "sie.config.models.{bundle_id}"
-
-# Characters that are invalid in NATS subject tokens
-_NATS_WILDCARD_CHARS = frozenset({"*", ">", " "})
-
-
-def _validate_bundle_id(bundle_id: str) -> str:
- """Validate bundle_id does not contain NATS wildcard characters.
-
- NATS subjects use '*' and '>' as wildcards, and '.' as a token
- separator. If bundle_id contains these, subscriptions would match
- unintended subjects.
-
- Args:
- bundle_id: The bundle identifier to validate.
-
- Returns:
- The validated bundle_id.
-
- Raises:
- ValueError: If bundle_id contains wildcard characters.
- """
- invalid = _NATS_WILDCARD_CHARS & set(bundle_id)
- if invalid:
- msg = f"bundle_id contains invalid NATS characters: {invalid!r}"
- raise ValueError(msg)
- if "." in bundle_id:
- msg = "bundle_id contains '.' which is a NATS subject token separator"
- raise ValueError(msg)
- return bundle_id
-
-
-class NatsSubscriber:
- """Worker-side NATS subscriber for config notifications.
-
- Subscribes to the bundle-scoped subject and applies config changes
- to the worker's model registry.
-
- Args:
- bundle_id: This worker's bundle identifier.
- nats_url: NATS connection URL.
- on_model_config: Async callback when a new model config is received.
- Signature: async def callback(model_id: str, config_yaml: str) -> None
- The callback should parse the YAML and add the config to the
- worker's model registry.
- """
-
- def __repr__(self) -> str:
- return (
- f"NatsSubscriber(bundle_id={self._bundle_id!r}, nats_url={self._nats_url!r}, connected={self._connected})"
- )
-
- def __init__(
- self,
- bundle_id: str | None = None,
- nats_url: str | None = None,
- on_model_config: Callable[[str, str], Awaitable[None]] | None = None,
- ) -> None:
- self._bundle_id = _validate_bundle_id(bundle_id or os.environ.get("SIE_BUNDLE", "default"))
- self._nats_url = nats_url or os.environ.get("SIE_NATS_URL", "nats://localhost:4222")
- self._on_model_config: Callable[[str, str], Awaitable[None]] | None = on_model_config
- self._model_epochs: dict[str, int] = {}
- self._nc: Any = None
- self._sub: Any = None
- self._connected = False
- self._extra_reconnect_handlers: list[Callable[[], Awaitable[None]]] = []
-
- @property
- def connected(self) -> bool:
- """Whether NATS connection is active."""
- return self._connected and self._nc is not None and self._nc.is_connected
-
- @property
- def nc(self) -> Any:
- """The underlying NATS connection, or None if not connected."""
- return self._nc
-
- def add_reconnect_handler(self, handler: Callable[[], Awaitable[None]]) -> None:
- """Register an additional handler to run after NATS reconnect.
-
- Handlers are invoked in registration order after the subscriber's
- own reconnect logic (clearing epoch watermarks).
- """
- self._extra_reconnect_handlers.append(handler)
-
- async def start(self) -> None:
- """Connect to NATS and subscribe to bundle subject.
-
- Does not raise on failure — worker operates without NATS
- (config changes from API won't be received until reconnect).
- """
- try:
- self._nc = await nats.connect(
- self._nats_url,
- reconnected_cb=self._handle_reconnect,
- disconnected_cb=self._handle_disconnect,
- error_cb=self._handle_error,
- max_reconnect_attempts=-1,
- reconnect_time_wait=2,
- )
- self._connected = True
-
- subject = _BUNDLE_SUBJECT.format(bundle_id=self._bundle_id)
- self._sub = await self._nc.subscribe(subject, cb=self._handle_notification)
-
- logger.info(
- "NATS subscriber started: bundle=%s, subject=%s, url=%s",
- self._bundle_id,
- subject,
- self._nats_url,
- )
-
- except Exception: # noqa: BLE001 — graceful degradation when NATS unavailable
- self._connected = False
- logger.warning(
- "Failed to connect to NATS at %s — worker will not receive config notifications",
- self._nats_url,
- exc_info=True,
- )
-
- async def stop(self) -> None:
- """Disconnect from NATS."""
- if self._nc:
- try:
- await self._nc.drain()
- except Exception: # noqa: BLE001 — best-effort cleanup
- logger.debug("Failed to drain NATS connection", exc_info=True)
- self._nc = None
- self._sub = None
- self._connected = False
- logger.info("NATS subscriber stopped")
-
- async def _handle_notification(self, msg: Any) -> None:
- """Handle incoming config notification on bundle subject."""
- try:
- data = json.loads(msg.data.decode())
-
- if not isinstance(data, dict):
- logger.warning("Dropping non-dict NATS notification: %s", type(data).__name__)
- return
-
- model_id = data.get("model_id", "")
- profiles_added = data.get("profiles_added", [])
- model_config_yaml = data.get("model_config", "")
- epoch = data.get("epoch", 0)
- router_id = data.get("router_id", "unknown")
-
- logger.info(
- "Received config notification: model=%s, profiles=%s, epoch=%d, from=%s",
- model_id,
- profiles_added,
- epoch,
- router_id,
- )
-
- # Epoch high-water-mark: reject stale notifications that arrive
- # out of order. Since add_model_config is append-only (profiles
- # cannot be removed), this only prevents redundant re-application.
- if self._on_model_config and model_config_yaml:
- last_epoch = self._model_epochs.get(model_id, -1)
- if epoch <= last_epoch:
- logger.debug(
- "Dropping stale notification for %s: epoch %d <= %d",
- model_id,
- epoch,
- last_epoch,
- )
- return
- try:
- await self._on_model_config(model_id, model_config_yaml)
- except Exception:
- logger.exception(
- "Failed to apply config for model %s (epoch %d) — will retry on next notification",
- model_id,
- epoch,
- )
- return
- self._model_epochs[model_id] = epoch
-
- except json.JSONDecodeError:
- logger.warning("Dropping malformed NATS notification (invalid JSON)")
- except Exception:
- logger.exception("Failed to handle config notification")
-
- async def _handle_reconnect(self) -> None:
- """Handle NATS reconnection.
-
- Clears per-model epoch watermarks so notifications received after
- reconnect are not rejected as stale. Workers do not pull config
- from the object store (design non-goal), so any notifications
- missed during the disconnect are lost until the next config
- mutation or a manual resync.
-
- Also invokes any registered extra reconnect handlers (e.g.,
- NatsPullLoop.handle_reconnect).
- """
- stale_count = len(self._model_epochs)
- self._model_epochs.clear()
- logger.info(
- "NATS subscriber reconnected — cleared %d model epoch watermarks; "
- "notifications missed during disconnect will not be recovered automatically",
- stale_count,
- )
- self._connected = True
- for handler in self._extra_reconnect_handlers:
- try:
- await handler()
- except Exception:
- logger.exception("Extra reconnect handler failed")
- raise
-
- async def _handle_disconnect(self) -> None:
- """Handle NATS disconnection."""
- self._connected = False
- logger.warning("NATS subscriber disconnected — config notifications paused")
-
- async def _handle_error(self, e: Exception) -> None:
- """Handle NATS errors."""
- logger.error("NATS subscriber error: %s", e)
diff --git a/packages/sie_server/src/sie_server/observability/__init__.py b/packages/sie_server/src/sie_server/observability/__init__.py
index 2d2b66e14..f05cb2dea 100644
--- a/packages/sie_server/src/sie_server/observability/__init__.py
+++ b/packages/sie_server/src/sie_server/observability/__init__.py
@@ -4,26 +4,20 @@ Provides Prometheus metrics and OpenTelemetry tracing.
"""
from sie_server.observability.metrics import (
- BATCH_SIZE,
MODEL_LOADED,
MODEL_MEMORY_BYTES,
- QUEUE_DEPTH,
REQUEST_DURATION,
REQUESTS_TOTAL,
- TOKENS_PROCESSED,
record_request,
set_model_loaded,
set_model_memory,
)
__all__ = [
- "BATCH_SIZE",
"MODEL_LOADED",
"MODEL_MEMORY_BYTES",
- "QUEUE_DEPTH",
"REQUESTS_TOTAL",
"REQUEST_DURATION",
- "TOKENS_PROCESSED",
"record_request",
"set_model_loaded",
"set_model_memory",
diff --git a/packages/sie_server/src/sie_server/observability/gpu.py b/packages/sie_server/src/sie_server/observability/gpu.py
index bcf6e8750..5e8dbea4a 100644
--- a/packages/sie_server/src/sie_server/observability/gpu.py
+++ b/packages/sie_server/src/sie_server/observability/gpu.py
@@ -5,8 +5,6 @@ Gracefully handles missing pynvml or no GPU.
Note: the ``pynvml`` module is supplied at runtime by the ``nvidia-ml-py``
package (the legacy ``pynvml`` PyPI package is deprecated).
-
-See DESIGN.md Section 5.6.
"""
from __future__ import annotations
diff --git a/packages/sie_server/src/sie_server/observability/metrics.py b/packages/sie_server/src/sie_server/observability/metrics.py
index f02ef8457..f02bcdae5 100644
--- a/packages/sie_server/src/sie_server/observability/metrics.py
+++ b/packages/sie_server/src/sie_server/observability/metrics.py
@@ -8,8 +8,6 @@ Metrics follow Prometheus naming conventions:
- _total suffix for counters
- _seconds suffix for duration histograms
- _bytes suffix for memory metrics
-
-See DESIGN.md Section 5.6 for observability design.
"""
from __future__ import annotations
@@ -198,11 +196,11 @@ GRAMMAR_PREWARM_TOTAL = Counter(
)
# -----------------------------------------------------------------------------
-# ADR-0002 metrics — SGLang owns request-time grammar compilation
+# Structured-output grammar metrics
# -----------------------------------------------------------------------------
#
-# Per ADR-0002 the worker-side Outlines preflight is no longer on the
-# request hot path; SGLang's server-side grammar backend (Outlines,
+# The worker-side Outlines preflight is no longer on the request hot
+# path; SGLang's server-side grammar backend (Outlines,
# xgrammar, or llguidance) is the single authority. These metrics give
# operators visibility into structured-output behaviour from the
# worker's side without re-introducing the duplicate preflight.
@@ -221,29 +219,27 @@ GRAMMAR_PREWARM_TOTAL = Counter(
# output TTFT histogram is the proxy for SGLang's own internal compile
# cost — when SGLang has to construct an FSM for a unique schema, the
# first-token latency for that request inflates accordingly.
-GRAMMAR_COMPILE_SECONDS_ADR0002 = Histogram(
+GRAMMAR_COMPILE_SECONDS_STRUCTURED_OUTPUT = Histogram(
"sie_grammar_compile_seconds",
- "Worker-side preflight grammar-compile duration (only emitted when "
- "SIE_GRAMMAR_PREFLIGHT_DEBUG=1; off by default per ADR-0002)",
+ "Worker-side preflight grammar-compile duration (only emitted when SIE_GRAMMAR_PREFLIGHT_DEBUG=1; off by default)",
["backend", "mode"],
buckets=(0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0),
)
STRUCTURED_OUTPUT_TTFT_SECONDS = Histogram(
"sie_structured_output_ttft_seconds",
- "Time-to-first-token for structured-output requests, proxy for "
- "SGLang's server-side grammar-construction cost (ADR-0002)",
+ "Time-to-first-token for structured-output requests, proxy for SGLang's server-side grammar-construction cost",
["backend", "mode"],
buckets=TTFT_TPOT_BUCKETS,
)
-GRAMMAR_CACHE_HITS_ADR0002 = Counter(
+GRAMMAR_CACHE_HITS_STRUCTURED_OUTPUT = Counter(
"sie_grammar_cache_hits_total",
"Worker-side grammar-cache hits (preflight cache; only fires when SIE_GRAMMAR_PREFLIGHT_DEBUG=1)",
["backend"],
)
-GRAMMAR_CACHE_MISSES_ADR0002 = Counter(
+GRAMMAR_CACHE_MISSES_STRUCTURED_OUTPUT = Counter(
"sie_grammar_cache_misses_total",
"Worker-side grammar-cache misses (preflight cache; only fires when SIE_GRAMMAR_PREFLIGHT_DEBUG=1)",
["backend"],
@@ -364,6 +360,32 @@ QUEUE_DEPTH = Gauge(
["model"],
)
+# IPC batch shape metrics expose how one sidecar batch fragments into
+# Python/GPU forward passes. Bucket sizes match `sie_gpu_batch_items`
+# so dashboards can compare IPC and GPU batch shapes directly.
+_IPC_BATCH_SIZE_BUCKETS = (1, 2, 4, 8, 16, 32, 64, 128, 256, 512)
+
+IPC_BATCH_ITEMS = Histogram(
+ "sie_ipc_batch_items",
+ "Number of items in a single IPC batch received from the worker-sidecar",
+ ["model", "endpoint"],
+ buckets=_IPC_BATCH_SIZE_BUCKETS,
+)
+
+IPC_BATCH_SUB_GROUPS = Histogram(
+ "sie_ipc_batch_sub_groups",
+ "Number of sub-groups (separate GPU forward passes) from one IPC batch",
+ ["model", "endpoint"],
+ buckets=_IPC_BATCH_SIZE_BUCKETS,
+)
+
+IPC_BATCH_SUB_GROUP_ITEMS = Histogram(
+ "sie_ipc_batch_sub_group_items",
+ "Items per sub-group after IPC-batch splitting",
+ ["model", "endpoint"],
+ buckets=_IPC_BATCH_SIZE_BUCKETS,
+)
+
# -----------------------------------------------------------------------------
# Model Metrics
@@ -384,7 +406,7 @@ MODEL_MEMORY_BYTES = Gauge(
MODEL_LOAD_TIMEOUTS = Counter(
"sie_model_load_timeouts_total",
"Number of post-download model-load timeouts, broken down by stage. "
- "Stage is one of: ``instantiate`` (adapter object construction) or "
+ "The stage label is one of: ``instantiate`` (adapter object construction) or "
"``load`` (adapter.load + warmup). Download is bounded separately by "
"HF_HUB_DOWNLOAD_TIMEOUT and does NOT increment this counter.",
["model", "stage"],
@@ -565,6 +587,24 @@ def set_queue_depth(model: str, depth: int) -> None:
QUEUE_DEPTH.labels(model=model).set(depth)
+def record_ipc_batch_shape(
+ model: str,
+ endpoint: str,
+ total_items: int,
+ sub_group_sizes: list[int],
+) -> None:
+ """Record the IPC batch shape before Python dispatches GPU work."""
+ if total_items <= 0:
+ return
+ IPC_BATCH_ITEMS.labels(model=model, endpoint=endpoint).observe(total_items)
+ IPC_BATCH_SUB_GROUPS.labels(model=model, endpoint=endpoint).observe(len(sub_group_sizes))
+ for size in sub_group_sizes:
+ # Zero-size entries are invalid; skip them rather than recording
+ # misleading 0-bucket samples.
+ if size > 0:
+ IPC_BATCH_SUB_GROUP_ITEMS.labels(model=model, endpoint=endpoint).observe(size)
+
+
def set_model_loaded(model: str, device: str, loaded: bool) -> None:
"""Update the model loaded gauge.
diff --git a/packages/sie_server/src/sie_server/observability/prometheus.py b/packages/sie_server/src/sie_server/observability/prometheus.py
index a6942c5fa..ba612b9fa 100644
--- a/packages/sie_server/src/sie_server/observability/prometheus.py
+++ b/packages/sie_server/src/sie_server/observability/prometheus.py
@@ -2,8 +2,6 @@
Extracts current counter and histogram values from Prometheus registry
for real-time display in the Terminal UI.
-
-See DESIGN.md Section 5.6.
"""
from __future__ import annotations
diff --git a/packages/sie_server/src/sie_server/observability/tracing.py b/packages/sie_server/src/sie_server/observability/tracing.py
index 41abccff1..9dce92b24 100644
--- a/packages/sie_server/src/sie_server/observability/tracing.py
+++ b/packages/sie_server/src/sie_server/observability/tracing.py
@@ -10,7 +10,6 @@ Configuration via standard OTel environment variables:
- OTEL_TRACES_SAMPLER: Sampling strategy
- OTEL_TRACES_SAMPLER_ARG: Sampling rate
-See DESIGN.md Section 5.6 for observability design.
See https://opentelemetry.io/docs/concepts/sdk-configuration/ for OTel config.
"""
diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.py
index 2fd28b3f1..4c058368a 100644
--- a/packages/sie_server/src/sie_server/processors/streaming.py
+++ b/packages/sie_server/src/sie_server/processors/streaming.py
@@ -20,9 +20,7 @@ The streaming rollout (this revision) drives the adapter as an async iterator:
request queue cap >64 unsent), publish a final ``{error,
code: "transport_failure", done: true}`` chunk and ACK
-The chunk envelope is *not* the walking-skeleton ``WorkResult`` shape — see
-``product/plans/m4-req2-generate-issues/02-streaming-async-iterator.md``
-§2.2 of the plan for the discriminated wire shape:
+The chunk envelope uses a discriminated streaming wire shape:
{ kind: "chunk", request_id, attempt_id, seq, text_delta,
is_first?, done, finish_reason?, usage?, ttft_ms?, error? }
@@ -34,6 +32,7 @@ import asyncio
import collections
import json
import logging
+import math
import os
import time
import uuid
@@ -41,7 +40,7 @@ from collections.abc import AsyncGenerator, Callable
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Self, cast
+from typing import TYPE_CHECKING, Any, Protocol, Self, cast
import msgpack
from opentelemetry import propagate
@@ -91,7 +90,7 @@ _GRAMMAR_EXECUTOR = ThreadPoolExecutor(max_workers=4, thread_name_prefix="gramma
# until ack_wait (which would trigger a JetStream redelivery storm).
_GRAMMAR_FOLLOWER_TIMEOUT_S = 30.0
-# ADR-0002 — SGLang owns request-time grammar compilation.
+# SGLang owns request-time grammar compilation.
#
# By default the worker forwards the raw schema/regex/EBNF straight to
# SGLang's server-side grammar backend (the single grammar authority
@@ -155,13 +154,18 @@ _CANCEL_TOMBSTONE_TTL_S = 120.0
_CANCEL_TOMBSTONE_MAX = 1024
if TYPE_CHECKING:
- from nats.aio.client import Client as NATSClient
from transformers import PreTrainedTokenizer, PreTrainedTokenizerFast
from sie_server.core.registry import ModelRegistry
TokenizerLike = PreTrainedTokenizer | PreTrainedTokenizerFast
+
+class NatsPublisher(Protocol):
+ async def publish(self, reply_subject: str, payload: bytes) -> None:
+ raise NotImplementedError
+
+
logger = logging.getLogger(__name__)
# Default delay when NAKing a generate item because the model is not yet
@@ -207,7 +211,7 @@ _PUBLISH_FAIL_WINDOW_S = 1.0
# Heartbeat cadence for JetStream ``in_progress()`` calls. The pool
# consumer's ``ack_wait`` is 5 min for generation pools (per the streaming §4.4 spec);
# beat well below that so a slow decode doesn't lose the slot.
-_INPROGRESS_INTERVAL_S = 60.0
+_INPROGRESS_INTERVAL_S = float(os.environ.get("SIE_GENERATION_INPROGRESS_INTERVAL_S", "10.0"))
# Input-size caps applied BEFORE the CPU-bound, input-sized tokenizer
# calls (``apply_chat_template`` / ``tok.encode``). These run on the
@@ -304,6 +308,14 @@ class _GenerateRequestParams:
# validated; ``None`` → model/sampler default.
top_k: int | None = None
repetition_penalty: float | None = None
+ # SGLang ``sampling_params["min_new_tokens"]`` (int >= 0). Anti-
+ # stop-first knob; ``None`` → no minimum.
+ min_tokens: int | None = None
+ # Per-request kwargs for ``apply_chat_template`` (e.g.
+ # ``{"enable_thinking": False}``). Merged on top of the model YAML's
+ # ``chat_template_kwargs`` at render time. ``None`` → only YAML
+ # defaults apply.
+ chat_template_kwargs: dict[str, Any] | None = None
grammar: GrammarSpec | None = None
# OpenAI tools / tool_choice. The gateway has already shape-validated
# the schemas; the worker uses ``tools is not None`` as the flag that
@@ -354,7 +366,7 @@ class StreamingProcessor:
def __init__(
self,
- nc: NATSClient,
+ nc: NatsPublisher,
registry: ModelRegistry,
worker_id: str,
*,
@@ -669,7 +681,7 @@ class StreamingProcessor:
@staticmethod
def _resolve_grammar_backend_label(adapter: GenerationAdapter) -> str:
- """Bounded-cardinality backend label for the ADR-0002 metrics.
+ """Bounded-cardinality backend label for structured-output metrics.
Reads the adapter's ``_grammar_backend`` (the same field used to
drive the SGLang ``--grammar-backend`` flag). Anything that
@@ -686,7 +698,7 @@ class StreamingProcessor:
adapter: GenerationAdapter,
grammar: GrammarSpec,
) -> None:
- """Record per-request grammar observability signal (ADR-0002).
+ """Record per-request grammar observability signal.
Runs on every structured-output request, regardless of whether
the legacy preflight is enabled. Cheap — one counter increment
@@ -974,7 +986,7 @@ class StreamingProcessor:
# attempt_id it observes and drops chunks from any other.
attempt_id = uuid.uuid4().hex
- # M5: W3C Trace Context propagation. If the gateway populated
+ # W3C Trace Context propagation. If the gateway populated
# the ``traceparent`` (and optionally ``tracestate``) fields on
# the envelope, extract a parent ``opentelemetry.Context`` and
# open the worker-side processing span as its child. The span
@@ -1169,8 +1181,8 @@ class StreamingProcessor:
# Routing-key plumbing: inert at this layer. Read so the values land
# in a single place, but do not act on them.
- _routing_key = wi.get("routing_key") # routing-affinity hint
- _prompt_cache_key = wi.get("prompt_cache_key") # prompt-cache hint
+ _ = wi.get("routing_key") # routing-affinity hint
+ _ = wi.get("prompt_cache_key") # prompt-cache hint
validation = self._validate_generate_params(wi)
if isinstance(validation, _ValidationError):
@@ -1203,7 +1215,12 @@ class StreamingProcessor:
# the underlying adapter. ``Prompt`` shape goes straight through.
prompt_str: str
if isinstance(params.input, _MessagesInput):
- rendered = await self._render_chat_template(model_id, params.input.messages, effective_tools)
+ rendered = await self._render_chat_template(
+ model_id,
+ params.input.messages,
+ effective_tools,
+ request_kwargs=params.chat_template_kwargs,
+ )
if isinstance(rendered, _ValidationError):
await self._terminal_error_then_settle(
reply_subject,
@@ -1287,7 +1304,7 @@ class StreamingProcessor:
# gateway rejects the combo before the request reaches here).
effective_grammar = forcing_grammar if forcing_grammar is not None else params.grammar
- # ADR-0002 — SGLang owns request-time grammar compilation.
+ # SGLang owns request-time grammar compilation.
#
# The default path forwards the raw schema/regex/EBNF straight to
# SGLang's server-side grammar backend (the single grammar
@@ -1390,6 +1407,8 @@ class StreamingProcessor:
presence_penalty=params.presence_penalty,
top_k=params.top_k,
repetition_penalty=params.repetition_penalty,
+ min_tokens=params.min_tokens,
+ chat_template_kwargs=params.chat_template_kwargs,
grammar=effective_grammar,
tools=effective_tools,
enable_tool_parser=enable_tool_parser,
@@ -1435,6 +1454,12 @@ class StreamingProcessor:
presence_penalty: float | None = None,
top_k: int | None = None,
repetition_penalty: float | None = None,
+ min_tokens: int | None = None,
+ # ``chat_template_kwargs`` is consumed upstream in
+ # :meth:`_render_chat_template`; accepted here only so the
+ # caller can forward the whole ``params`` block without sniffing
+ # which fields belong to which stage.
+ chat_template_kwargs: dict[str, Any] | None = None,
grammar: GrammarSpec | None = None,
tools: tuple[dict[str, Any], ...] | None = None,
enable_tool_parser: bool | None = None,
@@ -1481,9 +1506,17 @@ class StreamingProcessor:
gen_kwargs["top_k"] = top_k
if repetition_penalty is not None:
gen_kwargs["repetition_penalty"] = repetition_penalty
+ if min_tokens is not None:
+ # SGLang names the knob ``min_new_tokens`` server-side; the
+ # OpenAI-compat surface (mirroring vLLM / Together) takes it
+ # as ``min_tokens``. Translate at this edge.
+ gen_kwargs["min_new_tokens"] = min_tokens
+ # ``chat_template_kwargs`` is consumed in _render_chat_template
+ # upstream; nothing to forward from here.
+ _ = chat_template_kwargs
if grammar is not None:
gen_kwargs["grammar"] = grammar
- # Slice M5: seed / logit_bias / logprobs / top_logprobs. Only
+ # Optional sampler controls: seed / logit_bias / logprobs / top_logprobs. Only
# forward when set so older adapters that don't accept the
# kwargs still work for the (common) no-extra-sampler path.
if seed is not None:
@@ -1753,7 +1786,7 @@ class StreamingProcessor:
# Record first-text timing for TTFT.
if chunk.text_delta and first_text_at is None:
first_text_at = time.monotonic()
- # ADR-0002 — structured-output TTFT is the proxy for
+ # Structured-output TTFT is the proxy for
# SGLang's server-side grammar-construction cost. Only
# observe when this request actually carries a
# grammar; non-structured requests already feed the
@@ -2289,7 +2322,7 @@ class StreamingProcessor:
raw,
)
return None
- if v != v or v < -2.0 or v > 2.0: # noqa: PLR0124, PLR2004 — explicit NaN check, OpenAI penalty range is the spec value
+ if math.isnan(v) or v < -2.0 or v > 2.0: # noqa: PLR2004 — OpenAI penalty range is the spec value
logger.debug(
"generate request: %s %r out of [-2.0, 2.0] — dropping",
name,
@@ -2332,12 +2365,37 @@ class StreamingProcessor:
)
repetition_penalty = None
else:
- # Range (0, 2] is the documented gateway contract; the
- # ``v == v`` guard rejects NaN.
+ # Range (0, 2] is the documented gateway contract;
+ # NaN is rejected via ``math.isnan``.
repetition_penalty = (
- rep_pen_val if (rep_pen_val == rep_pen_val and 0.0 < rep_pen_val <= 2.0) else None # noqa: PLR0124, PLR2004
+ rep_pen_val if (not math.isnan(rep_pen_val) and 0.0 < rep_pen_val <= 2.0) else None # noqa: PLR2004
)
+ # SGLang ``sampling_params["min_new_tokens"]``. Gateway validates
+ # as ``>= 0``; defensive coerce here.
+ min_tokens_raw = params.get("min_tokens")
+ min_tokens: int | None
+ if min_tokens_raw is None or isinstance(min_tokens_raw, bool):
+ min_tokens = None
+ else:
+ try:
+ min_tokens_val = int(min_tokens_raw)
+ except (TypeError, ValueError):
+ logger.debug("generate request: non-integer min_tokens %r — dropping", min_tokens_raw)
+ min_tokens = None
+ else:
+ min_tokens = min_tokens_val if min_tokens_val >= 0 else None
+
+ # Per-request chat-template kwargs. Gateway has already validated
+ # this is an object (or absent); store as-is and merge with the
+ # model YAML defaults in ``_render_chat_template`` below.
+ chat_template_kwargs_raw = params.get("chat_template_kwargs")
+ chat_template_kwargs: dict[str, Any] | None
+ if isinstance(chat_template_kwargs_raw, dict):
+ chat_template_kwargs = dict(chat_template_kwargs_raw)
+ else:
+ chat_template_kwargs = None
+
# OpenAI ``seed`` / ``logit_bias`` / ``logprobs`` / ``top_logprobs``
# round-trips. Gateway is the authority for shape validation
# (u64 / range / cap); the worker only coerces defensively.
@@ -2457,6 +2515,8 @@ class StreamingProcessor:
presence_penalty=presence_penalty,
top_k=top_k,
repetition_penalty=repetition_penalty,
+ min_tokens=min_tokens,
+ chat_template_kwargs=chat_template_kwargs,
grammar=grammar,
tools=tools,
tool_choice=tool_choice,
@@ -2531,6 +2591,7 @@ class StreamingProcessor:
model_id: str,
messages: tuple[_ChatMessage, ...],
tools: tuple[dict[str, Any], ...] | None = None,
+ request_kwargs: dict[str, Any] | None = None,
) -> str | _ValidationError:
"""Render a chat-message list into a prompt string via the tokenizer's
chat template. Returns the rendered string or a validation error
@@ -2540,6 +2601,16 @@ class StreamingProcessor:
the tool definitions are rendered into the prompt — without this the
model never sees the available tools and never emits ``<tool_call>``
blocks, so native tool calling silently degrades to prose.
+
+ ``request_kwargs`` are per-request overrides for the tokenizer's
+ template kwargs (sourced from the client's
+ ``chat_template_kwargs`` body field). Merged on top of the model
+ YAML's ``chat_template_kwargs`` so the YAML stays the default
+ while clients can flip individual switches per request (e.g.
+ ``{"enable_thinking": False}`` to suppress Qwen3's ``<think>``
+ reasoning on a one-off basis). The YAML wins on conflict —
+ operator config is authoritative; per-request overrides only
+ fill in keys the YAML didn't set.
"""
try:
tok = await self._get_tokenizer(model_id)
@@ -2555,7 +2626,14 @@ class StreamingProcessor:
)
# Tokenizer-extension kwargs (e.g. Qwen3's ``enable_thinking``).
+ # Start from any per-request overrides, then layer the model
+ # YAML on top — YAML defaults win on conflict so an operator
+ # can fence off a kwarg the client shouldn't be flipping just
+ # by setting it in the YAML. Empty/missing client kwargs are
+ # a no-op.
kwargs: dict[str, Any] = {}
+ if request_kwargs:
+ kwargs.update(request_kwargs)
try:
config = self._registry.get_config(model_id)
except KeyError:
@@ -2563,7 +2641,7 @@ class StreamingProcessor:
if config is not None and config.tasks.generate is not None:
raw_kwargs = config.tasks.generate.chat_template_kwargs
if isinstance(raw_kwargs, dict):
- kwargs = dict(raw_kwargs)
+ kwargs.update(raw_kwargs)
# Reject pathologically large message lists before the CPU-bound
# render: ``apply_chat_template`` is input-sized and runs on the
@@ -2786,9 +2864,9 @@ class StreamingProcessor:
if cached is not None:
_metrics.GRAMMAR_CACHE_HITS.labels(model=model_id).inc()
try:
- _metrics.GRAMMAR_CACHE_HITS_ADR0002.labels(backend="outlines").inc()
+ _metrics.GRAMMAR_CACHE_HITS_STRUCTURED_OUTPUT.labels(backend="outlines").inc()
except Exception: # noqa: BLE001
- logger.debug("ADR-0002 grammar cache-hit metric failed", exc_info=True)
+ logger.debug("structured-output grammar cache-hit metric failed", exc_info=True)
return True
# Single-flight: if another coroutine is already compiling this
@@ -2832,9 +2910,9 @@ class StreamingProcessor:
return False
_metrics.GRAMMAR_CACHE_HITS.labels(model=model_id).inc()
try:
- _metrics.GRAMMAR_CACHE_HITS_ADR0002.labels(backend="outlines").inc()
+ _metrics.GRAMMAR_CACHE_HITS_STRUCTURED_OUTPUT.labels(backend="outlines").inc()
except Exception: # noqa: BLE001
- logger.debug("ADR-0002 grammar cache-hit metric failed", exc_info=True)
+ logger.debug("structured-output grammar cache-hit metric failed", exc_info=True)
return True
# Leader path: load tokenizer + run the bounded-pool compile.
@@ -2962,14 +3040,16 @@ class StreamingProcessor:
elapsed = time.monotonic() - t0
_metrics.GRAMMAR_COMPILE_SECONDS.labels(model=model_id, kind=grammar.kind).observe(elapsed)
_metrics.GRAMMAR_CACHE_MISSES.labels(model=model_id).inc()
- # ADR-0002 metrics — the preflight only runs when
+ # Structured-output grammar metrics: the preflight only runs when
# ``SIE_GRAMMAR_PREFLIGHT_DEBUG=1``, so these observations are
# diagnostic-only by construction.
try:
- _metrics.GRAMMAR_COMPILE_SECONDS_ADR0002.labels(backend="outlines", mode=grammar.kind).observe(elapsed)
- _metrics.GRAMMAR_CACHE_MISSES_ADR0002.labels(backend="outlines").inc()
+ _metrics.GRAMMAR_COMPILE_SECONDS_STRUCTURED_OUTPUT.labels(backend="outlines", mode=grammar.kind).observe(
+ elapsed
+ )
+ _metrics.GRAMMAR_CACHE_MISSES_STRUCTURED_OUTPUT.labels(backend="outlines").inc()
except Exception: # noqa: BLE001
- logger.debug("ADR-0002 grammar compile/miss metric failed", exc_info=True)
+ logger.debug("structured-output grammar compile/miss metric failed", exc_info=True)
self._grammar_cache.put(key, compiled)
future_to_await.set_result(compiled)
return True
diff --git a/packages/sie_server/src/sie_server/processors/work_class_scheduler.py b/packages/sie_server/src/sie_server/processors/work_class_scheduler.py
index b87bc51b7..ffe4f5b74 100644
--- a/packages/sie_server/src/sie_server/processors/work_class_scheduler.py
+++ b/packages/sie_server/src/sie_server/processors/work_class_scheduler.py
@@ -7,11 +7,10 @@ worker's slots between work classes when the operator opts in via
consumable by another class, so neither starves) and competes for the
remaining shared slots by weight via a virtual-time deficit counter.
-This module is the algorithmic core (roadmap §6.1, plan step 1): pure
-:mod:`asyncio`, no NATS. The pull-loop integration (acquire-before-dispatch,
-release-at-chunk-boundary), the ``SaturationGate`` snapshot wiring, and the
-A100 loadtest are the deferred follow-up; this component is unit-tested in
-isolation first.
+This module is the algorithmic core: pure :mod:`asyncio`, no NATS. The
+pull-loop integration (acquire-before-dispatch, release-at-chunk-boundary),
+the ``SaturationGate`` snapshot wiring, and load tests are separate layers;
+this component is unit-tested in isolation first.
Slots are released at **completion** (chunk boundary for generation, batch
completion for embedding) — never mid-decode — so KV-cache locality is
diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.py
new file mode 100644
index 000000000..85fb3a031
--- /dev/null
+++ b/packages/sie_server/src/sie_server/queue_executor.py
@@ -0,0 +1,1088 @@
+from __future__ import annotations
+
+import logging
+import os
+import tempfile
+from pathlib import Path
+from typing import Any, Final, cast
+
+import msgpack
+import yaml
+
+from sie_server.api.ws import compute_bundle_config_hash_cached
+from sie_server.config.model import ModelConfig
+from sie_server.core.oom import is_oom_error
+from sie_server.core.prepared import ExtractPreparedItem, ScorePreparedItem
+from sie_server.core.registry import ModelRegistry
+from sie_server.core.timing import RequestTiming
+from sie_server.core.worker.handlers.extract import ExtractHandler
+from sie_server.ipc_types import (
+ ApplyModelConfigRequest,
+ ApplyModelConfigResponse,
+ BatchOutcome,
+ DenseOutput,
+ EncodeBatchItem,
+ ExtractBatchItem,
+ ItemOutcome,
+ ModelDescriptor,
+ MultivectorOutput,
+ ProcessEncodeBatchRequest,
+ ProcessExtractBatchRequest,
+ ProcessScoreBatchRequest,
+ RawOutput,
+ ReadinessState,
+ ScoreBatchItem,
+ ScoreOutputRaw,
+ SparseOutput,
+)
+from sie_server.observability.metrics import record_ipc_batch_shape
+from sie_server.types.inputs import InvalidMediaError, Item
+from sie_server.types.responses import ErrorCode
+
+logger = logging.getLogger(__name__)
+
+
+# ---------------------------------------------------------------------------
+# Rust-side output framing: every adapter that emits typed RawOutput
+# ---------------------------------------------------------------------------
+#
+# Per-request safety rules in ``_maybe_dense_raw_output`` /
+# ``_maybe_sparse_raw_output`` / ``_maybe_multivector_raw_output`` emit
+# ``RawOutput`` only when the adapter's output is the exact (single-key,
+# float32, well-shaped) form Rust knows how to frame byte-identically;
+# everything else still falls back to the legacy
+# ``msgpack.packb(_wrap_encode_output(...))`` path.
+#
+# Safety rules:
+# * Dense: ONLY when the adapter emits a single ``dense`` output key
+# backed by a float32 ``np.ndarray``. Binary / int8 / float16 dense
+# still go through the Python-framed fallback path so nothing
+# regresses.
+# * Sparse: ONLY when the adapter emits a single ``sparse`` output
+# key with int32 indices + float32 values (the
+# ``SparseVector(indices=..., values=...)`` shape every in-tree
+# sparse adapter produces). float16 values fall back.
+# * Multivector: ONLY for a single ``multivector`` output key with
+# a float32 ``[num_tokens, token_dims]`` ndarray. Bit-packed
+# binary multivector (``shape[1] < mv_dim``) and float16 fall back.
+# * Score: always eligible — Rust mirrors the Python sort + rank
+# assignment byte-for-byte.
+# * Multi-output items (e.g. dense + sparse in one response) always
+# fall back — the wire contract is one variant per ``RawOutput``.
+# * On any shape error the Rust publisher converts the outcome into
+# ``publish_error_and_ack`` with ``error_code="raw_output_shape_error"``.
+# We never silently drop or mis-frame a request.
+
+# ---------------------------------------------------------------------------
+# Tokenizer materialisation
+# ---------------------------------------------------------------------------
+
+# Treat ``model_max_length`` ≥ this value as "unset" — HF defaults
+# slow tokenizers to ``int(1e30)`` when no cap is declared. Anything
+# above 1M tokens is implausible for the encoders we run; the sidecar
+# falls back to its own default cap rather than truncating after a
+# trillion tokens.
+_TOKENIZER_MAX_SEQ_LEN_PLAUSIBILITY_CAP: Final[int] = 1_000_000
+#
+# The worker-sidecar can't read the adapter's HF cache directly (different
+# container in the split-image world; in single-container today it's the
+# same FS but the path is hard to discover from the model_id alone). On
+# first ``EnsureModelReady`` we write the adapter's ``tokenizer.json``
+# to a stable, per-model path inside an emptyDir-equivalent staging
+# directory and ship that path to the sidecar in
+# ``ModelDescriptor.tokenizer_path``. The sidecar loads from there.
+#
+# The directory is configurable via ``SIE_TOKENIZER_STAGING_DIR`` for
+# the split-container deploy (point both containers at the same
+# ``emptyDir`` mount); defaults to ``$TMPDIR/sie-tokenizers`` so unit
+# tests and dev shells need no extra config.
+
+_TOKENIZER_STAGING_DIR = Path(
+ os.environ.get("SIE_TOKENIZER_STAGING_DIR") or (tempfile.gettempdir() + "/sie-tokenizers")
+)
+
+
+def _safe_model_id_for_path(model_id: str) -> str:
+ """Map a HF-style ``org/name`` (or worse, ``Org/Name@revision``) to
+ a single filesystem-safe path component. We keep the mapping
+ intentionally lossy (no reverse) because the Rust side gets the
+ full path back via the descriptor, not by reconstruction.
+ """
+ return "".join(ch if ch.isalnum() or ch in ("_", "-", ".") else "__" for ch in model_id)
+
+
+def _materialise_tokenizer(model_id: str, tokenizer: Any) -> str | None:
+ """Write the canonical ``tokenizer.json`` for ``tokenizer`` to a
+ per-model path under :data:`_TOKENIZER_STAGING_DIR` and return the
+ absolute path. Returns ``None`` when the tokenizer is a slow (Python)
+ tokenizer that doesn't expose a ``backend_tokenizer`` — the sidecar
+ cannot fast-path those anyway, so there is no value in materialising
+ them.
+
+ Idempotent on repeat invocations: if the target file already exists
+ with matching size, we trust the cached descriptor (the per-process
+ cache in :class:`QueueExecutor` short-circuits before we get here on
+ the steady-state hot path; this routine is the cold-start writer
+ plus the cross-process recovery path).
+
+ Concurrency-safe: the temporary file name embeds ``os.getpid()`` so
+ two adapter processes (or two threads in the same process taking
+ different identity locks) writing the same model's tokenizer don't
+ stomp each other's tmp file. POSIX ``rename`` then publishes the
+ final ``tokenizer.json`` atomically — readers in the sidecar never
+ see a partial write.
+ """
+ backend = getattr(tokenizer, "backend_tokenizer", None)
+ if backend is None:
+ return None
+ try:
+ raw = backend.to_str(pretty=False)
+ except Exception: # noqa: BLE001
+ logger.debug("materialise_tokenizer: backend_tokenizer.to_str failed for %s", model_id, exc_info=True)
+ return None
+ # ``to_str`` MUST return ``str`` on a real ``tokenizers.Tokenizer``.
+ # Anything else (MagicMock, None, bytes) is treated as "no canonical
+ # JSON available" — the sidecar will fall back to Python tokenisation
+ # for this model.
+ if not isinstance(raw, str):
+ return None
+ canonical = raw.encode("utf-8")
+
+ target_dir = _TOKENIZER_STAGING_DIR / _safe_model_id_for_path(model_id)
+ target_path = target_dir / "tokenizer.json"
+ try:
+ if target_path.is_file() and target_path.stat().st_size == len(canonical):
+ # Size match is a cheap proxy for byte identity. The sidecar
+ # additionally hashes on its side and reconciles against the
+ # ``tokenizer_id`` on the descriptor, so a false positive
+ # here just means the registry refuses the registration and
+ # Python keeps tokenising — never a silent mis-frame.
+ return str(target_path)
+ target_dir.mkdir(parents=True, exist_ok=True)
+ tmp_path = target_dir / f"tokenizer.json.{os.getpid()}.tmp"
+ tmp_path.write_bytes(canonical)
+ tmp_path.replace(target_path)
+ return str(target_path)
+ except OSError:
+ logger.warning(
+ "materialise_tokenizer: failed to write %s — sidecar will fall back to Python tokenisation",
+ target_path,
+ exc_info=True,
+ )
+ return None
+
+
+def _maybe_dense_raw_output(
+ formatted: dict[str, Any],
+ config: Any,
+ output_types: list[str],
+) -> RawOutput | None:
+ """Return a ``RawOutput`` for the dense-only fast path, or ``None``
+ to fall back to the Python-framed fallback path.
+
+ All conditions must hold — the gate is deliberately strict so
+ Rust-side framing only intercepts cases the Rust shaper is known
+ to produce byte-identical bytes for.
+ """
+ import numpy as np # noqa: PLC0415
+
+ if output_types != ["dense"]:
+ return None
+ if set(formatted.keys()) - {"dense"}:
+ # Sparse / multivector in the same item would need different
+ # Rust framers — not in v1.
+ return None
+ arr = formatted.get("dense")
+ if not isinstance(arr, np.ndarray):
+ return None
+ if arr.dtype != np.float32:
+ # Binary (uint8 bit-packed), float16, int8 all need different
+ # framers and/or dtype tags; Python still handles them.
+ return None
+ if arr.ndim != 1:
+ return None
+
+ encode_task = getattr(getattr(config, "tasks", None), "encode", None)
+ dense_cfg = getattr(encode_task, "dense", None) if encode_task else None
+ dense_dim = dense_cfg.dim if dense_cfg else None
+ dim = int(dense_dim) if dense_dim is not None else int(arr.shape[0])
+ if arr.shape[0] != dim:
+ # Don't try to hide a shape mismatch; fall back and let the
+ # legacy path mis-label it the same way it does today rather
+ # than introduce a new error class here.
+ return None
+
+ # ``arr.tolist()`` widens each ``np.float32`` to a Python ``float``
+ # (f64). The Rust side narrows back to ``f32`` on decode — this
+ # round-trip is exact because every f32 has a unique f64
+ # representation. The Rust shaper then widens back to f64 before
+ # emitting the ``msgpack_numpy`` sentinel's raw-bytes payload,
+ # matching Python's ``arr.tobytes()`` bit-for-bit.
+ return RawOutput(
+ dense=DenseOutput(
+ values=arr.tolist(),
+ dim=dim,
+ # v1 policy: adapter-side normalize stays in Python.
+ # Flipping this to ``True`` is a later optimisation.
+ normalize=False,
+ ),
+ )
+
+
+def _maybe_sparse_raw_output(
+ formatted: dict[str, Any],
+ config: Any,
+ output_types: list[str],
+) -> RawOutput | None:
+ """Sparse-only fast path. Returns a ``RawOutput`` carrying a
+ ``SparseOutput`` when every v1 invariant holds, otherwise ``None``
+ so the Python-framed fallback path takes over.
+
+ The Rust shaper emits the exact bytes that
+ ``_wrap_encode_output`` packs today — see
+ ``sie_server_sidecar::output::build_sparse_payload`` and the
+ byte-identity tests in
+ ``test_stage1d_byte_identity.py::test_sparse_legacy_matches_rust_golden``.
+ """
+ import numpy as np # noqa: PLC0415
+
+ if output_types != ["sparse"]:
+ return None
+ if set(formatted.keys()) - {"sparse"}:
+ return None
+ sparse_in = formatted.get("sparse")
+ if not isinstance(sparse_in, dict):
+ return None
+ indices = sparse_in.get("indices")
+ values = sparse_in.get("values")
+ if indices is None or values is None:
+ return None
+ if not isinstance(indices, np.ndarray) or not isinstance(values, np.ndarray):
+ return None
+ if indices.ndim != 1 or values.ndim != 1:
+ return None
+ if indices.shape[0] != values.shape[0]:
+ return None
+ # Adapter-layer convention is ``np.int32`` indices; anything
+ # wider / signedness-different would reshape on .tolist() but we
+ # stay strict so the gate is obvious at review time.
+ if indices.dtype != np.int32:
+ return None
+ # v1: float32 values only. float16 (the other dtype the legacy
+ # path labels) stays on Python until we teach the Rust shaper
+ # the ``"<f2"`` sentinel variant.
+ if values.dtype != np.float32:
+ return None
+
+ encode_task = getattr(getattr(config, "tasks", None), "encode", None)
+ sparse_cfg = getattr(encode_task, "sparse", None) if encode_task else None
+ sparse_dim = sparse_cfg.dim if sparse_cfg else None
+ dims = int(sparse_dim) if sparse_dim is not None else None
+
+ return RawOutput(
+ sparse=SparseOutput(
+ # ``.tolist()`` widens np.int32 → Python int (exact) and
+ # np.float32 → Python float (exact round-trip). Rust
+ # rehydrates via ``Vec<i32>`` / ``Vec<f32>`` with narrowing.
+ indices=indices.tolist(),
+ values=values.tolist(),
+ dims=dims,
+ ),
+ )
+
+
+def _maybe_multivector_raw_output(
+ formatted: dict[str, Any],
+ config: Any,
+ output_types: list[str],
+) -> RawOutput | None:
+ """Multivector-only fast path for the Rust output shaper.
+
+ Mirrors the invariants of the ``multivector`` branch of
+ ``_wrap_encode_output``:
+
+ * Single output key == ``multivector``.
+ * ``np.float32`` 2-D ``[num_tokens, token_dims]`` ndarray.
+ * NOT bit-packed binary (``shape[1] < mv_dim`` with uint8
+ dtype) — the binary path stays in Python for v1 because the
+ Rust shaper does not know the ``"binary"`` dtype tag yet.
+ * ``shape[1]`` matches the configured ``token_dims`` when the
+ model exposes one, so the Rust shaper's ``num_tokens ×
+ token_dims`` invariant holds without Python-side backfill.
+ """
+ import numpy as np # noqa: PLC0415
+
+ _MV_NDIM = 2 # `[num_tokens, token_dims]` — the only shape we forward.
+
+ if output_types != ["multivector"]:
+ return None
+ if set(formatted.keys()) - {"multivector"}:
+ return None
+ arr = formatted.get("multivector")
+ if not isinstance(arr, np.ndarray):
+ return None
+ if arr.dtype != np.float32:
+ return None
+ if arr.ndim != _MV_NDIM:
+ return None
+
+ encode_task = getattr(getattr(config, "tasks", None), "encode", None)
+ mv_cfg = getattr(encode_task, "multivector", None) if encode_task else None
+ mv_dim = mv_cfg.dim if mv_cfg else None
+
+ num_tokens = int(arr.shape[0])
+ if mv_dim is not None:
+ # Bit-packed binary has shape[1] == dim/8 with uint8 dtype —
+ # the dtype check above already refused uint8, but also
+ # refuse a narrower float32 shape just in case an adapter
+ # ever pre-flattens/truncates.
+ if arr.shape[1] != int(mv_dim):
+ return None
+ token_dims = int(mv_dim)
+ else:
+ token_dims = int(arr.shape[1])
+
+ # Values must be contiguous in C order so ``.tobytes()`` (and the
+ # Rust ``values.to_le_bytes()`` equivalent) agree. ``tolist()``
+ # on a 2-D ndarray returns a nested list; ``ravel()`` flattens
+ # row-major first so we stay byte-compatible regardless of input
+ # memory layout.
+ return RawOutput(
+ multivector=MultivectorOutput(
+ values=arr.ravel(order="C").tolist(),
+ num_tokens=num_tokens,
+ token_dims=token_dims,
+ ),
+ )
+
+
+# ---------------------------------------------------------------------------
+# Wire formatting helpers
+# ---------------------------------------------------------------------------
+
+_NP_DTYPE_MAP = {"float32": "float32", "float16": "float16", "int8": "int8", "uint8": "binary"}
+
+
+def _wrap_encode_output(output: dict, config: Any) -> dict:
+ """Wrap raw numpy arrays from EncodeHandler.format_output into the
+ DenseVector / SparseVector / MultiVector wire format the SDK expects.
+
+ The HTTP path does this via pydantic models (see
+ ``api/encode.py::_format_dense`` / ``_format_sparse`` /
+ ``_format_multivector``); the queue path publishes msgpack bytes
+ directly, so the same wrapping must happen here. Keeping the two
+ paths in sync matters — an SDK client that round-trips via HTTP then
+ via queue otherwise sees different shapes for ``sparse`` and
+ ``multivector``.
+ """
+ import numpy as np # noqa: PLC0415
+
+ wrapped = dict(output)
+
+ encode_task = getattr(config, "tasks", None)
+ encode_task = getattr(encode_task, "encode", None)
+
+ if "dense" in wrapped and isinstance(wrapped["dense"], np.ndarray):
+ arr = wrapped["dense"]
+ dense_cfg = getattr(encode_task, "dense", None) if encode_task else None
+ dense_dim = dense_cfg.dim if dense_cfg else None
+
+ is_binary = arr.dtype == np.uint8 and dense_dim and arr.shape[0] < dense_dim
+ dims = dense_dim if dense_dim is not None else arr.shape[0]
+ dtype = "binary" if is_binary else _NP_DTYPE_MAP.get(str(arr.dtype), "float32")
+
+ wrapped["dense"] = {"dims": int(dims), "dtype": dtype, "values": arr}
+
+ if "sparse" in wrapped and isinstance(wrapped["sparse"], dict):
+ # Adapter output shape: {"indices": np.ndarray, "values": np.ndarray}
+ # SDK wire shape: {"dims": int|None, "dtype": "float32"|"float16",
+ # "indices": np.ndarray, "values": np.ndarray}
+ sparse_in = wrapped["sparse"]
+ indices = sparse_in.get("indices")
+ values = sparse_in.get("values")
+ if indices is not None and values is not None:
+ if not isinstance(indices, np.ndarray):
+ indices = np.asarray(indices)
+ if not isinstance(values, np.ndarray):
+ values = np.asarray(values)
+ sparse_cfg = getattr(encode_task, "sparse", None) if encode_task else None
+ sparse_dim = sparse_cfg.dim if sparse_cfg else None
+ dtype = _NP_DTYPE_MAP.get(str(values.dtype), "float32")
+ # Sparse only supports float{32,16}; fall back rather than
+ # silently mislabel.
+ if dtype not in {"float32", "float16"}:
+ dtype = "float32"
+ wrapped["sparse"] = {
+ "dims": int(sparse_dim) if sparse_dim is not None else None,
+ "dtype": dtype,
+ "indices": indices,
+ "values": values,
+ }
+
+ if "multivector" in wrapped and isinstance(wrapped["multivector"], np.ndarray):
+ arr = wrapped["multivector"]
+ mv_cfg = getattr(encode_task, "multivector", None) if encode_task else None
+ mv_dim = mv_cfg.dim if mv_cfg else None
+ # Binary multivector packs `dim/8` bytes per token; detect by
+ # `shape[1] < mv_dim` like `_format_multivector` does.
+ if arr.dtype == np.uint8 and mv_dim is not None and arr.shape[1] < mv_dim:
+ token_dims = int(mv_dim)
+ dtype = "binary"
+ else:
+ token_dims = int(mv_dim if mv_dim is not None else arr.shape[1])
+ dtype = _NP_DTYPE_MAP.get(str(arr.dtype), "float32")
+ wrapped["multivector"] = {
+ "token_dims": token_dims,
+ "num_tokens": int(arr.shape[0]),
+ "dtype": dtype,
+ "values": arr,
+ }
+
+ return wrapped
+
+
+def _dict_to_item(d: dict) -> Item:
+ """Convert an SDK wire-format dict into a server-side Item struct.
+
+ The SDK ships ``content`` while the server expects ``text``; remap and
+ drop any unknown keys so the Item constructor does not raise.
+ """
+ if "content" in d and "text" not in d:
+ d = {**d, "text": d.pop("content")}
+ known = set(Item.__struct_fields__)
+ return Item(**{k: v for k, v in d.items() if k in known})
+
+
+# ---------------------------------------------------------------------------
+# QueueExecutor
+# ---------------------------------------------------------------------------
+
+
+class QueueExecutor:
+ """NATS-free execution layer fronted by the IPC server for the worker-sidecar.
+
+ The executor owns the path from "decoded work items have arrived for model X"
+ to "per-item outcomes ready to be ACKed, NAKed, or replied to". It does NOT
+ own JetStream fetch, ACK/NAK, payload store fetch, or reply publish — those
+ live in the worker-sidecar.
+ """
+
+ def __init__(self, registry: ModelRegistry) -> None:
+ self._registry = registry
+ # Per-model descriptor cache. Populated on the first
+ # ``EnsureModelReady`` for a model and reused on every
+ # subsequent batch's handshake (the dispatcher re-handshakes
+ # per group). Keeps file I/O off the hot path:
+ # ``_materialise_tokenizer`` runs once at cold start, then we
+ # just hand back the cached struct. Cleared by
+ # :meth:`invalidate_model_descriptor` when a model is unloaded
+ # or hot-reloaded.
+ self._descriptor_cache: dict[str, ModelDescriptor] = {}
+
+ @property
+ def registry(self) -> ModelRegistry:
+ return self._registry
+
+ def invalidate_model_descriptor(self, model_id: str) -> None:
+ """Drop the cached descriptor for ``model_id``.
+
+ Called when a model is unloaded or hot-reloaded so the next
+ ``EnsureModelReady`` re-materialises the tokeniser and the
+ sidecar picks up the new ``tokenizer_id``. Safe to call for
+ unknown models (no-op).
+ """
+ self._descriptor_cache.pop(model_id, None)
+
+ def apply_model_config(self, req: ApplyModelConfigRequest) -> ApplyModelConfigResponse:
+ """Validate and add a bundle-scoped config delta to the local registry."""
+ if not req.bundle_id:
+ msg = "bundle_id is required"
+ raise ValueError(msg)
+ if not req.model_config.strip():
+ msg = "model_config is required"
+ raise ValueError(msg)
+
+ raw = yaml.safe_load(req.model_config)
+ if not isinstance(raw, dict):
+ msg = "model_config must decode to a YAML mapping"
+ raise ValueError(msg)
+
+ model_config = ModelConfig(**raw)
+ if req.model_id and model_config.sie_id != req.model_id:
+ msg = f"model_id mismatch: notification={req.model_id!r} config={model_config.sie_id!r}"
+ raise ValueError(msg)
+
+ self._registry.add_config(model_config)
+ self.invalidate_model_descriptor(model_config.sie_id)
+ bundle_hash = compute_bundle_config_hash_cached(self._registry, req.bundle_id)
+ return ApplyModelConfigResponse(
+ applied=True,
+ bundle_config_hash=bundle_hash,
+ config_version=int(getattr(self._registry, "_config_version", 0)),
+ )
+
+ def compute_bundle_config_hash(self, bundle_id: str) -> str:
+ """Return the local registry hash for ``bundle_id``."""
+ if not bundle_id:
+ return ""
+ return compute_bundle_config_hash_cached(self._registry, bundle_id)
+
+ # -- Readiness ---------------------------------------------------------
+
+ async def ensure_model_ready(self, model_id: str) -> ReadinessState:
+ """Return the current readiness state for a model, triggering a load if needed.
+
+ Mapping (for the Rust side):
+ - ``ready``: continue processing
+ - ``loading_started``: NAK with base delay (this call triggered a new load)
+ - ``loading_in_progress``: NAK with longer delay (already loading)
+ - ``retry_later``: NAK with base delay (unknown error path)
+ """
+ if self._registry.is_loaded(model_id):
+ return "ready"
+
+ if self._registry.is_loading(model_id):
+ return "loading_in_progress"
+
+ try:
+ started = await self._registry.start_load_async(model_id, self._registry.device)
+ except KeyError:
+ # Unknown model — gateway should not be sending us work for it, but
+ # be defensive: tell caller to retry rather than hard-erroring.
+ return "retry_later"
+ except Exception: # noqa: BLE001
+ logger.warning("ensure_model_ready: start_load_async failed for %s", model_id, exc_info=True)
+ return "retry_later"
+
+ return "loading_started" if started else "loading_in_progress"
+
+ # -- Handshake-driven model descriptor --------------------------------
+
+ def get_model_descriptor(self, model_id: str) -> ModelDescriptor | None:
+ """Return the ``ModelDescriptor`` carried on the
+ ``EnsureModelReadyResponse`` for this model, or ``None`` if the
+ adapter has nothing structured to declare yet (slow tokenizer,
+ image / audio adapter, model not yet loaded).
+
+ The descriptor lets the worker-sidecar discover per-model
+ capabilities at runtime; see
+ ``packages/sie_server_sidecar/docs/architecture-guide.md``.
+
+ Populates:
+
+ * ``tokenizer_path`` — path to a sidecar-readable
+ ``tokenizer.json`` materialised from
+ ``preprocessor.backend_tokenizer.to_str(pretty=False)``. Stays
+ ``None`` for slow tokenizers (no canonical JSON to ship) and
+ for adapters that don't expose a ``TextPreprocessor`` (image /
+ audio).
+ * ``tokenizer_id`` — BLAKE3 (32 hex) of the canonical tokenizer
+ JSON. Same value the sidecar will compute from the
+ materialised file, so the two sides can verify byte-identity
+ before enabling the Rust-tokenise fast path.
+ * ``max_seq_len`` — ``tokenizer.model_max_length`` when sane
+ (``< 10**6``; HF's ``VERY_LARGE_INTEGER`` sentinel reads as
+ ``None`` here).
+ * ``output_types`` — informational; left empty for now since
+ per-request shape checks in ``_maybe_*_raw_output`` are the
+ authoritative gate. Future work can populate from
+ ``adapter.supported_output_types`` if/when adapters expose it.
+ * ``supports_run_batch`` — every Python adapter does.
+
+ Cached after the first successful build; the dispatcher
+ re-handshakes on every batch and we don't want to re-stat the
+ staging dir each time. Use
+ :meth:`invalidate_model_descriptor` on unload / hot reload.
+ """
+ cached = self._descriptor_cache.get(model_id)
+ if cached is not None:
+ return cached
+
+ # Gate on the model actually being loaded — calling this before
+ # ``ensure_model_ready`` would race the registry. The IPC
+ # server only invokes us on the ``ready`` branch so this is
+ # belt-and-braces, but it also short-circuits MagicMock-based
+ # tests where ``get_worker`` returns ``None`` for unknown ids.
+ try:
+ if self._registry.get_worker(model_id) is None:
+ return None
+ except (KeyError, AttributeError):
+ return None
+
+ tokenizer_path: str | None = None
+ tokenizer_id: str | None = None
+ max_seq_len: int | None = None
+
+ try:
+ preprocessor = self._registry.preprocessor_registry.get_preprocessor(model_id, "text")
+ except Exception: # noqa: BLE001
+ preprocessor = None
+ if preprocessor is not None and hasattr(preprocessor, "tokenizer_id"):
+ try:
+ candidate_id = preprocessor.tokenizer_id # may be None for slow tokenizers
+ except Exception: # noqa: BLE001
+ logger.debug("get_model_descriptor: tokenizer_id property raised for %s", model_id, exc_info=True)
+ candidate_id = None
+ # Strict type guard: only ``str`` survives. Test fixtures
+ # often pass ``MagicMock``-based preprocessors whose
+ # ``tokenizer_id`` would otherwise be a Mock; treating that
+ # as a real id would crash msgpack later.
+ if isinstance(candidate_id, str):
+ tokenizer_id = candidate_id
+ inner = getattr(preprocessor, "_tokenizer", None)
+ if inner is not None:
+ tokenizer_path = _materialise_tokenizer(model_id, inner)
+ # ``model_max_length`` is set to a giant sentinel
+ # (``int(1e30)``) when the tokenizer doesn't declare a
+ # cap; treat anything implausibly large as "unset".
+ raw_max = getattr(inner, "model_max_length", None)
+ if (
+ isinstance(raw_max, int)
+ and not isinstance(raw_max, bool)
+ and 0 < raw_max < _TOKENIZER_MAX_SEQ_LEN_PLAUSIBILITY_CAP
+ ):
+ max_seq_len = raw_max
+
+ # Surface the adapter's model-default templates so the sidecar
+ # can apply them before tokenising in Rust. All
+ # text adapters store these as ``_query_template`` /
+ # ``_doc_template`` (set in their ``__init__`` from the model
+ # YAML). Image / audio adapters and adapters without text
+ # templating leave them as ``None``, which keeps the sidecar
+ # on the legacy "no Rust-side templating" path for that model.
+ # ``MagicMock``-based test fixtures and adapters that don't
+ # follow the convention silently degrade the same way.
+ default_query_template: str | None = None
+ default_doc_template: str | None = None
+ try:
+ worker = self._registry.get_worker(model_id)
+ adapter = worker.adapter if worker is not None else None
+ except Exception: # noqa: BLE001
+ adapter = None
+ if adapter is not None:
+ qt = getattr(adapter, "_query_template", None)
+ if isinstance(qt, str):
+ default_query_template = qt
+ dt = getattr(adapter, "_doc_template", None)
+ if isinstance(dt, str):
+ default_doc_template = dt
+
+ descriptor = ModelDescriptor(
+ tokenizer_path=tokenizer_path,
+ tokenizer_id=tokenizer_id,
+ max_seq_len=max_seq_len,
+ output_types=[],
+ supports_run_batch=True,
+ default_query_template=default_query_template,
+ default_doc_template=default_doc_template,
+ )
+ self._descriptor_cache[model_id] = descriptor
+ return descriptor
+
+ def get_batch_budget(self, model_id: str) -> int | None:
+ """Return the per-batch dispatch budget for a model, or ``None`` if
+ unknown / model not loaded.
+
+ Reads ``worker._batch_config.max_batch_requests`` when available. Queue
+ consumers (Python or Rust) use this to cap how many messages for
+ one model are processed per fetch batch so a hot model doesn't
+ monopolise the GPU.
+ """
+ try:
+ worker = self._registry.get_worker(model_id)
+ except (KeyError, AttributeError):
+ return None
+ if worker is None:
+ return None
+ batch_config = getattr(worker, "_batch_config", None)
+ if batch_config is None:
+ return None
+ budget = getattr(batch_config, "max_batch_requests", None)
+ if isinstance(budget, int) and budget > 0:
+ return budget
+ return None
+
+ # -- Encode ------------------------------------------------------------
+
+ async def process_encode_batch(self, req: ProcessEncodeBatchRequest) -> BatchOutcome:
+ """Run an encode batch through EncodePipeline and return per-item outcomes.
+
+ Sub-grouping: items from different API requests may have different ``output_types``,
+ ``instruction``, ``is_query``, or ``options`` — these cannot share a
+ single ``EncodePipeline.run_encode()`` call.
+ """
+ from sie_server.core.encode_pipeline import EncodePipeline # noqa: PLC0415
+
+ model_id = req.model_id
+ items = req.items
+
+ try:
+ config = self._registry.get_config(model_id)
+ except KeyError:
+ # Model evicted mid-batch — NAK all items so another worker (or
+ # this one after re-loading) processes them.
+ return BatchOutcome(outcomes=[_nak_outcome(it) for it in items])
+
+ outcomes: dict[str, ItemOutcome] = {}
+
+ # Group key includes `profile_id` and `bundle_config_hash` — the
+ # gateway uses those to select adapter variants / postprocessors,
+ # and merging items with different values would run the wrong
+ # pipeline. Keep the key in sync with whatever `EncodePipeline.run_encode`
+ # actually reads; add more fields here if it grows.
+ groups: dict[tuple, list[EncodeBatchItem]] = {}
+ for bi in items:
+ output_types = tuple(bi.output_types or ["dense"])
+ options_key = msgpack.packb(bi.options, use_bin_type=True) if bi.options else b""
+ key = (
+ output_types,
+ bi.instruction,
+ bi.is_query,
+ options_key,
+ bi.profile_id,
+ bi.bundle_config_hash,
+ )
+ groups.setdefault(key, []).append(bi)
+
+ # Record IPC-batch shape so operators can see the fragmentation
+ # ratio (items per IPC batch vs items per GPU forward pass).
+ # Emitted once per batch *after* grouping but *before* running
+ # any forward pass, so batches whose inference throws are still
+ # accounted for in the histogram. Model-eviction NAKs above
+ # are intentionally not recorded — no real work was attempted.
+ record_ipc_batch_shape(
+ model=model_id,
+ endpoint="encode",
+ total_items=len(items),
+ sub_group_sizes=[len(g) for g in groups.values()],
+ )
+
+ for group_key, group in groups.items():
+ (output_types_t, instruction, is_query, options_key, _profile_id, _bundle_hash) = group_key
+ output_types = list(output_types_t)
+ options = msgpack.unpackb(options_key, raw=False) if options_key else {}
+ server_items = [_dict_to_item(bi.item) for bi in group]
+ # Collect worker-sidecar prepared_tokens aligned with
+ # ``server_items``. ``None`` per item is expected for the
+ # v1 safety-rule skips (`is_query`, `instruction`,
+ # non-text, empty text). The pipeline accepts the mix
+ # per-item: items with usable Rust bytes skip Python
+ # tokenisation, items with ``None`` are tokenised in
+ # Python and spliced back — see
+ # ``TextPreprocessor.try_prepare_from_prepared_tokens``
+ # for the hybrid policy. Whole-batch fallback only fires
+ # on correctness-critical drift (tokenizer_id mismatch,
+ # malformed wire shape).
+ prepared_tokens_per_item = [bi.prepared_tokens for bi in group]
+ if not any(pt is not None for pt in prepared_tokens_per_item):
+ # Not a single fast-path candidate — pass None so the
+ # pipeline doesn't even bother looking up the
+ # preprocessor's cached tokenizer_id.
+ prepared_tokens_per_item = None
+
+ try:
+ formatted_outputs, timing = await EncodePipeline.run_encode(
+ registry=self._registry,
+ model=model_id,
+ items=server_items,
+ output_types=output_types,
+ instruction=instruction,
+ config=config,
+ is_query=is_query,
+ options=options,
+ prepared_tokens_per_item=prepared_tokens_per_item,
+ )
+
+ if len(formatted_outputs) != len(group):
+ # Output/input length mismatch means the adapter
+ # silently dropped items. Surface as a per-item error
+ # rather than publishing empty success results.
+ logger.warning(
+ "Encode sub-batch for %s returned %d outputs for %d items — emitting per-item errors",
+ model_id,
+ len(formatted_outputs),
+ len(group),
+ )
+ for bi in group:
+ outcomes[bi.work_item_id] = _error_outcome(
+ bi,
+ "inference_error",
+ "adapter returned fewer outputs than items",
+ )
+ else:
+ for idx, bi in enumerate(group):
+ raw_output: RawOutput | None = None
+ result_msgpack: bytes | None = None
+ # Dispatch by the single declared output type —
+ # the v1 wire contract is exactly one variant
+ # per ``RawOutput``. Multi-output items (no
+ # single key matches) and adapter outputs that
+ # don't pass the per-helper safety rules drop
+ # to the legacy ``_wrap_encode_output`` path
+ # below.
+ if output_types == ["dense"]:
+ raw_output = _maybe_dense_raw_output(
+ formatted_outputs[idx],
+ config,
+ output_types,
+ )
+ elif output_types == ["sparse"]:
+ raw_output = _maybe_sparse_raw_output(
+ formatted_outputs[idx],
+ config,
+ output_types,
+ )
+ elif output_types == ["multivector"]:
+ raw_output = _maybe_multivector_raw_output(
+ formatted_outputs[idx],
+ config,
+ output_types,
+ )
+ if raw_output is None:
+ output = _wrap_encode_output(formatted_outputs[idx], config)
+ result_msgpack = msgpack.packb(output, use_bin_type=True)
+ outcomes[bi.work_item_id] = ItemOutcome(
+ work_item_id=bi.work_item_id,
+ request_id=bi.request_id,
+ item_index=bi.item_index,
+ disposition="publish_and_ack",
+ result_msgpack=result_msgpack,
+ raw_output=raw_output,
+ 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,
+ )
+ except Exception as e: # noqa: BLE001
+ logger.warning("Encode sub-batch failed for model %s: %s", model_id, e)
+ for bi in group:
+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)
+
+ return BatchOutcome(outcomes=[outcomes[bi.work_item_id] for bi in items])
+
+ # -- Score -------------------------------------------------------------
+
+ async def process_score_batch(self, req: ProcessScoreBatchRequest) -> BatchOutcome:
+ """Run a score batch — items are submitted concurrently so BatchFormer
+ can cross-batch them inside ``ModelWorker`` (same as the legacy path).
+ """
+ import asyncio # noqa: PLC0415
+
+ model_id = req.model_id
+
+ # Score dispatches one task per IPC item; actual GPU batching
+ # happens below in BatchFormer. We still report
+ # sub_groups == items so the fragmentation dashboard panel
+ # treats all three endpoints uniformly (any deviation then
+ # becomes a signal that BatchFormer merged less than expected
+ # — surfaced via sie_gpu_batch_items in model_worker.py).
+ record_ipc_batch_shape(
+ model=model_id,
+ endpoint="score",
+ total_items=len(req.items),
+ sub_group_sizes=[1] * len(req.items),
+ )
+
+ tasks = [self._process_single_score(model_id, bi) for bi in req.items]
+ outcomes = await asyncio.gather(*tasks)
+ return BatchOutcome(outcomes=list(outcomes))
+
+ async def _process_single_score(self, model_id: str, bi: ScoreBatchItem) -> ItemOutcome:
+ try:
+ worker = await self._registry.start_worker(model_id)
+ except (KeyError, RuntimeError) as e:
+ logger.info("Model %s not available for score: %s — NAKing", model_id, e)
+ return _nak_outcome(bi)
+
+ query_item = _dict_to_item(bi.query_item)
+ score_items = [_dict_to_item(it) for it in bi.score_items]
+
+ try:
+ timing = RequestTiming()
+
+ query_len = len(query_item.text) if query_item.text else 0
+ timing.start_tokenization()
+ prepared_items = []
+ for i, it in enumerate(score_items):
+ doc_len = len(it.text) if it.text else 0
+ prepared_items.append(ScorePreparedItem(cost=query_len + doc_len, original_index=i))
+ timing.end_tokenization()
+
+ future = await worker.submit_score(
+ prepared_items=prepared_items,
+ query=query_item,
+ items=score_items,
+ instruction=bi.instruction,
+ options=bi.options or {},
+ timing=timing,
+ )
+ worker_result = await future
+
+ score_output = cast("Any", worker_result.output)
+ raw_scores = [float(score_output.scores[i]) for i in range(score_output.batch_size)]
+ 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)
+ ]
+
+ # Score output is always Rust-frameable: the Python and Rust
+ # sort/rank paths produce byte-identical results (see the
+ # parity test in ``test_queue_executor_stage1d.py``).
+ # Rust-side framing is unconditional for score; the Python-framed fallback
+ # sort+pack lives only as a doc-comment record of what
+ # ``sie_server_sidecar::output::build_score_payload`` mirrors.
+ raw_output: RawOutput | None = RawOutput(
+ score=ScoreOutputRaw(scores=raw_scores, item_ids=item_ids),
+ )
+ result_msgpack: bytes | None = None
+
+ return ItemOutcome(
+ work_item_id=bi.work_item_id,
+ request_id=bi.request_id,
+ item_index=bi.item_index,
+ disposition="publish_and_ack",
+ result_msgpack=result_msgpack,
+ raw_output=raw_output,
+ 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,
+ )
+ except Exception as e: # noqa: BLE001
+ logger.warning("Score failed for %s: %s", bi.work_item_id, e)
+ return _inference_exception_outcome(bi, e)
+
+ # -- Extract -----------------------------------------------------------
+
+ async def process_extract_batch(self, req: ProcessExtractBatchRequest) -> BatchOutcome:
+ """Run an extract batch — items submitted concurrently so BatchFormer can batch them."""
+ import asyncio # noqa: PLC0415
+
+ model_id = req.model_id
+
+ record_ipc_batch_shape(
+ model=model_id,
+ endpoint="extract",
+ total_items=len(req.items),
+ sub_group_sizes=[1] * len(req.items),
+ )
+
+ tasks = [self._process_single_extract(model_id, bi) for bi in req.items]
+ outcomes = await asyncio.gather(*tasks)
+ return BatchOutcome(outcomes=list(outcomes))
+
+ async def _process_single_extract(self, model_id: str, bi: ExtractBatchItem) -> ItemOutcome:
+ try:
+ worker = await self._registry.start_worker(model_id)
+ except (KeyError, RuntimeError) as e:
+ logger.info("Model %s not available for extract: %s — NAKing", model_id, e)
+ return _nak_outcome(bi)
+
+ server_item = _dict_to_item(bi.item)
+
+ try:
+ timing = RequestTiming()
+ timing.start_tokenization()
+ char_count = len(server_item.text) if server_item.text else 0
+ prepared_items = [ExtractPreparedItem(cost=char_count, original_index=0)]
+ timing.end_tokenization()
+
+ future = await worker.submit_extract(
+ prepared_items=prepared_items,
+ items=[server_item],
+ labels=bi.labels,
+ output_schema=bi.output_schema,
+ instruction=bi.instruction,
+ options=bi.options or {},
+ timing=timing,
+ )
+ worker_result = await future
+
+ extraction_results = ExtractHandler.format_output(cast("Any", worker_result.output))
+ if not extraction_results:
+ # Adapter returned no results for a single-item request —
+ # surface as an error instead of silently publishing an
+ # empty object (which the client would parse as "success
+ # with no fields").
+ return _error_outcome(bi, "inference_error", "adapter returned no extraction results")
+ result_msgpack = msgpack.packb(extraction_results[0], use_bin_type=True)
+
+ return ItemOutcome(
+ work_item_id=bi.work_item_id,
+ request_id=bi.request_id,
+ item_index=bi.item_index,
+ disposition="publish_and_ack",
+ result_msgpack=result_msgpack,
+ 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,
+ )
+ except Exception as e: # noqa: BLE001
+ logger.warning("Extract failed for %s: %s", bi.work_item_id, e)
+ return _inference_exception_outcome(bi, e)
+
+
+# ---------------------------------------------------------------------------
+# Outcome helpers
+# ---------------------------------------------------------------------------
+
+
+def _nak_outcome(bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem) -> ItemOutcome:
+ return ItemOutcome(
+ work_item_id=bi.work_item_id,
+ request_id=bi.request_id,
+ item_index=bi.item_index,
+ disposition="nak_retry",
+ nak_delay_ms=int(_default_nak_delay_s() * 1000),
+ )
+
+
+def _oom_nak_outcome(bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem) -> ItemOutcome:
+ return ItemOutcome(
+ work_item_id=bi.work_item_id,
+ request_id=bi.request_id,
+ item_index=bi.item_index,
+ disposition="nak_retry",
+ nak_delay_ms=int(_oom_nak_delay_s() * 1000),
+ )
+
+
+def _inference_exception_outcome(
+ bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem,
+ exc: BaseException,
+) -> ItemOutcome:
+ if is_oom_error(exc):
+ return _oom_nak_outcome(bi)
+ if isinstance(exc, InvalidMediaError):
+ return _error_outcome(bi, ErrorCode.INVALID_INPUT.value, str(exc))
+ return _error_outcome(bi, "inference_error", str(exc))
+
+
+def _error_outcome(bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem, code: str, message: str) -> ItemOutcome:
+ return ItemOutcome(
+ work_item_id=bi.work_item_id,
+ request_id=bi.request_id,
+ item_index=bi.item_index,
+ disposition="publish_error_and_ack",
+ error=message,
+ error_code=code,
+ )
+
+
+def _default_nak_delay_s() -> float:
+ """NAK delay (seconds) used when a model is evicted / not yet ready.
+
+ Must agree with the worker-sidecar's ``SIE_NAK_DELAY_S`` default so
+ redelivery behaviour is consistent across either side choosing the
+ fallback.
+ """
+ import os # noqa: PLC0415
+
+ return float(os.environ.get("SIE_NAK_DELAY_S", "5.0"))
+
+
+def _oom_nak_delay_s() -> float:
+ """NAK delay (seconds) for retryable OOM / RESOURCE_EXHAUSTED failures.
+
+ This mirrors the deleted Python NATS worker contract: do not publish an
+ error and ACK for OOM, because JetStream redelivery may land on a sibling
+ worker after memory pressure clears.
+ """
+ return float(os.environ.get("SIE_OOM_NAK_DELAY_S", "10.0"))
diff --git a/packages/sie_server/src/sie_server/types/inputs.py b/packages/sie_server/src/sie_server/types/inputs.py
index b7175281d..465e4cad4 100644
--- a/packages/sie_server/src/sie_server/types/inputs.py
+++ b/packages/sie_server/src/sie_server/types/inputs.py
@@ -169,8 +169,8 @@ class InvalidMediaError(ValueError):
- HTTP / in-process: the endpoints' ``except ValueError`` routes it through
``InferenceErrorHandler.handle_value_error`` (see ``api/encode.py``).
- - Queue / NATS: ``_classify_inference_exception`` maps it to
- ``ErrorCode.INVALID_INPUT`` (see ``nats_pull_loop.py``).
+ - Queue / sidecar: ``queue_executor._inference_exception_outcome`` maps it
+ to ``ErrorCode.INVALID_INPUT`` before the sidecar publishes the result.
Without this, an un-decoded base64 ``str`` slipping past the wire boundary
raised ``TypeError: a bytes-like object is required, not 'str'`` deep inside
diff --git a/packages/sie_server/src/sie_server/types/outputs.py b/packages/sie_server/src/sie_server/types/outputs.py
index 0d044f4ca..24a7cad03 100644
--- a/packages/sie_server/src/sie_server/types/outputs.py
+++ b/packages/sie_server/src/sie_server/types/outputs.py
@@ -3,7 +3,7 @@
These types define the structure of embedding outputs: dense vectors, sparse vectors,
and multi-vectors (for late-interaction models like ColBERT).
-Per DESIGN.md Section 5.9, numpy arrays are preserved for msgpack serialization.
+Numpy arrays are preserved for msgpack serialization.
For JSON fallback, arrays are converted to lists on serialization.
Using TypedDict for zero runtime overhead.
diff --git a/packages/sie_server/tests/adapters/test_clip.py b/packages/sie_server/tests/adapters/test_clip.py
index 2ce8d351b..a5b5ff0a0 100644
--- a/packages/sie_server/tests/adapters/test_clip.py
+++ b/packages/sie_server/tests/adapters/test_clip.py
@@ -67,6 +67,15 @@ class TestCLIPAdapter:
dims = adapter.dims
assert dims.dense is None
+ def test_accepts_dense_dim_kwarg(self) -> None:
+ """Construction with dense_dim= must not raise (loader contract)."""
+ adapter = CLIPAdapter(
+ "openai/clip-vit-base-patch32",
+ dense_dim=512,
+ )
+ assert adapter._configured_dense_dim == 512
+ assert adapter.dims.dense == 512
+
def test_encode_before_load_raises(self, adapter: CLIPAdapter) -> None:
"""Encode before load raises error."""
items = [Item(text="hello")]
@@ -94,26 +103,61 @@ class TestCLIPAdapter:
with pytest.raises(ValueError, match="Unsupported output types"):
adapter.encode(items, output_types=["multivector"])
- @patch("transformers.CLIPModel")
- @patch("transformers.CLIPProcessor")
+ @patch("transformers.CLIPModel.from_pretrained")
+ @patch("transformers.CLIPProcessor.from_pretrained")
def test_load(
self,
- mock_processor_class: MagicMock,
- mock_model_class: MagicMock,
+ mock_processor_from_pretrained: MagicMock,
+ mock_model_from_pretrained: MagicMock,
adapter: CLIPAdapter,
mock_clip_model: MagicMock,
mock_clip_processor: MagicMock,
) -> None:
"""Load initializes the model."""
- mock_model_class.from_pretrained.return_value = mock_clip_model
- mock_processor_class.from_pretrained.return_value = mock_clip_processor
+ mock_model_from_pretrained.return_value = mock_clip_model
+ mock_processor_from_pretrained.return_value = mock_clip_processor
adapter.load("cpu")
- mock_model_class.from_pretrained.assert_called_once()
- mock_processor_class.from_pretrained.assert_called_once()
+ mock_model_from_pretrained.assert_called_once()
+ mock_processor_from_pretrained.assert_called_once()
assert adapter.dims.dense == 512
+ @patch("transformers.CLIPModel.from_pretrained")
+ @patch("transformers.CLIPProcessor.from_pretrained")
+ def test_load_accepts_matching_dense_dim(
+ self,
+ mock_processor_from_pretrained: MagicMock,
+ mock_model_from_pretrained: MagicMock,
+ mock_clip_model: MagicMock,
+ mock_clip_processor: MagicMock,
+ ) -> None:
+ """Load accepts catalog dense_dim when it matches projection_dim."""
+ adapter = CLIPAdapter("openai/clip-vit-base-patch32", dense_dim=512)
+ mock_model_from_pretrained.return_value = mock_clip_model
+ mock_processor_from_pretrained.return_value = mock_clip_processor
+
+ adapter.load("cpu")
+
+ assert adapter.dims.dense == 512
+
+ @patch("transformers.CLIPModel.from_pretrained")
+ @patch("transformers.CLIPProcessor.from_pretrained")
+ def test_load_rejects_dense_dim_mismatch(
+ self,
+ mock_processor_from_pretrained: MagicMock,
+ mock_model_from_pretrained: MagicMock,
+ mock_clip_model: MagicMock,
+ mock_clip_processor: MagicMock,
+ ) -> None:
+ """Load rejects catalog dense_dim when it differs from projection_dim."""
+ adapter = CLIPAdapter("openai/clip-vit-base-patch32", dense_dim=768)
+ mock_model_from_pretrained.return_value = mock_clip_model
+ mock_processor_from_pretrained.return_value = mock_clip_processor
+
+ with pytest.raises(ValueError, match="configured dense_dim=768, model projection_dim=512"):
+ adapter.load("cpu")
+
@patch("sie_server.adapters.clip.torch")
def test_unload(self, mock_torch: MagicMock, adapter: CLIPAdapter) -> None:
"""Unload clears the model."""
diff --git a/packages/sie_server/tests/adapters/test_docling.py b/packages/sie_server/tests/adapters/test_docling.py
index 263461813..3c2d409fb 100644
--- a/packages/sie_server/tests/adapters/test_docling.py
+++ b/packages/sie_server/tests/adapters/test_docling.py
@@ -83,10 +83,66 @@ class TestDoclingExtract:
assert out.data is not None
assert "error" in out.data[0]
- assert "document" in out.data[0]["error"].lower()
+ assert out.data[0]["error"] # non-empty
# No converter is constructed for a malformed item
factory.assert_not_called()
+ def test_image_only_item_routes_to_converter(self) -> None:
+ adapter, factory = _make_adapter()
+
+ out = adapter.extract([Item(images=[{"data": b"\x89PNG\r\n\x1a\nfake", "format": "png"}])])
+
+ assert out.data is not None
+ assert out.data[0]["text"] == "text:default"
+ # Stream name should reflect the image format hint
+ assert out.data[0]["document"] == {"name": "document.png"}
+ factory.assert_called_once_with(ocr_enabled=False)
+
+ def test_image_without_format_defaults_to_png_name(self) -> None:
+ adapter, _ = _make_adapter()
+
+ out = adapter.extract([Item(images=[{"data": b"\x89PNG"}])])
+
+ assert out.data is not None
+ # When no format is supplied, the adapter defaults to "png" so Docling
+ # has a usable extension hint.
+ assert out.data[0]["document"] == {"name": "document.png"}
+
+ def test_document_wins_when_both_document_and_image_present(self) -> None:
+ adapter, _ = _make_adapter()
+
+ out = adapter.extract(
+ [
+ Item(
+ document={"data": b"%PDF-1.4 real", "format": "pdf"},
+ images=[{"data": b"\x89PNG ignored", "format": "png"}],
+ )
+ ]
+ )
+
+ assert out.data is not None
+ # Document path uses ``document.pdf`` stream name; image path would
+ # have produced ``document.png``.
+ assert out.data[0]["document"] == {"name": "document.pdf"}
+
+ def test_neither_document_nor_image_yields_per_item_error(self) -> None:
+ adapter, factory = _make_adapter()
+
+ out = adapter.extract([Item(text="just text")])
+
+ assert out.data is not None
+ assert "error" in out.data[0]
+ factory.assert_not_called()
+
+ def test_empty_images_list_yields_per_item_error(self) -> None:
+ adapter, factory = _make_adapter()
+
+ out = adapter.extract([Item(images=[])])
+
+ assert out.data is not None
+ assert "error" in out.data[0]
+ factory.assert_not_called()
+
def test_per_item_failure_does_not_poison_batch(self) -> None:
adapter = DoclingAdapter()
adapter._loaded = True
@@ -177,7 +233,7 @@ class TestDoclingExtract:
class TestDoclingSpec:
def test_capabilities(self) -> None:
adapter = DoclingAdapter()
- assert adapter.capabilities.inputs == ["document"]
+ assert adapter.capabilities.inputs == ["document", "image"]
assert adapter.capabilities.outputs == ["json"]
def test_unload_clears_converter_cache(self) -> None:
@@ -206,6 +262,7 @@ class TestDoclingMakeConverter:
patch("docling.document_converter.DocumentConverter") as mock_cls,
patch("docling.datamodel.pipeline_options.PdfPipelineOptions") as mock_opts,
patch("docling.document_converter.PdfFormatOption") as mock_fmt_opt,
+ patch("docling.document_converter.ImageFormatOption"),
):
adapter._make_converter(ocr_enabled=False)
@@ -221,6 +278,7 @@ class TestDoclingMakeConverter:
patch("docling.document_converter.DocumentConverter") as mock_cls,
patch("docling.datamodel.pipeline_options.PdfPipelineOptions") as mock_opts,
patch("docling.document_converter.PdfFormatOption") as mock_fmt_opt,
+ patch("docling.document_converter.ImageFormatOption"),
):
adapter._make_converter(ocr_enabled=True)
@@ -238,6 +296,7 @@ class TestDoclingMakeConverter:
patch("docling.datamodel.pipeline_options.PdfPipelineOptions") as mock_opts,
patch("docling.datamodel.accelerator_options.AcceleratorOptions") as mock_accel,
patch("docling.document_converter.PdfFormatOption") as mock_fmt_opt,
+ patch("docling.document_converter.ImageFormatOption"),
):
adapter._make_converter(ocr_enabled=False)
@@ -258,6 +317,7 @@ class TestDoclingMakeConverter:
patch("docling.datamodel.pipeline_options.PdfPipelineOptions") as mock_opts,
patch("docling.datamodel.accelerator_options.AcceleratorOptions") as mock_accel,
patch("docling.document_converter.PdfFormatOption"),
+ patch("docling.document_converter.ImageFormatOption"),
):
adapter._make_converter(ocr_enabled=True)
@@ -277,6 +337,7 @@ class TestDoclingMakeConverter:
patch("docling.datamodel.pipeline_options.PdfPipelineOptions"),
patch("docling.datamodel.accelerator_options.AcceleratorOptions") as mock_accel,
patch("docling.document_converter.PdfFormatOption"),
+ patch("docling.document_converter.ImageFormatOption"),
):
adapter._make_converter(ocr_enabled=True)
@@ -291,6 +352,7 @@ class TestDoclingMakeConverter:
patch("docling.datamodel.pipeline_options.PdfPipelineOptions"),
patch("docling.datamodel.accelerator_options.AcceleratorOptions") as mock_accel,
patch("docling.document_converter.PdfFormatOption"),
+ patch("docling.document_converter.ImageFormatOption"),
):
mock_accel.side_effect = [ValueError("invalid device"), MagicMock()]
adapter._make_converter(ocr_enabled=True)
diff --git a/packages/sie_server/tests/adapters/test_mineru_vl.py b/packages/sie_server/tests/adapters/test_mineru_vl.py
new file mode 100644
index 000000000..7511a1bd6
--- /dev/null
+++ b/packages/sie_server/tests/adapters/test_mineru_vl.py
@@ -0,0 +1,380 @@
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+import transformers
+from sie_server.types.inputs import ImageInput, Item
+
+# Force eager resolution of lazy-imported transformers classes so
+# unittest.mock.patch("transformers.AutoProcessor", ...) can intercept them.
+# Without this, `from transformers import AutoProcessor` inside the adapter's
+# load() bypasses the patched attribute and hits the real HuggingFace Hub.
+_ = transformers.AutoProcessor
+_ = transformers.Qwen2VLForConditionalGeneration
+
+
+class TestMinerUVLAdapter:
+ """Tests for MinerUVLAdapter with mocked model + processor."""
+
+ @pytest.fixture
+ def adapter(self) -> MinerUVLAdapter:
+ from sie_server.adapters.mineru_vl import MinerUVLAdapter
+
+ return MinerUVLAdapter(
+ "opendatalab/MinerU2.5-Pro-2604-1.2B",
+ compute_precision="bfloat16",
+ )
+
+ def test_capabilities(self, adapter: MinerUVLAdapter) -> None:
+ caps = adapter.capabilities
+ assert caps.inputs == ["image"]
+ assert caps.outputs == ["json"]
+
+ def test_dims_empty(self, adapter: MinerUVLAdapter) -> None:
+ dims = adapter.dims
+ assert dims.dense is None
+ assert dims.sparse is None
+ assert dims.multivector is None
+
+ def test_encode_raises(self, adapter: MinerUVLAdapter) -> None:
+ with pytest.raises(NotImplementedError, match="does not support encode"):
+ adapter.encode([Item(text="hello")], output_types=["dense"])
+
+ def test_extract_before_load_raises(self, adapter: MinerUVLAdapter) -> None:
+ items = [Item(images=[ImageInput(data=b"fake", format="jpeg")])]
+ with pytest.raises(RuntimeError, match="Model not loaded"):
+ adapter.extract(items)
+
+ def test_build_messages_default(self, adapter: MinerUVLAdapter) -> None:
+ messages = adapter._build_messages(task="[default]", instruction=None)
+ assert len(messages) == 1
+ assert messages[0]["role"] == "user"
+ content = messages[0]["content"]
+ assert content[0] == {"type": "image"}
+ assert content[1] == {"type": "text", "text": "\nText Recognition:"}
+
+ def test_build_messages_each_task(self, adapter: MinerUVLAdapter) -> None:
+ expected = {
+ "[default]": "\nText Recognition:",
+ "table": "\nTable Recognition:",
+ "equation": "\nFormula Recognition:",
+ "image": "\nImage Analysis:",
+ "chart": "\nImage Analysis:",
+ "[layout]": "\nLayout Detection:",
+ }
+ for task, prompt in expected.items():
+ messages = adapter._build_messages(task=task, instruction=None)
+ assert messages[0]["content"][1]["text"] == prompt, f"task={task}"
+
+ def test_build_messages_instruction_overrides_task(self, adapter: MinerUVLAdapter) -> None:
+ messages = adapter._build_messages(task="[default]", instruction="Read all text in Tibetan.")
+ assert messages[0]["content"][1]["text"] == "Read all text in Tibetan."
+
+ def test_default_task_validated(self) -> None:
+ from sie_server.adapters.mineru_vl import MinerUVLAdapter
+
+ with pytest.raises(ValueError, match="default_task"):
+ MinerUVLAdapter("opendatalab/MinerU2.5-Pro-2604-1.2B", default_task="nonsense")
+
+ def test_fp16_on_cuda_rejected(self, adapter: MinerUVLAdapter) -> None:
+ adapter._compute_precision = "float16"
+ with pytest.raises(ValueError, match="float16"):
+ adapter._resolve_dtype_for("cuda:0")
+
+ def test_fp16_on_cpu_falls_back_to_fp32(self, adapter: MinerUVLAdapter) -> None:
+ import torch
+
+ adapter._compute_precision = "float16"
+ # CPU path ignores compute_precision and uses fp32 — no crash.
+ assert adapter._resolve_dtype_for("cpu") == torch.float32
+
+ def test_convert_output_label_mapping(self, adapter: MinerUVLAdapter) -> None:
+ expected = {
+ "[default]": "mineru_text",
+ "table": "mineru_table",
+ "equation": "mineru_equation",
+ "image": "mineru_image",
+ "chart": "mineru_chart",
+ "[layout]": "mineru_layout",
+ }
+ for task, label in expected.items():
+ entities = adapter._convert_output("hello", task=task)
+ assert len(entities) == 1
+ assert entities[0]["text"] == "hello"
+ assert entities[0]["label"] == label, f"task={task}"
+ assert entities[0]["score"] == 1.0
+
+ def test_convert_output_strips_whitespace(self, adapter: MinerUVLAdapter) -> None:
+ entities = adapter._convert_output(" \n body \n ", task="[default]")
+ assert entities[0]["text"] == "body"
+
+ def test_extract_invalid_task_rejected(self, adapter: MinerUVLAdapter) -> None:
+ adapter._model = MagicMock()
+ adapter._processor = MagicMock()
+ items = [Item(images=[ImageInput(data=b"fake", format="jpeg")])]
+ with pytest.raises(ValueError, match="must be one of"):
+ adapter.extract(items, options={"task": "bogus"})
+
+ def test_load_passes_revision(self) -> None:
+ """load() threads revision into both from_pretrained calls and never sets trust_remote_code."""
+ from sie_server.adapters.mineru_vl import MinerUVLAdapter
+
+ adapter = MinerUVLAdapter(
+ "opendatalab/MinerU2.5-Pro-2604-1.2B",
+ revision="abc123",
+ )
+
+ mock_processor = MagicMock()
+ mock_model = MagicMock()
+ mock_model.to.return_value = mock_model
+
+ with (
+ patch("transformers.AutoProcessor") as mock_ap_cls,
+ patch("transformers.Qwen2VLForConditionalGeneration") as mock_qm_cls,
+ ):
+ mock_ap_cls.from_pretrained.return_value = mock_processor
+ mock_qm_cls.from_pretrained.return_value = mock_model
+
+ adapter.load("cpu")
+
+ ap_kwargs = mock_ap_cls.from_pretrained.call_args.kwargs
+ qm_kwargs = mock_qm_cls.from_pretrained.call_args.kwargs
+ assert ap_kwargs["revision"] == "abc123"
+ assert ap_kwargs["use_fast"] is True
+ assert qm_kwargs["revision"] == "abc123"
+ assert "trust_remote_code" not in ap_kwargs
+ assert "trust_remote_code" not in qm_kwargs
+
+ def test_load_without_revision_omits_kwarg(self) -> None:
+ from sie_server.adapters.mineru_vl import MinerUVLAdapter
+
+ adapter = MinerUVLAdapter(
+ "opendatalab/MinerU2.5-Pro-2604-1.2B",
+ revision=None,
+ )
+
+ mock_model = MagicMock()
+ mock_model.to.return_value = mock_model
+
+ with (
+ patch("transformers.AutoProcessor") as mock_ap_cls,
+ patch("transformers.Qwen2VLForConditionalGeneration") as mock_qm_cls,
+ ):
+ mock_ap_cls.from_pretrained.return_value = MagicMock()
+ mock_qm_cls.from_pretrained.return_value = mock_model
+
+ adapter.load("cpu")
+
+ assert "revision" not in mock_ap_cls.from_pretrained.call_args.kwargs
+ assert "revision" not in mock_qm_cls.from_pretrained.call_args.kwargs
+
+ def test_preprocessor_built_after_load(self) -> None:
+ from sie_server.adapters.mineru_vl import MinerUVLAdapter
+
+ adapter = MinerUVLAdapter("opendatalab/MinerU2.5-Pro-2604-1.2B")
+
+ mock_model = MagicMock()
+ mock_model.to.return_value = mock_model
+
+ with (
+ patch("transformers.AutoProcessor") as mock_ap_cls,
+ patch("transformers.Qwen2VLForConditionalGeneration") as mock_qm_cls,
+ ):
+ mock_ap_cls.from_pretrained.return_value = MagicMock()
+ mock_qm_cls.from_pretrained.return_value = mock_model
+
+ assert adapter.get_preprocessor() is None
+ adapter.load("cpu")
+
+ prep = adapter.get_preprocessor()
+ assert prep is not None
+ assert prep.modality == "image"
+
+ def test_extract_single_passes_use_cache_true_and_mineru_kwargs(self) -> None:
+ """``_extract_single`` must pass ``use_cache=True`` plus MinerU's HF recipe.
+
+ MinerU's transformers backend wires ``repetition_penalty=1.0`` and
+ ``do_sample=False`` into HF generate; ``use_cache=True`` keeps the
+ KV-cache enabled for O(N) decode. The ``no_repeat_ngram_size=100``
+ guard is applied for greedy decoding via the fast incremental
+ ``logits_processor`` (not the slow built-in kwarg).
+ """
+ import io
+
+ import torch
+ from PIL import Image as PILImage
+ from sie_server.adapters.mineru_vl import (
+ MinerUVLAdapter,
+ _IncrementalNoRepeatNGramLogitsProcessor,
+ )
+
+ adapter = MinerUVLAdapter("opendatalab/MinerU2.5-Pro-2604-1.2B")
+ adapter._device = "cpu"
+
+ mock_model = MagicMock()
+ mock_model.dtype = torch.float32
+ mock_model.generate.return_value = torch.zeros((1, 4), dtype=torch.long)
+ adapter._model = mock_model
+
+ mock_processor = MagicMock()
+ mock_processor.apply_chat_template.return_value = ""
+ mock_processor.decode.return_value = ""
+ mock_processor.return_value = {
+ "input_ids": torch.zeros((1, 1), dtype=torch.long),
+ "attention_mask": torch.zeros((1, 1), dtype=torch.long),
+ "pixel_values": torch.zeros((1, 1), dtype=torch.long),
+ "image_grid_thw": torch.zeros((1, 1), dtype=torch.long),
+ }
+ adapter._processor = mock_processor
+
+ buf = io.BytesIO()
+ PILImage.new("RGB", (4, 4)).save(buf, format="JPEG")
+ item = Item(images=[ImageInput(data=buf.getvalue(), format="jpeg")])
+
+ adapter._extract_single(
+ item,
+ task="[default]",
+ instruction=None,
+ max_new_tokens=8,
+ num_beams=1,
+ )
+
+ kwargs = mock_model.generate.call_args.kwargs
+ assert kwargs["use_cache"] is True
+ assert kwargs["do_sample"] is False
+ assert kwargs["repetition_penalty"] == 1.0
+ # Greedy (num_beams=1): ngram guard rides the fast incremental processor,
+ # NOT the slow built-in kwarg.
+ assert "no_repeat_ngram_size" not in kwargs
+ procs = kwargs["logits_processor"]
+ assert len(procs) == 1
+ assert isinstance(procs[0], _IncrementalNoRepeatNGramLogitsProcessor)
+ assert procs[0]._n == 100
+
+ def test_extract_single_beam_search_uses_builtin_ngram_kwarg(self) -> None:
+ """Beam search (num_beams>1) keeps HF's stateless ngram kwarg.
+
+ The incremental processor caches per-sequence n-gram state, which beam
+ reordering would invalidate, so the adapter must fall back to the
+ built-in ``no_repeat_ngram_size`` kwarg and use no custom processor.
+ """
+ import io
+
+ import torch
+ from PIL import Image as PILImage
+ from sie_server.adapters.mineru_vl import MinerUVLAdapter
+
+ adapter = MinerUVLAdapter("opendatalab/MinerU2.5-Pro-2604-1.2B")
+ adapter._device = "cpu"
+
+ mock_model = MagicMock()
+ mock_model.dtype = torch.float32
+ mock_model.generate.return_value = torch.zeros((1, 4), dtype=torch.long)
+ adapter._model = mock_model
+
+ mock_processor = MagicMock()
+ mock_processor.apply_chat_template.return_value = ""
+ mock_processor.decode.return_value = ""
+ mock_processor.return_value = {
+ "input_ids": torch.zeros((1, 1), dtype=torch.long),
+ "attention_mask": torch.zeros((1, 1), dtype=torch.long),
+ "pixel_values": torch.zeros((1, 1), dtype=torch.long),
+ "image_grid_thw": torch.zeros((1, 1), dtype=torch.long),
+ }
+ adapter._processor = mock_processor
+
+ buf = io.BytesIO()
+ PILImage.new("RGB", (4, 4)).save(buf, format="JPEG")
+ item = Item(images=[ImageInput(data=buf.getvalue(), format="jpeg")])
+
+ adapter._extract_single(item, task="[default]", instruction=None, max_new_tokens=8, num_beams=4)
+
+ kwargs = mock_model.generate.call_args.kwargs
+ assert kwargs["no_repeat_ngram_size"] == 100
+ assert "logits_processor" not in kwargs
+
+ def test_yaml_config_loads(self) -> None:
+ """The shipped model YAML parses and resolves an adapter path."""
+ import yaml
+ from sie_server.config.model import ModelConfig
+
+ path = "packages/sie_server/models/opendatalab__MinerU2.5-Pro-2604-1.2B.yaml"
+ with open(path) as f:
+ data = yaml.safe_load(f)
+ config = ModelConfig(**data)
+ assert config.sie_id == "opendatalab/MinerU2.5-Pro-2604-1.2B"
+ assert config.hf_id == "opendatalab/MinerU2.5-Pro-2604-1.2B"
+ assert config.hf_revision == "d3f5e08d073c21466bbabe21c71bb1e9c2e595da"
+ assert config.inputs.image is True
+ resolved = config.resolve_profile("default")
+ assert resolved.adapter_path == "sie_server.adapters.mineru_vl:MinerUVLAdapter"
+ assert resolved.compute_precision == "bfloat16"
+
+
+class TestIncrementalNoRepeatNGram:
+ """The fast incremental processor must be bit-identical to HF's stock one.
+
+ Each test drives a real greedy loop, calling both processors with the same
+ growing ``input_ids`` every step and asserting identical ban masks and
+ identical finite scores — so an identical next token, keeping the sequences
+ in lockstep.
+ """
+
+ @staticmethod
+ def _assert_same(fast_scores, hf_scores, step: int) -> None:
+ import torch
+
+ fast_banned = torch.isneginf(fast_scores)
+ hf_banned = torch.isneginf(hf_scores)
+ assert torch.equal(fast_banned, hf_banned), f"ban-mask mismatch at step {step}"
+ finite = ~hf_banned
+ assert torch.equal(fast_scores[finite], hf_scores[finite]), f"finite-score mismatch at step {step}"
+
+ @pytest.mark.parametrize("ngram_size", [3, 4, 8, 100])
+ def test_matches_hf_random_greedy_loop(self, ngram_size: int) -> None:
+ import torch
+ from sie_server.adapters.mineru_vl import _IncrementalNoRepeatNGramLogitsProcessor
+ from transformers.generation.logits_process import NoRepeatNGramLogitsProcessor
+
+ torch.manual_seed(0)
+ vocab = 40 # small vocab + repeats so small-n guards actually fire
+ input_ids = torch.randint(0, vocab, (1, ngram_size + 5))
+ fast = _IncrementalNoRepeatNGramLogitsProcessor(ngram_size)
+ hf = NoRepeatNGramLogitsProcessor(ngram_size)
+ bans = 0
+ for step in range(250):
+ logits = torch.randn(1, vocab)
+ fast_scores = fast(input_ids, logits.clone())
+ hf_scores = hf(input_ids, logits.clone())
+ self._assert_same(fast_scores, hf_scores, step)
+ bans += int(torch.isneginf(hf_scores).sum())
+ nxt = torch.argmax(fast_scores, dim=-1, keepdim=True)
+ input_ids = torch.cat([input_ids, nxt], dim=-1)
+ # Small n reliably repeats in random text; larger-n ban firing is
+ # covered deterministically by test_matches_hf_repetitive_prompt_forces_bans.
+ if ngram_size <= 4:
+ assert bans > 0, "test never exercised a ban; not a meaningful comparison"
+
+ @pytest.mark.parametrize("ngram_size", [3, 100])
+ def test_matches_hf_repetitive_prompt_forces_bans(self, ngram_size: int) -> None:
+ """A constant-token prompt forces the guard to fire even at n=100."""
+ import torch
+ from sie_server.adapters.mineru_vl import _IncrementalNoRepeatNGramLogitsProcessor
+ from transformers.generation.logits_process import NoRepeatNGramLogitsProcessor
+
+ torch.manual_seed(1)
+ vocab = 20
+ input_ids = torch.full((1, ngram_size + 30), 5, dtype=torch.long)
+ fast = _IncrementalNoRepeatNGramLogitsProcessor(ngram_size)
+ hf = NoRepeatNGramLogitsProcessor(ngram_size)
+ fired = False
+ for step in range(25):
+ logits = torch.randn(1, vocab)
+ fast_scores = fast(input_ids, logits.clone())
+ hf_scores = hf(input_ids, logits.clone())
+ self._assert_same(fast_scores, hf_scores, step)
+ fired = fired or bool(torch.isneginf(hf_scores).any())
+ nxt = torch.argmax(fast_scores, dim=-1, keepdim=True)
+ input_ids = torch.cat([input_ids, nxt], dim=-1)
+ assert fired, "repetitive prompt should have triggered the n-gram guard"
diff --git a/packages/sie_server/tests/adapters/test_pytorch_embedding_revision.py b/packages/sie_server/tests/adapters/test_pytorch_embedding_revision.py
index 72956d8f0..d85bb8d3e 100644
--- a/packages/sie_server/tests/adapters/test_pytorch_embedding_revision.py
+++ b/packages/sie_server/tests/adapters/test_pytorch_embedding_revision.py
@@ -2,6 +2,7 @@ from __future__ import annotations
from unittest.mock import MagicMock, patch
+import pytest
from sie_server.adapters.pytorch_embedding import PyTorchEmbeddingAdapter
@@ -13,10 +14,10 @@ class TestPyTorchEmbeddingAdapterRevision:
when ModelConfig.hf_revision is set.
"""
- def _patched_load(self, adapter: PyTorchEmbeddingAdapter) -> tuple[MagicMock, MagicMock]:
+ def _patched_load(self, adapter: PyTorchEmbeddingAdapter, hidden_size: int = 8) -> tuple[MagicMock, MagicMock]:
"""Drive adapter.load("cpu") with mocked HF loaders. Returns (tokenizer_cls, model_cls)."""
mock_model = MagicMock()
- mock_model.config.hidden_size = 8
+ mock_model.config.hidden_size = hidden_size
mock_model.to.return_value = mock_model
mock_tokenizer = MagicMock()
@@ -75,3 +76,34 @@ class TestPyTorchEmbeddingAdapterRevision:
assert mock_tok_cls.from_pretrained.call_args.kwargs["trust_remote_code"] is True
assert mock_mdl_cls.from_pretrained.call_args.kwargs["trust_remote_code"] is True
+
+ def test_accepts_dense_dim_kwarg(self) -> None:
+ """Construction with dense_dim= must not raise (loader contract)."""
+ adapter = PyTorchEmbeddingAdapter(
+ "google/embeddinggemma-300m",
+ pooling="last_token",
+ dense_dim=768,
+ )
+ assert adapter._configured_dense_dim == 768
+ assert adapter.dims.dense == 768
+
+ def test_load_accepts_matching_dense_dim(self) -> None:
+ adapter = PyTorchEmbeddingAdapter(
+ "google/embeddinggemma-300m",
+ pooling="last_token",
+ dense_dim=768,
+ )
+
+ self._patched_load(adapter, hidden_size=768)
+
+ assert adapter.dims.dense == 768
+
+ def test_load_rejects_dense_dim_mismatch(self) -> None:
+ adapter = PyTorchEmbeddingAdapter(
+ "google/embeddinggemma-300m",
+ pooling="last_token",
+ dense_dim=768,
+ )
+
+ with pytest.raises(ValueError, match="configured dense_dim=768, model hidden_size=1024"):
+ self._patched_load(adapter, hidden_size=1024)
diff --git a/packages/sie_server/tests/adapters/test_sentence_transformer.py b/packages/sie_server/tests/adapters/test_sentence_transformer.py
index b17b2c023..e5d93a7b9 100644
--- a/packages/sie_server/tests/adapters/test_sentence_transformer.py
+++ b/packages/sie_server/tests/adapters/test_sentence_transformer.py
@@ -70,6 +70,52 @@ class TestSentenceTransformerDenseAdapter:
)
assert adapter.dims.dense == 384
+ @patch("sie_server.adapters.sentence_transformer.SentenceTransformer")
+ def test_load_gpu_preserves_sentence_transformers_defaults(
+ self,
+ mock_st_class: MagicMock,
+ mock_st_model: MagicMock,
+ ) -> None:
+ """GPU load path does not force dtype/attention globally."""
+ mock_st_class.return_value = mock_st_model
+ adapter = SentenceTransformerDenseAdapter(
+ "test-model",
+ compute_precision="float16",
+ )
+ adapter.load("cuda:0")
+
+ assert "model_kwargs" not in mock_st_class.call_args.kwargs
+
+ @patch("sie_server.adapters.sentence_transformer.SentenceTransformer")
+ def test_load_gpu_bf16_preserves_sentence_transformers_defaults(
+ self,
+ mock_st_class: MagicMock,
+ mock_st_model: MagicMock,
+ ) -> None:
+ """``bfloat16`` does not force a global dtype override."""
+ mock_st_class.return_value = mock_st_model
+ adapter = SentenceTransformerDenseAdapter(
+ "test-model",
+ compute_precision="bfloat16",
+ )
+ adapter.load("cuda:0")
+ assert "model_kwargs" not in mock_st_class.call_args.kwargs
+
+ @patch("sie_server.adapters.sentence_transformer.SentenceTransformer")
+ def test_load_gpu_fp32_leaves_dtype_unset(
+ self,
+ mock_st_class: MagicMock,
+ mock_st_model: MagicMock,
+ ) -> None:
+ """``float32`` deliberately doesn't override model defaults."""
+ mock_st_class.return_value = mock_st_model
+ adapter = SentenceTransformerDenseAdapter(
+ "test-model",
+ compute_precision="float32",
+ )
+ adapter.load("cuda:0")
+ assert "model_kwargs" not in mock_st_class.call_args.kwargs
+
@patch("sie_server.adapters.sentence_transformer.SentenceTransformer")
def test_encode(
self,
@@ -198,6 +244,21 @@ class TestSentenceTransformerSparseAdapter:
assert adapter.dims.sparse == 30522
assert adapter.dims.dense is None
+ @patch("sie_server.adapters.sentence_transformer.SparseEncoder")
+ def test_load_gpu_preserves_sparse_encoder_defaults(
+ self,
+ mock_sparse_class: MagicMock,
+ mock_sparse_model: MagicMock,
+ ) -> None:
+ """GPU load path does not force dtype/attention globally."""
+ mock_sparse_class.return_value = mock_sparse_model
+ adapter = SentenceTransformerSparseAdapter(
+ "test-sparse-model",
+ compute_precision="float16",
+ )
+ adapter.load("cuda:0")
+ assert "model_kwargs" not in mock_sparse_class.call_args.kwargs
+
@patch("sie_server.adapters.sentence_transformer.SparseEncoder")
def test_encode_document(
self,
diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.py
index 6450e2c23..c29e4b01a 100644
--- a/packages/sie_server/tests/adapters/test_sglang_generation.py
+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py
@@ -923,7 +923,7 @@ def test_chunk_translator_tolerates_2tuple_shape() -> None:
assert chunk.logprobs[0]["token"] == ""
-# ── H4 / M4 multi-candidate logprobs ─────────────────────────────────────
+# ── Multi-candidate logprobs ─────────────────────────────────────
@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
@@ -990,7 +990,7 @@ def test_generate_streaming_n_gt_one_attaches_per_candidate_logprobs(mock_async_
@patch("sie_server.adapters.sglang.generation.httpx.AsyncClient")
def test_generate_n_gt_one_non_streaming_emits_per_candidate_logprobs(mock_async_client: MagicMock, adapter) -> None:
- """M4: non-streaming ``n>1`` with ``logprobs=True`` populates each
+ """Non-streaming ``n>1`` with ``logprobs=True`` populates each
candidate's ``logprobs`` field from SGLang's
``meta_info.output_token_logprobs`` (was ``None`` pre-fix).
"""
diff --git a/packages/sie_server/tests/adapters/test_visual_document.py b/packages/sie_server/tests/adapters/test_visual_document.py
index 388ff1b67..bd0d41569 100644
--- a/packages/sie_server/tests/adapters/test_visual_document.py
+++ b/packages/sie_server/tests/adapters/test_visual_document.py
@@ -15,9 +15,6 @@ from sie_server.adapters.colqwen3 import ColQwen3Adapter
from sie_server.adapters.nemo_colembed import NemoColEmbedAdapter
from sie_server.types.inputs import Item
-# Create a random generator for tests
-_RNG = np.random.default_rng(42)
-
class TestColPaliAdapter:
"""Tests for ColPaliAdapter with mocked model."""
@@ -381,6 +378,24 @@ class TestVLMCudaCacheClearing:
"ColPali._encode_prepared_batch must call torch.cuda.empty_cache() to prevent OOM"
)
+ def test_colpali_encode_images_has_empty_cache(self) -> None:
+ """ColPali _encode_images (single-item fallback) source contains empty_cache call."""
+ import inspect
+
+ source = inspect.getsource(ColPaliAdapter._encode_images)
+ assert "torch.cuda.empty_cache()" in source, (
+ "ColPali._encode_images must call torch.cuda.empty_cache() to prevent OOM"
+ )
+
+ def test_colqwen2_encode_images_batched_has_empty_cache(self) -> None:
+ """ColQwen2 _encode_images_batched (document-path) source contains empty_cache call."""
+ import inspect
+
+ source = inspect.getsource(ColQwen2Adapter._encode_images_batched)
+ assert "torch.cuda.empty_cache()" in source, (
+ "ColQwen2._encode_images_batched 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_dtype.py b/packages/sie_server/tests/api/test_encode_dtype.py
index c6abcfec0..8a7285017 100644
--- a/packages/sie_server/tests/api/test_encode_dtype.py
+++ b/packages/sie_server/tests/api/test_encode_dtype.py
@@ -116,7 +116,7 @@ def client(mock_registry: MagicMock) -> TestClient:
class TestOutputDtype:
- """Tests for output_dtype parameter (DESIGN.md Section 5.9)."""
+ """Tests for output_dtype parameter."""
def test_default_dtype_is_float32(self, client: TestClient) -> None:
"""Default output dtype is float32."""
diff --git a/packages/sie_server/tests/api/test_encode_endpoint.py b/packages/sie_server/tests/api/test_encode_endpoint.py
index 12012aa18..346ae13a3 100644
--- a/packages/sie_server/tests/api/test_encode_endpoint.py
+++ b/packages/sie_server/tests/api/test_encode_endpoint.py
@@ -388,7 +388,7 @@ class TestEncodeEndpoint:
class TestMsgpackRequests:
- """Tests for msgpack request body handling (DESIGN.md Section 4.3)."""
+ """Tests for msgpack request body handling."""
def test_msgpack_request_basic(self, client: TestClient) -> None:
"""Msgpack request body is parsed correctly."""
diff --git a/packages/sie_server/tests/api/test_encode_timing.py b/packages/sie_server/tests/api/test_encode_timing.py
index d377124ca..090a43453 100644
--- a/packages/sie_server/tests/api/test_encode_timing.py
+++ b/packages/sie_server/tests/api/test_encode_timing.py
@@ -114,7 +114,7 @@ def client(mock_registry: MagicMock) -> TestClient:
class TestTimingHeaders:
- """Tests for timing headers in encode responses (DESIGN.md Section 5.7)."""
+ """Tests for timing headers in encode responses."""
@pytest.fixture
def mock_adapter_with_timing(self) -> MagicMock:
diff --git a/packages/sie_server/tests/api/test_extract.py b/packages/sie_server/tests/api/test_extract.py
index ca16d7df0..ef1dcb2ad 100644
--- a/packages/sie_server/tests/api/test_extract.py
+++ b/packages/sie_server/tests/api/test_extract.py
@@ -48,7 +48,7 @@ def _mock_extract_impl(
Returns ExtractOutput with mock entities based on item text and provided labels.
"""
all_entities: list[list[Entity]] = []
- for _item in items:
+ for _ in items:
entities: list[Entity] = []
# Simulate finding entities for each label
if labels:
@@ -398,6 +398,31 @@ class TestExtractEndpoint:
assert data["detail"]["code"] == "INVALID_INPUT"
assert data["detail"]["message"] == "Expected `array | null`, got `str` - at `$.items[0].images`"
+ def test_image_preprocessor_model_rejects_text_only_request(
+ self,
+ client: TestClient,
+ mock_registry: MagicMock,
+ ) -> None:
+ """Image-only preprocessors reject text-only extract requests with 400."""
+ preprocessor_registry = MagicMock()
+ preprocessor_registry.has_preprocessor.side_effect = lambda _model, modality: modality == "image"
+ mock_registry.preprocessor_registry = preprocessor_registry
+
+ response = client.post(
+ "/v1/extract/test-extractor",
+ json={
+ "items": [{"text": "receipt total"}],
+ "params": {},
+ },
+ headers=JSON_HEADERS,
+ )
+
+ assert response.status_code == 400
+ data = response.json()
+ assert data["detail"]["code"] == "INVALID_INPUT"
+ assert "requires image input" in data["detail"]["message"]
+ mock_registry.start_worker.assert_not_called()
+
class TestExtractEntityResults:
"""Tests for entity extraction result format."""
diff --git a/packages/sie_server/tests/api/test_generate.py b/packages/sie_server/tests/api/test_generate.py
index 953a28ab6..3f743a764 100644
--- a/packages/sie_server/tests/api/test_generate.py
+++ b/packages/sie_server/tests/api/test_generate.py
@@ -290,9 +290,7 @@ class TestGenerateEndpoint:
def test_oversized_prompt_returns_413(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
# Shrink the cap so the test doesn't have to build a 4 MiB string.
- import sie_server.api.generate as generate_mod
-
- monkeypatch.setattr(generate_mod, "_MAX_PROMPT_BYTES", 16)
+ monkeypatch.setattr("sie_server.api.generate._MAX_PROMPT_BYTES", 16)
response = client.post(
"/v1/generate/Qwen__Qwen3-4B-Instruct",
json={"prompt": "x" * 64, "max_new_tokens": 8},
@@ -376,9 +374,7 @@ class TestGenerateEndpoint:
def test_prompt_at_cap_is_accepted(self, client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
# A prompt exactly at the byte cap is allowed (boundary check).
- import sie_server.api.generate as generate_mod
-
- monkeypatch.setattr(generate_mod, "_MAX_PROMPT_BYTES", 16)
+ monkeypatch.setattr("sie_server.api.generate._MAX_PROMPT_BYTES", 16)
response = client.post(
"/v1/generate/Qwen__Qwen3-4B-Instruct",
json={"prompt": "x" * 16, "max_new_tokens": 8},
diff --git a/packages/sie_server/tests/app/test_app_factory.py b/packages/sie_server/tests/app/test_app_factory.py
index f73569a12..7a6515f9b 100644
--- a/packages/sie_server/tests/app/test_app_factory.py
+++ b/packages/sie_server/tests/app/test_app_factory.py
@@ -1,13 +1,21 @@
"""Tests for the FastAPI app factory."""
import logging
+import uuid
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+from typing import Any
from unittest.mock import AsyncMock, MagicMock
+import numpy as np
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sie_server.app.app_factory import AppFactory
from sie_server.app.app_state_config import AppStateConfig
+from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks
+from sie_server.core import readiness
+from sie_server.core.postprocessor_registry import PostprocessorRegistry
@pytest.fixture
@@ -33,7 +41,6 @@ class TestAppFactory:
def test_health_routes_registered(self, client: TestClient) -> None:
"""Health routes are registered in the app."""
- # Get OpenAPI schema to verify routes exist
response = client.get("/openapi.json")
assert response.status_code == 200
@@ -45,29 +52,178 @@ class TestAppFactory:
assert "/readyz" in paths
-class TestNatsPullLoopGuard:
- """Tests for _nats_pull_loop RuntimeError when NATS is None."""
+class TestAllRoutersAlwaysMounted:
+ """Queue routing is the only supported mode, so routers are mounted
+ unconditionally.
- @pytest.mark.asyncio
- async def test_nats_pull_loop_raises_when_nats_is_none(self, monkeypatch) -> None:
- """SIE_CLUSTER_ROUTING=queue with no NATS subscriber raises RuntimeError."""
- monkeypatch.setenv("SIE_CLUSTER_ROUTING", "queue")
+ /ws/status MUST be mounted because it is the gateway's
+ worker-registration channel: the gateway opens
+ `ws://<worker>/ws/status` to learn pool_name, bundle,
+ machine_profile, and readiness. Without it, the gateway's
+ WorkerRegistry stays empty and every request falls through to the
+ 202 "no queue worker available" branch. This test suite locks that
+ contract in.
+ """
+
+ @staticmethod
+ def _route_paths(app: FastAPI) -> set[str]:
+ return {getattr(r, "path", "") for r in app.router.routes}
+
+ def test_ws_status_is_always_mounted(self) -> None:
+ app = AppFactory.create_app(AppStateConfig())
+ assert "/ws/status" in self._route_paths(app)
+
+ def test_probe_and_metrics_routes_are_always_mounted(self) -> None:
+ app = AppFactory.create_app(AppStateConfig())
+ paths = self._route_paths(app)
+ for path in ("/healthz", "/readyz", "/metrics"):
+ assert path in paths, f"{path} missing — breaks K8s probes/Prometheus"
+
+ def test_inference_routers_are_mounted(self) -> None:
+ """Inference routers stay mounted unconditionally.
+
+ In production these endpoints are not a real ingress (the Rust
+ gateway is queue-only and publishes to JetStream, not HTTP),
+ but the routes exist on every pod for local debugging and to
+ keep the existing test/OpenAPI surface intact. If a future
+ refactor deletes them, update this test along with the router
+ imports in ``app_factory.create_app``.
+ """
+ app = AppFactory.create_app(AppStateConfig())
+ paths = self._route_paths(app)
+ for path in (
+ "/v1/encode/{model:path}",
+ "/v1/score/{model:path}",
+ "/v1/extract/{model:path}",
+ "/v1/embeddings",
+ "/v1/models",
+ ):
+ assert path in paths, f"{path} router missing"
- registry = MagicMock()
- with pytest.raises(RuntimeError, match="no NATS subscriber available"):
- async with AppFactory._nats_pull_loop(registry, None):
- pass # pragma: no cover
+class TestIpcHeartbeatReadiness:
+ """IPC heartbeat readiness is opt-in so direct HTTP stays usable."""
+
+ @staticmethod
+ def _short_socket_path() -> Path:
+ # macOS caps AF_UNIX paths at 104 bytes; pytest temp roots can exceed it.
+ return Path("/tmp") / f"sie-ipc-{uuid.uuid4().hex[:12]}.sock" # noqa: S108
+
+ @pytest.mark.asyncio
+ async def test_direct_server_readiness_does_not_require_sidecar_ping(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("SIE_IPC_REQUIRE_HEARTBEAT", raising=False)
+ socket_path = self._short_socket_path()
+ monkeypatch.setenv("SIE_IPC_SOCKET_PATH", str(socket_path))
+ readiness.register_liveness_probe(None)
+ readiness.mark_ready()
+
+ try:
+ async with AppFactory._ipc_server(MagicMock()):
+ assert readiness.is_ready() is True
+ finally:
+ readiness.mark_not_ready()
+ readiness.register_liveness_probe(None)
+ socket_path.unlink(missing_ok=True)
@pytest.mark.asyncio
- async def test_nats_pull_loop_yields_none_when_not_queue(self, monkeypatch) -> None:
- """When SIE_CLUSTER_ROUTING != queue, _nats_pull_loop yields None."""
- monkeypatch.delenv("SIE_CLUSTER_ROUTING", raising=False)
+ async def test_sidecar_deployments_gate_readiness_on_ipc_ping(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_IPC_REQUIRE_HEARTBEAT", "true")
+ socket_path = self._short_socket_path()
+ monkeypatch.setenv("SIE_IPC_SOCKET_PATH", str(socket_path))
+ readiness.register_liveness_probe(None)
+ readiness.mark_ready()
+
+ try:
+ async with AppFactory._ipc_server(MagicMock()):
+ assert readiness.is_ready() is False
+ finally:
+ readiness.mark_not_ready()
+ readiness.register_liveness_probe(None)
+ socket_path.unlink(missing_ok=True)
+
+
+def _direct_encode_adapter_output(items: list[Any], output_types: list[str], **_kwargs: Any) -> Any:
+ from sie_server.core.inference_output import EncodeOutput
+
+ dense = None
+ if "dense" in output_types:
+ dense = np.array([[0.1, 0.2, 0.3]] * len(items), dtype=np.float32)
+
+ return EncodeOutput(
+ dense=dense,
+ sparse=None,
+ multivector=None,
+ batch_size=len(items),
+ dense_dim=3 if dense is not None else None,
+ multivector_token_dim=None,
+ )
+
+
+def _direct_http_registry() -> tuple[MagicMock, ThreadPoolExecutor]:
+ adapter = MagicMock()
+ adapter.encode = MagicMock(side_effect=_direct_encode_adapter_output)
+
+ registry = MagicMock()
+ registry.has_model.return_value = True
+ registry.is_loaded.return_value = True
+ registry.is_loading.return_value = False
+ registry.is_unloading.return_value = False
+ registry.is_failed.return_value = False
+ registry.get_failure.return_value = None
+ registry.get.return_value = adapter
+ registry.get_config.return_value = ModelConfig(
+ sie_id="test-model",
+ hf_id="org/test-model",
+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=3))),
+ profiles={"default": ProfileConfig(adapter_path="test:Adapter", max_batch_tokens=8192)},
+ )
+ registry.model_names = ["test-model"]
+ registry.device = "cpu"
+
+ preprocessor_registry = MagicMock()
+ preprocessor_registry.has_tokenizer.return_value = False
+ preprocessor_registry.has_preprocessor.return_value = False
+ registry.preprocessor_registry = preprocessor_registry
+
+ executor = ThreadPoolExecutor(max_workers=1)
+ registry.postprocessor_registry = PostprocessorRegistry(executor)
+ return registry, executor
+
+
+class TestDirectServerHttpPath:
+ """Direct Python HTTP inference remains usable without the worker-sidecar."""
+
+ def test_app_factory_mounts_direct_generate_route(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("SIE_IPC_REQUIRE_HEARTBEAT", raising=False)
+ app = AppFactory.create_app(AppStateConfig())
+ paths = {getattr(route, "path", "") for route in app.routes}
+ assert "/v1/generate/{model:path}" in paths
- registry = MagicMock()
+ def test_app_factory_direct_encode_path_without_sidecar(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("SIE_IPC_REQUIRE_HEARTBEAT", raising=False)
+ app = AppFactory.create_app(AppStateConfig())
+ registry, executor = _direct_http_registry()
+ app.state.registry = registry
+
+ try:
+ client = TestClient(app)
+ response = client.post(
+ "/v1/encode/test-model",
+ json={"items": [{"text": "direct python path"}]},
+ headers={"Accept": "application/json"},
+ )
+ models_response = client.get("/v1/models")
+ finally:
+ executor.shutdown(wait=True)
+
+ assert response.status_code == 200
+ data = response.json()
+ assert data["model"] == "test-model"
+ assert data["items"][0]["dense"]["dims"] == 3
+ assert data["items"][0]["dense"]["values"] == pytest.approx([0.1, 0.2, 0.3])
- async with AppFactory._nats_pull_loop(registry, None) as pull_loop:
- assert pull_loop is None
+ assert models_response.status_code == 200
+ assert models_response.json()["models"][0]["name"] == "test-model"
class TestPreloadModels:
diff --git a/packages/sie_server/tests/config/test_bundle_coverage.py b/packages/sie_server/tests/config/test_bundle_coverage.py
index 41ca1f229..7bf7263d3 100644
--- a/packages/sie_server/tests/config/test_bundle_coverage.py
+++ b/packages/sie_server/tests/config/test_bundle_coverage.py
@@ -2,8 +2,7 @@
#
# If this ever fails again we get a clear CI error instead of a silent
# "Adapter(s) not in any known bundle" warning at gateway bootstrap time
-# and a stuck sie-config epoch. See PR #702 (and the Qwen3-VL bundle
-# omission surfaced during the 2025-04 eu-central-1 deployment) for context.
+# and a stuck sie-config epoch.
from __future__ import annotations
@@ -136,7 +135,5 @@ def test_bundle_yaml_has_required_fields(bundle_yaml: Path) -> None:
# the same adapter is intentionally available in multiple dependency
# stacks (e.g. a CPU bundle and a CUDA bundle that both ship the same
# sentence-transformer adapter). If equal-priority resolution ever
-# needs to be fully deterministic in sie-config too (the Rust gateway
-# already tie-breaks by bundle name per PR #702, but the Python side
-# only sorts by priority), the fix is a registry-level secondary sort
-# key, not a CI lint on bundle contents.
+# needs to be fully deterministic in sie-config too, the fix is a
+# registry-level secondary sort key, not a CI lint on bundle contents.
diff --git a/packages/sie_server/tests/config/test_config.py b/packages/sie_server/tests/config/test_config.py
index d6b981143..2f2a69f17 100644
--- a/packages/sie_server/tests/config/test_config.py
+++ b/packages/sie_server/tests/config/test_config.py
@@ -27,7 +27,9 @@ class TestEngineConfig:
config = EngineConfig()
# Note: max_batch_tokens is per-model (in ModelConfig), not engine-level
assert config.max_batch_requests == 64
- assert config.max_batch_wait_ms == 10
+ assert config.max_batch_wait_ms == 15
+ assert config.coalesce_ms == 15.0
+ assert config.coalesce_ratio == 0.5
assert config.max_concurrent_requests == 512
assert config.memory_pressure_threshold_percent == 85
assert config.max_loras_per_model == 10
@@ -36,6 +38,11 @@ class TestEngineConfig:
assert config.default_compute_precision == "float16"
assert config.instrumentation is False
assert config.models_dir == Path("./models")
+ assert config.adaptive_batching.min_wait_ms == 15.0
+ assert config.adaptive_batching.max_wait_ms == 50.0
+ assert config.adaptive_batching.starvation_recovery_enabled is True
+ assert config.adaptive_batching.starvation_window == 20
+ assert config.adaptive_batching.starvation_batch_size == 1
def test_custom_values(self) -> None:
"""EngineConfig accepts custom values."""
@@ -419,7 +426,7 @@ class TestModelConfig:
)
def test_generate_capabilities_accepts_ebnf(self) -> None:
- """``ebnf`` was added to the accepted grammar list when M4 req2's
+ """``ebnf`` was added to the accepted grammar list when
Outlines / XGrammar EBNF support landed. Prior to that this test
asserted rejection; it's flipped to acceptance as the regression
guard so a future refactor doesn't silently drop EBNF support.
diff --git a/packages/sie_server/tests/config/test_profile_backend_consistency.py b/packages/sie_server/tests/config/test_profile_backend_consistency.py
index 17b4d94cd..aa14bdd08 100644
--- a/packages/sie_server/tests/config/test_profile_backend_consistency.py
+++ b/packages/sie_server/tests/config/test_profile_backend_consistency.py
@@ -1,15 +1,6 @@
-# Release-gate guard: the Qwen3.5 profiles' ``grammar_backend`` value must
-# match the backend-of-record declared in
-# ``product/research/generation-primitive-status.md`` (§4.2 Decision record).
-#
-# Closes finding H10. If you change either side, change both — this test is
-# *intended* to break when the YAML and the status doc drift apart.
-#
-# Context: production Qwen3.5 profiles ship with ``grammar_backend: outlines``
-# (dottxt partnership; the codebase default). The status doc historically
-# carried five contradictory passages claiming the profiles were pinned to
-# ``xgrammar`` "until the Outlines A100 smoke re-verification". The doc has
-# been reconciled with the code; this test guards the alignment.
+# Release-gate guard: production Qwen3.5 profiles ship with
+# ``grammar_backend: outlines`` (dottxt partnership; the codebase default).
+# This test keeps the YAML aligned with that backend-of-record.
from __future__ import annotations
diff --git a/packages/sie_server/tests/conftest.py b/packages/sie_server/tests/conftest.py
index 1f51277a1..99a3141f9 100644
--- a/packages/sie_server/tests/conftest.py
+++ b/packages/sie_server/tests/conftest.py
@@ -8,9 +8,9 @@ from __future__ import annotations
import logging
import os
-import shutil
import socket
import subprocess
+import sys
import time
from collections.abc import Generator
from pathlib import Path
@@ -36,6 +36,7 @@ def device() -> str:
if torch.cuda.is_available():
return "cuda:0"
except ImportError:
+ # torch not installed — caller will fall back to CPU.
pass
return "cpu"
@@ -53,10 +54,17 @@ def _find_free_port(start: int = 8090, end: int = 8200) -> int:
raise RuntimeError(msg)
-def _wait_for_health(url: str, timeout_s: float = 120.0, poll_interval_s: float = 1.0) -> bool:
+def _wait_for_health(
+ url: str,
+ timeout_s: float = 120.0,
+ poll_interval_s: float = 1.0,
+ proc: subprocess.Popen | None = None,
+) -> bool:
"""Wait for server health endpoint to respond 200."""
start = time.monotonic()
while time.monotonic() - start < timeout_s:
+ if proc is not None and proc.poll() is not None:
+ return False
try:
response = httpx.get(f"{url}/healthz", timeout=5.0)
if response.status_code == 200:
@@ -84,10 +92,6 @@ def sie_server(device: str) -> Generator[str]:
client = SIEClient(sie_server)
# ... test code ...
"""
- mise_path = shutil.which("mise")
- if mise_path is None:
- pytest.skip("mise not found in PATH - required for integration tests")
-
models_dir = _project_root / "packages" / "sie_server" / "models"
port = _find_free_port(8090, 8200)
@@ -97,10 +101,10 @@ def sie_server(device: str) -> Generator[str]:
models = "BAAI/bge-m3:bge_m3_flag,NeuML/gliner-bert-tiny"
cmd = [
- mise_path,
- "run",
+ sys.executable,
+ "-m",
+ "sie_server.cli",
"serve",
- "--",
"-p",
str(port),
"-d",
@@ -123,10 +127,13 @@ def sie_server(device: str) -> Generator[str]:
try:
health_timeout = float(os.environ.get("SIE_TEST_SERVER_TIMEOUT", "120"))
- if not _wait_for_health(url, timeout_s=health_timeout):
- proc.terminate()
- proc.wait(timeout=10)
- pytest.fail(f"Server failed to start within {health_timeout:.0f}s — check server output above")
+ if not _wait_for_health(url, timeout_s=health_timeout, proc=proc):
+ returncode = proc.poll()
+ if returncode is None:
+ proc.terminate()
+ proc.wait(timeout=10)
+ pytest.fail(f"Server failed to start within {health_timeout:.0f}s — check server output above")
+ pytest.fail(f"Server process exited before health check passed (exit code {returncode})")
logger.info("Integration test server ready at %s", url)
yield url
@@ -172,6 +179,8 @@ def _get_docker_client() -> Any:
pytest.skip("docker package not installed")
except Exception as e: # noqa: BLE001 — Docker API errors are varied
pytest.skip(f"Docker not available: {e}")
+ # Unreachable: both except branches call pytest.skip (NoReturn).
+ raise RuntimeError("unreachable")
def _build_docker_image(
@@ -349,8 +358,13 @@ def sie_docker_server() -> Generator[str]:
@pytest.fixture(scope="session")
-def docker_client(sie_docker_server: str) -> SIEClient:
- """Create an SIEClient connected to the Docker test server."""
+def sie_docker_client(sie_docker_server: str) -> SIEClient:
+ """Create an SIEClient connected to the Docker test server.
+
+ Named ``sie_docker_client`` (not ``docker_client``) to avoid clashing with the
+ local ``docker_client`` variable inside fixtures that hold the actual Docker
+ SDK client.
+ """
return SIEClient(sie_docker_server, timeout_s=180.0)
diff --git a/packages/sie_server/tests/core/test_adaptive_batching.py b/packages/sie_server/tests/core/test_adaptive_batching.py
index 525bddb8e..6a6eca693 100644
--- a/packages/sie_server/tests/core/test_adaptive_batching.py
+++ b/packages/sie_server/tests/core/test_adaptive_batching.py
@@ -373,6 +373,7 @@ class TestAdaptiveBatchController:
assert ctrl.current_batch_cost == 8192
def test_reset(self) -> None:
+ """Reset restores the controller to the values it was constructed with."""
ctrl = AdaptiveBatchController(
min_wait_ms=2.0,
max_wait_ms=40.0,
@@ -384,8 +385,11 @@ class TestAdaptiveBatchController:
)
ctrl.step(observed_p50_ms=100.0, fill_ratio=0.5)
ctrl.reset()
- assert ctrl.current_wait_ms == 10.0
- assert ctrl.current_batch_cost == 16384
+ # Reset returns to the values provided at construction, clamped
+ # to the configured min/max bounds. This lets operators pin the
+ # recovery anchor via helm values without a code change.
+ assert ctrl.current_wait_ms == 30.0
+ assert ctrl.current_batch_cost == 20000
assert ctrl._steps_since_update == 0
def test_sequential_adjustments(self) -> None:
@@ -501,7 +505,9 @@ class TestAdaptiveBatchingWorkerIntegration:
prepared = [make_text_item([1, 2, 3], 0)]
f = await worker.submit(prepared, items, ["dense"])
await asyncio.wait_for(f, timeout=5.0)
- assert worker._batch_config.max_batch_wait_ms == 10
+ # Tracks WorkerConfig().max_batch_wait_ms (kept in sync with
+ # the adaptive controller's min_wait_ms floor).
+ assert worker._batch_config.max_batch_wait_ms == WorkerConfig().max_batch_wait_ms
finally:
await worker.stop()
@@ -891,3 +897,273 @@ class TestProfileAdaptiveBatchingMerge:
engine = AdaptiveBatchingParams(enabled=True, target_p50_ms=None, gain=0.3)
result = _merge_adaptive_params(engine, None)
assert result is engine
+
+
+class TestCostAntiWindup:
+ """Cost knob must not accumulate further into saturation once pinned.
+
+ Regression test for the deadlock observed on the queue path where the
+ controller shrank ``max_batch_cost`` to ``min_batch_cost`` under load
+ and could not escape because fill_ratio stayed high (tiny batches
+ always fill their tiny budget) while headroom stayed negative.
+ """
+
+ def test_cost_does_not_shrink_below_min_when_pinned(self) -> None:
+ ctrl = AdaptiveBatchController(
+ target_p50_ms=50.0,
+ cost_gain=0.5,
+ fill_ratio_threshold=0.7,
+ min_batch_cost=256,
+ max_batch_cost=65536,
+ update_interval=1,
+ _current_batch_cost=256, # already at floor
+ )
+ # Very-over-SLO + saturated — exactly the deadlock scenario.
+ _, cost = ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99)
+ assert cost == 256
+ # The controller must not add negative slack to the floor.
+ assert ctrl._current_batch_cost == 256
+
+ def test_cost_can_still_grow_when_pinned_at_min_with_headroom(self) -> None:
+ """At floor + positive headroom, growth is allowed (recovery path)."""
+ ctrl = AdaptiveBatchController(
+ target_p50_ms=100.0,
+ cost_gain=0.5,
+ fill_ratio_threshold=0.7,
+ min_batch_cost=256,
+ update_interval=1,
+ _current_batch_cost=256,
+ )
+ _, cost = ctrl.step(observed_p50_ms=40.0, fill_ratio=0.9)
+ # headroom_frac = 0.6, cost_adj = 256 * 0.6 * 0.5 = 76.8 → new_cost ~332
+ assert cost > 256
+
+ def test_cost_does_not_grow_above_max_when_pinned(self) -> None:
+ """Symmetric: at ceiling + positive headroom, cost stays capped."""
+ ctrl = AdaptiveBatchController(
+ target_p50_ms=100.0,
+ cost_gain=0.5,
+ fill_ratio_threshold=0.7,
+ max_batch_cost=20000,
+ update_interval=1,
+ _current_batch_cost=20000,
+ )
+ _, cost = ctrl.step(observed_p50_ms=10.0, fill_ratio=0.99)
+ assert cost == 20000
+
+
+class TestStarvationRecovery:
+ """Deadlock escape hatch: consecutive tiny batches at the floor → reset.
+
+ See ``packages/sie_server_sidecar/docs/architecture-guide.md`` for
+ the queue-mode regression guard that motivated this feature.
+ """
+
+ def _make_pinned_controller(
+ self,
+ *,
+ starvation_window: int = 5,
+ starvation_recovery_enabled: bool = True,
+ ) -> AdaptiveBatchController:
+ """Controller pre-pinned at the floor on both knobs.
+
+ We construct the controller with healthy startup values so that
+ ``_initial_*`` anchors are meaningful, then manually drive the
+ current knobs down to the floor. This mirrors what happens in
+ production when the PI loop shrinks in response to sustained SLO
+ violation.
+ """
+ ctrl = AdaptiveBatchController(
+ target_p50_ms=50.0,
+ min_wait_ms=1.0,
+ max_wait_ms=50.0,
+ min_batch_cost=256,
+ max_batch_cost=65536,
+ gain=0.3,
+ integral_gain=0.05,
+ cost_gain=0.15,
+ update_interval=1,
+ starvation_window=starvation_window,
+ starvation_recovery_enabled=starvation_recovery_enabled,
+ _current_wait_ms=10.0,
+ _current_batch_cost=16384,
+ )
+ ctrl._current_wait_ms = ctrl.min_wait_ms
+ ctrl._current_batch_cost = ctrl.min_batch_cost
+ return ctrl
+
+ def test_streak_increments_on_tiny_batches(self) -> None:
+ ctrl = self._make_pinned_controller(starvation_window=100)
+ for _ in range(3):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ assert ctrl.starvation_streak == 3
+
+ def test_streak_resets_on_healthy_batch(self) -> None:
+ ctrl = self._make_pinned_controller(starvation_window=100)
+ for _ in range(3):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ assert ctrl.starvation_streak == 3
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=16)
+ assert ctrl.starvation_streak == 0
+
+ def test_streak_resets_when_batch_size_omitted(self) -> None:
+ """Backward-compat: callers can omit batch_size to disable detection."""
+ ctrl = self._make_pinned_controller(starvation_window=100)
+ for _ in range(3):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ assert ctrl.starvation_streak == 3
+
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99) # no batch_size
+ assert ctrl.starvation_streak == 0
+
+ def test_streak_does_not_count_until_both_knobs_at_floor(self) -> None:
+ ctrl = AdaptiveBatchController(
+ target_p50_ms=50.0,
+ min_wait_ms=1.0,
+ min_batch_cost=256,
+ update_interval=1,
+ starvation_window=3,
+ _current_wait_ms=1.0,
+ _current_batch_cost=4096,
+ )
+ for _ in range(3):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.1, batch_size=1)
+ assert ctrl.starvation_streak == 0
+ assert ctrl.starvation_resets == 0
+
+ def test_recovery_fires_after_window(self) -> None:
+ ctrl = self._make_pinned_controller(starvation_window=5)
+ pre_wait = ctrl.current_wait_ms
+ pre_cost = ctrl.current_batch_cost
+ # Five consecutive tiny batches at the floor → trip the detector.
+ for _ in range(5):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ # After recovery the knobs must be above the floor.
+ assert ctrl.current_wait_ms > pre_wait
+ assert ctrl.current_batch_cost > pre_cost
+ assert ctrl.starvation_resets == 1
+ # Streak is cleared so we don't immediately re-recover on the next batch.
+ assert ctrl.starvation_streak == 0
+
+ def test_recovery_anchors_to_initial_values(self) -> None:
+ """Recovery pulls knobs halfway toward the construction-time values."""
+ ctrl = AdaptiveBatchController(
+ target_p50_ms=50.0,
+ min_wait_ms=1.0,
+ max_wait_ms=50.0,
+ min_batch_cost=256,
+ max_batch_cost=65536,
+ update_interval=1,
+ starvation_window=3,
+ _current_wait_ms=20.0, # operator-configured startup
+ _current_batch_cost=16384,
+ )
+ # Force knobs to the floor by hand, then drive tiny batches.
+ ctrl._current_wait_ms = ctrl.min_wait_ms
+ ctrl._current_batch_cost = ctrl.min_batch_cost
+ for _ in range(3):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ # Midway between floor (1.0) and initial (20.0) = 10.5
+ assert ctrl.current_wait_ms == pytest.approx(10.5)
+ # Midway is max(initial/2=8192, min_cost*4=1024) = 8192
+ assert ctrl.current_batch_cost == 8192
+
+ def test_recovery_skipped_if_not_at_both_floors(self) -> None:
+ """Tiny batches alone are not enough — both knobs must be pinned.
+
+ We suppress the cost knob (``fill_ratio`` below its threshold) so
+ the PI loop can't drive cost down during the test window; that
+ lets us observe the "streak overflow but cost above floor" branch
+ in isolation.
+ """
+ ctrl = AdaptiveBatchController(
+ target_p50_ms=50.0,
+ min_wait_ms=1.0,
+ min_batch_cost=256,
+ fill_ratio_threshold=0.7,
+ update_interval=1,
+ starvation_window=3,
+ _current_wait_ms=1.0,
+ _current_batch_cost=4096,
+ )
+ # fill_ratio=0.1 is below the threshold → cost adjustment gated off.
+ for _ in range(3):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.1, batch_size=1)
+ assert ctrl.current_batch_cost == 4096 # confirm cost didn't move
+ assert ctrl.starvation_streak == 0 # detector waits for both floors
+ assert ctrl.starvation_resets == 0
+
+ def test_recovery_clears_integrator(self) -> None:
+ ctrl = self._make_pinned_controller(starvation_window=3)
+ ctrl._integral = -15.0
+ ctrl._last_step_time = time.monotonic() - 1.0
+ for _ in range(3):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ assert ctrl._integral == 0.0
+ assert ctrl._last_step_time is None
+
+ def test_recovery_disabled_by_flag(self) -> None:
+ ctrl = self._make_pinned_controller(starvation_window=3, starvation_recovery_enabled=False)
+ for _ in range(10):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ # Streak still tracked but no recovery fired.
+ assert ctrl.starvation_streak == 10
+ assert ctrl.starvation_resets == 0
+ assert ctrl.current_wait_ms == 1.0
+ assert ctrl.current_batch_cost == 256
+
+ def test_recovery_counted_monotonically(self) -> None:
+ """Multiple separate deadlocks increment the counter each time."""
+ ctrl = self._make_pinned_controller(starvation_window=3)
+ for _ in range(3):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ assert ctrl.starvation_resets == 1
+ # Force back to floor + drive tiny batches again.
+ ctrl._current_wait_ms = ctrl.min_wait_ms
+ ctrl._current_batch_cost = ctrl.min_batch_cost
+ for _ in range(3):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ assert ctrl.starvation_resets == 2
+
+ def test_end_to_end_deadlock_then_recovery(self) -> None:
+ """Simulate the real regression: a healthy controller driven into the
+ batch-of-1 attractor, then observe that it escapes without manual
+ intervention.
+ """
+ ctrl = AdaptiveBatchController(
+ target_p50_ms=50.0,
+ min_wait_ms=1.0,
+ max_wait_ms=50.0,
+ min_batch_cost=256,
+ max_batch_cost=65536,
+ gain=0.3,
+ integral_gain=0.05,
+ cost_gain=0.15,
+ update_interval=1,
+ starvation_window=5,
+ _current_wait_ms=10.0,
+ _current_batch_cost=16384,
+ )
+ # Load spike pushes p50 above target, controller shrinks.
+ # Drive ten very-over-SLO updates with saturated fill.
+ for _ in range(10):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=32)
+ # Both knobs should have shrunk toward the floor.
+ assert ctrl.current_wait_ms < 10.0
+ # Batches collapse to 1-item. Simulate that sustained state.
+ ctrl._current_wait_ms = ctrl.min_wait_ms
+ ctrl._current_batch_cost = ctrl.min_batch_cost
+ for _ in range(5):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ # Recovery should have fired.
+ assert ctrl.starvation_resets >= 1
+ assert ctrl.current_wait_ms > ctrl.min_wait_ms
+ assert ctrl.current_batch_cost > ctrl.min_batch_cost
+
+ def test_snapshot_exposes_starvation_state(self) -> None:
+ ctrl = self._make_pinned_controller(starvation_window=10)
+ for _ in range(3):
+ ctrl.step(observed_p50_ms=500.0, fill_ratio=0.99, batch_size=1)
+ snap = ctrl.snapshot(observed_p50_ms=500.0, fill_ratio=0.99)
+ assert snap.starvation_streak == 3
+ assert snap.starvation_resets == 0
diff --git a/packages/sie_server/tests/core/test_batcher.py b/packages/sie_server/tests/core/test_batcher.py
index 8e385820b..dd73fe770 100644
--- a/packages/sie_server/tests/core/test_batcher.py
+++ b/packages/sie_server/tests/core/test_batcher.py
@@ -119,7 +119,9 @@ class TestBatchConfig:
assert config.max_batch_tokens == 16384
assert config.max_batch_requests == 64
- assert config.max_batch_wait_ms == 10
+ assert config.max_batch_wait_ms == 15
+ assert config.coalesce_ms == 15.0
+ assert config.coalesce_ratio == 0.5
def test_custom_values(self) -> None:
"""Can create config with custom values."""
@@ -877,32 +879,32 @@ class TestEffectiveCoalesce:
"""Tests for proportional coalesce scaling (effective_coalesce_ms)."""
def test_default_scaling(self) -> None:
- """With default ratio (0.2), effective coalesce is 20% of batch wait."""
+ """With default ratio (0.5), effective coalesce is half of batch wait."""
config = BatchConfig(max_batch_wait_ms=50, coalesce_ms=20.0)
- # 50 * 0.2 = 10, min(20, 10) = 10
- assert config.effective_coalesce_ms == 10.0
+ # 50 * 0.5 = 25, min(20, 25) = 20
+ assert config.effective_coalesce_ms == 20.0
def test_ceiling_respected(self) -> None:
"""When ratio * wait > coalesce_ms, coalesce_ms is the ceiling."""
config = BatchConfig(max_batch_wait_ms=50, coalesce_ms=5.0)
- # 50 * 0.2 = 10, min(5, 10) = 5
+ # 50 * 0.5 = 25, min(5, 25) = 5
assert config.effective_coalesce_ms == 5.0
def test_scales_with_adaptive_wait(self) -> None:
"""Effective coalesce tracks changes to max_batch_wait_ms."""
config = BatchConfig(max_batch_wait_ms=10, coalesce_ms=20.0)
- # Initial: 10 * 0.2 = 2, min(20, 2) = 2
- assert config.effective_coalesce_ms == 2.0
+ # Initial: 10 * 0.5 = 5, min(20, 5) = 5
+ assert config.effective_coalesce_ms == 5.0
# Simulate adaptive controller increasing wait
config.max_batch_wait_ms = 50.0
- # 50 * 0.2 = 10, min(20, 10) = 10
- assert config.effective_coalesce_ms == 10.0
+ # 50 * 0.5 = 25, min(20, 25) = 20
+ assert config.effective_coalesce_ms == 20.0
# Simulate adaptive controller decreasing wait
config.max_batch_wait_ms = 2.0
- # 2 * 0.2 = 0.4, min(20, 0.4) = 0.4
- assert config.effective_coalesce_ms == pytest.approx(0.4)
+ # 2 * 0.5 = 1, min(20, 1) = 1
+ assert config.effective_coalesce_ms == pytest.approx(1.0)
def test_custom_ratio(self) -> None:
"""Custom coalesce_ratio is respected."""
diff --git a/packages/sie_server/tests/core/test_loader.py b/packages/sie_server/tests/core/test_loader.py
index 9d85ec318..f003f38e0 100644
--- a/packages/sie_server/tests/core/test_loader.py
+++ b/packages/sie_server/tests/core/test_loader.py
@@ -350,6 +350,85 @@ class MyCustomAdapter(ModelAdapter):
assert adapter.model_path == "org/custom" # type: ignore
+ def test_runtime_default_sampling_wired_when_adapter_accepts_it(self, tmp_path: Path) -> None:
+ """A profile's ``runtime.default_sampling`` reaches an adapter that declares the kwarg.
+
+ Regression: the block lived under ``adapter_options.runtime`` and was
+ dropped by ``_build_adapter_kwargs`` (which only spreads ``loadtime``),
+ so e.g. a ``min_new_tokens`` floor never reached SGLang.
+ """
+ adapter_file = tmp_path / "ds_adapter.py"
+ adapter_file.write_text("""
+from sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDims
+
+class DSAdapter(ModelAdapter):
+ def __init__(self, model_name_or_path, *, default_sampling=None, **kwargs):
+ self.model_path = model_name_or_path
+ self.default_sampling = default_sampling
+
+ @property
+ def capabilities(self):
+ return ModelCapabilities(inputs=["text"], outputs=["dense"])
+
+ @property
+ def dims(self):
+ return ModelDims(dense=768)
+
+ def load(self, device: str) -> None:
+ pass
+
+ def unload(self) -> None:
+ pass
+""")
+ config = _make_config(
+ sie_id="ds-model",
+ hf_id="org/ds",
+ adapter_path="ds_adapter.py:DSAdapter",
+ adapter_options=AdapterOptions(runtime={"default_sampling": {"min_new_tokens": 10, "temperature": 0.7}}),
+ )
+
+ adapter = load_adapter(config, tmp_path, device="cpu")
+
+ assert adapter.default_sampling == {"min_new_tokens": 10, "temperature": 0.7} # type: ignore
+
+ def test_runtime_default_sampling_skipped_when_adapter_lacks_kwarg(self, tmp_path: Path) -> None:
+ """Adapters without a ``default_sampling`` parameter are unaffected (no kwarg leak)."""
+ adapter_file = tmp_path / "plain_adapter.py"
+ adapter_file.write_text("""
+from sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDims
+
+class PlainAdapter(ModelAdapter):
+ def __init__(self, model_name_or_path, **kwargs):
+ self.model_path = model_name_or_path
+ self.seen_kwargs = kwargs
+
+ @property
+ def capabilities(self):
+ return ModelCapabilities(inputs=["text"], outputs=["dense"])
+
+ @property
+ def dims(self):
+ return ModelDims(dense=768)
+
+ def load(self, device: str) -> None:
+ pass
+
+ def unload(self) -> None:
+ pass
+""")
+ config = _make_config(
+ sie_id="plain-model",
+ hf_id="org/plain",
+ adapter_path="plain_adapter.py:PlainAdapter",
+ adapter_options=AdapterOptions(runtime={"default_sampling": {"min_new_tokens": 10}}),
+ )
+
+ adapter = load_adapter(config, tmp_path, device="cpu")
+
+ # **kwargs is not a named ``default_sampling`` parameter, so the guard
+ # skips it rather than leaking an unexpected kwarg.
+ assert "default_sampling" not in adapter.seen_kwargs # type: ignore
+
def test_invalid_adapter_path(self, tmp_path: Path) -> None:
"""Raises error for invalid adapter path."""
config = _make_config(
diff --git a/packages/sie_server/tests/core/test_lora_generation_exclusion.py b/packages/sie_server/tests/core/test_lora_generation_exclusion.py
index 06d010bfc..c9157351e 100644
--- a/packages/sie_server/tests/core/test_lora_generation_exclusion.py
+++ b/packages/sie_server/tests/core/test_lora_generation_exclusion.py
@@ -13,7 +13,7 @@ The validator runs at config-load and at
is a hard invariant. Encode/score/extract models continue to use the
scalar ``lora_id`` form and are accepted.
-See ``product/research/generation-primitive-status.md`` §5 / §6.2.
+This test locks the generation-specific config-load rejection.
"""
from __future__ import annotations
diff --git a/packages/sie_server/tests/core/test_model_load_timeout.py b/packages/sie_server/tests/core/test_model_load_timeout.py
index 0641f28d7..507d6797f 100644
--- a/packages/sie_server/tests/core/test_model_load_timeout.py
+++ b/packages/sie_server/tests/core/test_model_load_timeout.py
@@ -314,7 +314,7 @@ class TestRegistryIntegration:
)
async def test_sglang_startup_timeout_classifies_as_timeout(self) -> None:
- """M3 regression: ``_load_main_thread`` rewraps SGLang's
+ """Regression: ``_load_main_thread`` rewraps SGLang's
``RuntimeError('SGLang server failed to start within timeout')``
into ``ModelLoadTimeoutError`` so the classifier buckets it as
``LoadErrorClass.TIMEOUT`` (30 s cooldown) instead of UNKNOWN
diff --git a/packages/sie_server/tests/core/test_preprocessor.py b/packages/sie_server/tests/core/test_preprocessor.py
index efb0b8fe9..4a8761b64 100644
--- a/packages/sie_server/tests/core/test_preprocessor.py
+++ b/packages/sie_server/tests/core/test_preprocessor.py
@@ -199,6 +199,364 @@ class TestTextPreprocessor:
assert result["attention_mask"].numel() == 0
+class TestTextPreprocessorFastPath:
+ """Tests for the Rust-tokenise fast-path consumer on TextPreprocessor.
+
+ These tests cover the contract exposed over IPC: the worker-sidecar
+ attaches a ``PreparedTokens`` bundle, Python validates the
+ ``tokenizer_id`` hash and, on match, assembles ``PreparedBatch``
+ directly without calling the HF tokenizer. On any mismatch, drift,
+ or unsupported shape the method MUST return ``None`` so the caller
+ falls back to ``prepare()`` — correctness always wins over speed.
+ """
+
+ @pytest.fixture
+ def mock_config(self):
+ config = MagicMock()
+ config.max_sequence_length = 512
+ return config
+
+ @staticmethod
+ def _make_preprocessor(tokenizer_canonical: bytes) -> tuple[TextPreprocessor, str]:
+ """Build a preprocessor whose ``backend_tokenizer.to_str()``
+ returns ``tokenizer_canonical``. Returns the preprocessor and
+ its expected tokenizer_id (BLAKE3, truncated to 32 hex).
+ """
+ import blake3
+
+ backend = MagicMock()
+ backend.to_str.return_value = tokenizer_canonical.decode("utf-8")
+ tokenizer = MagicMock()
+ tokenizer.backend_tokenizer = backend
+ preprocessor = TextPreprocessor(tokenizer, "fast-model")
+ expected = blake3.blake3(tokenizer_canonical).hexdigest()[:32]
+ return preprocessor, expected
+
+ def test_tokenizer_id_is_cached_and_matches_blake3(self):
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ preprocessor, expected = self._make_preprocessor(canonical)
+
+ first = preprocessor.tokenizer_id
+ second = preprocessor.tokenizer_id
+
+ assert first == expected
+ assert first == second
+ # ``backend.to_str`` must be called exactly once regardless of
+ # how many callers read the property — it's on the hot path.
+ assert preprocessor._tokenizer.backend_tokenizer.to_str.call_count == 1
+
+ def test_tokenizer_id_is_none_for_slow_tokenizer(self):
+ """Slow tokenizers don't expose ``backend_tokenizer`` — no hash."""
+ tokenizer = MagicMock(spec=[]) # nothing but what we set explicitly
+ preprocessor = TextPreprocessor(tokenizer, "slow-model")
+ assert preprocessor.tokenizer_id is None
+
+ def test_fast_path_builds_prepared_batch_on_hash_match(self, mock_config):
+ from sie_server.ipc_types import PreparedTokens
+
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ preprocessor, tok_id = self._make_preprocessor(canonical)
+
+ items = [Item(text="foo"), Item(text="bar"), Item(text="baz")]
+ prepared_tokens = [
+ PreparedTokens(
+ input_ids=[[101, 2003, 102]],
+ tokenizer_id=tok_id,
+ # Omit attention_mask — Rust elides when all-ones. The
+ # consumer must rebuild it as [1]*len(input_ids).
+ attention_mask=[],
+ token_type_ids=[],
+ max_seq_len=128,
+ ),
+ PreparedTokens(
+ input_ids=[[101, 3231, 102]],
+ tokenizer_id=tok_id,
+ attention_mask=[[1, 1, 1]],
+ token_type_ids=[],
+ max_seq_len=128,
+ ),
+ PreparedTokens(
+ input_ids=[[101, 4, 5, 102]],
+ tokenizer_id=tok_id,
+ attention_mask=[[1, 1, 1, 1]],
+ # All-zero token_type_ids are allowed (BERT-style
+ # single-segment default).
+ token_type_ids=[[0, 0, 0, 0]],
+ max_seq_len=128,
+ ),
+ ]
+
+ batch = preprocessor.try_prepare_from_prepared_tokens(items, prepared_tokens, config=mock_config)
+
+ assert batch is not None
+ assert batch.modality == "text"
+ assert batch.size == 3
+ assert batch.total_cost == 3 + 3 + 4
+
+ # First item used the elided-attention-mask path — rebuilt as all ones.
+ assert batch.items[0].payload.input_ids == [101, 2003, 102]
+ assert batch.items[0].payload.attention_mask == [1, 1, 1]
+ assert batch.items[0].cost == 3
+ assert batch.items[0].original_index == 0
+
+ # Second item had an explicit attention mask; preserved verbatim.
+ assert batch.items[1].payload.attention_mask == [1, 1, 1]
+ assert batch.items[2].payload.attention_mask == [1, 1, 1, 1]
+
+ def test_fast_path_rejects_tokenizer_id_mismatch(self, mock_config):
+ from sie_server.ipc_types import PreparedTokens
+
+ preprocessor, _ = self._make_preprocessor(b'{"version":"1.0","model":{"type":"WordLevel"}}')
+
+ batch = preprocessor.try_prepare_from_prepared_tokens(
+ [Item(text="x")],
+ [
+ PreparedTokens(
+ input_ids=[[1, 2, 3]],
+ tokenizer_id="a" * 32, # deliberately wrong
+ attention_mask=[[1, 1, 1]],
+ token_type_ids=[],
+ max_seq_len=128,
+ )
+ ],
+ config=mock_config,
+ )
+ assert batch is None
+
+ def test_fast_path_rejects_malformed_attention_mask_shape(self, mock_config):
+ from sie_server.ipc_types import PreparedTokens
+
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ preprocessor, tok_id = self._make_preprocessor(canonical)
+
+ batch = preprocessor.try_prepare_from_prepared_tokens(
+ [Item(text="x")],
+ [
+ PreparedTokens(
+ input_ids=[[1, 2, 3]],
+ tokenizer_id=tok_id,
+ attention_mask=[[1, 1]],
+ token_type_ids=[],
+ max_seq_len=128,
+ )
+ ],
+ config=mock_config,
+ )
+ assert batch is None
+
+ def test_fast_path_rejects_non_zero_token_type_ids(self, mock_config):
+ from sie_server.ipc_types import PreparedTokens
+
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ preprocessor, tok_id = self._make_preprocessor(canonical)
+
+ batch = preprocessor.try_prepare_from_prepared_tokens(
+ [Item(text="x")],
+ [
+ PreparedTokens(
+ input_ids=[[1, 2, 3]],
+ tokenizer_id=tok_id,
+ attention_mask=[[1, 1, 1]],
+ # Segment ids for a sentence-pair encoder are not
+ # part of the Rust-side text payload contract.
+ token_type_ids=[[0, 1, 1]],
+ max_seq_len=128,
+ )
+ ],
+ config=mock_config,
+ )
+ assert batch is None
+
+ def test_fast_path_hybrid_tokenises_slow_subset_in_python(self, mock_config):
+ """Per-item hybrid: items with ``pt=None`` fall back to the
+ Python tokeniser inline, other items take the Rust bytes
+ unchanged. A single merged ``PreparedBatch`` comes out with
+ ``original_index`` preserved so the adapter's output routing
+ continues to work.
+ """
+ from sie_server.ipc_types import PreparedTokens
+
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ preprocessor, tok_id = self._make_preprocessor(canonical)
+
+ # Wire in a tokeniser stub for the Python fall-back side —
+ # only the "b" item (index 1) should flow through.
+ preprocessor._tokenizer.return_value = {
+ "input_ids": [[101, 999, 102]],
+ "attention_mask": [[1, 1, 1]],
+ }
+
+ batch = preprocessor.try_prepare_from_prepared_tokens(
+ [Item(text="a"), Item(text="b"), Item(text="c")],
+ [
+ PreparedTokens(
+ input_ids=[[101, 1, 102]],
+ tokenizer_id=tok_id,
+ attention_mask=[[1, 1, 1]],
+ token_type_ids=[],
+ max_seq_len=128,
+ ),
+ None, # Rust skipped this item (e.g. empty-text gate).
+ PreparedTokens(
+ input_ids=[[101, 2, 3, 102]],
+ tokenizer_id=tok_id,
+ attention_mask=[[1, 1, 1, 1]],
+ token_type_ids=[],
+ max_seq_len=128,
+ ),
+ ],
+ config=mock_config,
+ )
+ assert batch is not None
+ assert batch.size == 3
+
+ # Fast-path item (index 0) — Rust bytes verbatim.
+ assert batch.items[0].payload.input_ids == [101, 1, 102]
+ assert batch.items[0].original_index == 0
+
+ # Slow-path item (index 1) — tokenised in Python via the stub.
+ assert batch.items[1].payload.input_ids == [101, 999, 102]
+ assert batch.items[1].original_index == 1
+
+ # Fast-path item (index 2) — Rust bytes verbatim.
+ assert batch.items[2].payload.input_ids == [101, 2, 3, 102]
+ assert batch.items[2].original_index == 2
+
+ # The Python tokeniser was called exactly once, on the
+ # one-item slow subset. Multi-call would indicate we re-ran
+ # tokenisation on already-prepared inputs.
+ assert preprocessor._tokenizer.call_count == 1
+ (_, kwargs) = preprocessor._tokenizer.call_args
+ assert kwargs["truncation"] is True
+ assert kwargs["padding"] is False
+
+ def test_fast_path_returns_none_when_all_items_miss(self, mock_config):
+ """All-slow batch: skip the hybrid path entirely so the
+ caller's normal ``prepare()`` can run without an extra
+ tokeniser call from inside the fast-path helper.
+ """
+ from sie_server.ipc_types import PreparedTokens as _PT # noqa: F401, N814
+
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ preprocessor, _ = self._make_preprocessor(canonical)
+
+ batch = preprocessor.try_prepare_from_prepared_tokens(
+ [Item(text="a"), Item(text="b")],
+ [None, None],
+ config=mock_config,
+ )
+ assert batch is None
+ # Python tokeniser was NOT called from the fast-path helper —
+ # the caller will invoke ``prepare()`` on the full batch.
+ assert preprocessor._tokenizer.call_count == 0
+
+ def test_fast_path_hybrid_for_nonzero_token_type_ids(self, mock_config):
+ """Non-zero ``token_type_ids`` on a single item falls back to
+ Python for that item without killing the whole batch.
+ """
+ from sie_server.ipc_types import PreparedTokens
+
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ preprocessor, tok_id = self._make_preprocessor(canonical)
+
+ preprocessor._tokenizer.return_value = {
+ "input_ids": [[101, 500, 102]],
+ "attention_mask": [[1, 1, 1]],
+ }
+
+ batch = preprocessor.try_prepare_from_prepared_tokens(
+ [Item(text="clean"), Item(text="pair")],
+ [
+ PreparedTokens(
+ input_ids=[[101, 1, 102]],
+ tokenizer_id=tok_id,
+ attention_mask=[[1, 1, 1]],
+ token_type_ids=[],
+ max_seq_len=128,
+ ),
+ PreparedTokens(
+ input_ids=[[101, 2, 3, 102]],
+ tokenizer_id=tok_id,
+ attention_mask=[[1, 1, 1, 1]],
+ token_type_ids=[[0, 1, 1, 0]], # segment ids.
+ max_seq_len=128,
+ ),
+ ],
+ config=mock_config,
+ )
+ assert batch is not None
+ assert batch.items[0].payload.input_ids == [101, 1, 102]
+ # Item 1 went through Python.
+ assert batch.items[1].payload.input_ids == [101, 500, 102]
+ assert preprocessor._tokenizer.call_count == 1
+
+ def test_fast_path_rejects_whole_batch_on_tokenizer_drift(self, mock_config):
+ """Tokenizer_id drift on ANY item collapses the whole batch —
+ the hybrid split doesn't help if Rust and Python disagree on
+ what tokeniser they're running.
+ """
+ from sie_server.ipc_types import PreparedTokens
+
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ preprocessor, tok_id = self._make_preprocessor(canonical)
+
+ batch = preprocessor.try_prepare_from_prepared_tokens(
+ [Item(text="a"), Item(text="b")],
+ [
+ PreparedTokens(
+ input_ids=[[1, 2, 3]],
+ tokenizer_id=tok_id,
+ attention_mask=[[1, 1, 1]],
+ token_type_ids=[],
+ max_seq_len=128,
+ ),
+ PreparedTokens(
+ input_ids=[[4, 5, 6]],
+ tokenizer_id="deadbeef" * 4, # drift signal.
+ attention_mask=[[1, 1, 1]],
+ token_type_ids=[],
+ max_seq_len=128,
+ ),
+ ],
+ config=mock_config,
+ )
+ assert batch is None
+
+ def test_fast_path_rejects_when_truncated_above_model_cap(self, mock_config):
+ from sie_server.ipc_types import PreparedTokens
+
+ # Model caps at 128; Rust used 512. Staying on Python path
+ # ensures the truncation policy the operator configured is
+ # the one that takes effect.
+ mock_config.max_sequence_length = 128
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ preprocessor, tok_id = self._make_preprocessor(canonical)
+
+ batch = preprocessor.try_prepare_from_prepared_tokens(
+ [Item(text="x")],
+ [
+ PreparedTokens(
+ input_ids=[[1, 2, 3]],
+ tokenizer_id=tok_id,
+ attention_mask=[[1, 1, 1]],
+ token_type_ids=[],
+ max_seq_len=512,
+ )
+ ],
+ config=mock_config,
+ )
+ assert batch is None
+
+ def test_fast_path_empty_items_returns_empty_batch(self, mock_config):
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ preprocessor, _ = self._make_preprocessor(canonical)
+
+ batch = preprocessor.try_prepare_from_prepared_tokens([], [], config=mock_config)
+ assert batch is not None
+ assert batch.size == 0
+ assert batch.total_cost == 0
+
+
class TestImagePreprocessor:
"""Tests for ImagePreprocessor."""
diff --git a/packages/sie_server/tests/core/test_registry_async.py b/packages/sie_server/tests/core/test_registry_async.py
index 2a11895ac..528e5d2fd 100644
--- a/packages/sie_server/tests/core/test_registry_async.py
+++ b/packages/sie_server/tests/core/test_registry_async.py
@@ -35,7 +35,7 @@ def patch_ensure_model_cached():
class TestAsyncLoading:
- """Tests for async model loading (DESIGN.md Section 5.4)."""
+ """Tests for async model loading."""
@pytest.fixture
def mock_adapter(self) -> MagicMock:
diff --git a/packages/sie_server/tests/core/test_worker_core.py b/packages/sie_server/tests/core/test_worker_core.py
index af144f1e5..95e45f117 100644
--- a/packages/sie_server/tests/core/test_worker_core.py
+++ b/packages/sie_server/tests/core/test_worker_core.py
@@ -68,7 +68,9 @@ class TestWorkerConfig:
assert config.max_batch_tokens == 16384
assert config.max_batch_requests == 256
- assert config.max_batch_wait_ms == 10
+ assert config.max_batch_wait_ms == 15
+ assert config.coalesce_ms == 15.0
+ assert config.coalesce_ratio == 0.5
def test_custom_values(self) -> None:
"""Can set custom config values."""
@@ -130,6 +132,42 @@ class TestModelWorker:
assert worker.config.max_batch_tokens == 8192
+ def test_adaptive_cost_floor_anchors_to_max_batch_tokens(self, mock_adapter: MagicMock) -> None:
+ """The adaptive controller's cost floor scales with max_batch_tokens.
+
+ Regression guard: before this fix, ``min_batch_cost`` was always
+ ``min(256, max_batch_tokens)`` — i.e. 256 for anything realistic,
+ which let the PI loop collapse each GPU forward to a single item
+ under sustained negative-headroom load. The floor must now be at
+ least ``max_batch_tokens // 4`` so even a fully-collapsed cost knob
+ still packs several items per forward.
+ """
+ from sie_server.core.worker.types import AdaptiveBatchingParams
+
+ ab = AdaptiveBatchingParams(enabled=True)
+
+ # Typical production model: floor should be a quarter of budget.
+ worker_big = ModelWorker(mock_adapter, WorkerConfig(max_batch_tokens=16384, adaptive_batching=ab))
+ assert worker_big._adaptive_controller is not None
+ assert worker_big._adaptive_controller.min_batch_cost == 4096
+
+ # Medium model: still anchored to budget // 4.
+ worker_med = ModelWorker(mock_adapter, WorkerConfig(max_batch_tokens=8192, adaptive_batching=ab))
+ assert worker_med._adaptive_controller is not None
+ assert worker_med._adaptive_controller.min_batch_cost == 2048
+
+ # Small model where max_batch_tokens > 256: floor stays at the 256
+ # legacy minimum (max(256, 1024//4) = max(256, 256) = 256).
+ worker_boundary = ModelWorker(mock_adapter, WorkerConfig(max_batch_tokens=1024, adaptive_batching=ab))
+ assert worker_boundary._adaptive_controller is not None
+ assert worker_boundary._adaptive_controller.min_batch_cost == 256
+
+ # Tiny ``max_batch_tokens`` (pathological unit tests): clamp the
+ # floor to the configured budget so we never drive min above max.
+ worker_small = ModelWorker(mock_adapter, WorkerConfig(max_batch_tokens=100, adaptive_batching=ab))
+ assert worker_small._adaptive_controller is not None
+ assert worker_small._adaptive_controller.min_batch_cost == 100
+
@pytest.mark.asyncio
async def test_start_stop(self, mock_adapter: MagicMock) -> None:
"""Start and stop worker."""
diff --git a/packages/sie_server/tests/core/test_worker_passthrough.py b/packages/sie_server/tests/core/test_worker_passthrough.py
new file mode 100644
index 000000000..8ffca0e1b
--- /dev/null
+++ b/packages/sie_server/tests/core/test_worker_passthrough.py
@@ -0,0 +1,220 @@
+"""Tests for ModelWorker passthrough mode.
+
+In passthrough mode the ModelWorker bypasses its internal BatchFormer /
+per-LoRA queues / adaptive controller / FCFS process loop, and treats
+every ``submit*`` call as a fully-formed GPU forward pass — exactly the
+frame that arrived over IPC from the worker-sidecar.
+
+These tests assert the contract:
+
+1. No background ``_process_loop`` task is spawned.
+2. No per-LoRA ``BatchFormer`` is constructed.
+3. No adaptive controller is built (even if ``adaptive_batching.enabled=True``).
+4. Submit dispatches synchronously: by the time ``submit*`` returns its
+ future, the future is already done.
+5. Concurrent submits with different LoRAs serialise around
+ ``set_active_lora`` so the GPU never sees the wrong LoRA active.
+6. Backward compat: with passthrough off, every existing test behaviour
+ stays unchanged (covered by the existing 42 worker tests).
+"""
+
+from __future__ import annotations
+
+import asyncio
+from unittest.mock import MagicMock
+
+import numpy as np
+import pytest
+from sie_server.core.inference_output import EncodeOutput
+from sie_server.core.prepared import TextPreparedItem, make_text_item
+from sie_server.core.worker import ModelWorker, WorkerConfig
+from sie_server.core.worker.types import AdaptiveBatchingParams
+from sie_server.types.inputs import Item
+
+
+def mock_adapter() -> MagicMock:
+ """Adapter that echoes a [batch_size, 3] dense tensor."""
+ mock = MagicMock()
+ mock.encode.side_effect = lambda items, *args, **kwargs: EncodeOutput(
+ dense=np.array([[0.1, 0.2, 0.3]] * len(items), dtype=np.float32),
+ batch_size=len(items),
+ )
+ return mock
+
+
+def prepared_item() -> TextPreparedItem:
+ return make_text_item([1, 2, 3, 4, 5], 0)
+
+
+def test_passthrough_skips_internal_state(mock_adapter: MagicMock) -> None:
+ """Passthrough mode skips per-LoRA batchers + adaptive controller.
+
+ The internal worker state still exists (so existing call-sites that
+ iterate ``self._batchers`` don't crash), but nothing is allocated
+ upfront — the dict is empty and the controller is None.
+ """
+ config = WorkerConfig(
+ passthrough_mode=True,
+ adaptive_batching=AdaptiveBatchingParams(enabled=True), # MUST be ignored.
+ )
+ worker = ModelWorker(mock_adapter, config)
+
+ assert worker._passthrough_mode is True
+ assert worker._batchers == {}, "no BatchFormer should be allocated upfront"
+ assert worker._adaptive_controller is None, "adaptive controller forced off in passthrough"
+ assert worker._latency_tracker is None
+ assert worker._efficiency_tracker is None
+
+
+async def test_passthrough_start_does_not_spawn_process_loop(mock_adapter: MagicMock) -> None:
+ """``start()`` in passthrough returns without creating a background task."""
+ worker = ModelWorker(mock_adapter, WorkerConfig(passthrough_mode=True))
+ await worker.start()
+ try:
+ assert worker.is_running is True
+ assert worker._process_task is None, "no _process_loop should be spawned"
+ finally:
+ await worker.stop()
+
+
+async def test_passthrough_submit_dispatches_immediately(
+ mock_adapter: MagicMock, prepared_item: TextPreparedItem
+) -> None:
+ """The future is already done by the time submit() returns.
+
+ No batcher means no coalesce wait, no FCFS poll loop. The single GPU
+ forward pass runs synchronously inside the inference executor and
+ completes before submit() returns its (already-resolved) future.
+ """
+ worker = ModelWorker(mock_adapter, WorkerConfig(passthrough_mode=True))
+ await worker.start()
+ try:
+ future = await worker.submit(
+ [prepared_item],
+ [Item(text="hello")],
+ ["dense"],
+ )
+ # Already resolved — no extra await needed beyond the executor
+ # round-trip already consumed by submit_passthrough().
+ assert future.done(), "passthrough submit must resolve the future synchronously"
+
+ worker_result = future.result()
+ assert worker_result.output.batch_size == 1
+ np.testing.assert_array_equal(
+ worker_result.output.dense[0],
+ np.array([0.1, 0.2, 0.3], dtype=np.float32),
+ )
+ finally:
+ await worker.stop()
+
+
+async def test_passthrough_each_submit_is_one_forward_pass(
+ mock_adapter: MagicMock, prepared_item: TextPreparedItem
+) -> None:
+ """N concurrent submits → N adapter.encode() calls (NOT one big batch).
+
+ Default mode coalesces concurrent submits into a single GPU batch.
+ Passthrough deliberately does NOT — the worker-sidecar already owns
+ batch formation, and re-batching here is the dual-controller path
+ we're carving out. The adapter sees exactly the frames the sidecar
+ sent.
+ """
+ worker = ModelWorker(mock_adapter, WorkerConfig(passthrough_mode=True))
+ await worker.start()
+ try:
+ # Three independent submits, each with one prepared item.
+ results = await asyncio.gather(
+ worker.submit([prepared_item], [Item(text="a")], ["dense"]),
+ worker.submit([prepared_item], [Item(text="b")], ["dense"]),
+ worker.submit([prepared_item], [Item(text="c")], ["dense"]),
+ )
+ assert len(results) == 3
+
+ # In passthrough every submit dispatches its own GPU call. Default-
+ # mode coalescing would collapse this into 1 call; we want 3.
+ assert mock_adapter.encode.call_count == 3, (
+ f"passthrough: expected 3 forward passes (one per submit), got {mock_adapter.encode.call_count}"
+ )
+ finally:
+ await worker.stop()
+
+
+async def test_passthrough_serialises_lora_switch(mock_adapter: MagicMock, prepared_item: TextPreparedItem) -> None:
+ """Concurrent submits across LoRAs serialise around set_active_lora.
+
+ The hazard: coro A sets LoRA "x", schedules its forward pass on the
+ inference executor (returns immediately), then coro B sets LoRA "y"
+ on the asyncio thread *before* A's forward pass actually runs on the
+ executor — so A executes with LoRA "y" active. The passthrough lock
+ prevents this by holding the (set_lora → process_batch) pair atomic.
+
+ We assert the invariant by tracking, for each call, the LoRA that
+ was active when ``encode`` actually fired.
+ """
+ set_lora_calls: list[str | None] = []
+ encode_lora_at_call: list[str | None] = []
+
+ def on_set_lora(lora: str | None) -> None:
+ mock_adapter._current_lora = lora
+ set_lora_calls.append(lora)
+
+ def on_encode(items, *args, **kwargs):
+ # Record which LoRA was active at the moment encode was invoked
+ # by the inference thread. Under the passthrough lock this MUST
+ # equal the LoRA the corresponding submit() requested.
+ encode_lora_at_call.append(getattr(mock_adapter, "_current_lora", None))
+ return EncodeOutput(
+ dense=np.array([[0.1, 0.2, 0.3]] * len(items), dtype=np.float32),
+ batch_size=len(items),
+ )
+
+ mock_adapter.set_active_lora.side_effect = on_set_lora
+ mock_adapter.encode.side_effect = on_encode
+
+ worker = ModelWorker(mock_adapter, WorkerConfig(passthrough_mode=True))
+ await worker.start()
+ try:
+ await asyncio.gather(
+ worker.submit([prepared_item], [Item(text="a")], ["dense"], options={"lora": "lora-x"}),
+ worker.submit([prepared_item], [Item(text="b")], ["dense"], options={"lora": "lora-y"}),
+ worker.submit([prepared_item], [Item(text="c")], ["dense"], options={"lora": "lora-x"}),
+ )
+
+ # Each submit must have set LoRA right before its own encode.
+ # The pairing isn't guaranteed in order across concurrent submits,
+ # but the count must match and every encode must see SOME LoRA
+ # that was set by the immediately-preceding set_active_lora call.
+ assert mock_adapter.encode.call_count == 3
+ assert mock_adapter.set_active_lora.call_count == 3
+ # The atomic pairing means each encode_lora MUST equal one of the
+ # LoRAs we asked for, with the right multiset.
+ assert sorted(s or "" for s in encode_lora_at_call) == ["lora-x", "lora-x", "lora-y"]
+ finally:
+ await worker.stop()
+
+
+def test_passthrough_default_off() -> None:
+ """Default config has passthrough OFF — backwards compat with default deploys."""
+ config = WorkerConfig()
+ assert config.passthrough_mode is False
+
+
+def test_passthrough_env_var_override(monkeypatch: pytest.MonkeyPatch, mock_adapter: MagicMock) -> None:
+ """``SIE_WORKER_PASSTHROUGH=1`` forces passthrough even on default config."""
+ monkeypatch.setenv("SIE_WORKER_PASSTHROUGH", "1")
+ worker = ModelWorker(mock_adapter, WorkerConfig()) # passthrough_mode=False
+ assert worker._passthrough_mode is True
+
+
+def test_passthrough_env_var_off_by_default(mock_adapter: MagicMock) -> None:
+ """Without the env var, default config keeps passthrough OFF."""
+ worker = ModelWorker(mock_adapter, WorkerConfig())
+ assert worker._passthrough_mode is False
+ # And the existing worker state is up.
+ assert None in worker._batchers
diff --git a/packages/sie_server/tests/integration/test_chat_completions.py b/packages/sie_server/tests/integration/test_chat_completions.py
index de12c3d75..ae2764507 100644
--- a/packages/sie_server/tests/integration/test_chat_completions.py
+++ b/packages/sie_server/tests/integration/test_chat_completions.py
@@ -10,8 +10,7 @@ Run via ``mise run test -- -i`` after starting a local gateway with::
target/release/sie-gateway --nats-url ... &
mise run serve -- -m Qwen/Qwen3-4B-Instruct-2507
-Acceptance criteria from
-``product/plans/m4-req2-generate-issues/03-chat-completions-openai-compat.md``:
+Acceptance criteria:
* official OpenAI Python SDK round-trip
* unsupported field rejection with OpenAI envelope (``frequency_penalty``,
@@ -69,7 +68,7 @@ def test_frequency_penalty_nonzero_accepted(gateway_url: str) -> None:
"""Penalties in OpenAI's ``[-2.0, 2.0]`` range are validated by the
gateway and forwarded to the SGLang sampler (``ChatRequestParams``
plumbing in ``packages/sie_gateway/src/handlers/proxy.rs``). Prior
- to M4-req2 the gateway 400-rejected non-zero values; the regression
+ the gateway used to 400-reject non-zero values; the regression
guard here flips to "request must succeed" so we don't silently
re-introduce the reject.
"""
diff --git a/packages/sie_server/tests/integration/test_grammar_generate.py b/packages/sie_server/tests/integration/test_grammar_generate.py
index 4499208cc..b7728135e 100644
--- a/packages/sie_server/tests/integration/test_grammar_generate.py
+++ b/packages/sie_server/tests/integration/test_grammar_generate.py
@@ -2,7 +2,7 @@
``grammar``.
Skipped unless ``SIE_GATEWAY_URL`` is set. Mirrors the acceptance
-criteria from ``product/plans/m4-req2-generate-issues/04-structured-outputs-outlines.md``:
+criteria for structured outputs:
* §5.7 — moderate JSON Schema returns JSON conforming to the schema.
* §5.9 — two identical-schema requests show exactly 1 compile + 1 hit
diff --git a/packages/sie_server/tests/observability/test_generation_metrics.py b/packages/sie_server/tests/observability/test_generation_metrics.py
index 1e5ea03ae..4c06f8d2b 100644
--- a/packages/sie_server/tests/observability/test_generation_metrics.py
+++ b/packages/sie_server/tests/observability/test_generation_metrics.py
@@ -222,12 +222,12 @@ def test_metrics_export_contains_no_routing_or_prompt_identifiers() -> None:
assert needle not in body, f"forbidden label/value {needle!r} leaked into /metrics body"
-def test_m5_observability_metrics_module_still_excludes_opentelemetry() -> None:
- """M5+: the metrics surface module is still pure Prometheus.
+def test_observability_metrics_module_still_excludes_opentelemetry() -> None:
+ """The metrics surface module is still pure Prometheus.
The metrics rollout originally banned OpenTelemetry mentions from this
*specific module* because trace propagation was out of scope for
- that work. M5 introduces trace context propagation, but the
+ that work. Trace context propagation exists, but the
*worker observability metrics module itself* still has no need
to import OpenTelemetry — the propagation surface lives in
:mod:`sie_server.processors.streaming` and the FastAPI tracing
@@ -243,7 +243,7 @@ def test_m5_observability_metrics_module_still_excludes_opentelemetry() -> None:
metrics_path = pathlib.Path(obs_metrics.__file__)
source = metrics_path.read_text(encoding="utf-8").lower()
- # `traceparent` is fine to mention in M5 docs/comments anywhere
+ # `traceparent` is fine to mention in docs/comments anywhere
# else, but should still not bleed into the metrics-text rendering
# module. We still ban it here to keep that module focused.
for forbidden in ("traceparent", "opentelemetry"):
diff --git a/packages/sie_server/tests/observability/test_metrics.py b/packages/sie_server/tests/observability/test_metrics.py
index 5dc19433c..0679448c9 100644
--- a/packages/sie_server/tests/observability/test_metrics.py
+++ b/packages/sie_server/tests/observability/test_metrics.py
@@ -5,16 +5,15 @@ from unittest.mock import MagicMock
import pytest
from sie_server.observability.metrics import (
- BATCH_SIZE,
+ IPC_BATCH_ITEMS,
+ IPC_BATCH_SUB_GROUP_ITEMS,
+ IPC_BATCH_SUB_GROUPS,
MODEL_LOADED,
- QUEUE_DEPTH,
REQUEST_DURATION,
REQUESTS_TOTAL,
- TOKENS_PROCESSED,
- record_batch,
+ record_ipc_batch_shape,
record_request,
set_model_loaded,
- set_queue_depth,
)
@@ -139,45 +138,6 @@ class TestRecordRequest:
assert rec.status == "error" # type: ignore
-class TestRecordBatch:
- """Tests for record_batch helper."""
-
- def test_records_batch_size(self) -> None:
- """record_batch should observe batch size."""
- record_batch(model="batch-test", batch_size=16, tokens=1024)
-
- # Verify the histogram was observed
- assert BATCH_SIZE.labels(model="batch-test") is not None
-
- def test_records_tokens_processed(self) -> None:
- """record_batch should increment tokens counter."""
- initial = TOKENS_PROCESSED.labels(model="tokens-test")._value.get()
-
- record_batch(model="tokens-test", batch_size=8, tokens=512)
-
- new_value = TOKENS_PROCESSED.labels(model="tokens-test")._value.get()
- assert new_value == initial + 512
-
-
-class TestSetQueueDepth:
- """Tests for set_queue_depth helper."""
-
- def test_sets_gauge_value(self) -> None:
- """set_queue_depth should set the gauge to the specified value."""
- set_queue_depth(model="queue-test", depth=42)
-
- value = QUEUE_DEPTH.labels(model="queue-test")._value.get()
- assert value == 42
-
- def test_can_update_value(self) -> None:
- """set_queue_depth should be able to update the value."""
- set_queue_depth(model="queue-update-test", depth=10)
- set_queue_depth(model="queue-update-test", depth=5)
-
- value = QUEUE_DEPTH.labels(model="queue-update-test")._value.get()
- assert value == 5
-
-
class TestSetModelLoaded:
"""Tests for set_model_loaded helper."""
@@ -194,3 +154,109 @@ class TestSetModelLoaded:
value = MODEL_LOADED.labels(model="unloaded-test", device="cpu")._value.get()
assert value == 0
+
+
+class TestRecordIpcBatchShape:
+ """Guards the IPC-batch fragmentation metric.
+
+ The three histograms together answer:
+ "How many items did an IPC batch deliver, into how many GPU
+ forward passes did that batch split, and how many items were
+ in each resulting pass?"
+
+ Every commit that changes the dispatch strategy in the queue
+ executor should make sure these semantics stay true — otherwise
+ Grafana panels built on these metrics become subtly wrong.
+ """
+
+ @staticmethod
+ def _sample_count(histogram: object, **labels: str) -> float:
+ return histogram.labels(**labels)._sum.get() # type: ignore[attr-defined]
+
+ @staticmethod
+ def _observation_count(histogram: object, **labels: str) -> float:
+ # prometheus_client Histograms expose per-label-tuple samples via
+ # the private `_sum` (running sum) and per-bucket counters; for a
+ # cumulative check we read `.collect()` and sum the `+Inf` bucket.
+ samples = histogram.labels(**labels).collect()[0].samples # type: ignore[attr-defined]
+ for s in samples:
+ if s.name.endswith("_count"):
+ return s.value
+ return 0.0
+
+ def test_observes_all_three_histograms(self) -> None:
+ # Use a fresh (model, endpoint) tuple so the test is
+ # independent of anything else that ran in the same process.
+ model, endpoint = "shape-test/model-1", "encode"
+
+ before_items = self._observation_count(IPC_BATCH_ITEMS, model=model, endpoint=endpoint)
+ before_groups = self._observation_count(IPC_BATCH_SUB_GROUPS, model=model, endpoint=endpoint)
+ before_sub = self._observation_count(IPC_BATCH_SUB_GROUP_ITEMS, model=model, endpoint=endpoint)
+
+ record_ipc_batch_shape(
+ model=model,
+ endpoint=endpoint,
+ total_items=10,
+ sub_group_sizes=[4, 3, 3],
+ )
+
+ assert self._observation_count(IPC_BATCH_ITEMS, model=model, endpoint=endpoint) == before_items + 1
+ assert self._observation_count(IPC_BATCH_SUB_GROUPS, model=model, endpoint=endpoint) == before_groups + 1
+ # One observation per sub-group size (3 entries).
+ assert self._observation_count(IPC_BATCH_SUB_GROUP_ITEMS, model=model, endpoint=endpoint) == before_sub + 3
+
+ def test_sums_reflect_reported_shape(self) -> None:
+ model, endpoint = "shape-test/model-2", "encode"
+ before_items_sum = self._sample_count(IPC_BATCH_ITEMS, model=model, endpoint=endpoint)
+ before_groups_sum = self._sample_count(IPC_BATCH_SUB_GROUPS, model=model, endpoint=endpoint)
+ before_sub_sum = self._sample_count(IPC_BATCH_SUB_GROUP_ITEMS, model=model, endpoint=endpoint)
+
+ record_ipc_batch_shape(
+ model=model,
+ endpoint=endpoint,
+ total_items=29,
+ sub_group_sizes=[17, 9, 3],
+ )
+
+ assert self._sample_count(IPC_BATCH_ITEMS, model=model, endpoint=endpoint) == pytest.approx(
+ before_items_sum + 29
+ )
+ assert self._sample_count(IPC_BATCH_SUB_GROUPS, model=model, endpoint=endpoint) == pytest.approx(
+ before_groups_sum + 3
+ )
+ assert self._sample_count(IPC_BATCH_SUB_GROUP_ITEMS, model=model, endpoint=endpoint) == pytest.approx(
+ before_sub_sum + 17 + 9 + 3
+ )
+
+ def test_empty_batch_is_a_noop(self) -> None:
+ # Zero-item IPC batches don't happen in practice but the helper
+ # must refuse to poison the histogram with a 0-bucket sample —
+ # that would bias any p50 computation.
+ model, endpoint = "shape-test/model-3", "encode"
+ before = self._observation_count(IPC_BATCH_ITEMS, model=model, endpoint=endpoint)
+
+ record_ipc_batch_shape(model=model, endpoint=endpoint, total_items=0, sub_group_sizes=[])
+
+ assert self._observation_count(IPC_BATCH_ITEMS, model=model, endpoint=endpoint) == before
+
+ def test_ignores_zero_sized_sub_groups(self) -> None:
+ # Defensive: if a caller ever passed `[2, 0, 1]` (shouldn't
+ # happen but could during refactors), we record only the
+ # truthy entries so we don't skew the group-items histogram.
+ model, endpoint = "shape-test/model-4", "encode"
+ before_sub = self._observation_count(IPC_BATCH_SUB_GROUP_ITEMS, model=model, endpoint=endpoint)
+ before_groups = self._observation_count(IPC_BATCH_SUB_GROUPS, model=model, endpoint=endpoint)
+
+ record_ipc_batch_shape(
+ model=model,
+ endpoint=endpoint,
+ total_items=3,
+ sub_group_sizes=[2, 0, 1],
+ )
+
+ assert self._observation_count(IPC_BATCH_SUB_GROUP_ITEMS, model=model, endpoint=endpoint) == before_sub + 2
+ # The sub_groups count itself still reflects what the caller
+ # reported — the 0 is a caller bug, and this metric surfaces
+ # it as a "group count > non-zero items" anomaly rather than
+ # silently dropping it.
+ assert self._observation_count(IPC_BATCH_SUB_GROUPS, model=model, endpoint=endpoint) == before_groups + 1
diff --git a/packages/sie_server/tests/observability/test_trace_propagation.py b/packages/sie_server/tests/observability/test_trace_propagation.py
index 5c0d87261..0a66347b2 100644
--- a/packages/sie_server/tests/observability/test_trace_propagation.py
+++ b/packages/sie_server/tests/observability/test_trace_propagation.py
@@ -1,4 +1,4 @@
-"""W3C Trace Context propagation through the worker streaming processor (M5).
+"""W3C Trace Context propagation through the worker streaming processor.
These tests pin the contract that
:meth:`sie_server.processors.streaming.StreamingProcessor.process`
@@ -156,7 +156,7 @@ async def test_worker_span_is_child_of_envelope_traceparent(
) -> None:
"""The worker span's trace_id must match the inbound traceparent.
- This is the load-bearing assertion of the whole M5 wire — if
+ This is the load-bearing assertion of the trace propagation wire — if
the worker did not extract the parent context the span would
root a *new* trace tree and the assertion fails. The
`parent_span_id` check additionally proves it's a child of the
@@ -232,7 +232,7 @@ async def test_worker_span_is_root_when_envelope_omits_traceparent(
) -> None:
"""Backward-compat: envelopes without `traceparent` still emit a span.
- Pre-M5 gateways do not populate the trace fields, and we must
+ Gateways without trace propagation do not populate the trace fields, and we must
not crash or skip the worker span just because the envelope
omits them. The worker emits a root span instead — the trace
just won't link back to a gateway parent.
diff --git a/packages/sie_server/tests/processors/test_grammar_prewarm.py b/packages/sie_server/tests/processors/test_grammar_prewarm.py
index 99081ba30..99db24935 100644
--- a/packages/sie_server/tests/processors/test_grammar_prewarm.py
+++ b/packages/sie_server/tests/processors/test_grammar_prewarm.py
@@ -97,8 +97,6 @@ def _patch_compile(
When ``grammar.label`` is in ``raise_on`` the stub raises a
:class:`RuntimeError` so we can exercise the per-entry failure path.
"""
- import sie_server.processors.streaming as streaming_mod
-
calls: list[tuple[Any, Any]] = []
def _stub_compile(tok: Any, grammar: Any) -> Any:
@@ -108,13 +106,13 @@ def _patch_compile(
raise RuntimeError(msg)
return True
- monkeypatch.setattr(streaming_mod, "compile_outlines", _stub_compile)
+ monkeypatch.setattr("sie_server.processors.streaming.compile_outlines", _stub_compile)
async def _fake_get_tokenizer(self: Any, model_id: str) -> Any:
return object()
monkeypatch.setattr(
- streaming_mod.StreamingProcessor,
+ StreamingProcessor,
"_get_tokenizer",
_fake_get_tokenizer,
)
diff --git a/packages/sie_server/tests/processors/test_streaming.py b/packages/sie_server/tests/processors/test_streaming.py
index e6a10b672..946e3e0d6 100644
--- a/packages/sie_server/tests/processors/test_streaming.py
+++ b/packages/sie_server/tests/processors/test_streaming.py
@@ -232,10 +232,7 @@ async def test_cancel_event_emits_cancelled_terminal() -> None:
GenerationChunk(text_delta=" more"), # will never be yielded — held
GenerationChunk(text_delta="", done=True, finish_reason="stop"),
]
- adapter = _FakeGenAdapter(script, hold_event=hold)
- # First chunk yields immediately (hold unset for the first iteration?).
- # We need the first chunk to come through; then we hold subsequent yields.
- # Easiest: don't use hold for the first; set it after first.
+ # First chunk yields immediately; subsequent yields wait on `hold`.
# Workaround: tweak the adapter to not hold on the first yield.
class _AdapterFirstFree(_FakeGenAdapter):
@@ -709,8 +706,6 @@ def _patch_compile(monkeypatch: pytest.MonkeyPatch, fn: Any) -> list[int]:
exercise the legacy worker-side preflight (now off by default per
ADR-0002) still run the preflight code path.
"""
- import sie_server.processors.streaming as streaming_mod
-
# ADR-0002: the worker-side preflight is off by default. Tests that
# use this helper are explicitly exercising the preflight path, so
# enable the debug flag for their scope.
@@ -722,7 +717,7 @@ def _patch_compile(monkeypatch: pytest.MonkeyPatch, fn: Any) -> list[int]:
calls.append(1)
return fn(tok, grammar)
- monkeypatch.setattr(streaming_mod, "compile_outlines", _wrapped)
+ monkeypatch.setattr("sie_server.processors.streaming.compile_outlines", _wrapped)
# Stub the per-model tokenizer fetch so tests don't need an
# ``hf_id``-shaped fixture. ``_ensure_grammar_ready`` only needs an
@@ -732,7 +727,7 @@ def _patch_compile(monkeypatch: pytest.MonkeyPatch, fn: Any) -> list[int]:
return object()
monkeypatch.setattr(
- streaming_mod.StreamingProcessor,
+ StreamingProcessor,
"_get_tokenizer",
_fake_get_tokenizer,
)
@@ -814,9 +809,7 @@ async def test_grammar_compile_timeout_surfaces_grammar_compile_failed(
# ``streaming._wait_for`` so the override is scoped to this
# module — patching ``asyncio.wait_for`` directly would affect
# every concurrent coroutine.
- import sie_server.processors.streaming as streaming_mod
-
- real_wait_for = streaming_mod._wait_for
+ from sie_server.processors.streaming import _wait_for as real_wait_for
# The ``timeout`` kw mirrors :func:`asyncio.wait_for`'s signature
# — required because the shim replaces it 1:1. The lint rule
@@ -826,7 +819,7 @@ async def test_grammar_compile_timeout_surfaces_grammar_compile_failed(
_ = timeout
return await real_wait_for(coro, timeout=0.05)
- monkeypatch.setattr(streaming_mod, "_wait_for", _short_wait)
+ monkeypatch.setattr("sie_server.processors.streaming._wait_for", _short_wait)
def _slow_compile(_tok: Any, _g: Any) -> Any:
import time as _time
@@ -1301,15 +1294,14 @@ async def test_ebnf_on_outlines_backend_not_rejected_at_preflight(
registry=_make_registry(adapter),
worker_id="w1",
)
+
# The real ``compile_outlines`` is exercised — but with the fix it
# short-circuits for EBNF before resolving any Outlines factory, so we
# don't need to stub it. Stub only the tokenizer fetch.
- import sie_server.processors.streaming as streaming_mod
-
async def _fake_get_tokenizer(self: Any, model_id: str) -> Any:
return object()
- monkeypatch.setattr(streaming_mod.StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)
+ monkeypatch.setattr(StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)
grammar_payload = {"kind": "ebnf", "value": 'root ::= "yes" | "no"'}
msg = _make_msg(_make_work_item(generate={"prompt": "Hi", "max_new_tokens": 8, "grammar": grammar_payload}))
@@ -1342,12 +1334,10 @@ async def test_cancel_during_grammar_compile_window_is_honored(
registry = _make_registry(_FakeGenAdapter(script))
proc = StreamingProcessor(nc=nc, registry=registry, worker_id="w1")
- import sie_server.processors.streaming as streaming_mod
-
async def _fake_get_tokenizer(self: Any, model_id: str) -> Any:
return object()
- monkeypatch.setattr(streaming_mod.StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)
+ monkeypatch.setattr(StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)
compile_started = asyncio.Event()
compile_release = threading.Event()
@@ -1707,22 +1697,20 @@ async def test_grammar_preflight_default_does_not_call_compile_outlines(
# other test fixture could have set it).
monkeypatch.delenv("SIE_GRAMMAR_PREFLIGHT_DEBUG", raising=False)
- import sie_server.processors.streaming as streaming_mod
-
calls: list[int] = []
def _spy(_tok: Any, _g: Any) -> Any:
calls.append(1)
return True
- monkeypatch.setattr(streaming_mod, "compile_outlines", _spy)
+ monkeypatch.setattr("sie_server.processors.streaming.compile_outlines", _spy)
# Stub the tokenizer fetch in case the env flag is accidentally on
# somewhere — we still don't want the test crashing on a missing HF id.
async def _fake_get_tokenizer(self: Any, model_id: str) -> Any:
return object()
- monkeypatch.setattr(streaming_mod.StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)
+ monkeypatch.setattr(StreamingProcessor, "_get_tokenizer", _fake_get_tokenizer)
nc = AsyncMock()
script = [
@@ -1824,12 +1812,12 @@ def test_adr0002_metrics_register_without_error() -> None:
"""
from sie_server.observability import metrics as obs_metrics
- obs_metrics.GRAMMAR_COMPILE_SECONDS_ADR0002.labels(backend="outlines", mode="json_schema").observe(0.01)
- obs_metrics.GRAMMAR_COMPILE_SECONDS_ADR0002.labels(backend="xgrammar", mode="regex").observe(0.02)
+ obs_metrics.GRAMMAR_COMPILE_SECONDS_STRUCTURED_OUTPUT.labels(backend="outlines", mode="json_schema").observe(0.01)
+ obs_metrics.GRAMMAR_COMPILE_SECONDS_STRUCTURED_OUTPUT.labels(backend="xgrammar", mode="regex").observe(0.02)
obs_metrics.STRUCTURED_OUTPUT_TTFT_SECONDS.labels(backend="outlines", mode="json_schema").observe(0.1)
obs_metrics.STRUCTURED_OUTPUT_TTFT_SECONDS.labels(backend="llguidance", mode="ebnf").observe(0.2)
- obs_metrics.GRAMMAR_CACHE_HITS_ADR0002.labels(backend="outlines").inc()
- obs_metrics.GRAMMAR_CACHE_MISSES_ADR0002.labels(backend="outlines").inc()
+ obs_metrics.GRAMMAR_CACHE_HITS_STRUCTURED_OUTPUT.labels(backend="outlines").inc()
+ obs_metrics.GRAMMAR_CACHE_MISSES_STRUCTURED_OUTPUT.labels(backend="outlines").inc()
obs_metrics.GRAMMAR_UNIQUE_SCHEMA_TOTAL.labels(backend="outlines", mode="json_schema").inc()
obs_metrics.GRAMMAR_UNIQUE_SCHEMA_TOTAL.labels(backend="unknown", mode="ebnf").inc()
diff --git a/packages/sie_server/tests/processors/test_work_class_scheduler.py b/packages/sie_server/tests/processors/test_work_class_scheduler.py
index e8d575fb4..b636efd52 100644
--- a/packages/sie_server/tests/processors/test_work_class_scheduler.py
+++ b/packages/sie_server/tests/processors/test_work_class_scheduler.py
@@ -1,4 +1,4 @@
-"""Unit tests for the mixed-pool fair-queue scheduler (roadmap §6.1).
+"""Unit tests for the mixed-pool fair-queue scheduler.
Pure asyncio — no NATS. Covers config validation, the min_slots starvation
floor, weighted-fair shares, slot release waking the most-owed waiter,
diff --git a/packages/sie_server/tests/test_adapter_call_loop.py b/packages/sie_server/tests/test_adapter_call_loop.py
new file mode 100644
index 000000000..bd6737592
--- /dev/null
+++ b/packages/sie_server/tests/test_adapter_call_loop.py
@@ -0,0 +1,295 @@
+"""Unit tests for :mod:`sie_server.adapter_call_loop`.
+
+Scope:
+ * Dispatches to the correct per-op ``QueueExecutor`` method.
+ * Preserves item order when forwarding.
+ * Rejects mixed-op batches with per-item error outcomes.
+ * Produces typed errors (``run_batch_*``) for malformed inputs
+ without crashing.
+
+Out of scope: the IPC round-trip (that's ``test_ipc_server.py``) and
+the actual adapter forward pass (that's ``test_queue_executor*.py``).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import AsyncMock
+
+import pytest
+from sie_server.adapter_call_loop import (
+ RUN_BATCH_INVALID_ITEM,
+ RUN_BATCH_MIXED_OP,
+ RUN_BATCH_UNKNOWN_OP,
+ handle_run_batch,
+)
+from sie_server.ipc_types import (
+ BatchOutcome,
+ EncodeBatchItem,
+ ExtractBatchItem,
+ ItemOutcome,
+ RunBatchItem,
+ RunBatchRequest,
+ ScoreBatchItem,
+)
+
+# --------------------------------------------------------------------
+# Helpers
+# --------------------------------------------------------------------
+
+
+def _mk_encode(idx: int, text: str = "hello") -> EncodeBatchItem:
+ return EncodeBatchItem(
+ work_item_id=f"w{idx}",
+ request_id=f"r{idx}",
+ item_index=idx,
+ total_items=1,
+ timestamp=0.0,
+ item={"text": text},
+ )
+
+
+def _mk_score(idx: int) -> ScoreBatchItem:
+ return ScoreBatchItem(
+ work_item_id=f"w{idx}",
+ request_id=f"r{idx}",
+ item_index=idx,
+ total_items=1,
+ timestamp=0.0,
+ query_item={"text": "q"},
+ score_items=[{"text": "d1"}, {"text": "d2"}],
+ )
+
+
+def _mk_extract(idx: int) -> ExtractBatchItem:
+ return ExtractBatchItem(
+ work_item_id=f"w{idx}",
+ request_id=f"r{idx}",
+ item_index=idx,
+ total_items=1,
+ timestamp=0.0,
+ item={"text": "extract me"},
+ )
+
+
+def _ok_outcome(idx: int, result: bytes = b"\x80") -> ItemOutcome:
+ return ItemOutcome(
+ work_item_id=f"w{idx}",
+ request_id=f"r{idx}",
+ item_index=idx,
+ disposition="publish_and_ack",
+ result_msgpack=result,
+ )
+
+
+def _mk_request(
+ *items: RunBatchItem,
+ model_id: str = "test/model",
+ batch_id: int = 1,
+ lora_key: str = "",
+ total_cost: int = 0,
+) -> RunBatchRequest:
+ return RunBatchRequest(
+ model_id=model_id,
+ batch_id=batch_id,
+ lora_key=lora_key,
+ total_cost=total_cost,
+ items=list(items),
+ )
+
+
+def _mock_executor(**responses: Any) -> AsyncMock:
+ """Build an AsyncMock executor with the three per-op methods.
+
+ Pass ``encode=BatchOutcome(...)`` etc to control what each method
+ returns.
+ """
+ exe = AsyncMock()
+ exe.process_encode_batch = AsyncMock(
+ return_value=responses.get("encode", BatchOutcome(outcomes=[])),
+ )
+ exe.process_score_batch = AsyncMock(
+ return_value=responses.get("score", BatchOutcome(outcomes=[])),
+ )
+ exe.process_extract_batch = AsyncMock(
+ return_value=responses.get("extract", BatchOutcome(outcomes=[])),
+ )
+ return exe
+
+
+# --------------------------------------------------------------------
+# Happy paths
+# --------------------------------------------------------------------
+
+
+async def test_encode_batch_dispatches_to_process_encode() -> None:
+ expected = BatchOutcome(outcomes=[_ok_outcome(0), _ok_outcome(1)])
+ exe = _mock_executor(encode=expected)
+ req = _mk_request(
+ RunBatchItem(op="encode", encode=_mk_encode(0)),
+ RunBatchItem(op="encode", encode=_mk_encode(1)),
+ )
+
+ result = await handle_run_batch(exe, req)
+
+ assert result.outcomes == expected.outcomes
+ exe.process_encode_batch.assert_awaited_once()
+ inner = exe.process_encode_batch.call_args.args[0]
+ assert inner.model_id == "test/model"
+ assert len(inner.items) == 2
+ # Order must be preserved so per-item index alignment holds.
+ assert [it.item_index for it in inner.items] == [0, 1]
+ # Score / extract handlers never called.
+ exe.process_score_batch.assert_not_called()
+ exe.process_extract_batch.assert_not_called()
+
+
+async def test_score_batch_dispatches_to_process_score() -> None:
+ expected = BatchOutcome(outcomes=[_ok_outcome(0)])
+ exe = _mock_executor(score=expected)
+ req = _mk_request(RunBatchItem(op="score", score=_mk_score(0)))
+
+ result = await handle_run_batch(exe, req)
+
+ assert result.outcomes == expected.outcomes
+ exe.process_score_batch.assert_awaited_once()
+ exe.process_encode_batch.assert_not_called()
+ exe.process_extract_batch.assert_not_called()
+
+
+async def test_extract_batch_dispatches_to_process_extract() -> None:
+ expected = BatchOutcome(outcomes=[_ok_outcome(0)])
+ exe = _mock_executor(extract=expected)
+ req = _mk_request(RunBatchItem(op="extract", extract=_mk_extract(0)))
+
+ result = await handle_run_batch(exe, req)
+
+ assert result.outcomes == expected.outcomes
+ exe.process_extract_batch.assert_awaited_once()
+
+
+# --------------------------------------------------------------------
+# Error paths
+# --------------------------------------------------------------------
+
+
+async def test_empty_batch_returns_empty_outcome() -> None:
+ exe = _mock_executor()
+ req = _mk_request() # no items
+
+ result = await handle_run_batch(exe, req)
+
+ assert result.outcomes == []
+ exe.process_encode_batch.assert_not_called()
+
+
+async def test_mixed_op_batch_is_rejected_wholesale() -> None:
+ exe = _mock_executor()
+ req = _mk_request(
+ RunBatchItem(op="encode", item_index=7, encode=_mk_encode(7)),
+ RunBatchItem(op="score", item_index=9, score=_mk_score(9)),
+ )
+
+ result = await handle_run_batch(exe, req)
+
+ assert len(result.outcomes) == 2
+ for o in result.outcomes:
+ assert o.disposition == "publish_error_and_ack"
+ assert o.error_code == RUN_BATCH_MIXED_OP
+ assert [o.item_index for o in result.outcomes] == [7, 9]
+ # Neither underlying handler was called — protocol violation
+ # short-circuits before any executor work.
+ exe.process_encode_batch.assert_not_called()
+ exe.process_score_batch.assert_not_called()
+
+
+async def test_unknown_op_is_rejected_with_typed_error_code() -> None:
+ exe = _mock_executor()
+ # msgspec can't enforce the Literal at construction time without
+ # being given a RunBatchItem instance; we bypass here to simulate
+ # a future op the current Python doesn't know.
+ req = RunBatchRequest(
+ model_id="m",
+ batch_id=1,
+ lora_key="",
+ total_cost=0,
+ items=[RunBatchItem(op="future_op")], # type: ignore[arg-type]
+ )
+
+ result = await handle_run_batch(exe, req)
+
+ assert len(result.outcomes) == 1
+ assert result.outcomes[0].error_code == RUN_BATCH_UNKNOWN_OP
+ assert result.outcomes[0].disposition == "publish_error_and_ack"
+
+
+async def test_invalid_item_tagged_but_batch_continues() -> None:
+ # Second item has op=encode but encode payload missing — that
+ # one becomes an invalid_item outcome, and the rest of the batch
+ # still goes to process_encode_batch for item 0.
+ expected = BatchOutcome(outcomes=[_ok_outcome(0)])
+ exe = _mock_executor(encode=expected)
+ req = _mk_request(
+ RunBatchItem(op="encode", encode=_mk_encode(0)),
+ RunBatchItem(op="encode", work_item_id="w1", request_id="r1", item_index=1, encode=None),
+ )
+
+ result = await handle_run_batch(exe, req)
+
+ assert len(result.outcomes) == 2
+ # Invalid outcomes come first, followed by the executor's outcomes.
+ assert result.outcomes[0].error_code == RUN_BATCH_INVALID_ITEM
+ assert result.outcomes[0].disposition == "publish_error_and_ack"
+ assert result.outcomes[0].work_item_id == "w1"
+ assert result.outcomes[0].request_id == "r1"
+ assert result.outcomes[0].item_index == 1
+ assert result.outcomes[1].work_item_id == "w0"
+ # The executor was called with only the valid item.
+ exe.process_encode_batch.assert_awaited_once()
+ inner = exe.process_encode_batch.call_args.args[0]
+ assert len(inner.items) == 1
+
+
+async def test_all_items_invalid_short_circuits_executor() -> None:
+ exe = _mock_executor()
+ req = _mk_request(
+ RunBatchItem(op="encode", work_item_id="w0", request_id="r0", item_index=0, encode=None),
+ RunBatchItem(op="encode", work_item_id="w1", request_id="r1", item_index=1, encode=None),
+ )
+
+ result = await handle_run_batch(exe, req)
+
+ assert len(result.outcomes) == 2
+ assert all(o.error_code == RUN_BATCH_INVALID_ITEM for o in result.outcomes)
+ assert [o.work_item_id for o in result.outcomes] == ["w0", "w1"]
+ assert [o.request_id for o in result.outcomes] == ["r0", "r1"]
+ exe.process_encode_batch.assert_not_called()
+
+
+async def test_lora_key_is_passed_through_to_model_id_untouched() -> None:
+ # The lora_key isn't plumbed into the per-op request types for
+ # v1 (the Python adapter picks the active LoRA from its own
+ # state) — we just assert that model_id passes through verbatim.
+ # When the adapter becomes LoRA-aware in a later stage this test
+ # can be tightened to also check set_active_lora(lora_key).
+ expected = BatchOutcome(outcomes=[_ok_outcome(0)])
+ exe = _mock_executor(encode=expected)
+ req = _mk_request(
+ RunBatchItem(op="encode", encode=_mk_encode(0)),
+ model_id="special/model-v7",
+ lora_key="some-lora",
+ )
+
+ await handle_run_batch(exe, req)
+
+ inner = exe.process_encode_batch.call_args.args[0]
+ assert inner.model_id == "special/model-v7"
diff --git a/packages/sie_server/tests/test_docker_integration.py b/packages/sie_server/tests/test_docker_integration.py
index ebdf7eacf..2106cfd86 100644
--- a/packages/sie_server/tests/test_docker_integration.py
+++ b/packages/sie_server/tests/test_docker_integration.py
@@ -40,9 +40,9 @@ class TestDockerImageBasics:
response = httpx.get(f"{sie_docker_server}/livez", timeout=10.0)
assert response.status_code == 200
- def test_models_endpoint(self, docker_client: SIEClient) -> None:
+ def test_models_endpoint(self, sie_docker_client: SIEClient) -> None:
"""Docker container can list available models."""
- models = docker_client.list_models()
+ models = sie_docker_client.list_models()
assert len(models) > 0
# Should include the model we started with
# Model list returns "name" not "id"
@@ -57,7 +57,7 @@ class TestDockerModelDownload:
be able to download models to the HuggingFace cache directory.
"""
- def test_encode_triggers_model_load(self, docker_client: SIEClient) -> None:
+ def test_encode_triggers_model_load(self, sie_docker_client: SIEClient) -> None:
"""Encoding request successfully loads model and returns embeddings.
This tests the full flow:
@@ -72,14 +72,14 @@ class TestDockerModelDownload:
from sie_sdk.types import Item
model = "sentence-transformers/all-MiniLM-L6-v2"
- result = docker_client.encode(model, Item(text="Hello, world!"))
+ result = sie_docker_client.encode(model, Item(text="Hello, world!"))
# Should get a dense embedding
assert "dense" in result
assert result["dense"] is not None
assert len(result["dense"]) == 384 # MiniLM embedding dimension
- def test_encode_batch(self, docker_client: SIEClient) -> None:
+ def test_encode_batch(self, sie_docker_client: SIEClient) -> None:
"""Batch encoding works correctly."""
from sie_sdk.types import Item
@@ -90,7 +90,7 @@ class TestDockerModelDownload:
Item(text="Third sentence"),
]
- results = docker_client.encode(model, items)
+ results = sie_docker_client.encode(model, items)
assert len(results) == 3
for result in results:
@@ -105,7 +105,7 @@ class TestDockerCachePermissions:
and writable in the Docker container.
"""
- def test_second_request_uses_cache(self, docker_client: SIEClient) -> None:
+ def test_second_request_uses_cache(self, sie_docker_client: SIEClient) -> None:
"""Second request should be faster (model cached).
This indirectly tests that:
@@ -120,12 +120,12 @@ class TestDockerCachePermissions:
# First request (may need to load model)
start1 = time.perf_counter()
- docker_client.encode(model, Item(text="First request"))
+ sie_docker_client.encode(model, Item(text="First request"))
time1 = time.perf_counter() - start1
# Second request (model should be loaded)
start2 = time.perf_counter()
- docker_client.encode(model, Item(text="Second request"))
+ sie_docker_client.encode(model, Item(text="Second request"))
time2 = time.perf_counter() - start2
# Second request should be significantly faster
diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.py
new file mode 100644
index 000000000..92ab0d53e
--- /dev/null
+++ b/packages/sie_server/tests/test_ipc_server.py
@@ -0,0 +1,712 @@
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import os
+import struct
+import tempfile
+import time
+import uuid
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import msgpack
+import numpy as np
+import pytest
+from sie_server.api.ws import compute_bundle_config_hash_cached
+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_server import IpcServer, IpcServerError
+from sie_server.ipc_types import IPC_VERSION, ApplyModelConfigRequest
+from sie_server.queue_executor import QueueExecutor
+
+_LEN_STRUCT = struct.Struct("!I")
+
+
+def _short_sock_path() -> Path:
+ """Return a UDS path short enough for AF_UNIX on macOS (~104 char limit).
+
+ pytest's ``tmp_path`` ends up under ``/private/var/folders/.../`` which
+ overshoots the limit — put sockets in ``/tmp`` with a short random name.
+ """
+ base = Path(os.environ.get("TMPDIR", tempfile.gettempdir()))
+ # Fall back to /tmp if TMPDIR is itself too long (macOS default TMPDIR is).
+ if len(str(base)) > 20:
+ base = Path("/tmp") # noqa: S108
+ return base / f"sie-{uuid.uuid4().hex[:12]}.sock"
+
+
+class _Client:
+ """Minimal UDS IPC client used only by these tests."""
+
+ def __init__(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
+ self.reader = reader
+ self.writer = writer
+
+ @classmethod
+ async def connect(cls, path: Path) -> _Client:
+ r, w = await asyncio.open_unix_connection(str(path))
+ return cls(r, w)
+
+ async def close(self) -> None:
+ self.writer.close()
+ with contextlib.suppress(Exception):
+ await self.writer.wait_closed()
+
+ async def rpc(self, method: str, body: dict, *, request_id: str = "r1") -> dict:
+ envelope = {
+ "version": IPC_VERSION,
+ "method": method,
+ "request_id": request_id,
+ "body": body,
+ }
+ payload = msgpack.packb(envelope, use_bin_type=True)
+ self.writer.write(_LEN_STRUCT.pack(len(payload)) + payload)
+ await self.writer.drain()
+
+ header = await self.reader.readexactly(_LEN_STRUCT.size)
+ (length,) = _LEN_STRUCT.unpack(header)
+ resp_bytes = await self.reader.readexactly(length)
+ return msgpack.unpackb(resp_bytes, raw=False)
+
+
+def _make_executor() -> tuple[QueueExecutor, MagicMock]:
+ reg = MagicMock()
+ reg.model_names = ["test/model"]
+ reg.device = "cpu"
+ reg.is_loaded.return_value = True
+ reg.is_loading.return_value = False
+ reg.get_config.return_value = MagicMock()
+ return QueueExecutor(reg), reg
+
+
+async def server_and_path():
+ executor, _reg = _make_executor()
+ sock = _short_sock_path()
+ srv = IpcServer(sock, executor, worker_id="worker-test", stale_after_ms=10_000)
+ await srv.start()
+ try:
+ yield srv, sock
+ finally:
+ await srv.stop(drain_timeout_s=1.0)
+
+
+# -----------------------------------------------------------------------------
+# Transport / framing
+# -----------------------------------------------------------------------------
+
+
+class TestFraming:
+ @pytest.mark.asyncio
+ async def test_ping_roundtrip(self, server_and_path) -> None:
+ srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc("Ping", {"timestamp_ms": 123.0})
+ assert resp["ok"] is True
+ assert resp["version"] == IPC_VERSION
+ assert resp["request_id"] == "r1"
+ assert resp["body"]["timestamp_ms"] == 123.0
+ assert resp["body"]["worker_id"] == "worker-test"
+ assert resp["body"]["bundle_config_hash"] == ""
+ assert srv.is_heartbeat_fresh()
+ 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
+ client = await _Client.connect(sock)
+ try:
+ r1 = await client.rpc("Ping", {"timestamp_ms": 1.0}, request_id="a")
+ r2 = await client.rpc("Ping", {"timestamp_ms": 2.0}, request_id="b")
+ assert r1["request_id"] == "a"
+ assert r2["request_id"] == "b"
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_unknown_method_returns_error(self, server_and_path) -> None:
+ _srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc("NoSuchMethod", {})
+ assert resp["ok"] is False
+ assert "unknown method" in (resp["error"] or "")
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_bad_envelope_version_returns_error(self) -> None:
+ executor, _reg = _make_executor()
+ sock = _short_sock_path()
+ async with IpcServer(sock, executor, worker_id="w"):
+ client = await _Client.connect(sock)
+ try:
+ envelope = {"version": 999, "method": "Ping", "request_id": "r1", "body": {}}
+ payload = msgpack.packb(envelope, use_bin_type=True)
+ client.writer.write(_LEN_STRUCT.pack(len(payload)) + payload)
+ await client.writer.drain()
+ header = await client.reader.readexactly(_LEN_STRUCT.size)
+ (length,) = _LEN_STRUCT.unpack(header)
+ resp_bytes = await client.reader.readexactly(length)
+ resp = msgpack.unpackb(resp_bytes, raw=False)
+ assert resp["ok"] is False
+ assert "unsupported version" in resp["error"]
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_malformed_msgpack_closes_connection(self, server_and_path) -> None:
+ _srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ client.writer.write(_LEN_STRUCT.pack(3) + b"\xff\xff\xff")
+ await client.writer.drain()
+ data = await client.reader.read(1)
+ assert data == b"" # connection closed on protocol error
+ finally:
+ await client.close()
+
+
+# -----------------------------------------------------------------------------
+# EnsureModelReady
+# -----------------------------------------------------------------------------
+
+
+class TestEnsureModelReady:
+ @pytest.mark.asyncio
+ async def test_ready_model(self, server_and_path) -> None:
+ _srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc("EnsureModelReady", {"model_id": "test/model"})
+ assert resp["ok"] is True
+ assert resp["body"]["state"] == "ready"
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_batch_budget_included_on_ready(self) -> None:
+ """Parity #4: EnsureModelReady carries per-model batch budget for the
+ Rust consumer's fair-dispatch cap.
+ """
+ reg = MagicMock()
+ reg.model_names = ["test/model"]
+ reg.device = "cpu"
+ reg.is_loaded.return_value = True
+ reg.is_loading.return_value = False
+ worker = MagicMock()
+ worker._batch_config = MagicMock(max_batch_requests=42)
+ reg.get_worker.return_value = worker
+ executor = QueueExecutor(reg)
+ sock = _short_sock_path()
+ srv = IpcServer(sock, executor, worker_id="worker-test", stale_after_ms=10_000)
+ await srv.start()
+ try:
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc("EnsureModelReady", {"model_id": "test/model"})
+ assert resp["ok"] is True
+ assert resp["body"]["state"] == "ready"
+ assert resp["body"]["batch_budget"] == 42
+ finally:
+ await client.close()
+ finally:
+ await srv.stop(drain_timeout_s=1.0)
+
+
+# -----------------------------------------------------------------------------
+# ApplyModelConfig
+# -----------------------------------------------------------------------------
+
+
+class TestApplyModelConfig:
+ def test_apply_model_config_hash_cache_is_per_registry(self) -> None:
+ stale_registry = ModelRegistry(models_dir=None)
+ stale_registry._config_version = 1
+ assert compute_bundle_config_hash_cached(stale_registry, "default") == ""
+
+ registry = ModelRegistry(models_dir=None, model_filter=["existing/model"])
+ executor = QueueExecutor(registry)
+
+ resp = executor.apply_model_config(
+ ApplyModelConfigRequest(
+ bundle_id="default",
+ model_id="test/model",
+ epoch=7,
+ bundle_config_hash="from-sie-config",
+ profiles_added=["default"],
+ model_config="""
+sie_id: test/model
+hf_id: sentence-transformers/all-MiniLM-L6-v2
+tasks:
+ encode:
+ dense:
+ dim: 384
+profiles:
+ default:
+ adapter_path: sie_server.adapters.sentence_transformer:Adapter
+ max_batch_tokens: 4096
+""",
+ )
+ )
+
+ assert resp.applied is True
+ assert resp.bundle_config_hash
+ assert resp.config_version == 1
+
+ @pytest.mark.asyncio
+ async def test_apply_model_config_adds_registry_config_and_returns_hash(self) -> None:
+ registry = ModelRegistry(models_dir=None, model_filter=["existing/model"])
+ executor = QueueExecutor(registry)
+ sock = _short_sock_path()
+ srv = IpcServer(sock, executor, worker_id="worker-test", stale_after_ms=10_000)
+ await srv.start()
+ try:
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc(
+ "ApplyModelConfig",
+ {
+ "bundle_id": "default",
+ "model_id": "test/model",
+ "epoch": 7,
+ "bundle_config_hash": "from-sie-config",
+ "profiles_added": ["default"],
+ "model_config": """
+sie_id: test/model
+hf_id: sentence-transformers/all-MiniLM-L6-v2
+tasks:
+ encode:
+ dense:
+ dim: 384
+profiles:
+ default:
+ adapter_path: sie_server.adapters.sentence_transformer:Adapter
+ max_batch_tokens: 4096
+""",
+ },
+ )
+ assert resp["ok"] is True
+ assert resp["body"]["applied"] is True
+ assert resp["body"]["bundle_config_hash"]
+ assert resp["body"]["config_version"] == 1
+ assert registry.get_config("test/model").sie_id == "test/model"
+ finally:
+ await client.close()
+ finally:
+ await srv.stop(drain_timeout_s=1.0)
+
+ @pytest.mark.asyncio
+ async def test_apply_model_config_rejects_model_id_mismatch(self) -> None:
+ registry = ModelRegistry(models_dir=None)
+ executor = QueueExecutor(registry)
+ sock = _short_sock_path()
+ srv = IpcServer(sock, executor, worker_id="worker-test", stale_after_ms=10_000)
+ await srv.start()
+ try:
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc(
+ "ApplyModelConfig",
+ {
+ "bundle_id": "default",
+ "model_id": "notification/model",
+ "epoch": 7,
+ "bundle_config_hash": "from-sie-config",
+ "profiles_added": ["default"],
+ "model_config": """
+sie_id: yaml/model
+hf_id: sentence-transformers/all-MiniLM-L6-v2
+tasks:
+ encode:
+ dense:
+ dim: 384
+profiles:
+ default:
+ adapter_path: sie_server.adapters.sentence_transformer:Adapter
+ max_batch_tokens: 4096
+""",
+ },
+ )
+ assert resp["ok"] is False
+ assert "model_id mismatch" in (resp["error"] or "")
+ finally:
+ await client.close()
+ finally:
+ await srv.stop(drain_timeout_s=1.0)
+
+
+# -----------------------------------------------------------------------------
+# ProcessEncodeBatch
+# -----------------------------------------------------------------------------
+
+
+class TestProcessEncodeBatch:
+ @pytest.mark.asyncio
+ async def test_encode_batch_roundtrip(self, server_and_path) -> None:
+ _srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ fake_outputs = [{"dense": [0.25, 0.75]}]
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ return_value=(fake_outputs, RequestTiming()),
+ ):
+ resp = await client.rpc(
+ "ProcessEncodeBatch",
+ {
+ "model_id": "test/model",
+ "items": [
+ {
+ "work_item_id": "req-1.0",
+ "request_id": "req-1",
+ "item_index": 0,
+ "total_items": 1,
+ "timestamp": time.time(),
+ "item": {"text": "hello"},
+ "output_types": ["dense"],
+ "is_query": False,
+ "payload_fetch_ms": 0.0,
+ }
+ ],
+ },
+ )
+
+ assert resp["ok"] is True
+ outcomes = resp["body"]["outcomes"]
+ assert len(outcomes) == 1
+ outcome = outcomes[0]
+ assert outcome["work_item_id"] == "req-1.0"
+ assert outcome["disposition"] == "publish_and_ack"
+ inner = msgpack.unpackb(outcome["result_msgpack"], raw=False)
+ assert inner == {"dense": [0.25, 0.75]}
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_encode_batch_during_drain_rejected(self, server_and_path) -> None:
+ srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ drain_resp = await client.rpc("Drain", {"deadline_ms": 1000})
+ assert drain_resp["ok"] is True
+ assert srv._drain_event.is_set()
+
+ resp = await client.rpc(
+ "ProcessEncodeBatch",
+ {
+ "model_id": "test/model",
+ "items": [
+ {
+ "work_item_id": "req-2.0",
+ "request_id": "req-2",
+ "item_index": 0,
+ "total_items": 1,
+ "timestamp": time.time(),
+ "item": {"text": "x"},
+ "output_types": ["dense"],
+ "is_query": False,
+ "payload_fetch_ms": 0.0,
+ }
+ ],
+ },
+ )
+ assert resp["ok"] is False
+ assert resp["error"] == "draining"
+ finally:
+ await client.close()
+
+
+# -----------------------------------------------------------------------------
+# ProcessScoreBatch / ProcessExtractBatch smoke
+# -----------------------------------------------------------------------------
+
+
+class TestProcessScoreAndExtract:
+ @pytest.mark.asyncio
+ async def test_score_batch_roundtrip(self, server_and_path) -> None:
+ srv, sock = server_and_path
+ worker = AsyncMock()
+ score_output = ScoreOutput(scores=np.array([0.9, 0.1], dtype=np.float32))
+ wr = WorkerResult(output=score_output, timing=RequestTiming())
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_result(wr)
+ worker.submit_score = AsyncMock(return_value=fut)
+ srv._executor._registry.start_worker = AsyncMock(return_value=worker)
+
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc(
+ "ProcessScoreBatch",
+ {
+ "model_id": "test/model",
+ "items": [
+ {
+ "work_item_id": "req-s.0",
+ "request_id": "req-s",
+ "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"},
+ ],
+ "payload_fetch_ms": 0.0,
+ }
+ ],
+ },
+ )
+ assert resp["ok"] is True
+ outcomes = resp["body"]["outcomes"]
+ assert outcomes[0]["disposition"] == "publish_and_ack"
+ # Score output is Rust-frameable. The legacy ``result_msgpack``
+ # is None; the parallel arrays land on ``raw_output.score`` and
+ # the Rust publisher does the descending stable sort + rank
+ # assignment.
+ assert outcomes[0]["result_msgpack"] is None
+ score = outcomes[0]["raw_output"]["score"]
+ assert score["item_ids"] == ["doc-a", "doc-b"]
+ assert score["scores"] == pytest.approx([0.9, 0.1])
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_extract_batch_roundtrip(self, server_and_path) -> None:
+ srv, sock = server_and_path
+ worker = AsyncMock()
+ extract_output = ExtractOutput(
+ entities=[[{"text": "Alice", "label": "person", "score": 0.99, "start": 0, "end": 5}]]
+ )
+ wr = WorkerResult(output=extract_output, timing=RequestTiming())
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_result(wr)
+ worker.submit_extract = AsyncMock(return_value=fut)
+ srv._executor._registry.start_worker = AsyncMock(return_value=worker)
+
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc(
+ "ProcessExtractBatch",
+ {
+ "model_id": "test/model",
+ "items": [
+ {
+ "work_item_id": "req-e.0",
+ "request_id": "req-e",
+ "item_index": 0,
+ "total_items": 1,
+ "timestamp": time.time(),
+ "item": {"text": "Alice works at Acme."},
+ "labels": ["person"],
+ "payload_fetch_ms": 0.0,
+ }
+ ],
+ },
+ )
+ assert resp["ok"] is True
+ outcomes = resp["body"]["outcomes"]
+ assert outcomes[0]["disposition"] == "publish_and_ack"
+ inner = msgpack.unpackb(outcomes[0]["result_msgpack"], raw=False)
+ assert "entities" in inner
+ finally:
+ await client.close()
+
+
+# -----------------------------------------------------------------------------
+# Heartbeat / readiness
+# -----------------------------------------------------------------------------
+
+
+class TestHeartbeat:
+ @pytest.mark.asyncio
+ async def test_heartbeat_stale_when_never_pinged(self) -> None:
+ executor, _reg = _make_executor()
+ srv = IpcServer(_short_sock_path(), executor, worker_id="w", stale_after_ms=100)
+ assert srv.is_heartbeat_fresh() is False
+
+ @pytest.mark.asyncio
+ async def test_heartbeat_expires(self) -> None:
+ executor, _reg = _make_executor()
+ sock = _short_sock_path()
+ async with IpcServer(sock, executor, worker_id="w", stale_after_ms=50) as srv:
+ client = await _Client.connect(sock)
+ try:
+ await client.rpc("Ping", {"timestamp_ms": 0.0})
+ assert srv.is_heartbeat_fresh() is True
+ # Simulate stale heartbeat by asking about a future monotonic time.
+ future = (srv.last_ping_monotonic or 0.0) + 10.0
+ assert srv.is_heartbeat_fresh(now_monotonic=future) is False
+ finally:
+ await client.close()
+
+
+# -----------------------------------------------------------------------------
+# Generation sidecar IPC
+# -----------------------------------------------------------------------------
+
+
+class TestGenerationSidecarIpc:
+ @pytest.mark.asyncio
+ async def test_worker_capabilities_reports_generation_models(self) -> None:
+ executor, reg = _make_executor()
+ gen_cfg = MagicMock()
+ gen_cfg.tasks.generate = object()
+ encode_cfg = MagicMock()
+ encode_cfg.tasks.generate = None
+ reg.get_configs_snapshot.return_value = {
+ "encode/model": encode_cfg,
+ "z-generate/model": gen_cfg,
+ }
+ sock = _short_sock_path()
+ async with IpcServer(sock, executor, worker_id="w"):
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc("WorkerCapabilities", {})
+ finally:
+ await client.close()
+
+ assert resp["ok"] is True
+ assert resp["body"] == {
+ "has_generation_models": True,
+ "generation_models": ["z-generate/model"],
+ }
+
+ @pytest.mark.asyncio
+ async def test_signal_generate_cancel_forwards_to_streaming_processor(self) -> None:
+ executor, _reg = _make_executor()
+ processor = MagicMock()
+ processor.signal_cancel.return_value = True
+ sock = _short_sock_path()
+ async with IpcServer(sock, executor, worker_id="w") as srv:
+ srv._get_streaming_processor = AsyncMock(return_value=processor) # type: ignore[method-assign]
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc("SignalGenerateCancel", {"request_id": "req-123"})
+ finally:
+ await client.close()
+
+ assert resp["ok"] is True
+ assert resp["body"] == {"matched": True}
+ processor.signal_cancel.assert_called_once_with("req-123")
+
+
+# -----------------------------------------------------------------------------
+# Socket cleanup
+# -----------------------------------------------------------------------------
+
+
+class TestSocketLifecycle:
+ @pytest.mark.asyncio
+ async def test_stale_socket_is_unlinked_on_start(self) -> None:
+ sock = _short_sock_path()
+ sock.touch()
+ assert sock.exists()
+ executor, _reg = _make_executor()
+ async with IpcServer(sock, executor, worker_id="w"):
+ # Socket should exist but be of type socket now.
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc("Ping", {"timestamp_ms": 0.0})
+ assert resp["ok"] is True
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_socket_unlinked_on_stop(self) -> None:
+ sock = _short_sock_path()
+ executor, _reg = _make_executor()
+ srv = IpcServer(sock, executor, worker_id="w")
+ await srv.start()
+ assert sock.exists()
+ await srv.stop(drain_timeout_s=0.5)
+ assert not sock.exists()
+
+
+# -----------------------------------------------------------------------------
+# Drain deadline propagation
+# -----------------------------------------------------------------------------
+
+
+class TestDrainDeadline:
+ @pytest.mark.asyncio
+ async def test_deadline_ms_sets_drain_timeout(self, server_and_path) -> None:
+ srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc("Drain", {"deadline_ms": 2500})
+ assert resp["ok"] is True
+ assert resp["body"]["acknowledged"] is True
+ assert srv._drain_deadline_s == pytest.approx(2.5)
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_missing_deadline_leaves_drain_unset(self, server_and_path) -> None:
+ srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc("Drain", {})
+ assert resp["ok"] is True
+ assert srv._drain_deadline_s is None
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_non_positive_deadline_is_ignored(self, server_and_path) -> None:
+ srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ for bad in (0, -1, -1000.5):
+ resp = await client.rpc("Drain", {"deadline_ms": bad})
+ assert resp["ok"] is True
+ assert srv._drain_deadline_s is None
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_bool_deadline_is_ignored(self, server_and_path) -> None:
+ """`bool` is a subclass of `int` in Python, so `deadline_ms=True`
+ would otherwise set a 1ms timeout and break shutdowns.
+ """
+ srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ resp = await client.rpc("Drain", {"deadline_ms": True})
+ assert resp["ok"] is True
+ assert srv._drain_deadline_s is None
+ finally:
+ await client.close()
+
+ @pytest.mark.asyncio
+ async def test_repeated_drain_tightens_deadline(self, server_and_path) -> None:
+ """Second Drain with a smaller deadline must win; a later drain
+ with a LARGER deadline must not loosen the stored budget — Rust
+ may retry a Drain RPC and we can't let a retransmit extend the
+ SIGTERM countdown.
+ """
+ srv, sock = server_and_path
+ client = await _Client.connect(sock)
+ try:
+ await client.rpc("Drain", {"deadline_ms": 5000}, request_id="a")
+ assert srv._drain_deadline_s == pytest.approx(5.0)
+ await client.rpc("Drain", {"deadline_ms": 1000}, request_id="b")
+ assert srv._drain_deadline_s == pytest.approx(1.0)
+ # Loose retry must not widen the window.
+ await client.rpc("Drain", {"deadline_ms": 10_000}, request_id="c")
+ assert srv._drain_deadline_s == pytest.approx(1.0)
+ finally:
+ await client.close()
+
+
+# -----------------------------------------------------------------------------
+# Silence unused-import warning for IpcServerError; kept exported for future tests.
+# -----------------------------------------------------------------------------
+
+_ = IpcServerError
diff --git a/packages/sie_server/tests/test_ipc_types_raw_output.py b/packages/sie_server/tests/test_ipc_types_raw_output.py
new file mode 100644
index 000000000..be0b49a96
--- /dev/null
+++ b/packages/sie_server/tests/test_ipc_types_raw_output.py
@@ -0,0 +1,162 @@
+"""Additive Rust output wire-format contract tests.
+
+These tests pin the ``RawOutput`` / ``DenseOutput`` / ``ScoreOutputRaw``
+shapes we just added to ``sie_server.ipc_types`` so that:
+
+* New fields stay **additive** — older msgpack payloads without
+ ``raw_output`` round-trip cleanly into the new ``ItemOutcome``
+ with ``raw_output = None`` and every other field intact.
+* The field ordering / defaults match the Rust side
+ (``sie_server_sidecar::ipc_types``). The msgpack wire uses *named* maps
+ in both directions, so this is a field-name / default contract test,
+ not a byte-identity one.
+* When the Python adapter starts emitting a ``RawOutput`` for dense or
+ score variants, ``msgspec.msgpack`` encodes it into a shape the Rust
+ publisher can decode with its `#[serde(default)]` `Option<_>` fields
+ — i.e. both ends agree on which variants are present.
+"""
+
+from __future__ import annotations
+
+import msgspec
+from sie_server.ipc_types import (
+ BatchOutcome,
+ DenseOutput,
+ ItemOutcome,
+ RawOutput,
+ ScoreOutputRaw,
+)
+
+
+def _encode(outcome: ItemOutcome) -> bytes:
+ return msgspec.msgpack.encode(BatchOutcome(outcomes=[outcome]))
+
+
+def _decode(buf: bytes) -> ItemOutcome:
+ return msgspec.msgpack.decode(buf, type=BatchOutcome).outcomes[0]
+
+
+def test_item_outcome_roundtrips_without_raw_output() -> None:
+ """An outcome without ``raw_output`` must keep round-tripping
+ byte-for-byte through the new schema — this is the rolling-deploy
+ contract.
+ """
+ legacy = ItemOutcome(
+ work_item_id="wi-1",
+ request_id="req-1",
+ item_index=0,
+ disposition="publish_and_ack",
+ result_msgpack=b"\x80",
+ inference_ms=12.5,
+ )
+ out = _decode(_encode(legacy))
+ assert out.raw_output is None
+ assert out.result_msgpack == b"\x80"
+ assert out.disposition == "publish_and_ack"
+ assert out.inference_ms == 12.5
+
+
+def test_raw_output_dense_variant_roundtrips() -> None:
+ rt = _decode(
+ _encode(
+ ItemOutcome(
+ work_item_id="wi-dense",
+ request_id="req-dense",
+ item_index=3,
+ disposition="publish_and_ack",
+ raw_output=RawOutput(
+ dense=DenseOutput(
+ values=[0.25, -0.5, 0.75, 1.0],
+ dim=4,
+ normalize=True,
+ ),
+ ),
+ ),
+ ),
+ )
+ assert rt.result_msgpack is None
+ assert rt.raw_output is not None
+ assert rt.raw_output.score is None
+ dense = rt.raw_output.dense
+ assert dense is not None
+ assert dense.dim == 4
+ assert dense.normalize is True
+ assert dense.values == [0.25, -0.5, 0.75, 1.0]
+
+
+def test_raw_output_score_variant_roundtrips_and_preserves_order() -> None:
+ rt = _decode(
+ _encode(
+ ItemOutcome(
+ work_item_id="wi-score",
+ request_id="req-score",
+ item_index=0,
+ disposition="publish_and_ack",
+ raw_output=RawOutput(
+ score=ScoreOutputRaw(
+ scores=[0.1, 0.9, 0.5],
+ item_ids=["doc-a", "doc-b", "doc-c"],
+ ),
+ ),
+ ),
+ ),
+ )
+ assert rt.raw_output is not None
+ assert rt.raw_output.dense is None
+ score = rt.raw_output.score
+ assert score is not None
+ # Rust does the sort; the Python side MUST send parallel lists
+ # in input order.
+ assert score.scores == [0.1, 0.9, 0.5]
+ assert score.item_ids == ["doc-a", "doc-b", "doc-c"]
+
+
+def test_raw_output_defaults_match_rust_side() -> None:
+ """All inner variants default to ``None`` (mirrors
+ ``#[serde(default)] Option<_>`` on the Rust side).
+ """
+ empty = RawOutput()
+ assert empty.dense is None
+ assert empty.score is None
+ dense_only = RawOutput(dense=DenseOutput(values=[1.0], dim=1))
+ assert dense_only.dense is not None
+ assert dense_only.dense.normalize is False
+ assert dense_only.score is None
+
+
+def test_unknown_raw_output_variant_is_tolerated() -> None:
+ """Forward-compat: a future Python build emits a variant the current
+ Rust build doesn't know. ``msgspec`` ignores unknown fields by default
+ so the outcome still decodes, with the known variants preserved.
+
+ We simulate a truly-unknown variant (``"extract_json"`` — reserved
+ for future typed outputs) alongside a known one. As new variants land in
+ this file (dense / score / sparse / multivector today), pick any
+ field name not yet defined on ``RawOutput`` to keep the test
+ meaningful.
+ """
+ encoded = msgspec.msgpack.encode(
+ {
+ "outcomes": [
+ {
+ "work_item_id": "wi",
+ "request_id": "req",
+ "item_index": 0,
+ "disposition": "publish_and_ack",
+ "raw_output": {
+ "dense": {"values": [0.5, 0.5], "dim": 2, "normalize": False},
+ # Hypothetical future typed-output variant.
+ "extract_json": {"doc_id": "doc-1", "scores": [0.1, 0.2]},
+ },
+ },
+ ],
+ },
+ )
+ rt = msgspec.msgpack.decode(encoded, type=BatchOutcome).outcomes[0]
+ assert rt.raw_output is not None
+ assert rt.raw_output.dense is not None
+ assert rt.raw_output.dense.dim == 2
+ # Unknown variant dropped silently — this is the forward-compat
+ # guarantee. Rolling deploys work in either order because neither
+ # side has to know about the other's future fields.
+ assert not hasattr(rt.raw_output, "extract_json")
diff --git a/packages/sie_server/tests/test_model_yaml_filenames.py b/packages/sie_server/tests/test_model_yaml_filenames.py
new file mode 100644
index 000000000..f968c6774
--- /dev/null
+++ b/packages/sie_server/tests/test_model_yaml_filenames.py
@@ -0,0 +1,35 @@
+"""Regression tests for model YAML filenames in packages/sie_server/models/.
+
+sie_bench's `EvalRunner._get_local_model_info(model_name)` looks up a YAML by
+converting `model_name` to `model_name.replace("/", "__").replace(":", "__") + ".yaml"`.
+On a case-sensitive filesystem (Linux CI), any case mismatch between the filename
+and `sie_id` makes the lookup return `{}`, which silently downgrades the
+dispatched MTEB wrapper to text-only and trips the modality precheck. See
+issue #1058.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import yaml
+
+MODELS_DIR = Path(__file__).resolve().parents[1] / "models"
+
+
+def _expected_filename(sie_id: str) -> str:
+ return sie_id.replace("/", "__").replace(":", "__") + ".yaml"
+
+
[email protected]("yaml_path", sorted(MODELS_DIR.glob("*.yaml")), ids=lambda p: p.name)
+def test_yaml_filename_matches_sie_id(yaml_path: Path) -> None:
+ with yaml_path.open() as f:
+ config = yaml.safe_load(f) or {}
+ sie_id = config.get("sie_id")
+ assert sie_id, f"{yaml_path.name}: missing sie_id"
+ assert yaml_path.name == _expected_filename(sie_id), (
+ f"YAML filename {yaml_path.name!r} does not match sie_id {sie_id!r}; "
+ f"expected {_expected_filename(sie_id)!r}. "
+ f"Case-sensitive filesystems (Linux CI) will fail to find this config."
+ )
diff --git a/packages/sie_server/tests/test_nats_pull_loop.py b/packages/sie_server/tests/test_nats_pull_loop.py
deleted file mode 100644
index 2f903cd4f..000000000
--- a/packages/sie_server/tests/test_nats_pull_loop.py
+++ /dev/null
@@ -1,1122 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import os
-import time
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import msgpack
-import numpy as np
-import pytest
-from sie_server.core.inference_output import ExtractOutput, ScoreOutput
-from sie_server.core.timing import RequestTiming
-from sie_server.core.worker.types import WorkerResult
-from sie_server.nats_pull_loop import (
- _OOM_NAK_DELAY_S,
- NatsPullLoop,
- _fairness_config_from_env,
- _PoolAdmissionGate,
- _resolve_generation_admission,
-)
-from sie_server.types.inputs import Item
-
-
-def _make_work_item(**overrides) -> dict:
- """Build a minimal WorkItem dict with required fields."""
- wi = {
- "work_item_id": "req-1.0",
- "request_id": "req-1",
- "item_index": 0,
- "total_items": 1,
- "operation": "encode",
- "model_id": "test/model",
- "profile_id": "default",
- "pool_name": "_default",
- "router_id": "router-1",
- "reply_subject": "_INBOX.router-1.req-1",
- "timestamp": time.time(),
- }
- wi.update(overrides)
- return wi
-
-
-def _make_config(*, generate: bool = False) -> MagicMock:
- config = MagicMock()
- config.tasks.generate = object() if generate else None
- return config
-
-
-def _make_loop(
- *,
- registry: MagicMock | None = None,
- nc: AsyncMock | None = None,
- js: AsyncMock | None = None,
- payload_store_url: str | None = None,
-) -> NatsPullLoop:
- """Create a NatsPullLoop with mocked dependencies."""
- if nc is None:
- nc = AsyncMock()
- if js is None:
- js = AsyncMock()
- if registry is None:
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = _make_config()
- return NatsPullLoop(
- nc=nc,
- js=js,
- registry=registry,
- bundle_id="default",
- pool_name="_default",
- payload_store_url=payload_store_url,
- )
-
-
-def _make_msg(wi: dict) -> AsyncMock:
- """Wrap a WorkItem dict into a mock NATS message with serialized data."""
- msg = AsyncMock()
- msg.data = msgpack.packb(wi, use_bin_type=True)
- return msg
-
-
-def _published_result(nc_mock: AsyncMock) -> dict:
- """Extract the first published WorkResult from the mock nc.publish calls."""
- nc_mock.publish.assert_called_once()
- _subject, data = nc_mock.publish.call_args.args
- return msgpack.unpackb(data, raw=False)
-
-
-def test_resolve_generation_admission_uses_requested_model_config() -> None:
- registry = MagicMock()
-
- first = MagicMock()
- first.sie_id = "first/model"
- first.tasks.generate = object()
- first_resolved = MagicMock(kv_budget_tokens=1024, admission_enabled=False)
- first.resolve_profile.return_value = first_resolved
-
- second = MagicMock()
- second.sie_id = "second/model"
- second.tasks.generate = object()
- second_resolved = MagicMock(kv_budget_tokens=2048, admission_enabled=True)
- second.resolve_profile.return_value = second_resolved
-
- registry.get_config.side_effect = {"first/model": first, "second/model": second}.__getitem__
-
- assert _resolve_generation_admission(registry, "second/model") == (2048, True)
- second.resolve_profile.assert_called_once_with("default")
- first.resolve_profile.assert_not_called()
-
-
-class _FakePoolClient:
- def __init__(self, pool: dict | None = None, exc: Exception | None = None) -> None:
- self.pool = pool
- self.exc = exc
- self.closed = False
-
- async def get_pool(self, _name: str) -> dict | None:
- if self.exc is not None:
- raise self.exc
- return self.pool
-
- async def close(self) -> None:
- self.closed = True
-
-
-class TestPoolAdmissionGate:
- @pytest.mark.asyncio
- async def test_disabled_gate_admits(self) -> None:
- gate = _PoolAdmissionGate(
- pool_name="bench",
- worker_id="worker-1",
- machine_profile="l4",
- gateway_url="",
- api_key=None,
- )
-
- assert await gate.admitted() is True
-
- @pytest.mark.asyncio
- async def test_uncapped_pool_admits_any_worker(self) -> None:
- gate = _PoolAdmissionGate(
- pool_name="bench",
- worker_id="worker-1",
- machine_profile="l4",
- gateway_url="http://gateway",
- api_key=None,
- check_interval_s=0,
- client=_FakePoolClient({"spec": {"gpu_caps": {}}, "status": {"assigned_workers": []}}),
- )
-
- assert await gate.admitted() is True
-
- @pytest.mark.asyncio
- async def test_capped_pool_requires_assigned_worker(self) -> None:
- pool = {
- "spec": {"gpu_caps": {"l4": 1}},
- "status": {"assigned_workers": [{"name": "worker-1", "gpu": "l4"}]},
- }
- gate = _PoolAdmissionGate(
- pool_name="bench",
- worker_id="worker-1",
- machine_profile="l4",
- gateway_url="http://gateway",
- api_key=None,
- check_interval_s=0,
- client=_FakePoolClient(pool),
- )
-
- assert await gate.admitted() is True
-
- @pytest.mark.asyncio
- async def test_capped_pool_pauses_unassigned_worker(self) -> None:
- pool = {
- "spec": {"gpu_caps": {"l4": 1}},
- "status": {"assigned_workers": [{"name": "worker-2", "gpu": "l4"}]},
- }
- gate = _PoolAdmissionGate(
- pool_name="bench",
- worker_id="worker-1",
- machine_profile="l4",
- gateway_url="http://gateway",
- api_key=None,
- check_interval_s=0,
- client=_FakePoolClient(pool),
- )
-
- assert await gate.admitted() is False
-
- @pytest.mark.asyncio
- async def test_zero_cap_pauses_worker(self) -> None:
- gate = _PoolAdmissionGate(
- pool_name="bench",
- worker_id="worker-1",
- machine_profile="l4",
- gateway_url="http://gateway",
- api_key=None,
- check_interval_s=0,
- client=_FakePoolClient({"spec": {"gpu_caps": {"l4": 0}}, "status": {"assigned_workers": []}}),
- )
-
- assert await gate.admitted() is False
-
- @pytest.mark.asyncio
- async def test_zero_cap_pauses_even_if_worker_still_assigned(self) -> None:
- gate = _PoolAdmissionGate(
- pool_name="bench",
- worker_id="worker-1",
- machine_profile="l4",
- gateway_url="http://gateway",
- api_key=None,
- check_interval_s=0,
- client=_FakePoolClient(
- {
- "spec": {"gpu_caps": {"l4": 0}},
- "status": {"assigned_workers": [{"name": "worker-1", "gpu": "l4"}]},
- }
- ),
- )
-
- assert await gate.admitted() is False
-
- @pytest.mark.asyncio
- async def test_malformed_cap_pauses_worker(self) -> None:
- gate = _PoolAdmissionGate(
- pool_name="bench",
- worker_id="worker-1",
- machine_profile="l4",
- gateway_url="http://gateway",
- api_key=None,
- check_interval_s=0,
- client=_FakePoolClient(
- {
- "spec": {"gpu_caps": {"l4": "nope"}},
- "status": {"assigned_workers": [{"name": "worker-1", "gpu": "l4"}]},
- }
- ),
- )
-
- assert await gate.admitted() is False
-
- @pytest.mark.asyncio
- async def test_named_pool_status_error_fails_closed(self) -> None:
- gate = _PoolAdmissionGate(
- pool_name="bench",
- worker_id="worker-1",
- machine_profile="l4",
- gateway_url="http://gateway",
- api_key=None,
- check_interval_s=0,
- client=_FakePoolClient(exc=RuntimeError("boom")),
- )
-
- assert await gate.admitted() is False
-
-
-class TestPullLoopAdmission:
- @pytest.mark.asyncio
- async def test_run_skips_fetch_when_not_admitted(self) -> None:
- loop = _make_loop()
- loop._pool_sub = AsyncMock()
- loop._running = True
- gate = AsyncMock()
- gate.admitted = AsyncMock(return_value=False)
- gate.pause_s = 0.001
- loop._admission_gate = gate
-
- task = asyncio.create_task(loop._run())
- await asyncio.sleep(0.01)
- loop._running = False
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
-
- loop._pool_sub.fetch.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_run_waits_when_pool_subscription_is_temporarily_absent(self) -> None:
- loop = _make_loop()
- loop._pool_sub = None
- loop._running = True
- gate = AsyncMock()
- gate.admitted = AsyncMock(return_value=True)
- loop._admission_gate = gate
-
- task = asyncio.create_task(loop._run())
- await asyncio.sleep(0.01)
- loop._running = False
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
-
- gate.admitted.assert_awaited()
-
-
-class TestDirectDispatchIsolation:
- @pytest.mark.asyncio
- async def test_start_keeps_encode_pool_on_pool_only_subscription(self) -> None:
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = _make_config(generate=False)
-
- loop = _make_loop(registry=registry)
- loop._migrate_per_model_streams = AsyncMock()
- loop._ensure_pool_subscription = AsyncMock()
- loop._ensure_per_worker_subscription = AsyncMock()
- loop._ensure_cancel_subscription = AsyncMock()
- loop._prewarm_grammars = AsyncMock()
- loop._run = AsyncMock(return_value=None)
- loop._run_worker_pull = AsyncMock(return_value=None)
-
- await loop.start()
- await asyncio.sleep(0)
-
- loop._ensure_pool_subscription.assert_awaited_once()
- loop._ensure_per_worker_subscription.assert_not_awaited()
- loop._ensure_cancel_subscription.assert_not_awaited()
- assert loop._worker_sub is None
- assert loop._worker_pull_task is None
-
- if loop._pull_task is not None:
- await asyncio.gather(loop._pull_task, return_exceptions=True)
-
- @pytest.mark.asyncio
- async def test_start_preserves_generation_direct_dispatch_subscription(self) -> None:
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = _make_config(generate=True)
-
- loop = _make_loop(registry=registry)
- loop._migrate_per_model_streams = AsyncMock()
- loop._ensure_pool_subscription = AsyncMock()
-
- async def ensure_worker_subscription() -> None:
- loop._worker_sub = AsyncMock()
-
- loop._ensure_per_worker_subscription = AsyncMock(side_effect=ensure_worker_subscription)
- loop._ensure_cancel_subscription = AsyncMock()
- loop._prewarm_grammars = AsyncMock()
- loop._run = AsyncMock(return_value=None)
- loop._run_worker_pull = AsyncMock(return_value=None)
-
- await loop.start()
- await asyncio.sleep(0)
-
- loop._ensure_pool_subscription.assert_awaited_once()
- loop._ensure_per_worker_subscription.assert_awaited_once()
- loop._ensure_cancel_subscription.assert_awaited_once()
- assert loop._worker_sub is not None
- assert loop._worker_pull_task is not None
-
- await asyncio.gather(
- *(task for task in (loop._pull_task, loop._worker_pull_task) if task is not None),
- return_exceptions=True,
- )
-
- @pytest.mark.asyncio
- async def test_encode_saturation_counts_queue_batches_not_generation_streams(self) -> None:
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = _make_config(generate=False)
-
- loop = _make_loop(registry=registry)
- loop._streaming_processor.in_flight_count = MagicMock(return_value=7)
- loop._effective_kv_budget = MagicMock(return_value=None)
- loop.aggregate_max_batch_requests = MagicMock(return_value=4)
- loop._saturation_gate.update = MagicMock(return_value=False)
-
- task = asyncio.create_task(asyncio.sleep(60))
- loop._in_flight_tasks.add(task)
- try:
- assert loop.in_flight_count() == 1
- assert loop.update_saturation() is False
- loop._saturation_gate.update.assert_called_once_with(in_flight=1, capacity=4)
- finally:
- task.cancel()
- await asyncio.gather(task, return_exceptions=True)
-
- def test_transport_class_probe_is_cached_for_status_updates(self) -> None:
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = _make_config(generate=False)
-
- loop = _make_loop(registry=registry)
-
- assert loop._pool_hosts_generation_model() is False
- get_config_calls = registry.get_config.call_count
-
- assert loop.in_flight_count() == 0
- assert loop.in_flight_count() == 0
- assert registry.get_config.call_count == get_config_calls
-
- def test_generation_saturation_still_uses_kv_budget(self) -> None:
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = _make_config(generate=True)
-
- loop = _make_loop(registry=registry)
- loop._effective_kv_budget = MagicMock(return_value=100)
- loop._streaming_processor.kv_reserved_tokens = MagicMock(return_value=44)
- loop._saturation_gate.update = MagicMock(return_value=True)
-
- assert loop.update_saturation() is True
- loop._saturation_gate.update.assert_called_once_with(in_flight=44, capacity=100)
-
- @pytest.mark.asyncio
- async def test_add_model_enables_generation_direct_dispatch_after_hot_reload(self) -> None:
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = _make_config(generate=True)
-
- loop = _make_loop(registry=registry)
- loop._running = True
- loop._hosts_generation_model = False
-
- async def ensure_worker_subscription() -> None:
- loop._worker_sub = AsyncMock()
-
- loop._ensure_per_worker_subscription = AsyncMock(side_effect=ensure_worker_subscription)
- loop._rebind_pool_subscription = AsyncMock()
- loop._ensure_cancel_subscription = AsyncMock()
- loop._run_worker_pull = AsyncMock(return_value=None)
-
- await loop.add_model("test/model")
- await asyncio.sleep(0)
-
- loop._ensure_per_worker_subscription.assert_awaited_once()
- loop._rebind_pool_subscription.assert_awaited_once()
- loop._ensure_cancel_subscription.assert_awaited_once()
- assert loop._worker_pull_task is not None
-
- await asyncio.gather(loop._worker_pull_task, return_exceptions=True)
-
- @pytest.mark.asyncio
- async def test_add_model_rebinds_pool_fallback_when_direct_dispatch_setup_fails(self) -> None:
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = _make_config(generate=True)
-
- loop = _make_loop(registry=registry)
- loop._running = True
- loop._hosts_generation_model = False
- loop._ensure_per_worker_subscription = AsyncMock(side_effect=RuntimeError("nats unavailable"))
- loop._rebind_pool_subscription = AsyncMock()
- loop._ensure_cancel_subscription = AsyncMock()
-
- await loop.add_model("test/model")
-
- loop._ensure_per_worker_subscription.assert_awaited_once()
- loop._rebind_pool_subscription.assert_awaited_once()
- loop._ensure_cancel_subscription.assert_awaited_once()
- assert loop._worker_pull_task is None
-
- @pytest.mark.asyncio
- async def test_rebind_pool_subscription_recreates_existing_pool_consumer(self) -> None:
- loop = _make_loop()
- pool_sub = AsyncMock()
- loop._pool_sub = pool_sub
- loop._ensure_pool_subscription = AsyncMock()
-
- await loop._rebind_pool_subscription(reason="test")
-
- pool_sub.unsubscribe.assert_awaited_once()
- loop._ensure_pool_subscription.assert_awaited_once()
- assert loop._pool_sub is None
-
-
-class TestProcessEncodeItem:
- """Verify encode item goes through EncodePipeline.run_encode, result published."""
-
- @pytest.mark.asyncio
- async def test_process_encode_item(self) -> None:
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.start_worker = AsyncMock(return_value=MagicMock())
-
- loop = _make_loop(nc=nc, registry=registry)
-
- wi = _make_work_item(
- operation="encode",
- item={"text": "hello world"},
- output_types=["dense"],
- )
- msg = _make_msg(wi)
-
- fake_output = [{"dense": [0.1, 0.2]}]
- fake_timing = RequestTiming()
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- return_value=(fake_output, fake_timing),
- ) as mock_encode:
- await loop._process_messages("test/model", [msg])
-
- mock_encode.assert_called_once()
- call_kwargs = mock_encode.call_args.kwargs
- assert call_kwargs["model"] == "test/model"
- assert call_kwargs["output_types"] == ["dense"]
- assert call_kwargs["registry"] is registry
- # Batch API passes a list of Item objects
- assert len(call_kwargs["items"]) == 1
- assert call_kwargs["items"][0].text == "hello world"
-
- result = _published_result(nc)
- assert result["success"] is True
- assert result["work_item_id"] == "req-1.0"
- # The inner result_msgpack contains the formatted_output[0]
- inner = msgpack.unpackb(result["result_msgpack"], raw=False)
- assert inner == {"dense": [0.1, 0.2]}
- msg.ack.assert_awaited_once()
-
-
-class TestProcessScoreItem:
- """Verify score item skips _resolve_item, calls worker.submit_score."""
-
- @pytest.mark.asyncio
- async def test_process_score_item(self) -> None:
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- # Create mock worker with submit_score returning an awaitable future
- mock_worker = AsyncMock()
- score_output = ScoreOutput(scores=np.array([0.95, 0.42], dtype=np.float32))
- worker_result = WorkerResult(output=score_output, timing=RequestTiming())
- future: asyncio.Future[WorkerResult] = asyncio.Future()
- future.set_result(worker_result)
- mock_worker.submit_score = AsyncMock(return_value=future)
- registry.start_worker = AsyncMock(return_value=mock_worker)
-
- loop = _make_loop(nc=nc, registry=registry)
-
- wi = _make_work_item(
- operation="score",
- query_item={"text": "What is ML?"},
- score_items=[{"text": "ML is AI."}, {"text": "Cooking recipe."}],
- )
- msg = _make_msg(wi)
-
- await loop._process_messages("test/model", [msg])
-
- # Verify submit_score was called
- mock_worker.submit_score.assert_awaited_once()
- call_kwargs = mock_worker.submit_score.call_args.kwargs
- assert isinstance(call_kwargs["query"], Item)
- assert call_kwargs["query"].text == "What is ML?"
- assert len(call_kwargs["items"]) == 2
-
- # Verify result published
- result = _published_result(nc)
- assert result["success"] is True
- scores = msgpack.unpackb(result["result_msgpack"], raw=False)
- assert len(scores) == 2
- assert abs(scores[0]["score"] - 0.95) < 0.01
- assert abs(scores[1]["score"] - 0.42) < 0.01
- msg.ack.assert_awaited_once()
-
- @pytest.mark.asyncio
- async def test_score_item_no_resolve_item(self) -> None:
- """Score work items with query_item/score_items DON'T go through _resolve_item."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- mock_worker = AsyncMock()
- score_output = ScoreOutput(scores=np.array([0.5], dtype=np.float32))
- worker_result = WorkerResult(output=score_output, timing=RequestTiming())
- future: asyncio.Future[WorkerResult] = asyncio.Future()
- future.set_result(worker_result)
- mock_worker.submit_score = AsyncMock(return_value=future)
- registry.start_worker = AsyncMock(return_value=mock_worker)
-
- loop = _make_loop(nc=nc, registry=registry)
-
- wi = _make_work_item(
- operation="score",
- query_item={"text": "query"},
- score_items=[{"text": "doc"}],
- # Note: no "item" field — _resolve_item would fail for score
- # if it were called, since there's no item/payload_ref.
- )
- msg = _make_msg(wi)
-
- with patch.object(loop, "_resolve_item", new_callable=AsyncMock) as mock_resolve:
- await loop._process_messages("test/model", [msg])
- mock_resolve.assert_not_called()
-
- # Score should still succeed
- result = _published_result(nc)
- assert result["success"] is True
-
- @pytest.mark.asyncio
- async def test_score_with_payload_ref(self) -> None:
- """Score with offloaded payload fetches from store."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- mock_worker = AsyncMock()
- score_output = ScoreOutput(scores=np.array([0.8], dtype=np.float32))
- worker_result = WorkerResult(output=score_output, timing=RequestTiming())
- future: asyncio.Future[WorkerResult] = asyncio.Future()
- future.set_result(worker_result)
- mock_worker.submit_score = AsyncMock(return_value=future)
- registry.start_worker = AsyncMock(return_value=mock_worker)
-
- loop = _make_loop(nc=nc, registry=registry)
-
- # Set up payload store mock
- payload_data = msgpack.packb(
- {
- "query": {"text": "offloaded query"},
- "items": [{"text": "offloaded doc"}],
- },
- use_bin_type=True,
- )
- mock_store = AsyncMock()
- mock_store.get = AsyncMock(return_value=payload_data)
- loop._payload_store = mock_store
-
- wi = _make_work_item(
- operation="score",
- # No inline query_item/score_items — use payload ref
- query_payload_ref="payloads/abc123",
- )
- msg = _make_msg(wi)
-
- await loop._process_messages("test/model", [msg])
-
- # Verify payload was fetched
- mock_store.get.assert_awaited_once_with("payloads/abc123")
-
- # Verify submit_score received resolved items
- call_kwargs = mock_worker.submit_score.call_args.kwargs
- assert call_kwargs["query"].text == "offloaded query"
- assert len(call_kwargs["items"]) == 1
- assert call_kwargs["items"][0].text == "offloaded doc"
-
- result = _published_result(nc)
- assert result["success"] is True
-
-
-class TestProcessExtractItem:
- """Verify extract item calls worker.submit_extract, result published."""
-
- @pytest.mark.asyncio
- async def test_process_extract_item(self) -> None:
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- mock_worker = AsyncMock()
- extract_output = ExtractOutput(
- entities=[[{"text": "Alice", "label": "person", "score": 0.99, "start": 0, "end": 5}]]
- )
- worker_result = WorkerResult(output=extract_output, timing=RequestTiming())
- future: asyncio.Future[WorkerResult] = asyncio.Future()
- future.set_result(worker_result)
- mock_worker.submit_extract = AsyncMock(return_value=future)
- registry.start_worker = AsyncMock(return_value=mock_worker)
-
- loop = _make_loop(nc=nc, registry=registry)
-
- wi = _make_work_item(
- operation="extract",
- item={"text": "Alice works at Acme."},
- labels=["person", "organization"],
- )
- msg = _make_msg(wi)
-
- await loop._process_messages("test/model", [msg])
-
- # Verify submit_extract was called
- mock_worker.submit_extract.assert_awaited_once()
- call_kwargs = mock_worker.submit_extract.call_args.kwargs
- assert len(call_kwargs["items"]) == 1
- assert call_kwargs["items"][0].text == "Alice works at Acme."
- assert call_kwargs["labels"] == ["person", "organization"]
-
- # Verify result published
- result = _published_result(nc)
- assert result["success"] is True
- inner = msgpack.unpackb(result["result_msgpack"], raw=False)
- assert "entities" in inner
- msg.ack.assert_awaited_once()
-
- @pytest.mark.asyncio
- async def test_process_extract_item_with_document(self) -> None:
- """Document items round-trip through the queue and surface structured data."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- mock_worker = AsyncMock()
- extract_output = ExtractOutput(
- entities=[[]],
- data=[{"document": {"pages": [{"text": "hello"}]}}],
- )
- worker_result = WorkerResult(output=extract_output, timing=RequestTiming())
- future: asyncio.Future[WorkerResult] = asyncio.Future()
- future.set_result(worker_result)
- mock_worker.submit_extract = AsyncMock(return_value=future)
- registry.start_worker = AsyncMock(return_value=mock_worker)
-
- loop = _make_loop(nc=nc, registry=registry)
-
- document_bytes = b"%PDF-1.4 fake content"
- wi = _make_work_item(
- operation="extract",
- item={"document": {"data": document_bytes, "format": "pdf"}},
- )
- msg = _make_msg(wi)
-
- await loop._process_messages("test/model", [msg])
-
- mock_worker.submit_extract.assert_awaited_once()
- call_kwargs = mock_worker.submit_extract.call_args.kwargs
- assert call_kwargs["items"][0].document == {"data": document_bytes, "format": "pdf"}
- prepared = call_kwargs["prepared_items"]
- assert len(prepared) == 1
- assert prepared[0].cost == len(document_bytes)
-
- result = _published_result(nc)
- assert result["success"] is True
- inner = msgpack.unpackb(result["result_msgpack"], raw=False)
- assert inner["data"] == {"document": {"pages": [{"text": "hello"}]}}
- msg.ack.assert_awaited_once()
-
-
-class TestErrorPaths:
- """Verify error conditions publish error results."""
-
- @pytest.mark.asyncio
- async def test_unknown_operation_publishes_error(self) -> None:
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.start_worker = AsyncMock(return_value=MagicMock())
-
- loop = _make_loop(nc=nc, registry=registry)
-
- wi = _make_work_item(
- operation="summarize",
- item={"text": "some text"},
- )
- msg = _make_msg(wi)
-
- await loop._process_messages("test/model", [msg])
-
- result = _published_result(nc)
- assert result["success"] is False
- assert result["error_code"] == "unknown_operation"
- assert "summarize" in result["error"]
- msg.ack.assert_awaited_once()
-
- @pytest.mark.asyncio
- async def test_oom_during_encode_naks_without_publishing(self) -> None:
- """OOM in the encode pipeline must NAK and skip the error publish.
-
- Contract:
-
- 1. **No** ``WorkResult`` is published to the reply subject for
- ``RESOURCE_EXHAUSTED``. The gateway aggregates per-item replies
- into a per-request collector; once an item's slot is filled,
- the request_id is removed from ``pending_results`` and any
- later reply (e.g. from the redelivered work) is silently
- dropped at the inbox. Publishing the error here would defeat
- the redelivery — the gateway would already have responded to
- the client by the time JetStream redelivers, so the work
- done by the second worker is wasted compute.
- 2. The JetStream message is NAKed, not ACKed. NAK with
- ``_OOM_NAK_DELAY_S`` lets JetStream redeliver the work item —
- potentially to a sibling worker, or to this worker after its
- memory pressure clears. The gateway's existing result-await
- timeout still synthesises a 503 ``MODEL_LOADING`` /
- ``RESOURCE_EXHAUSTED`` response for the original client, and
- the SDK auto-retries; the NAK gives non-retrying clients
- (``max_oom_retries=0``) a real second attempt.
- """
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.start_worker = AsyncMock(return_value=MagicMock())
-
- loop = _make_loop(nc=nc, registry=registry)
-
- wi = _make_work_item(
- operation="encode",
- item={"text": "hello world"},
- output_types=["dense"],
- )
- msg = _make_msg(wi)
-
- oom = RuntimeError("CUDA out of memory. Tried to allocate 2.00 GiB")
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=oom,
- ):
- await loop._process_messages("test/model", [msg])
-
- # No reply published — the redelivery via NAK is the recovery path.
- nc.publish.assert_not_called()
- # Critical: delayed NAK for redelivery, not ACK. The delay must
- # match _OOM_NAK_DELAY_S so JetStream redelivers after the
- # configured backoff (gives the worker time to recover memory
- # or another worker time to take over).
- msg.nak.assert_awaited_once_with(delay=_OOM_NAK_DELAY_S)
- msg.ack.assert_not_awaited()
-
- @pytest.mark.asyncio
- async def test_oom_during_encode_multi_item_batch_silently_naks_all(self) -> None:
- """A unanimous-OOM multi-item batch must NAK every item with no replies.
-
- Regression guard for the gateway-awaiter contract: a sub-batch of N
- items hits OOM and the worker must skip ``_publish_error`` for
- every item AND NAK every JetStream message. Even one stray
- ``_publish_error`` would fill the gateway's per-item slot and let
- the request collector complete on the partial set, dropping the
- redelivered work for the remaining items.
- """
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.start_worker = AsyncMock(return_value=MagicMock())
-
- loop = _make_loop(nc=nc, registry=registry)
-
- msgs = []
- for idx in range(3):
- wi = _make_work_item(
- work_item_id=f"req-1.{idx}",
- item_index=idx,
- total_items=3,
- operation="encode",
- item={"text": f"hello {idx}"},
- output_types=["dense"],
- )
- msgs.append(_make_msg(wi))
-
- oom = RuntimeError("CUDA out of memory. Tried to allocate 2.00 GiB")
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=oom,
- ):
- await loop._process_messages("test/model", msgs)
-
- # No reply published for any item — the gateway will synthesize a
- # 503 from its own result-await timeout once the collector ages out.
- nc.publish.assert_not_called()
- # Every JetStream message NAKed exactly once for redelivery,
- # with the OOM-specific delay so JetStream waits before
- # redelivering (sibling workers or this worker after recovery).
- for msg in msgs:
- msg.nak.assert_awaited_once_with(delay=_OOM_NAK_DELAY_S)
- msg.ack.assert_not_awaited()
-
- @pytest.mark.asyncio
- async def test_non_oom_inference_error_keeps_legacy_code_and_acks(self) -> None:
- """Non-OOM inference exceptions still emit the legacy literal AND ACK.
-
- Regression guard: the OOM classifier must not swallow other
- failure modes (shape errors, adapter bugs, …). And — crucially —
- non-retryable errors are ACKed so JetStream doesn't redeliver
- the same broken request indefinitely.
- """
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.start_worker = AsyncMock(return_value=MagicMock())
-
- loop = _make_loop(nc=nc, registry=registry)
-
- wi = _make_work_item(
- operation="encode",
- item={"text": "hello"},
- output_types=["dense"],
- )
- msg = _make_msg(wi)
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=ValueError("bad shape"),
- ):
- await loop._process_messages("test/model", [msg])
-
- result = _published_result(nc)
- assert result["success"] is False
- assert result["error_code"] == "inference_error"
- # Non-retryable: ACK so the broken request doesn't redeliver.
- msg.ack.assert_awaited_once()
- msg.nak.assert_not_awaited()
-
- @pytest.mark.asyncio
- async def test_model_not_found_naks_for_redelivery(self) -> None:
- """When start_worker raises KeyError (model evicted), items are NAKed."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.start_worker = AsyncMock(side_effect=KeyError("test/model"))
-
- loop = _make_loop(nc=nc, registry=registry)
-
- wi = _make_work_item(
- operation="score",
- query_item={"text": "hello"},
- score_items=[{"text": "world"}],
- )
- msg = _make_msg(wi)
-
- await loop._process_messages("test/model", [msg])
-
- # Item should be NAKed (not ACKed with error) for redelivery
- msg.nak.assert_awaited_once()
- msg.ack.assert_not_awaited()
- # No result published — item goes back to queue
- nc.publish.assert_not_awaited()
-
- @pytest.mark.asyncio
- async def test_get_config_key_error_naks_for_redelivery(self) -> None:
- """When get_config raises KeyError (model evicted), items are NAKed."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.side_effect = KeyError("test/model")
- registry.start_worker = AsyncMock(return_value=MagicMock())
-
- loop = _make_loop(nc=nc, registry=registry)
-
- wi = _make_work_item(
- operation="encode",
- item={"text": "hello"},
- )
- msg = _make_msg(wi)
-
- await loop._process_messages("test/model", [msg])
-
- # Item should be NAKed (not ACKed with error) for redelivery
- msg.nak.assert_awaited_once()
- msg.ack.assert_not_awaited()
- nc.publish.assert_not_awaited()
-
-
-class TestBatchProcessing:
- """Verify _process_messages processes all messages in a batch."""
-
- @pytest.mark.asyncio
- async def test_batch_processes_all_messages(self) -> None:
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.start_worker = AsyncMock(return_value=MagicMock())
-
- loop = _make_loop(nc=nc, registry=registry)
-
- fake_timing = RequestTiming()
-
- # Create 5 encode messages
- messages = []
- fake_outputs = []
- for i in range(5):
- wi = _make_work_item(
- work_item_id=f"req-{i}.0",
- item={"text": f"text {i}"},
- output_types=["dense"],
- )
- messages.append(_make_msg(wi))
- fake_outputs.append({"dense": [float(i)]})
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- return_value=(fake_outputs, fake_timing),
- ):
- await loop._process_messages("test/model", messages)
-
- # All 5 messages should be acked
- assert sum(1 for m in messages if m.ack.await_count > 0) == 5
- # All 5 results should be published
- assert nc.publish.await_count == 5
-
-
-class TestGenerateDispatch:
- """Generate work items route through the StreamingProcessor seam."""
-
- @pytest.mark.asyncio
- async def test_generate_op_routes_through_streaming_processor(self) -> None:
- nc = AsyncMock()
- loop = _make_loop(nc=nc)
- # Stub the streaming processor — we only assert dispatch here.
- loop._streaming_processor = MagicMock()
- loop._streaming_processor.process = AsyncMock()
-
- wi = _make_work_item(
- operation="generate",
- generate={"prompt": "Hello", "max_new_tokens": 32},
- )
- msg = _make_msg(wi)
-
- await loop._process_messages("test/model", [msg])
-
- loop._streaming_processor.process.assert_awaited_once()
- # First positional arg is the message.
- call_args = loop._streaming_processor.process.await_args
- assert call_args.args[0] is msg
- assert call_args.args[1] == "test/model"
-
- @pytest.mark.asyncio
- async def test_encode_path_unchanged_after_seam_introduction(self) -> None:
- """Regression: introducing the generate seam must not perturb encode."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.start_worker = AsyncMock(return_value=MagicMock())
-
- loop = _make_loop(nc=nc, registry=registry)
- # Sanity: the streaming processor exists on the loop now.
- assert loop._streaming_processor is not None
-
- wi = _make_work_item(operation="encode", item={"text": "x"}, output_types=["dense"])
- msg = _make_msg(wi)
-
- fake_output = [{"dense": np.array([0.1, 0.2], dtype=np.float32)}]
- fake_timing = RequestTiming()
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- return_value=(fake_output, fake_timing),
- ):
- await loop._process_messages("test/model", [msg])
-
- msg.ack.assert_awaited()
- nc.publish.assert_awaited()
-
-
-# ── Mixed-pool fairness scheduler wiring ──────────────────────────────
-
-
-def test_fairness_config_from_env_disabled_by_default(monkeypatch) -> None:
- for k in list(os.environ):
- if k.startswith("SIE_POOL_FAIRNESS"):
- monkeypatch.delenv(k, raising=False)
- assert _fairness_config_from_env() is None
-
-
-def test_fairness_config_from_env_enabled(monkeypatch) -> None:
- monkeypatch.setenv("SIE_POOL_FAIRNESS_ENABLED", "true")
- monkeypatch.setenv("SIE_POOL_FAIRNESS_TOTAL_SLOTS", "6")
- monkeypatch.setenv("SIE_POOL_FAIRNESS_GEN_WEIGHT", "3")
- monkeypatch.setenv("SIE_POOL_FAIRNESS_EMB_MIN_SLOTS", "2")
- cfg = _fairness_config_from_env()
- assert cfg is not None
- assert cfg.total_slots == 6
- from sie_server.processors.work_class_scheduler import EMBEDDING_CLASS, GENERATION_CLASS
-
- assert cfg.classes[GENERATION_CLASS].weight == 3.0
- assert cfg.classes[EMBEDDING_CLASS].min_slots == 2
-
-
-def test_fairness_config_from_env_invalid_disables(monkeypatch) -> None:
- # Over-subscribed floor (sum(min_slots) > total_slots) would deadlock;
- # the helper logs and returns None rather than crashing the worker.
- monkeypatch.setenv("SIE_POOL_FAIRNESS_ENABLED", "1")
- monkeypatch.setenv("SIE_POOL_FAIRNESS_TOTAL_SLOTS", "2")
- monkeypatch.setenv("SIE_POOL_FAIRNESS_GEN_MIN_SLOTS", "2")
- monkeypatch.setenv("SIE_POOL_FAIRNESS_EMB_MIN_SLOTS", "2")
- assert _fairness_config_from_env() is None
-
-
-def test_class_slot_noop_without_fairness(monkeypatch) -> None:
- for k in list(os.environ):
- if k.startswith("SIE_POOL_FAIRNESS"):
- monkeypatch.delenv(k, raising=False)
- loop = _make_loop()
- assert loop._scheduler is None
-
- async def _run() -> None:
- async with loop._class_slot("generate"):
- pass # no scheduler → pure pass-through
-
- asyncio.run(_run())
-
-
-def test_class_slot_gates_with_fairness(monkeypatch) -> None:
- monkeypatch.setenv("SIE_POOL_FAIRNESS_ENABLED", "true")
- monkeypatch.setenv("SIE_POOL_FAIRNESS_TOTAL_SLOTS", "4")
- monkeypatch.setenv("SIE_POOL_FAIRNESS_EMB_MIN_SLOTS", "1")
- loop = _make_loop()
- assert loop._scheduler is not None
-
- async def _run() -> dict:
- async with loop._class_slot("generate"):
- return loop._scheduler.saturation_snapshot()
-
- snap = asyncio.run(_run())
- from sie_server.processors.work_class_scheduler import GENERATION_CLASS
-
- # A generation slot was leased inside the block.
- assert snap["classes"][GENERATION_CLASS]["leased"] == 1
- # Released on exit → scheduler returns to idle.
- assert loop._scheduler.saturation_snapshot()["total_leased"] == 0
diff --git a/packages/sie_server/tests/test_nats_pull_loop_batching.py b/packages/sie_server/tests/test_nats_pull_loop_batching.py
deleted file mode 100644
index 92d77b622..000000000
--- a/packages/sie_server/tests/test_nats_pull_loop_batching.py
+++ /dev/null
@@ -1,1291 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import logging
-import time
-from typing import Any
-from unittest.mock import AsyncMock, MagicMock, patch
-
-import msgpack
-import pytest
-from sie_server.core.timing import RequestTiming
-from sie_server.nats_pull_loop import (
- _DEFAULT_BATCH_BUDGET,
- _MAX_CONCURRENT_BATCHES,
- _NAK_DELAY_S,
- _THRASH_THRESHOLD,
- NatsPullLoop,
-)
-
-
-def _make_work_item(**overrides) -> dict:
- """Build a minimal WorkItem dict with required fields."""
- wi = {
- "work_item_id": "req-1.0",
- "request_id": "req-1",
- "item_index": 0,
- "total_items": 1,
- "operation": "encode",
- "model_id": "test/model",
- "profile_id": "default",
- "pool_name": "_default",
- "router_id": "router-1",
- "reply_subject": "_INBOX.router-1.req-1",
- "timestamp": time.time(),
- }
- wi.update(overrides)
- return wi
-
-
-def _make_loop(
- *,
- registry: MagicMock | None = None,
- nc: AsyncMock | None = None,
- js: AsyncMock | None = None,
- payload_store_url: str | None = None,
-) -> NatsPullLoop:
- """Create a NatsPullLoop with mocked dependencies."""
- if nc is None:
- nc = AsyncMock()
- if js is None:
- js = AsyncMock()
- if registry is None:
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- return NatsPullLoop(
- nc=nc,
- js=js,
- registry=registry,
- bundle_id="default",
- pool_name="_default",
- payload_store_url=payload_store_url,
- )
-
-
-def _make_msg(wi: dict) -> AsyncMock:
- """Wrap a WorkItem dict into a mock NATS message with serialized data."""
- msg = AsyncMock()
- msg.data = msgpack.packb(wi, use_bin_type=True)
- return msg
-
-
-def _published_results(nc_mock: AsyncMock) -> list[dict]:
- """Extract all published WorkResults from the mock nc.publish calls."""
- results = []
- for call in nc_mock.publish.call_args_list:
- _subject, data = call.args
- results.append(msgpack.unpackb(data, raw=False))
- return results
-
-
-class TestEncodeBatching:
- """Verify encode items are sub-grouped by encode params for separate pipeline calls."""
-
- @pytest.mark.asyncio
- async def test_encode_batch_groups_by_output_types(self) -> None:
- """Items with different output_types should be processed in separate sub-batches."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
-
- fake_timing = RequestTiming()
-
- # 2 items with ["dense"], 1 with ["dense", "sparse"]
- messages = [
- _make_msg(
- _make_work_item(
- work_item_id="req-1.0",
- item_index=0,
- item={"text": "item A"},
- output_types=["dense"],
- )
- ),
- _make_msg(
- _make_work_item(
- work_item_id="req-1.1",
- item_index=1,
- item={"text": "item B"},
- output_types=["dense"],
- )
- ),
- _make_msg(
- _make_work_item(
- work_item_id="req-1.2",
- item_index=2,
- item={"text": "item C"},
- output_types=["dense", "sparse"],
- )
- ),
- ]
-
- call_items_counts: list[int] = []
-
- async def mock_run_encode(**kwargs):
- n = len(kwargs["items"])
- call_items_counts.append(n)
- fake_outputs = [{"dense": [0.1]} for _ in range(n)]
- return fake_outputs, fake_timing
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=mock_run_encode,
- ) as mock_encode:
- await loop._process_messages("test/model", messages)
-
- assert mock_encode.call_count == 2
- assert sorted(call_items_counts) == [1, 2]
-
- @pytest.mark.asyncio
- async def test_encode_batch_groups_by_instruction(self) -> None:
- """Items with different instruction values should be in separate sub-batches."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
- fake_timing = RequestTiming()
-
- messages = [
- _make_msg(
- _make_work_item(
- work_item_id="req-1.0",
- item_index=0,
- item={"text": "a"},
- output_types=["dense"],
- instruction="query:",
- )
- ),
- _make_msg(
- _make_work_item(
- work_item_id="req-1.1",
- item_index=1,
- item={"text": "b"},
- output_types=["dense"],
- instruction="query:",
- )
- ),
- _make_msg(
- _make_work_item(
- work_item_id="req-1.2",
- item_index=2,
- item={"text": "c"},
- output_types=["dense"],
- instruction="passage:",
- )
- ),
- ]
-
- call_instructions: list[str | None] = []
-
- async def mock_run_encode(**kwargs):
- call_instructions.append(kwargs.get("instruction"))
- n = len(kwargs["items"])
- return [{"dense": [0.1]} for _ in range(n)], fake_timing
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=mock_run_encode,
- ) as mock_encode:
- await loop._process_messages("test/model", messages)
-
- assert mock_encode.call_count == 2
- assert sorted(call_instructions) == ["passage:", "query:"]
-
- @pytest.mark.asyncio
- async def test_encode_batch_groups_by_is_query(self) -> None:
- """Items with is_query=True vs False should be in separate sub-batches."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
- fake_timing = RequestTiming()
-
- messages = [
- _make_msg(
- _make_work_item(
- work_item_id="req-1.0",
- item_index=0,
- item={"text": "query"},
- output_types=["dense"],
- is_query=True,
- )
- ),
- _make_msg(
- _make_work_item(
- work_item_id="req-1.1",
- item_index=1,
- item={"text": "doc1"},
- output_types=["dense"],
- is_query=False,
- )
- ),
- _make_msg(
- _make_work_item(
- work_item_id="req-1.2",
- item_index=2,
- item={"text": "doc2"},
- output_types=["dense"],
- is_query=False,
- )
- ),
- ]
-
- call_is_query_values: list[bool] = []
-
- async def mock_run_encode(**kwargs):
- call_is_query_values.append(kwargs.get("is_query", False))
- n = len(kwargs["items"])
- return [{"dense": [0.1]} for _ in range(n)], fake_timing
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=mock_run_encode,
- ) as mock_encode:
- await loop._process_messages("test/model", messages)
-
- assert mock_encode.call_count == 2
- assert sorted(call_is_query_values) == [False, True]
-
- @pytest.mark.asyncio
- async def test_encode_batch_groups_by_options(self) -> None:
- """Items with different options dicts (e.g., different LoRA adapters) get separate calls."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
- fake_timing = RequestTiming()
-
- messages = [
- _make_msg(
- _make_work_item(
- work_item_id="req-1.0",
- item_index=0,
- item={"text": "a"},
- output_types=["dense"],
- options={"lora": "adapter-a"},
- )
- ),
- _make_msg(
- _make_work_item(
- work_item_id="req-1.1",
- item_index=1,
- item={"text": "b"},
- output_types=["dense"],
- options={"lora": "adapter-b"},
- )
- ),
- ]
-
- call_options: list[dict] = []
-
- async def mock_run_encode(**kwargs):
- call_options.append(kwargs.get("options", {}))
- n = len(kwargs["items"])
- return [{"dense": [0.1]} for _ in range(n)], fake_timing
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=mock_run_encode,
- ) as mock_encode:
- await loop._process_messages("test/model", messages)
-
- assert mock_encode.call_count == 2
- assert {"lora": "adapter-a"} in call_options
- assert {"lora": "adapter-b"} in call_options
-
- @pytest.mark.asyncio
- async def test_encode_batch_homogeneous_single_call(self) -> None:
- """All items with identical params should result in a single run_encode call."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
- fake_timing = RequestTiming()
-
- messages = []
- for i in range(5):
- messages.append(
- _make_msg(
- _make_work_item(
- work_item_id=f"req-1.{i}",
- item_index=i,
- item={"text": f"text {i}"},
- output_types=["dense"],
- instruction="query:",
- is_query=True,
- options={"pooling": "mean"},
- )
- )
- )
-
- async def mock_run_encode(**kwargs):
- n = len(kwargs["items"])
- return [{"dense": [float(i)]} for i in range(n)], fake_timing
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=mock_run_encode,
- ) as mock_encode:
- await loop._process_messages("test/model", messages)
-
- # All 5 items have identical params — single call
- mock_encode.assert_called_once()
- assert len(mock_encode.call_args.kwargs["items"]) == 5
-
- # All 5 results published
- assert nc.publish.await_count == 5
-
-
-class TestConfigHash:
- """Verify bundle_config_hash validation behavior."""
-
- @pytest.mark.asyncio
- async def test_config_hash_mismatch_logs_but_processes(self) -> None:
- """Items with wrong bundle_config_hash are still processed (soft check)."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
-
- # Pre-seed a known config hash
- loop._config_hash_cache = "correct-hash-abc"
- loop._config_hash_cache_time = time.monotonic()
-
- fake_timing = RequestTiming()
-
- wi = _make_work_item(
- item={"text": "hello"},
- output_types=["dense"],
- bundle_config_hash="wrong-hash-xyz",
- )
- msg = _make_msg(wi)
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- return_value=([{"dense": [0.1]}], fake_timing),
- ) as mock_encode:
- await loop._process_messages("test/model", [msg])
-
- # Config hash mismatch is now a soft check — item is still processed
- mock_encode.assert_called_once()
-
- # Message should be ACKed (processed, not NAKed)
- msg.ack.assert_awaited_once()
-
- @pytest.mark.asyncio
- async def test_config_hash_empty_passes_through(self) -> None:
- """Items without bundle_config_hash pass through (backward compat)."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
- loop._config_hash_cache = "some-hash"
- loop._config_hash_cache_time = time.monotonic()
-
- fake_timing = RequestTiming()
-
- # No bundle_config_hash field in the work item
- wi = _make_work_item(
- item={"text": "hello"},
- output_types=["dense"],
- )
- msg = _make_msg(wi)
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- return_value=([{"dense": [0.1]}], fake_timing),
- ) as mock_encode:
- await loop._process_messages("test/model", [msg])
-
- # Should pass through — no hash means backward compat
- mock_encode.assert_called_once()
-
- msg.ack.assert_awaited_once()
-
- @pytest.mark.asyncio
- async def test_config_hash_cached(self) -> None:
- """Hash is only computed once per TTL window, not per-message."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
- fake_timing = RequestTiming()
-
- # Force cache to be stale so _check_config_hash will recompute
- loop._config_hash_cache = None
- loop._config_hash_cache_time = 0.0
-
- # Create 3 messages with matching hash
- messages = []
- for i in range(3):
- wi = _make_work_item(
- work_item_id=f"req-1.{i}",
- item_index=i,
- item={"text": f"text {i}"},
- output_types=["dense"],
- bundle_config_hash="hash-abc",
- )
- messages.append(_make_msg(wi))
-
- with (
- patch(
- "sie_server.api.ws._compute_bundle_config_hash",
- return_value="hash-abc",
- ) as mock_compute_hash,
- patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- return_value=([{"dense": [0.1]} for _ in range(3)], fake_timing),
- ),
- ):
- await loop._process_messages("test/model", messages)
-
- # Hash should be computed only once (cached for subsequent checks)
- mock_compute_hash.assert_called_once()
-
-
-class TestConcurrencyLimits:
- """Verify batch semaphore limits concurrent processing."""
-
- @pytest.mark.asyncio
- async def test_batch_semaphore_limits_concurrency(self) -> None:
- """_MAX_CONCURRENT_BATCHES limits how many batches process simultaneously."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
-
- # Verify the semaphore was initialized with the correct value
- assert loop._batch_sem._value == _MAX_CONCURRENT_BATCHES
-
- # Acquire all permits
- for _ in range(_MAX_CONCURRENT_BATCHES):
- acquired = loop._batch_sem.acquire()
- # Semaphore.acquire is a coroutine
- await acquired
-
- # Next acquire should block (semaphore exhausted)
- # We test this by checking the value is 0
- assert loop._batch_sem._value == 0
-
- # Release one and verify it becomes available
- loop._batch_sem.release()
- assert loop._batch_sem._value == 1
-
-
-class TestGracefulDrain:
- """Verify stop() drains in-flight tasks properly."""
-
- @pytest.mark.asyncio
- async def test_graceful_drain_waits_for_inflight(self) -> None:
- """stop() waits for in-flight tasks to complete before returning."""
- nc = AsyncMock()
- js = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, js=js, registry=registry)
- loop._running = True
- loop._pull_task = None # No main pull task to cancel
-
- task_completed = False
-
- async def slow_task():
- nonlocal task_completed
- await asyncio.sleep(0.05)
- task_completed = True
-
- task = asyncio.create_task(slow_task())
- loop._in_flight_tasks.add(task)
- task.add_done_callback(loop._in_flight_tasks.discard)
-
- await loop.stop()
-
- # Task should have completed (waited, not cancelled)
- assert task_completed
-
- @pytest.mark.asyncio
- async def test_graceful_drain_timeout_cancels(self) -> None:
- """If tasks don't complete within drain timeout, they are cancelled."""
- nc = AsyncMock()
- js = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, js=js, registry=registry)
- loop._running = True
- loop._pull_task = None
-
- task_cancelled = False
-
- async def stuck_task():
- nonlocal task_cancelled
- try:
- # This task runs longer than drain timeout
- await asyncio.sleep(999)
- except asyncio.CancelledError:
- task_cancelled = True
- raise
-
- task = asyncio.create_task(stuck_task())
- loop._in_flight_tasks.add(task)
- task.add_done_callback(loop._in_flight_tasks.discard)
-
- # Temporarily reduce drain timeout for test speed
- with patch("sie_server.nats_pull_loop._DRAIN_TIMEOUT_S", 0.01):
- await loop.stop()
-
- assert task_cancelled
-
-
-class TestMixedOperations:
- """Verify batches with mixed operation types are routed correctly."""
-
- @pytest.mark.asyncio
- async def test_mixed_operations_processed_separately(self) -> None:
- """A pull batch containing encode, score, and extract items triggers all processors."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.start_worker = AsyncMock(return_value=MagicMock())
-
- loop = _make_loop(nc=nc, registry=registry)
-
- encode_msg = _make_msg(
- _make_work_item(
- work_item_id="req-1.0",
- item_index=0,
- operation="encode",
- item={"text": "encode me"},
- output_types=["dense"],
- )
- )
- score_msg = _make_msg(
- _make_work_item(
- work_item_id="req-2.0",
- item_index=0,
- operation="score",
- query_item={"text": "q"},
- score_items=[{"text": "d"}],
- )
- )
- extract_msg = _make_msg(
- _make_work_item(
- work_item_id="req-3.0",
- item_index=0,
- operation="extract",
- item={"text": "extract me"},
- labels=["PER"],
- )
- )
-
- with (
- patch.object(
- loop,
- "_process_encode_batch",
- new_callable=AsyncMock,
- ) as mock_encode_batch,
- patch.object(
- loop,
- "_process_score_batch",
- new_callable=AsyncMock,
- ) as mock_score_batch,
- patch.object(
- loop,
- "_process_extract_batch",
- new_callable=AsyncMock,
- ) as mock_extract_batch,
- ):
- await loop._process_messages("test/model", [encode_msg, score_msg, extract_msg])
-
- mock_encode_batch.assert_called_once()
- mock_score_batch.assert_called_once()
- mock_extract_batch.assert_called_once()
-
- # Verify correct items were routed to each processor
- encode_items = mock_encode_batch.call_args[0][1]
- assert len(encode_items) == 1
- assert encode_items[0][0]["operation"] == "encode"
-
- score_items = mock_score_batch.call_args[0][1]
- assert len(score_items) == 1
- assert score_items[0][0]["operation"] == "score"
-
- extract_items = mock_extract_batch.call_args[0][1]
- assert len(extract_items) == 1
- assert extract_items[0][0]["operation"] == "extract"
-
-
-class TestBatchBudget:
- """Verify _get_batch_budget returns correct values."""
-
- def test_batch_budget_from_worker_config(self) -> None:
- """_get_batch_budget returns the worker's max_batch_requests."""
- registry = MagicMock()
- registry.model_names = ["test/model"]
-
- # Mock a worker with a batch config
- mock_worker = MagicMock()
- mock_worker._batch_config.max_batch_requests = 128
- registry.get_worker.return_value = mock_worker
-
- loop = _make_loop(registry=registry)
- budget = loop._get_batch_budget("test/model")
-
- assert budget == 128
-
- def test_batch_budget_default_when_no_worker(self) -> None:
- """When worker is not loaded yet, returns _DEFAULT_BATCH_BUDGET."""
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_worker.return_value = None
-
- loop = _make_loop(registry=registry)
- budget = loop._get_batch_budget("test/model")
-
- assert budget == _DEFAULT_BATCH_BUDGET
-
- def test_batch_budget_default_on_key_error(self) -> None:
- """When get_worker raises KeyError, returns _DEFAULT_BATCH_BUDGET."""
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_worker.side_effect = KeyError("test/model")
-
- loop = _make_loop(registry=registry)
- budget = loop._get_batch_budget("test/model")
-
- assert budget == _DEFAULT_BATCH_BUDGET
-
-
-class TestReactiveModelLoading:
- """Verify reactive model loading, eviction handling, backoff, and thrashing detection."""
-
- @pytest.mark.asyncio
- async def test_unloaded_model_naks_items_with_delay(self) -> None:
- """All items for an unloaded model are NAKed with delay; background load task created."""
- loop = _make_loop()
-
- msg1 = AsyncMock()
- msg2 = AsyncMock()
- msg3 = AsyncMock()
-
- await loop._handle_unloaded_model("test/model", [msg1, msg2, msg3])
-
- # All 3 messages NAKed with delay
- msg1.nak.assert_awaited_once_with(delay=_NAK_DELAY_S)
- msg2.nak.assert_awaited_once_with(delay=_NAK_DELAY_S)
- msg3.nak.assert_awaited_once_with(delay=_NAK_DELAY_S)
-
- # No messages ACKed
- msg1.ack.assert_not_awaited()
- msg2.ack.assert_not_awaited()
- msg3.ack.assert_not_awaited()
-
- # Background load task was created
- assert "test/model" in loop._loading_models
- assert "test/model" in loop._load_tasks
-
- @pytest.mark.asyncio
- async def test_unloaded_model_triggers_background_load(self) -> None:
- """_handle_unloaded_model calls registry.load_async for the model."""
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.device = "cpu"
- registry.load_async = AsyncMock()
-
- loop = _make_loop(registry=registry)
-
- msg = AsyncMock()
- await loop._handle_unloaded_model("test/model", [msg])
-
- # Wait for the background load task to complete
- load_task = loop._load_tasks["test/model"]
- await load_task
-
- registry.load_async.assert_awaited_once_with("test/model", "cpu")
-
- # After task completes and reap runs, model is cleaned up
- loop._reap_load_tasks()
- assert "test/model" not in loop._loading_models
-
- @pytest.mark.asyncio
- async def test_second_demand_does_not_double_load(self) -> None:
- """A second _handle_unloaded_model call while loading does not trigger a second load."""
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.device = "cpu"
-
- # Make load_async block until we release it
- load_started = asyncio.Event()
- load_release = asyncio.Event()
-
- async def slow_load(model_id: str, device: str) -> None:
- load_started.set()
- await load_release.wait()
-
- registry.load_async = AsyncMock(side_effect=slow_load)
-
- loop = _make_loop(registry=registry)
-
- msg1 = AsyncMock()
- msg2 = AsyncMock()
-
- # First demand — starts loading
- await loop._handle_unloaded_model("test/model", [msg1])
- await load_started.wait()
-
- # Second demand — should NOT trigger another load
- await loop._handle_unloaded_model("test/model", [msg2])
-
- # load_async called only once
- registry.load_async.assert_awaited_once()
-
- # Both messages were still NAKed
- msg1.nak.assert_awaited_once()
- msg2.nak.assert_awaited_once()
-
- # Clean up
- load_release.set()
- await loop._load_tasks["test/model"]
-
- @pytest.mark.asyncio
- async def test_failed_load_allows_retry(self) -> None:
- """A failed background load is cleaned up and allows a retry."""
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.device = "cpu"
- registry.load_async = AsyncMock(side_effect=RuntimeError("GPU OOM"))
-
- loop = _make_loop(registry=registry)
-
- msg1 = AsyncMock()
- await loop._handle_unloaded_model("test/model", [msg1])
-
- # Wait for the load task to finish (it will fail)
- load_task = loop._load_tasks["test/model"]
- with pytest.raises(RuntimeError, match="GPU OOM"):
- await load_task
-
- # Reap completed (failed) tasks
- loop._reap_load_tasks()
- assert "test/model" not in loop._loading_models
- assert "test/model" not in loop._load_tasks
-
- # Reset the mock to succeed this time and try again
- registry.load_async = AsyncMock()
- msg2 = AsyncMock()
- await loop._handle_unloaded_model("test/model", [msg2])
-
- # A new load task was created
- assert "test/model" in loop._loading_models
- assert "test/model" in loop._load_tasks
-
- # Clean up
- await loop._load_tasks["test/model"]
-
- def test_thrashing_detection(self, caplog: pytest.LogCaptureFixture) -> None:
- """_check_thrashing logs a warning when a model is loaded too frequently."""
- loop = _make_loop()
-
- now = time.monotonic()
- # Populate load history with THRASH_THRESHOLD entries within the window
- loop._load_history = [("test/model", now - i) for i in range(_THRASH_THRESHOLD)]
-
- with caplog.at_level(logging.WARNING, logger="sie_server.nats_pull_loop"):
- loop._check_thrashing("test/model")
-
- assert any("thrashing" in record.message.lower() for record in caplog.records)
- assert any("test/model" in record.message for record in caplog.records)
-
- @pytest.mark.asyncio
- async def test_encode_cancelled_error_naks(self) -> None:
- """CancelledError during encode NAKs items instead of ACKing with error."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
-
- msg = _make_msg(
- _make_work_item(
- operation="encode",
- item={"text": "hello"},
- output_types=["dense"],
- )
- )
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=asyncio.CancelledError,
- ):
- await loop._process_messages("test/model", [msg])
-
- # Message should be NAKed (eviction path), not ACKed
- msg.nak.assert_awaited()
- # No results published (error or otherwise)
- nc.publish.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_score_model_evicted_naks(self) -> None:
- """KeyError from start_worker (model evicted) NAKs the score message."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.start_worker = AsyncMock(side_effect=KeyError("test/model"))
-
- loop = _make_loop(nc=nc, registry=registry)
-
- msg = _make_msg(
- _make_work_item(
- operation="score",
- query_item={"text": "q"},
- score_items=[{"text": "d"}],
- )
- )
-
- await loop._process_messages("test/model", [msg])
-
- msg.nak.assert_awaited()
-
- @pytest.mark.asyncio
- async def test_reap_load_tasks_cleans_completed(self) -> None:
- """_reap_load_tasks removes completed tasks from both tracking structures."""
- loop = _make_loop()
-
- # Create and await a task so it's done
- async def noop() -> None:
- pass
-
- task = asyncio.create_task(noop())
- await task # Let it complete
-
- loop._load_tasks["test/model"] = task
- loop._loading_models.add("test/model")
-
- loop._reap_load_tasks()
-
- assert "test/model" not in loop._loading_models
- assert "test/model" not in loop._load_tasks
-
- @pytest.mark.asyncio
- async def test_reap_load_tasks_handles_cancelled_task(self) -> None:
- """_reap_load_tasks cleans up a cancelled-but-done task without raising."""
- loop = _make_loop()
-
- async def long_sleep() -> None:
- await asyncio.sleep(999)
-
- task = asyncio.create_task(long_sleep())
- # Cancel and let the cancellation propagate
- task.cancel()
- # Gather with return_exceptions so we don't re-raise
- await asyncio.gather(task, return_exceptions=True)
-
- # Task is now done + cancelled
- assert task.done()
- assert task.cancelled()
-
- loop._load_tasks["cancelled/model"] = task
- loop._loading_models.add("cancelled/model")
-
- # _reap_load_tasks should handle the CancelledError branch without raising
- loop._reap_load_tasks()
-
- assert "cancelled/model" not in loop._loading_models
- assert "cancelled/model" not in loop._load_tasks
-
- @pytest.mark.asyncio
- async def test_stop_cancels_load_tasks(self) -> None:
- """stop() cancels in-progress background load tasks."""
- nc = AsyncMock()
- js = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, js=js, registry=registry)
- loop._running = True
- loop._pull_task = None
-
- task_cancelled = False
-
- async def long_running_load() -> None:
- nonlocal task_cancelled
- try:
- await asyncio.sleep(999)
- except asyncio.CancelledError:
- task_cancelled = True
- raise
-
- load_task = asyncio.create_task(long_running_load())
- loop._load_tasks["test/model"] = load_task
- loop._loading_models.add("test/model")
-
- # Yield to let the task start running before we stop
- await asyncio.sleep(0)
-
- await loop.stop()
-
- # Yield to let cancellation propagate fully
- await asyncio.sleep(0)
-
- assert task_cancelled
- assert len(loop._load_tasks) == 0
- assert len(loop._loading_models) == 0
-
-
-class TestGenerationDecoupledFromBatchSem:
- """H2 regression: generation streams must NOT be capped by ``_batch_sem``.
-
- Generation is decoupled from the GPU-batch semaphore — each stream
- runs as its own tracked task and ``_batch_sem`` is released once the
- batch is dispatched. KV admission (inside StreamingProcessor) is the
- real backpressure. Without the fix, no more than
- ``_MAX_CONCURRENT_BATCHES`` (=4) generation streams could be in flight.
- """
-
- @pytest.mark.asyncio
- async def test_more_than_max_batches_generation_streams_in_flight(self) -> None:
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.is_loaded.return_value = True
-
- loop = _make_loop(nc=nc, registry=registry)
- # Per-model budget large enough to dispatch all messages in one batch.
- loop._get_batch_budget = MagicMock(return_value=256) # type: ignore[method-assign]
-
- n_streams = _MAX_CONCURRENT_BATCHES * 3 # 12 — well past the old cap
- concurrent = 0
- peak_concurrent = 0
- release = asyncio.Event()
-
- async def slow_stream(msg: Any, model_id: str) -> None:
- nonlocal concurrent, peak_concurrent
- concurrent += 1
- peak_concurrent = max(peak_concurrent, concurrent)
- try:
- await release.wait()
- finally:
- concurrent -= 1
-
- loop._streaming_processor.process = AsyncMock(side_effect=slow_stream) # type: ignore[method-assign]
-
- messages = []
- for i in range(n_streams):
- m = _make_msg(
- _make_work_item(
- work_item_id=f"req-{i}.0",
- request_id=f"req-{i}",
- item_index=0,
- operation="generate",
- generate={"prompt": "hi", "max_new_tokens": 8},
- )
- )
- # ``_dispatch_batch`` extracts model_id from the subject
- # (``sie.work.{normalized}.{pool}``); set a real string so the
- # AsyncMock attribute isn't a coroutine.
- m.subject = "sie.work.test__model._default"
- messages.append(m)
-
- # Dispatch through the real ``_dispatch_batch`` so ``_batch_sem`` is
- # exercised exactly as in production.
- await loop._dispatch_batch(messages)
-
- # ``_dispatch_batch`` schedules ``_guarded_process`` as a task; let
- # it run ``_process_messages`` -> ``_process_generate_items`` which
- # spawns the per-stream tasks and returns immediately, and let the
- # guarded task unwind so it releases ``_batch_sem``.
- for _ in range(50):
- await asyncio.sleep(0)
- if peak_concurrent >= n_streams and loop._batch_sem._value == _MAX_CONCURRENT_BATCHES:
- break
-
- # All streams are concurrently in flight — NOT capped at 4 — while
- # the streams are STILL running (release not set). This is the core
- # property: generation concurrency exceeds _MAX_CONCURRENT_BATCHES.
- assert not release.is_set()
- assert peak_concurrent == n_streams, (
- f"expected {n_streams} concurrent generation streams, "
- f"got peak={peak_concurrent} (still capped by _batch_sem?)"
- )
- assert concurrent == n_streams, "streams should still be running (release not set)"
- # The streams are tracked for graceful drain.
- assert len(loop._in_flight_generate_tasks) == n_streams
- # ``_batch_sem`` was released once the batch dispatched (NOT when the
- # streams finish) — so it is back to full even though n_streams >
- # _MAX_CONCURRENT_BATCHES streams are still in flight.
- assert loop._batch_sem._value == _MAX_CONCURRENT_BATCHES
-
- # Cleanup: release the streams and let the tasks finish.
- release.set()
- await asyncio.gather(*tuple(loop._in_flight_generate_tasks), return_exceptions=True)
- for _ in range(5):
- await asyncio.sleep(0)
-
- @pytest.mark.asyncio
- async def test_generate_streams_drained_on_stop(self) -> None:
- """stop() drains in-flight generation streams (graceful shutdown)."""
- nc = AsyncMock()
- js = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, js=js, registry=registry)
- loop._running = True
- loop._pull_task = None
-
- completed = False
-
- async def slow_stream() -> None:
- nonlocal completed
- await asyncio.sleep(0.05)
- completed = True
-
- task = asyncio.create_task(slow_stream())
- loop._in_flight_generate_tasks.add(task)
- task.add_done_callback(loop._in_flight_generate_tasks.discard)
-
- await loop.stop()
-
- assert completed
- assert len(loop._in_flight_generate_tasks) == 0
-
-
-class TestGenerateDispatchExceptionHandling:
- """BUG 3 regression: an unexpected exception escaping
- ``StreamingProcessor.process`` must NOT leave the JetStream message
- unsettled (→ redelivery storm + KV leak) nor surface as an
- unobserved-task-exception. The dispatch wrapper must NAK the message and
- log/observe the exception.
- """
-
- @pytest.mark.asyncio
- async def test_unhandled_process_exception_naks_and_is_observed(self, caplog: pytest.LogCaptureFixture) -> None:
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
- registry.is_loaded.return_value = True
-
- loop = _make_loop(nc=nc, registry=registry)
-
- # Make the REAL ``process`` run but force an internal failure: any
- # exception beyond the ``msgpack.unpackb`` guard escapes ``process``.
- # Monkeypatch ``_process_inner`` (called inside ``process`` after the
- # span opens) to raise.
- async def _boom(*_a: Any, **_k: Any) -> None:
- raise RuntimeError("kaboom-internal")
-
- loop._streaming_processor._process_inner = _boom # type: ignore[method-assign]
-
- msg = _make_msg(
- _make_work_item(
- operation="generate",
- generate={"prompt": "hi", "max_new_tokens": 8},
- )
- )
-
- with caplog.at_level(logging.ERROR):
- await loop._process_generate_items("test/model", [(_make_work_item(operation="generate"), msg)])
- # Let the dispatched task run to completion.
- tasks = tuple(loop._in_flight_generate_tasks)
- results = await asyncio.gather(*tasks, return_exceptions=True)
-
- # The dispatched task must NOT propagate the exception (it's handled
- # in the wrapper) — so gather sees clean results, not the RuntimeError.
- assert all(not isinstance(r, BaseException) for r in results), (
- f"exception escaped the dispatch wrapper (unobserved): {results!r}"
- )
- # The message was NAK'd for redelivery (not silently dropped).
- msg.nak.assert_awaited()
- msg.ack.assert_not_awaited()
- # The exception was logged/observed.
- assert any("kaboom-internal" in rec.getMessage() or rec.exc_info for rec in caplog.records), (
- "expected the unhandled exception to be logged"
- )
-
-
-class TestPayloadStoreFactory:
- """Tests for _create_payload_store factory function."""
-
- def test_gs_url_returns_gcs_store(self) -> None:
- """gs:// URLs return a _GCSPayloadStore."""
- from sie_server.nats_pull_loop import _create_payload_store, _GCSPayloadStore
-
- store = _create_payload_store("gs://my-bucket/payloads")
- assert isinstance(store, _GCSPayloadStore)
- assert store._bucket_name == "my-bucket"
- assert store._prefix == "payloads"
-
- def test_s3_url_returns_s3_store(self) -> None:
- """s3:// URLs return an _S3PayloadStore."""
- from sie_server.nats_pull_loop import _create_payload_store, _S3PayloadStore
-
- store = _create_payload_store("s3://my-bucket/payloads")
- assert isinstance(store, _S3PayloadStore)
- assert store._bucket == "my-bucket"
- assert store._prefix == "payloads"
-
- def test_local_path_returns_local_store(self) -> None:
- """Local paths return a _LocalPayloadStore."""
- from sie_server.nats_pull_loop import _create_payload_store, _LocalPayloadStore
-
- store = _create_payload_store("/tmp/payloads") # noqa: S108
- assert isinstance(store, _LocalPayloadStore)
-
- def test_none_returns_none(self) -> None:
- """None URL returns None."""
- from sie_server.nats_pull_loop import _create_payload_store
-
- assert _create_payload_store(None) is None
-
- def test_empty_string_returns_none(self) -> None:
- """Empty string URL returns None."""
- from sie_server.nats_pull_loop import _create_payload_store
-
- assert _create_payload_store("") is None
-
-
-class TestOptionsGroupingNestedDicts:
- """Verify options grouping handles nested dicts (e.g., adapter_options with lists)."""
-
- @pytest.mark.asyncio
- async def test_nested_options_group_correctly(self) -> None:
- """Items with nested options dicts (lists, nested dicts) group correctly and don't crash."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
- fake_timing = RequestTiming()
-
- # Items with nested options containing lists and nested dicts
- messages = [
- _make_msg(
- _make_work_item(
- work_item_id="req-1.0",
- item_index=0,
- item={"text": "a"},
- output_types=["dense"],
- options={"adapter_options": {"lora": [1, 2, 3]}, "pooling": "mean"},
- )
- ),
- _make_msg(
- _make_work_item(
- work_item_id="req-1.1",
- item_index=1,
- item={"text": "b"},
- output_types=["dense"],
- options={"adapter_options": {"lora": [1, 2, 3]}, "pooling": "mean"},
- )
- ),
- _make_msg(
- _make_work_item(
- work_item_id="req-1.2",
- item_index=2,
- item={"text": "c"},
- output_types=["dense"],
- options={"adapter_options": {"lora": [4, 5]}, "pooling": "cls"},
- )
- ),
- ]
-
- call_counts: list[int] = []
-
- async def mock_run_encode(**kwargs):
- n = len(kwargs["items"])
- call_counts.append(n)
- return [{"dense": [0.1]} for _ in range(n)], fake_timing
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=mock_run_encode,
- ) as mock_encode:
- await loop._process_messages("test/model", messages)
-
- # 2 groups: first two items share options, third has different options
- assert mock_encode.call_count == 2
- assert sorted(call_counts) == [1, 2]
-
- @pytest.mark.asyncio
- async def test_deeply_nested_options_do_not_crash(self) -> None:
- """Options with deeply nested structures (dict of dict of list) don't TypeError."""
- nc = AsyncMock()
- registry = MagicMock()
- registry.model_names = ["test/model"]
- registry.get_config.return_value = MagicMock()
-
- loop = _make_loop(nc=nc, registry=registry)
- fake_timing = RequestTiming()
-
- deep_options = {
- "adapter": {
- "weights": {"layer_0": [0.1, 0.2], "layer_1": [0.3, 0.4]},
- "mode": "inference",
- }
- }
-
- messages = [
- _make_msg(
- _make_work_item(
- work_item_id="req-1.0",
- item_index=0,
- item={"text": "deep"},
- output_types=["dense"],
- options=deep_options,
- )
- ),
- ]
-
- async def mock_run_encode(**kwargs):
- n = len(kwargs["items"])
- return [{"dense": [0.1]} for _ in range(n)], fake_timing
-
- with patch(
- "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
- new_callable=AsyncMock,
- side_effect=mock_run_encode,
- ) as mock_encode:
- # Should not raise TypeError from tuple(sorted(...)) on nested dicts
- await loop._process_messages("test/model", messages)
- mock_encode.assert_called_once()
diff --git a/packages/sie_server/tests/test_parity_run_batch.py b/packages/sie_server/tests/test_parity_run_batch.py
new file mode 100644
index 000000000..2205235e1
--- /dev/null
+++ b/packages/sie_server/tests/test_parity_run_batch.py
@@ -0,0 +1,332 @@
+"""Fixture tests for the RunBatch IPC contract.
+
+These tests load shared fixtures from ``<repo-root>/tests/parity/`` and
+assert that the Python adapter call loop
+(``sie_server.adapter_call_loop.handle_run_batch``) produces the
+canonical outcome shape declared in each fixture.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+from unittest.mock import AsyncMock
+
+import pytest
+from sie_server.adapter_call_loop import handle_run_batch
+from sie_server.ipc_types import (
+ BatchOutcome,
+ EncodeBatchItem,
+ ExtractBatchItem,
+ ItemOutcome,
+ RunBatchItem,
+ RunBatchRequest,
+ ScoreBatchItem,
+)
+
+# Resolve the shared fixtures directory once. Walks up from this test
+# file rather than hard-coding a path so the test still works inside
+# the workspace's various build / install layouts (uv venv vs.
+# editable install vs. CI tarball).
+PARITY_FIXTURES_DIR = Path(__file__).resolve().parent.parent.parent.parent / "tests" / "parity"
+
+# Explicit fixture list (rather than glob) so the test reports each
+# fixture as a separate pytest case with a stable id.
+PARITY_FIXTURES: tuple[str, ...] = (
+ "run_batch_empty.json",
+ "run_batch_encode_no_lora.json",
+ "run_batch_encode_lora.json",
+ "run_batch_extract_lora.json",
+ "run_batch_mixed_op.json",
+ "run_batch_score_basic.json",
+ "run_batch_score_lora_warns.json",
+ "run_batch_unknown_op.json",
+)
+
+
+@dataclass(frozen=True)
+class CanonicalOutcome:
+ """Subset of ItemOutcome fields that must be parity-stable.
+
+ Backend-specific fields (timing, raw inference bytes) are NOT in
+ this struct; the fixture ``notes.elided_fields`` lists them
+ explicitly and the comparator below ignores them.
+ """
+
+ work_item_id: str
+ request_id: str
+ item_index: int
+ disposition: str
+ error_code: str | None
+
+ @classmethod
+ def from_item_outcome(cls, oc: ItemOutcome) -> CanonicalOutcome:
+ return cls(
+ work_item_id=oc.work_item_id,
+ request_id=oc.request_id,
+ item_index=oc.item_index,
+ disposition=oc.disposition,
+ error_code=oc.error_code,
+ )
+
+ @classmethod
+ def from_fixture_dict(cls, d: dict[str, Any]) -> CanonicalOutcome:
+ return cls(
+ work_item_id=d["work_item_id"],
+ request_id=d["request_id"],
+ item_index=d["item_index"],
+ disposition=d["disposition"],
+ error_code=d.get("error_code"),
+ )
+
+
+def _build_encode(d: dict[str, Any]) -> EncodeBatchItem:
+ return EncodeBatchItem(
+ work_item_id=d["work_item_id"],
+ request_id=d["request_id"],
+ item_index=d["item_index"],
+ total_items=d["total_items"],
+ timestamp=d["timestamp"],
+ item=d["item"],
+ options=d.get("options"),
+ )
+
+
+def _build_score(d: dict[str, Any]) -> ScoreBatchItem:
+ return ScoreBatchItem(
+ work_item_id=d["work_item_id"],
+ request_id=d["request_id"],
+ item_index=d["item_index"],
+ total_items=d["total_items"],
+ timestamp=d["timestamp"],
+ query_item=d["query_item"],
+ score_items=d["score_items"],
+ options=d.get("options"),
+ )
+
+
+def _build_extract(d: dict[str, Any]) -> ExtractBatchItem:
+ return ExtractBatchItem(
+ work_item_id=d["work_item_id"],
+ request_id=d["request_id"],
+ item_index=d["item_index"],
+ total_items=d["total_items"],
+ timestamp=d["timestamp"],
+ item=d["item"],
+ labels=d.get("labels"),
+ output_schema=d.get("output_schema"),
+ options=d.get("options"),
+ )
+
+
+def _build_request(input_spec: dict[str, Any]) -> RunBatchRequest:
+ """Materialise an in-memory RunBatchRequest from a fixture's ``input``.
+
+ The fixture uses the same wire shape that ``msgspec.convert`` would
+ accept off the UDS, but the Python tests construct the typed
+ structs directly to keep msgspec out of the parity equation (we
+ want this test to fail on real divergence, not on
+ msgspec-vs-fixture-format quirks).
+ """
+ items: list[RunBatchItem] = []
+ for raw in input_spec["items"]:
+ encode = _build_encode(raw["encode"]) if raw.get("encode") is not None else None
+ score = _build_score(raw["score"]) if raw.get("score") is not None else None
+ extract = _build_extract(raw["extract"]) if raw.get("extract") is not None else None
+ items.append(
+ RunBatchItem(
+ op=raw["op"],
+ work_item_id=raw.get("work_item_id", ""),
+ request_id=raw.get("request_id", ""),
+ item_index=raw.get("item_index", 0),
+ encode=encode,
+ score=score,
+ extract=extract,
+ )
+ )
+ return RunBatchRequest(
+ model_id=input_spec["model_id"],
+ batch_id=input_spec["batch_id"],
+ lora_key=input_spec["lora_key"],
+ total_cost=input_spec["total_cost"],
+ items=items,
+ )
+
+
+def _assert_lora_invariant(
+ op: str,
+ items: list[Any],
+ expected_lora_in_options: str | None,
+) -> None:
+ """Per-item assertion for the lora-key plumbing contract.
+
+ * ``expected_lora_in_options is not None`` and op in {encode,
+ extract} → every item must arrive with options['lora'] == expected.
+ * ``expected_lora_in_options is None`` → no item may have options['lora']
+ set at all (the base fast path is required to be allocation-free
+ and indistinguishable from a non-LoRA deploy).
+ * ``op == "score"`` → score is base-only on both backends; a
+ non-empty wire-level lora_key is dropped with a WARN, so even
+ when ``expected_lora_in_options`` is provided we expect items
+ to arrive WITHOUT options['lora'].
+ """
+ if op == "score":
+ # Score never propagates lora_key into options regardless of
+ # the wire-level value. This pins the WARN-and-serve-base
+ # contract.
+ for it in items:
+ if it.options is not None:
+ assert "lora" not in it.options, (
+ f"parity violation: score item {it.work_item_id!r} arrived "
+ f"with options['lora']={it.options.get('lora')!r}; "
+ f"score is base-only — the dispatcher must NOT inject "
+ f"options['lora'] on the score path."
+ )
+ return
+
+ if expected_lora_in_options is None:
+ for it in items:
+ if it.options is not None:
+ assert "lora" not in it.options, (
+ f"parity violation: {op} item {it.work_item_id!r} arrived "
+ f"with options['lora']={it.options.get('lora')!r} but the "
+ f"fixture's expected_lora_in_options is null. Empty "
+ f"lora_key MUST resolve to no injection (base fast path)."
+ )
+ return
+
+ for it in items:
+ assert it.options is not None, (
+ f"parity violation: {op} item {it.work_item_id!r} arrived without "
+ f"options even though RunBatchRequest.lora_key was non-empty. The "
+ f"_dispatch_{op} path must inject lora_key into options['lora']."
+ )
+ assert it.options.get("lora") == expected_lora_in_options, (
+ f"parity violation on {op} item {it.work_item_id!r}: expected "
+ f"options['lora']={expected_lora_in_options!r}, got "
+ f"{it.options.get('lora')!r}."
+ )
+
+
+def _make_echo_executor(
+ expected_lora_in_options: str | None,
+) -> AsyncMock:
+ """Mock executor whose ``process_*_batch`` echoes its inputs.
+
+ Echoing per-item identifiers (rather than emitting opaque
+ ``ok.0`` / ``ok.1`` placeholders the way the Rust ``MockAdapter``
+ historically did) lets the parity comparator check that
+ work_item_id / request_id / item_index round-trip through the
+ dispatcher unchanged. That is part of the wire contract: the
+ publisher uses these to correlate outcomes back to NATS work
+ items.
+
+ Asserts the per-op LoRA-injection invariant via
+ :func:`_assert_lora_invariant` for whichever ``process_*_batch``
+ method gets called.
+ """
+
+ def _echo(op: str) -> AsyncMock:
+ async def _impl(req: Any) -> BatchOutcome:
+ _assert_lora_invariant(op, req.items, expected_lora_in_options)
+ return BatchOutcome(
+ outcomes=[
+ ItemOutcome(
+ work_item_id=it.work_item_id,
+ request_id=it.request_id,
+ item_index=it.item_index,
+ disposition="publish_and_ack",
+ result_msgpack=b"\x80",
+ )
+ for it in req.items
+ ]
+ )
+
+ return AsyncMock(side_effect=_impl)
+
+ exe = AsyncMock()
+ exe.process_encode_batch = _echo("encode")
+ exe.process_score_batch = _echo("score")
+ exe.process_extract_batch = _echo("extract")
+ return exe
+
+
+# --------------------------------------------------------------------
+# Fixture-driven parity test
+# --------------------------------------------------------------------
+
+
[email protected]("fixture_name", PARITY_FIXTURES, ids=lambda n: n[:-5])
+async def test_parity_run_batch(fixture_name: str) -> None:
+ fixture_path = PARITY_FIXTURES_DIR / fixture_name
+ assert fixture_path.exists(), (
+ f"parity fixture missing: {fixture_path}; keep PARITY_FIXTURES in sync with tests/parity/."
+ )
+ fixture = json.loads(fixture_path.read_text())
+
+ request = _build_request(fixture["input"])
+ expected_lora = fixture.get("expected_lora_in_options")
+ executor = _make_echo_executor(expected_lora)
+
+ actual = await handle_run_batch(executor, request)
+
+ expected_canonical = [CanonicalOutcome.from_fixture_dict(d) for d in fixture["expected_canonical_outcomes"]]
+ actual_canonical = [CanonicalOutcome.from_item_outcome(oc) for oc in actual.outcomes]
+
+ # Pinpoint diffs by element-by-element comparison rather than a
+ # single list equality so the failure message names the specific
+ # outcome index that drifted. (List equality lights up the whole
+ # list in pytest's diff which is harder to read.)
+ assert len(actual_canonical) == len(expected_canonical), (
+ f"parity violation on {fixture_name}: outcome count drift "
+ f"(expected {len(expected_canonical)}, got {len(actual_canonical)}); "
+ f"actual outcomes: {actual_canonical}"
+ )
+ for i, (got, want) in enumerate(zip(actual_canonical, expected_canonical, strict=True)):
+ assert got == want, (
+ f"parity violation in {fixture_name} at outcome[{i}]:\n expected: {want}\n got: {got}"
+ )
+
+ # Sanity-check that the right per-op handler was invoked (and not
+ # short-circuited by an empty-batch / mixed-op early-return).
+ # Empty / rejected batches don't reach any handler.
+ if not request.items:
+ executor.process_encode_batch.assert_not_awaited()
+ executor.process_score_batch.assert_not_awaited()
+ executor.process_extract_batch.assert_not_awaited()
+ return
+
+ ops = {it.op for it in request.items}
+ if len(ops) > 1: # mixed-op batch — wholesale rejected, no handler call
+ executor.process_encode_batch.assert_not_awaited()
+ executor.process_score_batch.assert_not_awaited()
+ executor.process_extract_batch.assert_not_awaited()
+ return
+
+ op = next(iter(ops))
+ if op == "encode":
+ # Some encode fixtures (e.g. all-invalid encode payloads) might
+ # short-circuit on the "no valid items" branch; gate the
+ # assertion on whether any encode item actually has a payload.
+ if any(it.encode is not None for it in request.items):
+ executor.process_encode_batch.assert_awaited_once()
+ executor.process_score_batch.assert_not_awaited()
+ executor.process_extract_batch.assert_not_awaited()
+ elif op == "score":
+ if any(it.score is not None for it in request.items):
+ executor.process_score_batch.assert_awaited_once()
+ executor.process_encode_batch.assert_not_awaited()
+ executor.process_extract_batch.assert_not_awaited()
+ elif op == "extract":
+ if any(it.extract is not None for it in request.items):
+ executor.process_extract_batch.assert_awaited_once()
+ executor.process_encode_batch.assert_not_awaited()
+ executor.process_score_batch.assert_not_awaited()
+ else:
+ # Unknown op → wholesale rejected, no handler should fire.
+ executor.process_encode_batch.assert_not_awaited()
+ executor.process_score_batch.assert_not_awaited()
+ executor.process_extract_batch.assert_not_awaited()
diff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.py
new file mode 100644
index 000000000..39d6b3706
--- /dev/null
+++ b/packages/sie_server/tests/test_queue_executor.py
@@ -0,0 +1,724 @@
+from __future__ import annotations
+
+import asyncio
+import time
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import msgpack
+import numpy as np
+import pytest
+from sie_server.core.inference_output import 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
+
+
+def _make_registry(*, loaded: bool = True, loading: bool = False) -> MagicMock:
+ reg = MagicMock()
+ reg.model_names = ["test/model"]
+ reg.device = "cpu"
+ reg.is_loaded.return_value = loaded
+ reg.is_loading.return_value = loading
+ reg.get_config.return_value = MagicMock()
+ return reg
+
+
+def _encode_item(
+ *,
+ wiid: str = "req-1.0",
+ item: dict | None = None,
+ output_types: list[str] | None = None,
+ instruction: str | None = None,
+ is_query: bool = False,
+ options: dict | None = None,
+ item_index: int = 0,
+) -> EncodeBatchItem:
+ return EncodeBatchItem(
+ work_item_id=wiid,
+ request_id=wiid.split(".", maxsplit=1)[0],
+ item_index=item_index,
+ total_items=1,
+ timestamp=time.time(),
+ item=item or {"text": "hello"},
+ output_types=output_types,
+ instruction=instruction,
+ is_query=is_query,
+ options=options,
+ )
+
+
+def _score_item() -> ScoreBatchItem:
+ return 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"}],
+ )
+
+
+def _extract_item() -> ExtractBatchItem:
+ return ExtractBatchItem(
+ work_item_id="req-1.0",
+ request_id="req-1",
+ item_index=0,
+ total_items=1,
+ timestamp=time.time(),
+ item={"text": "Alice works at Acme."},
+ labels=["person"],
+ )
+
+
+# -----------------------------------------------------------------------------
+# ensure_model_ready
+# -----------------------------------------------------------------------------
+
+
+class TestEnsureModelReady:
+ @pytest.mark.asyncio
+ async def test_loaded_returns_ready(self) -> None:
+ reg = _make_registry(loaded=True)
+ ex = QueueExecutor(reg)
+ assert await ex.ensure_model_ready("test/model") == "ready"
+ reg.start_load_async.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_already_loading_returns_in_progress(self) -> None:
+ reg = _make_registry(loaded=False, loading=True)
+ ex = QueueExecutor(reg)
+ assert await ex.ensure_model_ready("test/model") == "loading_in_progress"
+ reg.start_load_async.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_triggers_new_load(self) -> None:
+ reg = _make_registry(loaded=False, loading=False)
+ reg.start_load_async = AsyncMock(return_value=True)
+ ex = QueueExecutor(reg)
+ assert await ex.ensure_model_ready("test/model") == "loading_started"
+ reg.start_load_async.assert_awaited_once_with("test/model", "cpu")
+
+ @pytest.mark.asyncio
+ async def test_start_load_already_running_returns_in_progress(self) -> None:
+ reg = _make_registry(loaded=False, loading=False)
+ reg.start_load_async = AsyncMock(return_value=False) # already loading/loaded in another task
+ ex = QueueExecutor(reg)
+ assert await ex.ensure_model_ready("test/model") == "loading_in_progress"
+
+ @pytest.mark.asyncio
+ async def test_unknown_model_returns_retry_later(self) -> None:
+ reg = _make_registry(loaded=False, loading=False)
+ reg.start_load_async = AsyncMock(side_effect=KeyError("test/model"))
+ ex = QueueExecutor(reg)
+ assert await ex.ensure_model_ready("test/model") == "retry_later"
+
+
+class TestGetBatchBudget:
+ """Per-model batch budget advertised to the Rust queue consumer via
+ EnsureModelReadyResponse.
+ """
+
+ def test_returns_max_batch_requests_when_worker_has_batch_config(self) -> None:
+ reg = _make_registry()
+ worker = MagicMock()
+ worker._batch_config = MagicMock(max_batch_requests=37)
+ reg.get_worker.return_value = worker
+ ex = QueueExecutor(reg)
+ assert ex.get_batch_budget("test/model") == 37
+
+ def test_returns_none_when_worker_missing(self) -> None:
+ reg = _make_registry()
+ reg.get_worker.return_value = None
+ ex = QueueExecutor(reg)
+ assert ex.get_batch_budget("test/model") is None
+
+ def test_returns_none_when_worker_has_no_batch_config(self) -> None:
+ reg = _make_registry()
+ worker = object() # no `_batch_config` attribute
+ reg.get_worker.return_value = worker
+ ex = QueueExecutor(reg)
+ assert ex.get_batch_budget("test/model") is None
+
+ def test_returns_none_when_registry_raises(self) -> None:
+ reg = _make_registry()
+ reg.get_worker.side_effect = KeyError("test/model")
+ ex = QueueExecutor(reg)
+ assert ex.get_batch_budget("test/model") is None
+
+ def test_returns_none_when_budget_is_non_int(self) -> None:
+ # Protect the wire: a misconfigured BatchConfig with a non-int
+ # max_batch_requests should not leak a MagicMock / string / None
+ # into the IPC response where msgspec would choke on it.
+ reg = _make_registry()
+ worker = MagicMock()
+ worker._batch_config = MagicMock(max_batch_requests="64") # str, not int
+ reg.get_worker.return_value = worker
+ ex = QueueExecutor(reg)
+ assert ex.get_batch_budget("test/model") is None
+
+ def test_returns_none_when_budget_is_non_positive(self) -> None:
+ reg = _make_registry()
+ worker = MagicMock()
+ worker._batch_config = MagicMock(max_batch_requests=0)
+ reg.get_worker.return_value = worker
+ ex = QueueExecutor(reg)
+ assert ex.get_batch_budget("test/model") is None
+
+
+# -----------------------------------------------------------------------------
+# process_encode_batch
+# -----------------------------------------------------------------------------
+
+
+class TestProcessEncodeBatch:
+ @pytest.mark.asyncio
+ async def test_single_item_publish_and_ack(self) -> None:
+ reg = _make_registry()
+ ex = QueueExecutor(reg)
+
+ fake_outputs = [{"dense": [0.1, 0.2]}]
+ fake_timing = RequestTiming()
+
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ return_value=(fake_outputs, fake_timing),
+ ) as mock_encode:
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(model_id="test/model", items=[_encode_item()])
+ )
+
+ assert len(outcome.outcomes) == 1
+ item = outcome.outcomes[0]
+ assert item.disposition == "publish_and_ack"
+ assert item.result_msgpack is not None
+ inner = msgpack.unpackb(item.result_msgpack, raw=False)
+ assert inner == {"dense": [0.1, 0.2]}
+ mock_encode.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_model_evicted_naks_all(self) -> None:
+ reg = _make_registry()
+ reg.get_config.side_effect = KeyError("test/model")
+ ex = QueueExecutor(reg)
+
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id="test/model",
+ items=[_encode_item(wiid="a.0"), _encode_item(wiid="b.0", item_index=1)],
+ )
+ )
+ assert len(outcome.outcomes) == 2
+ assert all(o.disposition == "nak_retry" for o in outcome.outcomes)
+ assert all((o.nak_delay_ms or 0) > 0 for o in outcome.outcomes)
+
+ @pytest.mark.asyncio
+ async def test_pipeline_exception_error_outcome(self) -> None:
+ reg = _make_registry()
+ ex = QueueExecutor(reg)
+
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("boom"),
+ ):
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(model_id="test/model", items=[_encode_item()])
+ )
+
+ assert len(outcome.outcomes) == 1
+ assert outcome.outcomes[0].disposition == "publish_error_and_ack"
+ assert outcome.outcomes[0].error_code == "inference_error"
+ assert "boom" in (outcome.outcomes[0].error or "")
+
+ @pytest.mark.asyncio
+ async def test_pipeline_oom_naks_without_publishing_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_OOM_NAK_DELAY_S", "11.0")
+ reg = _make_registry()
+ ex = QueueExecutor(reg)
+
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("CUDA out of memory. Tried to allocate 1.00 GiB"),
+ ):
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(model_id="test/model", items=[_encode_item()])
+ )
+
+ assert len(outcome.outcomes) == 1
+ assert outcome.outcomes[0].disposition == "nak_retry"
+ assert outcome.outcomes[0].nak_delay_ms == 11_000
+ assert outcome.outcomes[0].error_code is None
+ assert outcome.outcomes[0].error is None
+
+ @pytest.mark.asyncio
+ async def test_heterogeneous_batch_groups_by_params(self) -> None:
+ """Items with different (output_types, instruction, is_query, options) run as separate sub-batches."""
+ reg = _make_registry()
+ ex = QueueExecutor(reg)
+
+ call_count = 0
+ observed_output_types: list[list[str]] = []
+
+ async def fake_run_encode(**kwargs):
+ nonlocal call_count
+ call_count += 1
+ observed_output_types.append(kwargs["output_types"])
+ n = len(kwargs["items"])
+ return [{"dense": [float(call_count)]} for _ in range(n)], 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/model",
+ items=[
+ _encode_item(wiid="a.0", output_types=["dense"]),
+ _encode_item(wiid="b.0", output_types=["dense"], item_index=1),
+ _encode_item(wiid="c.0", output_types=["sparse"], item_index=2),
+ ],
+ )
+ )
+
+ assert call_count == 2
+ assert sorted([tuple(ot) for ot in observed_output_types]) == [("dense",), ("sparse",)]
+ assert len(outcome.outcomes) == 3
+ assert all(o.disposition == "publish_and_ack" for o in outcome.outcomes)
+ # Outcomes preserve input order regardless of grouping.
+ assert [o.work_item_id for o in outcome.outcomes] == ["a.0", "b.0", "c.0"]
+
+ @pytest.mark.asyncio
+ async def test_output_ordering_matches_input(self) -> None:
+ reg = _make_registry()
+ ex = QueueExecutor(reg)
+
+ fake_outputs = [{"dense": [float(i)]} for i in range(3)]
+ fake_timing = RequestTiming()
+
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ return_value=(fake_outputs, fake_timing),
+ ):
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id="test/model",
+ items=[
+ _encode_item(wiid="a.0", item_index=0),
+ _encode_item(wiid="b.0", item_index=1),
+ _encode_item(wiid="c.0", item_index=2),
+ ],
+ )
+ )
+
+ assert [o.work_item_id for o in outcome.outcomes] == ["a.0", "b.0", "c.0"]
+
+ @pytest.mark.asyncio
+ async def test_records_ipc_batch_shape_metric(self) -> None:
+ """process_encode_batch emits a fragmentation observation with
+ items==N and sub_groups==distinct(output_types, instruction, ...).
+
+ Guards the invariant that dashboards reading
+ `sie_ipc_batch_sub_groups / sie_ipc_batch_items` will correctly
+ reflect how many separate GPU forward passes the IPC batch
+ split into — that's the entire reason the metric exists.
+ """
+ reg = _make_registry()
+ ex = QueueExecutor(reg)
+
+ async def fake_run_encode(**kwargs):
+ n = len(kwargs["items"])
+ return [{"dense": [0.0]} for _ in range(n)], RequestTiming()
+
+ with (
+ patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new=AsyncMock(side_effect=fake_run_encode),
+ ),
+ patch("sie_server.queue_executor.record_ipc_batch_shape") as mock_record,
+ ):
+ await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id="test/model",
+ items=[
+ _encode_item(wiid="a.0", output_types=["dense"]),
+ _encode_item(wiid="b.0", output_types=["dense"], item_index=1),
+ _encode_item(wiid="c.0", output_types=["dense"], item_index=2),
+ _encode_item(wiid="d.0", output_types=["sparse"], item_index=3),
+ _encode_item(wiid="e.0", output_types=["sparse"], item_index=4),
+ ],
+ )
+ )
+
+ mock_record.assert_called_once()
+ kwargs = mock_record.call_args.kwargs
+ assert kwargs["model"] == "test/model"
+ assert kwargs["endpoint"] == "encode"
+ assert kwargs["total_items"] == 5
+ assert sorted(kwargs["sub_group_sizes"]) == [2, 3]
+
+ @pytest.mark.asyncio
+ async def test_ipc_batch_shape_recorded_even_when_pipeline_fails(self) -> None:
+ """Shape metric is observed before any forward pass runs, so
+ failed batches still populate the fragmentation histogram.
+ This keeps dashboards honest under error storms (otherwise
+ they'd under-report IPC batch volume).
+ """
+ reg = _make_registry()
+ ex = QueueExecutor(reg)
+
+ with (
+ patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new=AsyncMock(side_effect=RuntimeError("boom")),
+ ),
+ patch("sie_server.queue_executor.record_ipc_batch_shape") as mock_record,
+ ):
+ await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id="test/model",
+ items=[_encode_item(wiid="a.0"), _encode_item(wiid="b.0", item_index=1)],
+ )
+ )
+
+ mock_record.assert_called_once()
+ kwargs = mock_record.call_args.kwargs
+ assert kwargs["total_items"] == 2
+ assert kwargs["sub_group_sizes"] == [2]
+
+
+# -----------------------------------------------------------------------------
+# process_score_batch
+# -----------------------------------------------------------------------------
+
+
+class TestProcessScoreBatch:
+ @pytest.mark.asyncio
+ async def test_single_item_publish_and_ack(self) -> None:
+ reg = _make_registry()
+ worker = AsyncMock()
+ score_output = ScoreOutput(scores=np.array([0.9, 0.1], dtype=np.float32))
+ wr = WorkerResult(output=score_output, timing=RequestTiming())
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_result(wr)
+ worker.submit_score = AsyncMock(return_value=fut)
+ reg.start_worker = AsyncMock(return_value=worker)
+
+ ex = QueueExecutor(reg)
+ outcome = await ex.process_score_batch(
+ 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"}],
+ )
+ ],
+ )
+ )
+
+ assert len(outcome.outcomes) == 1
+ o = outcome.outcomes[0]
+ assert o.disposition == "publish_and_ack"
+ # Score output is Rust-frameable. The legacy ``result_msgpack``
+ # is None; the parallel arrays land on ``raw_output.score`` and
+ # ``sie_server_sidecar::output::build_score_payload`` does
+ # the descending stable sort + rank assignment byte-identically.
+ assert o.result_msgpack is None
+ assert o.raw_output is not None
+ assert o.raw_output.score is not None
+ assert o.raw_output.score.item_ids == ["doc-a", "doc-b"]
+ assert o.raw_output.score.scores == pytest.approx([0.9, 0.1])
+
+ @pytest.mark.asyncio
+ async def test_model_evicted_naks_individual_item(self) -> None:
+ reg = _make_registry()
+ reg.start_worker = AsyncMock(side_effect=KeyError("test/model"))
+ ex = QueueExecutor(reg)
+
+ outcome = await ex.process_score_batch(
+ 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"}],
+ )
+ ],
+ )
+ )
+ assert outcome.outcomes[0].disposition == "nak_retry"
+
+ @pytest.mark.asyncio
+ async def test_score_oom_naks_without_publishing_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_OOM_NAK_DELAY_S", "12.0")
+ reg = _make_registry()
+ worker = AsyncMock()
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_exception(RuntimeError("MPS backend out of memory"))
+ worker.submit_score = AsyncMock(return_value=fut)
+ reg.start_worker = AsyncMock(return_value=worker)
+
+ ex = QueueExecutor(reg)
+ outcome = await ex.process_score_batch(ProcessScoreBatchRequest(model_id="test/model", items=[_score_item()]))
+
+ assert outcome.outcomes[0].disposition == "nak_retry"
+ assert outcome.outcomes[0].nak_delay_ms == 12_000
+ assert outcome.outcomes[0].error_code is None
+ assert outcome.outcomes[0].error is None
+
+ @pytest.mark.asyncio
+ async def test_records_ipc_batch_shape(self) -> None:
+ """Score submits one task per IPC item, so the fragmentation
+ metric must report sub_groups == items. Any deviation means
+ the queue executor changed its dispatch strategy without
+ updating the dashboard semantics.
+ """
+ reg = _make_registry()
+ worker = AsyncMock()
+ score_output = ScoreOutput(scores=np.array([0.5], dtype=np.float32))
+ wr = WorkerResult(output=score_output, timing=RequestTiming())
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_result(wr)
+ worker.submit_score = AsyncMock(return_value=fut)
+ reg.start_worker = AsyncMock(return_value=worker)
+
+ ex = QueueExecutor(reg)
+
+ with patch("sie_server.queue_executor.record_ipc_batch_shape") as mock_record:
+ await ex.process_score_batch(
+ ProcessScoreBatchRequest(
+ model_id="test/model",
+ items=[
+ ScoreBatchItem(
+ work_item_id=f"req-{i}.0",
+ request_id=f"req-{i}",
+ item_index=0,
+ total_items=1,
+ timestamp=time.time(),
+ query_item={"text": "q"},
+ score_items=[{"text": "a"}],
+ )
+ for i in range(4)
+ ],
+ )
+ )
+
+ mock_record.assert_called_once()
+ kwargs = mock_record.call_args.kwargs
+ assert kwargs["endpoint"] == "score"
+ assert kwargs["total_items"] == 4
+ assert kwargs["sub_group_sizes"] == [1, 1, 1, 1]
+
+
+# -----------------------------------------------------------------------------
+# process_extract_batch
+# -----------------------------------------------------------------------------
+
+
+class TestProcessExtractBatch:
+ @pytest.mark.asyncio
+ async def test_single_item_publish_and_ack(self) -> None:
+ reg = _make_registry()
+ worker = AsyncMock()
+ extract_output = ExtractOutput(
+ entities=[[{"text": "Alice", "label": "person", "score": 0.99, "start": 0, "end": 5}]]
+ )
+ wr = WorkerResult(output=extract_output, timing=RequestTiming())
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_result(wr)
+ worker.submit_extract = AsyncMock(return_value=fut)
+ reg.start_worker = AsyncMock(return_value=worker)
+
+ ex = QueueExecutor(reg)
+ outcome = await ex.process_extract_batch(
+ 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={"text": "Alice works at Acme."},
+ labels=["person"],
+ )
+ ],
+ )
+ )
+
+ assert outcome.outcomes[0].disposition == "publish_and_ack"
+ inner = msgpack.unpackb(outcome.outcomes[0].result_msgpack, raw=False)
+ assert "entities" in inner
+
+ @pytest.mark.asyncio
+ async def test_model_evicted_naks(self) -> None:
+ reg = _make_registry()
+ reg.start_worker = AsyncMock(side_effect=RuntimeError("evicted"))
+ ex = QueueExecutor(reg)
+ outcome = await ex.process_extract_batch(
+ 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={"text": "x"},
+ )
+ ],
+ )
+ )
+ assert outcome.outcomes[0].disposition == "nak_retry"
+
+ @pytest.mark.asyncio
+ async def test_extract_oom_naks_without_publishing_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_OOM_NAK_DELAY_S", "13.0")
+ reg = _make_registry()
+ worker = AsyncMock()
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_exception(RuntimeError("CUDA out of memory"))
+ worker.submit_extract = AsyncMock(return_value=fut)
+ reg.start_worker = AsyncMock(return_value=worker)
+
+ ex = QueueExecutor(reg)
+ outcome = await ex.process_extract_batch(
+ ProcessExtractBatchRequest(model_id="test/model", items=[_extract_item()])
+ )
+
+ assert outcome.outcomes[0].disposition == "nak_retry"
+ assert outcome.outcomes[0].nak_delay_ms == 13_000
+ assert outcome.outcomes[0].error_code is None
+ assert outcome.outcomes[0].error is None
+
+ @pytest.mark.asyncio
+ async def test_records_ipc_batch_shape(self) -> None:
+ """Extract is also per-item dispatch; same semantics as score."""
+ reg = _make_registry()
+ worker = AsyncMock()
+ extract_output = ExtractOutput(entities=[[]])
+ wr = WorkerResult(output=extract_output, timing=RequestTiming())
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_result(wr)
+ worker.submit_extract = AsyncMock(return_value=fut)
+ reg.start_worker = AsyncMock(return_value=worker)
+
+ ex = QueueExecutor(reg)
+
+ with patch("sie_server.queue_executor.record_ipc_batch_shape") as mock_record:
+ await ex.process_extract_batch(
+ ProcessExtractBatchRequest(
+ model_id="test/model",
+ items=[
+ ExtractBatchItem(
+ work_item_id=f"req-{i}.0",
+ request_id=f"req-{i}",
+ item_index=0,
+ total_items=1,
+ timestamp=time.time(),
+ item={"text": "x"},
+ )
+ for i in range(3)
+ ],
+ )
+ )
+
+ mock_record.assert_called_once()
+ kwargs = mock_record.call_args.kwargs
+ assert kwargs["endpoint"] == "extract"
+ assert kwargs["total_items"] == 3
+ assert kwargs["sub_group_sizes"] == [1, 1, 1]
+
+
+# -----------------------------------------------------------------------------
+# _wrap_encode_output: queue path MUST match HTTP wire shape for every
+# output_type the SDK understands. Otherwise HTTP and queue consumers
+# see different encodings for the same model.
+# -----------------------------------------------------------------------------
+
+
+class TestWrapEncodeOutput:
+ @staticmethod
+ def _config(
+ *,
+ dense_dim: int | None = None,
+ sparse_dim: int | None = None,
+ multivector_dim: int | None = None,
+ ) -> MagicMock:
+ encode_task = MagicMock()
+ encode_task.dense = MagicMock(dim=dense_dim) if dense_dim is not None else None
+ encode_task.sparse = MagicMock(dim=sparse_dim) if sparse_dim is not None else None
+ encode_task.multivector = MagicMock(dim=multivector_dim) if multivector_dim is not None else None
+ cfg = MagicMock()
+ cfg.tasks = MagicMock(encode=encode_task)
+ return cfg
+
+ def test_dense_float32_wraps_with_dims_and_dtype(self) -> None:
+ from sie_server.queue_executor import _wrap_encode_output
+
+ arr = np.zeros(768, dtype=np.float32)
+ wrapped = _wrap_encode_output({"dense": arr}, self._config(dense_dim=768))
+ assert wrapped["dense"]["dims"] == 768
+ assert wrapped["dense"]["dtype"] == "float32"
+ assert np.array_equal(wrapped["dense"]["values"], arr)
+
+ def test_sparse_wraps_like_http_format_sparse(self) -> None:
+ from sie_server.queue_executor import _wrap_encode_output
+
+ indices = np.array([1, 7, 42], dtype=np.int64)
+ values = np.array([0.1, 0.2, 0.3], dtype=np.float32)
+ wrapped = _wrap_encode_output(
+ {"sparse": {"indices": indices, "values": values}},
+ self._config(sparse_dim=30522),
+ )
+ sp = wrapped["sparse"]
+ assert sp["dims"] == 30522
+ assert sp["dtype"] == "float32"
+ assert np.array_equal(sp["indices"], indices)
+ assert np.array_equal(sp["values"], values)
+
+ def test_multivector_wraps_with_token_dims_and_num_tokens(self) -> None:
+ from sie_server.queue_executor import _wrap_encode_output
+
+ arr = np.zeros((12, 128), dtype=np.float32)
+ wrapped = _wrap_encode_output({"multivector": arr}, self._config(multivector_dim=128))
+ mv = wrapped["multivector"]
+ assert mv["token_dims"] == 128
+ assert mv["num_tokens"] == 12
+ assert mv["dtype"] == "float32"
+ assert np.array_equal(mv["values"], arr)
+
+ def test_binary_multivector_sets_dtype_binary(self) -> None:
+ from sie_server.queue_executor import _wrap_encode_output
+
+ arr = np.zeros((7, 16), dtype=np.uint8) # 128-dim packed into 16 bytes/token
+ wrapped = _wrap_encode_output({"multivector": arr}, self._config(multivector_dim=128))
+ mv = wrapped["multivector"]
+ assert mv["token_dims"] == 128
+ assert mv["num_tokens"] == 7
+ assert mv["dtype"] == "binary"
diff --git a/packages/sie_server/tests/test_queue_executor_stage1d.py b/packages/sie_server/tests/test_queue_executor_stage1d.py
new file mode 100644
index 000000000..9893eb50a
--- /dev/null
+++ b/packages/sie_server/tests/test_queue_executor_stage1d.py
@@ -0,0 +1,622 @@
+"""Rust output-framing tests for ``QueueExecutor``.
+
+The gate is per-request: ``_maybe_*_raw_output`` returns a typed
+``RawOutput`` whenever the adapter's response is the exact single-key,
+float32, well-shaped form the Rust framing path knows how to encode
+byte-identically; otherwise the legacy ``msgpack.packb`` path runs. See
+the sidecar runtime architecture guide at
+``packages/sie_server_sidecar/docs/architecture-guide.md`` (component/crate
+name ``sie_server_sidecar``) for the full rationale.
+
+These tests pin:
+
+* The per-helper safety rules (single output key, float32 dtype,
+ multi-output items fall back, dim-mismatch falls back, ...).
+* End-to-end wiring of ``process_encode_batch`` /
+ ``process_score_batch``: dense / sparse / multivector / score requests
+ that meet the safety rules emit a typed ``RawOutput``. Multi-output /
+ non-float32 / float16 paths continue to fall back to ``result_msgpack``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import msgpack_numpy
+import numpy as np
+import pytest
+from sie_server.core.inference_output import ScoreOutput
+from sie_server.core.timing import RequestTiming
+from sie_server.core.worker.types import WorkerResult
+from sie_server.ipc_types import (
+ EncodeBatchItem,
+ ProcessEncodeBatchRequest,
+ ProcessScoreBatchRequest,
+ ScoreBatchItem,
+)
+from sie_server.queue_executor import (
+ QueueExecutor,
+ _maybe_dense_raw_output,
+ _maybe_multivector_raw_output,
+ _maybe_sparse_raw_output,
+)
+
+# The Python-framed reference path (``msgpack.packb(output, use_bin_type=True)``
+# inside ``QueueExecutor.process_encode_batch``) relies on
+# ``msgpack_numpy.patch()`` being active to serialise the ``np.ndarray``
+# ``dense``/``sparse``/``multivector`` payloads. Production wires this
+# through ``sie_server.api.serialization`` at import time. This test
+# module exercises that path directly, so we activate the patch here
+# as well — a no-op when another module already did it.
+msgpack_numpy.patch()
+
+MODEL_ID = "test/model"
+
+
+def _make_registry() -> MagicMock:
+ reg = MagicMock()
+ reg.model_names = [MODEL_ID]
+ reg.device = "cpu"
+ reg.is_loaded.return_value = True
+ reg.is_loading.return_value = False
+ config = MagicMock()
+ config.tasks.encode.dense.dim = 4
+ reg.get_config.return_value = config
+ return reg
+
+
+def _encode_item(
+ wiid: str = "req-1.0",
+ *,
+ output_types: list[str] | None = None,
+ item_index: int = 0,
+) -> EncodeBatchItem:
+ return EncodeBatchItem(
+ work_item_id=wiid,
+ request_id=wiid.split(".", maxsplit=1)[0],
+ item_index=item_index,
+ total_items=1,
+ timestamp=time.time(),
+ item={"text": "hello"},
+ output_types=output_types,
+ )
+
+
+# -----------------------------------------------------------------------------
+# Dense fast-path gate (per-request shape rules)
+# -----------------------------------------------------------------------------
+
+
+class TestDenseFastPathGate:
+ def _config(self, dim: int = 4) -> MagicMock:
+ cfg = MagicMock()
+ cfg.tasks.encode.dense.dim = dim
+ return cfg
+
+ def test_float32_dense_is_eligible(self) -> None:
+ arr = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
+ raw = _maybe_dense_raw_output({"dense": arr}, self._config(), ["dense"])
+ assert raw is not None
+ assert raw.dense is not None
+ assert raw.dense.dim == 4
+ assert raw.dense.values == [1.0, 2.0, 3.0, 4.0]
+ assert raw.dense.normalize is False
+
+ def test_non_float32_dense_is_skipped(self) -> None:
+ for dtype in (np.float16, np.int8, np.uint8):
+ arr = np.ones(4, dtype=dtype)
+ assert _maybe_dense_raw_output({"dense": arr}, self._config(), ["dense"]) is None
+
+ def test_sparse_or_multivector_disables_fastpath(self) -> None:
+ dense = np.ones(4, dtype=np.float32)
+ formatted = {
+ "dense": dense,
+ "sparse": {"indices": np.array([0, 1]), "values": np.array([0.1, 0.2], dtype=np.float32)},
+ }
+ assert _maybe_dense_raw_output(formatted, self._config(), ["dense", "sparse"]) is None
+
+ def test_multiple_output_types_disables_fastpath(self) -> None:
+ arr = np.ones(4, dtype=np.float32)
+ assert _maybe_dense_raw_output({"dense": arr}, self._config(), ["dense", "multivector"]) is None
+
+ def test_dim_mismatch_falls_back(self) -> None:
+ # Adapter returned 5 dims but config says 4 — do NOT take the
+ # fast path; let the legacy path mis-label consistently with
+ # the existing Python code.
+ arr = np.ones(5, dtype=np.float32)
+ assert _maybe_dense_raw_output({"dense": arr}, self._config(dim=4), ["dense"]) is None
+
+ def test_non_array_input_is_skipped(self) -> None:
+ # The mocked EncodeHandler in tests sometimes emits plain lists;
+ # the fast-path must not crash, it must fall back silently.
+ assert _maybe_dense_raw_output({"dense": [0.1, 0.2, 0.3, 0.4]}, self._config(), ["dense"]) is None
+
+
+# -----------------------------------------------------------------------------
+# process_encode_batch — Rust output framing is unconditional when safe
+# -----------------------------------------------------------------------------
+
+
+class TestProcessEncodeBatchRustOutputFraming:
+ @pytest.mark.asyncio
+ async def test_dense_emits_raw_output_by_default(self) -> None:
+ """Dense output framing is on by default. Any single-output
+ float32 dense item produces a typed ``RawOutput`` and leaves
+ ``result_msgpack`` at ``None`` for the Rust publisher to fill in.
+ """
+ reg = _make_registry()
+ ex = QueueExecutor(reg)
+
+ arr = np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float32)
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ return_value=([{"dense": arr}], RequestTiming()),
+ ):
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id=MODEL_ID,
+ items=[_encode_item(output_types=["dense"])],
+ ),
+ )
+
+ o = outcome.outcomes[0]
+ assert o.disposition == "publish_and_ack"
+ assert o.raw_output is not None
+ assert o.result_msgpack is None
+ assert o.raw_output.dense is not None
+ dense = o.raw_output.dense
+ assert dense.dim == 4
+ assert np.array(dense.values, dtype=np.float32).tolist() == arr.tolist()
+ assert dense.normalize is False
+
+ @pytest.mark.asyncio
+ async def test_multi_output_falls_back_to_legacy_path(self) -> None:
+ """Per-request safety rule: an item requesting dense + sparse
+ does NOT produce a typed ``RawOutput`` — the v1 wire contract
+ is one variant per ``RawOutput``. The Rust publisher then sees
+ the legacy ``result_msgpack`` and ships it through unchanged.
+ """
+ reg = _make_registry()
+ ex = QueueExecutor(reg)
+
+ dense = np.array([0.1, 0.2, 0.3, 0.4], dtype=np.float32)
+ sparse = {
+ "indices": np.array([1, 2], dtype=np.int64),
+ "values": np.array([0.5, 0.6], dtype=np.float32),
+ }
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ return_value=([{"dense": dense, "sparse": sparse}], RequestTiming()),
+ ):
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id=MODEL_ID,
+ items=[_encode_item(output_types=["dense", "sparse"])],
+ ),
+ )
+
+ o = outcome.outcomes[0]
+ assert o.raw_output is None
+ assert o.result_msgpack is not None
+
+
+# -----------------------------------------------------------------------------
+# process_score_batch — score is always Rust-frameable
+# -----------------------------------------------------------------------------
+
+
+class TestProcessScoreBatchRustOutputFraming:
+ def _make_score_item(self, wiid: str = "req-1.0") -> ScoreBatchItem:
+ return ScoreBatchItem(
+ work_item_id=wiid,
+ request_id=wiid.split(".", maxsplit=1)[0],
+ 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"},
+ {"text": "c", "id": "doc-c"},
+ ],
+ )
+
+ async def _run_score(self, reg: MagicMock, scores: list[float]):
+ worker = AsyncMock()
+ score_output = ScoreOutput(scores=np.array(scores, dtype=np.float32))
+ wr = WorkerResult(output=score_output, timing=RequestTiming())
+ fut: asyncio.Future[WorkerResult] = asyncio.Future()
+ fut.set_result(wr)
+ worker.submit_score = AsyncMock(return_value=fut)
+ reg.start_worker = AsyncMock(return_value=worker)
+
+ ex = QueueExecutor(reg)
+ return await ex.process_score_batch(
+ ProcessScoreBatchRequest(model_id=MODEL_ID, items=[self._make_score_item()]),
+ )
+
+ @pytest.mark.asyncio
+ async def test_score_emits_raw_parallel_arrays_in_input_order_unconditionally(
+ self,
+ ) -> None:
+ """Score is always Rust-frameable. The Python adapter ships the
+ unsorted parallel arrays; Rust does the descending stable sort
+ + rank assignment in
+ ``sie_server_sidecar::output::build_score_payload``.
+ """
+ outcome = await self._run_score(_make_registry(), [0.1, 0.9, 0.5])
+
+ o = outcome.outcomes[0]
+ assert o.disposition == "publish_and_ack"
+ assert o.result_msgpack is None
+ assert o.raw_output is not None
+ assert o.raw_output.score is not None
+ score = o.raw_output.score
+ # Critical: input order is preserved; sort happens in Rust.
+ assert score.item_ids == ["doc-a", "doc-b", "doc-c"]
+ # ``float(np.float32(x))`` widening — Rust narrows back to f32
+ # losslessly, and the production Python path uses the same
+ # widening too (see ``_process_single_score``).
+ assert score.scores == pytest.approx([0.1, 0.9, 0.5])
+
+
+# -----------------------------------------------------------------------------
+# Sparse fast-path gate (_maybe_sparse_raw_output) — per-request rules
+# -----------------------------------------------------------------------------
+
+
+class TestSparseFastPathGate:
+ def _config(self, dim: int | None = 30522) -> MagicMock:
+ cfg = MagicMock()
+ cfg.tasks.encode.sparse.dim = dim
+ return cfg
+
+ def test_int_indices_float32_values_eligible(self) -> None:
+ formatted = {
+ "sparse": {
+ "indices": np.array([3, 7, 42], dtype=np.int32),
+ "values": np.array([0.5, 1.5, 2.5], dtype=np.float32),
+ },
+ }
+ raw = _maybe_sparse_raw_output(formatted, self._config(), ["sparse"])
+ assert raw is not None
+ assert raw.sparse is not None
+ assert raw.sparse.indices == [3, 7, 42]
+ assert raw.sparse.values == [0.5, 1.5, 2.5]
+ assert raw.sparse.dims == 30522
+
+ def test_float16_values_falls_back(self) -> None:
+ formatted = {
+ "sparse": {
+ "indices": np.array([1, 2], dtype=np.int32),
+ "values": np.array([0.1, 0.2], dtype=np.float16),
+ },
+ }
+ assert _maybe_sparse_raw_output(formatted, self._config(), ["sparse"]) is None
+
+ def test_multi_output_falls_back(self) -> None:
+ formatted = {
+ "sparse": {
+ "indices": np.array([1, 2], dtype=np.int32),
+ "values": np.array([0.1, 0.2], dtype=np.float32),
+ },
+ "dense": np.ones(4, dtype=np.float32),
+ }
+ assert _maybe_sparse_raw_output(formatted, self._config(), ["sparse", "dense"]) is None
+
+
+# -----------------------------------------------------------------------------
+# Multivector fast-path gate (_maybe_multivector_raw_output) — per-request rules
+# -----------------------------------------------------------------------------
+
+
+class TestMultivectorFastPathGate:
+ def _config(self, mv_dim: int = 4) -> MagicMock:
+ cfg = MagicMock()
+ cfg.tasks.encode.multivector.dim = mv_dim
+ return cfg
+
+ def test_float32_2d_array_eligible(self) -> None:
+ arr = np.arange(12, dtype=np.float32).reshape(3, 4)
+ raw = _maybe_multivector_raw_output({"multivector": arr}, self._config(), ["multivector"])
+ assert raw is not None
+ assert raw.multivector is not None
+ assert raw.multivector.num_tokens == 3
+ assert raw.multivector.token_dims == 4
+
+ def test_float16_2d_array_falls_back(self) -> None:
+ arr = np.zeros((2, 4), dtype=np.float16)
+ assert _maybe_multivector_raw_output({"multivector": arr}, self._config(), ["multivector"]) is None
+
+ def test_bit_packed_binary_falls_back(self) -> None:
+ # ``shape[1] < mv_dim`` signals binary multivector packed into
+ # bytes; framing in Rust isn't supported yet, must fall back.
+ arr = np.zeros((3, 1), dtype=np.uint8)
+ assert _maybe_multivector_raw_output({"multivector": arr}, self._config(mv_dim=8), ["multivector"]) is None
+
+
+# -----------------------------------------------------------------------------
+# process_encode_batch — sparse + multivector end-to-end
+# -----------------------------------------------------------------------------
+
+
+class TestProcessEncodeBatchSparseMV:
+ def _sparse_registry(self, sparse_dim: int = 30522) -> MagicMock:
+ reg = MagicMock()
+ reg.model_names = [MODEL_ID]
+ reg.device = "cpu"
+ reg.is_loaded.return_value = True
+ reg.is_loading.return_value = False
+ config = MagicMock()
+ config.tasks.encode.sparse.dim = sparse_dim
+ reg.get_config.return_value = config
+ return reg
+
+ def _mv_registry(self, mv_dim: int = 4) -> MagicMock:
+ reg = MagicMock()
+ reg.model_names = [MODEL_ID]
+ reg.device = "cpu"
+ reg.is_loaded.return_value = True
+ reg.is_loading.return_value = False
+ config = MagicMock()
+ config.tasks.encode.multivector.dim = mv_dim
+ reg.get_config.return_value = config
+ return reg
+
+ @pytest.mark.asyncio
+ async def test_sparse_emits_raw_output_unconditionally(self) -> None:
+ reg = self._sparse_registry()
+ ex = QueueExecutor(reg)
+
+ formatted = {
+ "sparse": {
+ "indices": np.array([3, 7, 42], dtype=np.int32),
+ "values": np.array([0.5, 1.5, 2.5], dtype=np.float32),
+ },
+ }
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ return_value=([formatted], RequestTiming()),
+ ):
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id=MODEL_ID,
+ items=[_encode_item(output_types=["sparse"])],
+ ),
+ )
+
+ o = outcome.outcomes[0]
+ assert o.disposition == "publish_and_ack"
+ assert o.result_msgpack is None
+ assert o.raw_output is not None
+ assert o.raw_output.sparse is not None
+ assert o.raw_output.sparse.indices == [3, 7, 42]
+ assert o.raw_output.sparse.dims == 30522
+
+ @pytest.mark.asyncio
+ async def test_multivector_emits_raw_output_unconditionally(self) -> None:
+ reg = self._mv_registry()
+ ex = QueueExecutor(reg)
+
+ arr = np.arange(12, dtype=np.float32).reshape(3, 4)
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ return_value=([{"multivector": arr}], RequestTiming()),
+ ):
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id=MODEL_ID,
+ items=[_encode_item(output_types=["multivector"])],
+ ),
+ )
+
+ o = outcome.outcomes[0]
+ assert o.disposition == "publish_and_ack"
+ assert o.result_msgpack is None
+ assert o.raw_output is not None
+ assert o.raw_output.multivector is not None
+ mv = o.raw_output.multivector
+ assert mv.num_tokens == 3
+ assert mv.token_dims == 4
+ assert len(mv.values) == 12
+
+ @pytest.mark.asyncio
+ async def test_float16_multivector_falls_back(self) -> None:
+ """Per-request safety net: a model that returns a dtype the
+ Rust shaper doesn't yet understand must produce correct bytes
+ via the legacy path — never a silent mis-frame.
+ """
+ reg = self._mv_registry()
+ ex = QueueExecutor(reg)
+
+ arr = np.zeros((2, 4), dtype=np.float16)
+ with patch(
+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",
+ new_callable=AsyncMock,
+ return_value=([{"multivector": arr}], RequestTiming()),
+ ):
+ outcome = await ex.process_encode_batch(
+ ProcessEncodeBatchRequest(
+ model_id=MODEL_ID,
+ items=[_encode_item(output_types=["multivector"])],
+ ),
+ )
+
+ o = outcome.outcomes[0]
+ assert o.raw_output is None
+ assert o.result_msgpack is not None
+
+
+# -----------------------------------------------------------------------------
+# Score legacy-path verification — the unsorted/sorted equivalence
+# -----------------------------------------------------------------------------
+
+
+class TestScoreLegacySortParity:
+ """Score is always emitted as an unsorted ``RawOutput``.
+ Pin the Rust-side sort+rank semantics by re-implementing the
+ Python-framed fallback path in test code and asserting equivalence to the
+ raw arrays — this is the contract Rust mirrors in
+ ``sie_server_sidecar::output::build_score_payload``.
+ """
+
+ def test_legacy_sort_matches_input_arrays(self) -> None:
+ item_ids = ["doc-a", "doc-b", "doc-c"]
+ raw_scores = [0.1, 0.9, 0.5]
+
+ # Legacy Python path (kept here as the spec the Rust framing mirrors).
+ scored = list(zip(item_ids, raw_scores, strict=True))
+ scored.sort(key=lambda x: x[1], reverse=True)
+ legacy = [{"item_id": item_id, "score": sc, "rank": rank} for rank, (item_id, sc) in enumerate(scored)]
+ assert [e["item_id"] for e in legacy] == ["doc-b", "doc-c", "doc-a"]
+ assert [e["rank"] for e in legacy] == [0, 1, 2]
+
+
+# -----------------------------------------------------------------------------
+# ModelDescriptor handshake
+# -----------------------------------------------------------------------------
+
+
+class TestGetModelDescriptor:
+ """Cover ``QueueExecutor.get_model_descriptor`` and tokenizer materialisation.
+
+ The dispatcher re-handshakes on every batch so we pin two contracts:
+
+ 1. The descriptor carries the right tokenizer_id / max_seq_len.
+ 2. Subsequent calls hit the per-model cache (no extra file I/O,
+ no extra calls into the preprocessor registry).
+ """
+
+ def _descriptor_registry(self, *, tokenizer_id: str, max_len: int, canonical: bytes) -> MagicMock:
+ """Build a registry whose ``preprocessor_registry`` returns a
+ preprocessor that mimics the production ``TextPreprocessor``
+ contract: a ``tokenizer_id`` property returning a real ``str``
+ and a ``_tokenizer.backend_tokenizer.to_str`` returning real
+ canonical JSON bytes.
+ """
+ reg = MagicMock()
+ reg.model_names = [MODEL_ID]
+ reg.is_loaded.return_value = True
+ reg.is_loading.return_value = False
+ reg.get_worker.return_value = MagicMock() # any non-None object satisfies the gate
+
+ backend = MagicMock()
+ backend.to_str.return_value = canonical.decode("utf-8")
+ inner = MagicMock()
+ inner.backend_tokenizer = backend
+ inner.model_max_length = max_len
+
+ preprocessor = MagicMock()
+ type(preprocessor).tokenizer_id = property(lambda _self: tokenizer_id)
+ preprocessor._tokenizer = inner
+
+ reg.preprocessor_registry.get_preprocessor.return_value = preprocessor
+ return reg
+
+ def test_descriptor_carries_tokenizer_id_and_max_seq_len(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ ) -> None:
+ # Point the staging dir at the test's tmp dir so we don't
+ # litter ``$TMPDIR/sie-tokenizers`` and so different test
+ # runs don't see each other's files.
+ monkeypatch.setattr(
+ "sie_server.queue_executor._TOKENIZER_STAGING_DIR",
+ tmp_path,
+ )
+ canonical = b'{"version":"1.0","model":{"type":"WordLevel"}}'
+ reg = self._descriptor_registry(tokenizer_id="abc123", max_len=512, canonical=canonical)
+ ex = QueueExecutor(reg)
+
+ descriptor = ex.get_model_descriptor(MODEL_ID)
+ assert descriptor is not None
+ assert descriptor.tokenizer_id == "abc123"
+ assert descriptor.max_seq_len == 512
+ assert descriptor.supports_run_batch is True
+ assert descriptor.tokenizer_path is not None
+ # The materialised file lives under the per-model dir and
+ # holds the canonical bytes byte-for-byte. The sidecar will
+ # hash this on load and reconcile against ``tokenizer_id``.
+ assert Path(descriptor.tokenizer_path).read_bytes() == canonical
+
+ def test_descriptor_is_cached_per_model(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ ) -> None:
+ monkeypatch.setattr(
+ "sie_server.queue_executor._TOKENIZER_STAGING_DIR",
+ tmp_path,
+ )
+ canonical = b'{"version":"1.0"}'
+ reg = self._descriptor_registry(tokenizer_id="abc", max_len=128, canonical=canonical)
+ ex = QueueExecutor(reg)
+
+ first = ex.get_model_descriptor(MODEL_ID)
+ second = ex.get_model_descriptor(MODEL_ID)
+ # Same struct object → cache hit, no re-materialisation, no
+ # re-call into the preprocessor registry. Three calls total
+ # are allowed (other code paths in this test file may have
+ # called it earlier on this fixture); the contract we pin is
+ # "exactly one call by ``get_model_descriptor``".
+ assert first is second
+ # ``get_preprocessor`` should have been invoked exactly once
+ # by the two ``get_model_descriptor`` calls above (the second
+ # short-circuited at the cache).
+ assert reg.preprocessor_registry.get_preprocessor.call_count == 1
+
+ def test_invalidate_clears_cache(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ ) -> None:
+ monkeypatch.setattr(
+ "sie_server.queue_executor._TOKENIZER_STAGING_DIR",
+ tmp_path,
+ )
+ canonical = b'{"version":"1.0"}'
+ reg = self._descriptor_registry(tokenizer_id="v1", max_len=128, canonical=canonical)
+ ex = QueueExecutor(reg)
+
+ assert ex.get_model_descriptor(MODEL_ID) is not None
+ ex.invalidate_model_descriptor(MODEL_ID)
+ # After invalidation we expect a fresh registry call.
+ ex.get_model_descriptor(MODEL_ID)
+ assert reg.preprocessor_registry.get_preprocessor.call_count == 2
+
+ def test_unsane_max_length_reads_as_unset(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ ) -> None:
+ """HF defaults ``model_max_length`` to ``int(1e30)`` when no
+ cap is declared; the descriptor must report ``None`` rather
+ than ship a bogus billion-token cap to the sidecar.
+ """
+ monkeypatch.setattr(
+ "sie_server.queue_executor._TOKENIZER_STAGING_DIR",
+ tmp_path,
+ )
+ reg = self._descriptor_registry(
+ tokenizer_id="v1",
+ max_len=int(1e30),
+ canonical=b'{"version":"1.0"}',
+ )
+ ex = QueueExecutor(reg)
+ descriptor = ex.get_model_descriptor(MODEL_ID)
+ assert descriptor is not None
+ assert descriptor.max_seq_len is None
+
+ def test_returns_none_when_model_not_loaded(self) -> None:
+ reg = MagicMock()
+ reg.get_worker.return_value = None
+ ex = QueueExecutor(reg)
+ assert ex.get_model_descriptor("any/model") is None
diff --git a/packages/sie_server/tests/test_readiness.py b/packages/sie_server/tests/test_readiness.py
new file mode 100644
index 000000000..e071c0c7e
--- /dev/null
+++ b/packages/sie_server/tests/test_readiness.py
@@ -0,0 +1,53 @@
+from __future__ import annotations
+
+import pytest
+from sie_server.core import readiness
+
+
[email protected](autouse=True)
+def _reset_readiness_state():
+ readiness.register_liveness_probe(None)
+ readiness.mark_not_ready()
+ yield
+ readiness.register_liveness_probe(None)
+ readiness.mark_not_ready()
+
+
+def test_default_state_is_not_ready() -> None:
+ assert readiness.is_ready() is False
+
+
+def test_mark_ready_without_probe() -> None:
+ readiness.mark_ready()
+ assert readiness.is_ready() is True
+
+
+def test_mark_not_ready_is_sticky_until_mark_ready() -> None:
+ readiness.mark_ready()
+ readiness.mark_not_ready()
+ assert readiness.is_ready() is False
+
+
+def test_liveness_probe_false_blocks_ready() -> None:
+ readiness.mark_ready()
+ readiness.register_liveness_probe(lambda: False)
+ assert readiness.is_ready() is False
+
+
+def test_liveness_probe_true_allows_ready() -> None:
+ readiness.mark_ready()
+ readiness.register_liveness_probe(lambda: True)
+ assert readiness.is_ready() is True
+
+
+def test_liveness_probe_does_not_override_not_ready() -> None:
+ readiness.register_liveness_probe(lambda: True)
+ assert readiness.is_ready() is False
+
+
+def test_clearing_probe_with_none_restores_plain_ready_semantics() -> None:
+ readiness.mark_ready()
+ readiness.register_liveness_probe(lambda: False)
+ assert readiness.is_ready() is False
+ readiness.register_liveness_probe(None)
+ assert readiness.is_ready() is True
diff --git a/packages/sie_server/tests/test_server_smoke.py b/packages/sie_server/tests/test_server_smoke.py
index 485a58b03..bafe1ffe9 100644
--- a/packages/sie_server/tests/test_server_smoke.py
+++ b/packages/sie_server/tests/test_server_smoke.py
@@ -4,5 +4,11 @@ import sie_server
def test_import() -> None:
- """Verify package can be imported."""
- assert sie_server.__version__ == "0.1.0"
+ """Verify package can be imported and exposes a sensible __version__.
+
+ We don't pin an exact version string here — the version is sourced from
+ installed package metadata — but it must be non-empty so downstream code
+ that logs or reports it doesn't print an empty string.
+ """
+ assert isinstance(sie_server.__version__, str)
+ assert sie_server.__version__
diff --git a/packages/sie_server/tests/test_stage1d_byte_identity.py b/packages/sie_server/tests/test_stage1d_byte_identity.py
new file mode 100644
index 000000000..a9293cd9a
--- /dev/null
+++ b/packages/sie_server/tests/test_stage1d_byte_identity.py
@@ -0,0 +1,393 @@
+"""Rust output-framing byte-identity: Python legacy path == Rust shaper.
+
+This test establishes the equivalence:
+
+ legacy_python_bytes(input) == rust_shaped_bytes(input)
+
+by pinning **both** sides to the same hex goldens. The matching Rust
+assertion lives in crate ``sie_server_sidecar`` at repo path
+``packages/sie_server_sidecar/src/output/mod.rs`` as ``GOLDEN_DENSE_123`` /
+``GOLDEN_SCORE_AB`` — if either language's
+test breaks, the mismatch is immediately visible and the
+non-destructive output-framing contract (same wire bytes either way) is
+violated before any production traffic sees drift.
+
+Update protocol: if you change the Python wire shape here, update
+**both** goldens in lockstep. Never silently re-baseline just one
+side.
+"""
+
+from __future__ import annotations
+
+import msgpack
+import msgpack_numpy
+import numpy as np
+from sie_server.queue_executor import _wrap_encode_output
+
+msgpack_numpy.patch()
+
+# Must match ``sie_server_sidecar::output::tests::GOLDEN_DENSE_123``.
+GOLDEN_DENSE_123 = bytes(
+ [
+ 0x81,
+ 0xA5,
+ 0x64,
+ 0x65,
+ 0x6E,
+ 0x73,
+ 0x65,
+ 0x83,
+ 0xA4,
+ 0x64,
+ 0x69,
+ 0x6D,
+ 0x73,
+ 0x03,
+ 0xA5,
+ 0x64,
+ 0x74,
+ 0x79,
+ 0x70,
+ 0x65,
+ 0xA7,
+ 0x66,
+ 0x6C,
+ 0x6F,
+ 0x61,
+ 0x74,
+ 0x33,
+ 0x32,
+ 0xA6,
+ 0x76,
+ 0x61,
+ 0x6C,
+ 0x75,
+ 0x65,
+ 0x73,
+ 0x85,
+ 0xC4,
+ 0x02,
+ 0x6E,
+ 0x64,
+ 0xC3,
+ 0xC4,
+ 0x04,
+ 0x74,
+ 0x79,
+ 0x70,
+ 0x65,
+ 0xA3,
+ 0x3C,
+ 0x66,
+ 0x34,
+ 0xC4,
+ 0x04,
+ 0x6B,
+ 0x69,
+ 0x6E,
+ 0x64,
+ 0xC4,
+ 0x00,
+ 0xC4,
+ 0x05,
+ 0x73,
+ 0x68,
+ 0x61,
+ 0x70,
+ 0x65,
+ 0x91,
+ 0x03,
+ 0xC4,
+ 0x04,
+ 0x64,
+ 0x61,
+ 0x74,
+ 0x61,
+ 0xC4,
+ 0x0C,
+ 0x00,
+ 0x00,
+ 0x80,
+ 0x3F,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x40,
+ 0x00,
+ 0x00,
+ 0x40,
+ 0x40,
+ ],
+)
+
+
+# Must match ``sie_server_sidecar::output::tests::GOLDEN_SCORE_AB``.
+GOLDEN_SCORE_AB = bytes(
+ [
+ 0x92,
+ 0x83,
+ 0xA7,
+ 0x69,
+ 0x74,
+ 0x65,
+ 0x6D,
+ 0x5F,
+ 0x69,
+ 0x64,
+ 0xA1,
+ 0x61,
+ 0xA5,
+ 0x73,
+ 0x63,
+ 0x6F,
+ 0x72,
+ 0x65,
+ 0xCB,
+ 0x3F,
+ 0xEC,
+ 0xCC,
+ 0xCC,
+ 0xC0,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0xA4,
+ 0x72,
+ 0x61,
+ 0x6E,
+ 0x6B,
+ 0x00,
+ 0x83,
+ 0xA7,
+ 0x69,
+ 0x74,
+ 0x65,
+ 0x6D,
+ 0x5F,
+ 0x69,
+ 0x64,
+ 0xA1,
+ 0x62,
+ 0xA5,
+ 0x73,
+ 0x63,
+ 0x6F,
+ 0x72,
+ 0x65,
+ 0xCB,
+ 0x3F,
+ 0xE0,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0x00,
+ 0xA4,
+ 0x72,
+ 0x61,
+ 0x6E,
+ 0x6B,
+ 0x01,
+ ],
+)
+
+
+class _FakeDenseConfig:
+ """Minimal stand-in for the production encode config — only the
+ fields ``_wrap_encode_output`` actually reads.
+ """
+
+ class _Tasks:
+ class _Encode:
+ class _Dense:
+ dim = 3
+
+ dense = _Dense()
+
+ encode = _Encode()
+
+ tasks = _Tasks()
+
+
+def test_legacy_dense_matches_rust_golden() -> None:
+ """Legacy Python path (``_wrap_encode_output`` + ``msgpack.packb``
+ with ``msgpack_numpy`` active) must produce the exact bytes the
+ Rust ``build_dense_payload`` shaper asserts against.
+ """
+ arr = np.array([1.0, 2.0, 3.0], dtype=np.float32)
+ wrapped = _wrap_encode_output({"dense": arr}, _FakeDenseConfig())
+ assert isinstance(wrapped["dense"], dict)
+ bytes_out = msgpack.packb(wrapped, use_bin_type=True)
+ assert bytes_out == GOLDEN_DENSE_123, (
+ "Python legacy dense bytes diverged from the Rust shaper golden — "
+ "update BOTH sides in lockstep (crate sie_server_sidecar, see "
+ "packages/sie_server_sidecar/src/output/mod.rs::tests::GOLDEN_DENSE_123)."
+ )
+
+
+def test_legacy_score_matches_rust_golden() -> None:
+ """Legacy Python path (manual sort + dict list + ``msgpack.packb``)
+ must produce the same bytes as ``build_score_payload`` emits for
+ the identical input.
+ """
+ scores_raw = np.array([0.9, 0.5], dtype=np.float32)
+ item_ids = ["a", "b"]
+
+ scored = sorted(
+ zip(item_ids, (float(s) for s in scores_raw), strict=True),
+ key=lambda x: x[1],
+ reverse=True,
+ )
+ entries = [{"item_id": item_id, "score": sc, "rank": rank} for rank, (item_id, sc) in enumerate(scored)]
+ bytes_out = msgpack.packb(entries, use_bin_type=True)
+ assert bytes_out == GOLDEN_SCORE_AB, (
+ "Python legacy score bytes diverged from the Rust shaper golden — "
+ "update BOTH sides in lockstep (crate sie_server_sidecar, see "
+ "packages/sie_server_sidecar/src/output/mod.rs::tests::GOLDEN_SCORE_AB)."
+ )
+
+
+def test_legacy_score_stable_ties_match_rust_stable_sort() -> None:
+ """Equal scores must preserve input order on both sides (Python's
+ ``list.sort`` is stable; Rust uses ``slice::sort_by`` which is
+ documented stable).
+ """
+ scores_raw = np.array([0.5, 0.5, 0.5], dtype=np.float32)
+ item_ids = ["x", "y", "z"]
+
+ scored = sorted(
+ zip(item_ids, (float(s) for s in scores_raw), strict=True),
+ key=lambda x: x[1],
+ reverse=True,
+ )
+ entries = [{"item_id": item_id, "score": sc, "rank": rank} for rank, (item_id, sc) in enumerate(scored)]
+ assert [e["item_id"] for e in entries] == ["x", "y", "z"]
+ assert [e["rank"] for e in entries] == [0, 1, 2]
+
+
+# ---------------------------------------------------------------------------
+# Sparse + multivector goldens for the Rust framing path.
+#
+# Must match:
+# * sparse (dims=None, [3,7,42] i32 / [0.5,1.5,2.5] f32)
+# → ``sie_server_sidecar::output::tests::GOLDEN_SPARSE_NIL_DIM_HEX``
+# * sparse (dims=30522, same indices/values)
+# → ``GOLDEN_SPARSE_WITH_DIM_HEX``
+# * multivector (np.arange(12, f32).reshape(3, 4))
+# → ``GOLDEN_MULTIVECTOR_3X4_HEX``
+#
+# Keep these in lockstep — the whole point is that divergence on
+# either side surfaces on the next CI run, not in production.
+# ---------------------------------------------------------------------------
+
+GOLDEN_SPARSE_NIL_DIM = bytes.fromhex(
+ "81a673706172736584a464696d73c0a56474797065a7666c6f61743332a7696e6469636573"
+ "85c4026e64c3c40474797065a33c6934c4046b696e64c400c40573686170659103c4046461"
+ "7461c40c03000000070000002a000000a676616c75657385c4026e64c3c40474797065a33c"
+ "6634c4046b696e64c400c40573686170659103c40464617461c40c0000003f0000c03f0000"
+ "2040"
+)
+
+GOLDEN_SPARSE_WITH_DIM = bytes.fromhex(
+ "81a673706172736584a464696d73cd773aa56474797065a7666c6f61743332a7696e646963"
+ "657385c4026e64c3c40474797065a33c6934c4046b696e64c400c40573686170659103c404"
+ "64617461c40c03000000070000002a000000a676616c75657385c4026e64c3c40474797065"
+ "a33c6634c4046b696e64c400c40573686170659103c40464617461c40c0000003f0000c03f"
+ "00002040"
+)
+
+GOLDEN_MULTIVECTOR_3X4 = bytes.fromhex(
+ "81ab6d756c7469766563746f7284aa746f6b656e5f64696d7304aa6e756d5f746f6b656e73"
+ "03a56474797065a7666c6f61743332a676616c75657385c4026e64c3c40474797065a33c66"
+ "34c4046b696e64c400c4057368617065920304c40464617461c430000000000000803f0000"
+ "004000004040000080400000a0400000c0400000e04000000041000010410000204100003041"
+)
+
+
+class _FakeSparseConfig:
+ class _Tasks:
+ class _Encode:
+ class _Sparse:
+ dim = 30522
+
+ sparse = _Sparse()
+
+ encode = _Encode()
+
+ tasks = _Tasks()
+
+
+class _FakeSparseConfigNoDim:
+ """Config with no sparse.dim — exercises the ``dims=None`` wire."""
+
+ class _Tasks:
+ class _Encode:
+ sparse = None
+
+ encode = _Encode()
+
+ tasks = _Tasks()
+
+
+class _FakeMultivectorConfig:
+ class _Tasks:
+ class _Encode:
+ class _Multivector:
+ dim = 4
+
+ multivector = _Multivector()
+
+ encode = _Encode()
+
+ tasks = _Tasks()
+
+
+def test_legacy_sparse_nil_dim_matches_rust_golden() -> None:
+ """``_wrap_encode_output`` + ``msgpack.packb`` with ``dims=None``
+ (no configured ``sparse.dim``) must produce the same bytes as
+ ``build_sparse_payload(indices, values, None)``.
+ """
+ formatted = {
+ "sparse": {
+ "indices": np.array([3, 7, 42], dtype=np.int32),
+ "values": np.array([0.5, 1.5, 2.5], dtype=np.float32),
+ }
+ }
+ wrapped = _wrap_encode_output(formatted, _FakeSparseConfigNoDim())
+ bytes_out = msgpack.packb(wrapped, use_bin_type=True)
+ assert bytes_out == GOLDEN_SPARSE_NIL_DIM, (
+ "Python legacy sparse (dims=None) bytes diverged from the Rust "
+ "shaper golden — update BOTH sides in lockstep (crate sie_server_sidecar, see "
+ "packages/sie_server_sidecar/src/output/mod.rs::tests::GOLDEN_SPARSE_NIL_DIM_HEX)."
+ )
+
+
+def test_legacy_sparse_with_dim_matches_rust_golden() -> None:
+ formatted = {
+ "sparse": {
+ "indices": np.array([3, 7, 42], dtype=np.int32),
+ "values": np.array([0.5, 1.5, 2.5], dtype=np.float32),
+ }
+ }
+ wrapped = _wrap_encode_output(formatted, _FakeSparseConfig())
+ bytes_out = msgpack.packb(wrapped, use_bin_type=True)
+ assert bytes_out == GOLDEN_SPARSE_WITH_DIM, (
+ "Python legacy sparse (dims=30522) bytes diverged from the Rust "
+ "shaper golden — update BOTH sides in lockstep (crate sie_server_sidecar, see "
+ "packages/sie_server_sidecar/src/output/mod.rs::tests::GOLDEN_SPARSE_WITH_DIM_HEX)."
+ )
+
+
+def test_legacy_multivector_matches_rust_golden() -> None:
+ """3 tokens x 4 dims float32 multivector. Python legacy path ==
+ ``build_multivector_payload(values, 3, 4)``.
+ """
+ arr = np.arange(12, dtype=np.float32).reshape(3, 4)
+ wrapped = _wrap_encode_output({"multivector": arr}, _FakeMultivectorConfig())
+ bytes_out = msgpack.packb(wrapped, use_bin_type=True)
+ assert bytes_out == GOLDEN_MULTIVECTOR_3X4, (
+ "Python legacy multivector bytes diverged from the Rust "
+ "shaper golden — update BOTH sides in lockstep (crate sie_server_sidecar, see "
+ "packages/sie_server_sidecar/src/output/mod.rs::tests::GOLDEN_MULTIVECTOR_3X4_HEX)."
+ )
diff --git a/packages/sie_server/tests/type_defs/test_media_bytes.py b/packages/sie_server/tests/type_defs/test_media_bytes.py
index 63c74236d..f20df864e 100644
--- a/packages/sie_server/tests/type_defs/test_media_bytes.py
+++ b/packages/sie_server/tests/type_defs/test_media_bytes.py
@@ -73,20 +73,47 @@ class TestMediaBytesRejects:
class TestWorkerErrorClassification:
- """The queue/NATS path maps InvalidMediaError to INVALID_INPUT, not inference_error."""
+ """The queue/sidecar path maps InvalidMediaError to INVALID_INPUT, not inference_error."""
def test_invalid_media_maps_to_invalid_input(self) -> None:
- from sie_server.nats_pull_loop import NatsPullLoop
+ from sie_server.ipc_types import EncodeBatchItem
+ from sie_server.queue_executor import _inference_exception_outcome
from sie_server.types.responses import ErrorCode
- code, msg = NatsPullLoop._classify_inference_exception(InvalidMediaError("image data must be bytes, got str"))
-
- assert code == ErrorCode.INVALID_INPUT.value
- assert "must be bytes" in msg
+ outcome = _inference_exception_outcome(
+ EncodeBatchItem(
+ work_item_id="wi-1",
+ request_id="req-1",
+ item_index=0,
+ total_items=1,
+ timestamp=0.0,
+ item={},
+ output_types=["dense"],
+ ),
+ InvalidMediaError("image data must be bytes, got str"),
+ )
+
+ assert outcome.disposition == "publish_error_and_ack"
+ assert outcome.error_code == ErrorCode.INVALID_INPUT.value
+ assert outcome.error is not None
+ assert "must be bytes" in outcome.error
def test_generic_error_still_maps_to_inference_error(self) -> None:
- from sie_server.nats_pull_loop import NatsPullLoop
-
- code, _ = NatsPullLoop._classify_inference_exception(RuntimeError("boom"))
-
- assert code == "inference_error"
+ from sie_server.ipc_types import EncodeBatchItem
+ from sie_server.queue_executor import _inference_exception_outcome
+
+ outcome = _inference_exception_outcome(
+ EncodeBatchItem(
+ work_item_id="wi-1",
+ request_id="req-1",
+ item_index=0,
+ total_items=1,
+ timestamp=0.0,
+ item={},
+ output_types=["dense"],
+ ),
+ RuntimeError("boom"),
+ )
+
+ assert outcome.disposition == "publish_error_and_ack"
+ assert outcome.error_code == "inference_error"
diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lock
new file mode 100644
index 000000000..56a0b3dbc
--- /dev/null
+++ b/packages/sie_server_sidecar/Cargo.lock
@@ -0,0 +1,3466 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "ahash"
+version = "0.8.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75"
+dependencies = [
+ "cfg-if",
+ "getrandom 0.3.4",
+ "once_cell",
+ "serde",
+ "version_check",
+ "zerocopy",
+]
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "anstream"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
+
+[[package]]
+name = "anstyle-parse"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+
+[[package]]
+name = "arrayref"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"
+
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
+[[package]]
+name = "async-nats"
+version = "0.38.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76433c4de73442daedb3a59e991d94e85c14ebfc33db53dfcd347a21cd6ef4f8"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures",
+ "memchr",
+ "nkeys",
+ "nuid",
+ "once_cell",
+ "pin-project",
+ "portable-atomic",
+ "rand 0.8.6",
+ "regex",
+ "ring",
+ "rustls-native-certs 0.7.3",
+ "rustls-pemfile",
+ "rustls-webpki 0.102.8",
+ "serde",
+ "serde_json",
+ "serde_nanos",
+ "serde_repr",
+ "thiserror 1.0.69",
+ "time",
+ "tokio",
+ "tokio-rustls",
+ "tokio-util",
+ "tokio-websockets",
+ "tracing",
+ "tryhard",
+ "url",
+]
+
+[[package]]
+name = "async-trait"
+version = "0.1.89"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "base64"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
+[[package]]
+name = "bitflags"
+version = "2.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "84d7ced0ae9557296835c32bf1b1e02b44c746701f898460fb000d7eaa84f00a"
+
+[[package]]
+name = "blake3"
+version = "1.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0aa83c34e62843d924f905e0f5c866eb1dd6545fc4d719e803d9ba6030371fce"
+dependencies = [
+ "arrayref",
+ "arrayvec",
+ "cc",
+ "cfg-if",
+ "constant_time_eq",
+ "cpufeatures 0.3.0",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytes"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "castaway"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
+dependencies = [
+ "rustversion",
+]
+
+[[package]]
+name = "cc"
+version = "1.2.63"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
+
+[[package]]
+name = "chrono"
+version = "0.4.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"
+dependencies = [
+ "iana-time-zone",
+ "num-traits",
+ "serde",
+ "windows-link",
+]
+
+[[package]]
+name = "clap"
+version = "4.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "clap_lex"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
+
+[[package]]
+name = "compact_str"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9dfdd1c2274d9aa354115b09dc9a901d6c5576818cdf70d14cae2bdb47df00ab"
+dependencies = [
+ "castaway",
+ "cfg-if",
+ "itoa",
+ "rustversion",
+ "ryu",
+ "serde",
+ "static_assertions",
+]
+
+[[package]]
+name = "const-oid"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
+
+[[package]]
+name = "constant_time_eq"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
+
+[[package]]
+name = "core-foundation"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "curve25519-dalek-derive",
+ "digest",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "darling"
+version = "0.20.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
+
+[[package]]
+name = "darling_core"
+version = "0.20.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"
+dependencies = [
+ "fnv",
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim",
+ "syn",
+]
+
+[[package]]
+name = "darling_macro"
+version = "0.20.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
+dependencies = [
+ "darling_core",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "dary_heap"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b1e3a325bc115f096c8b77bbf027a7c2592230e70be2d985be950d3d5e60ebe"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "data-encoding"
+version = "2.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"
+
+[[package]]
+name = "der"
+version = "0.7.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
+dependencies = [
+ "const-oid",
+ "pem-rfc7468",
+ "zeroize",
+]
+
+[[package]]
+name = "deranged"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+dependencies = [
+ "powerfmt",
+ "serde_core",
+]
+
+[[package]]
+name = "derive_builder"
+version = "0.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"
+dependencies = [
+ "derive_builder_macro",
+]
+
+[[package]]
+name = "derive_builder_core"
+version = "0.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"
+dependencies = [
+ "darling",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "derive_builder_macro"
+version = "0.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"
+dependencies = [
+ "derive_builder_core",
+ "syn",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "displaydoc"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "ed25519"
+version = "2.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
+dependencies = [
+ "signature",
+]
+
+[[package]]
+name = "ed25519-dalek"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
+dependencies = [
+ "curve25519-dalek",
+ "ed25519",
+ "sha2",
+ "signature",
+ "subtle",
+]
+
+[[package]]
+name = "either"
+version = "1.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "esaxx-rs"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d817e038c30374a4bcb22f94d0a8a0e216958d4c3dcde369b1439fec4bdda6e6"
+
+[[package]]
+name = "fastrand"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
+
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
+
+[[package]]
+name = "futures-macro"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
+
+[[package]]
+name = "futures-task"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
+
+[[package]]
+name = "futures-util"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "wasi",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 6.0.0",
+ "wasip2",
+ "wasip3",
+]
+
+[[package]]
+name = "h2"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "fnv",
+ "futures-core",
+ "futures-sink",
+ "http",
+ "indexmap",
+ "slab",
+ "tokio",
+ "tokio-util",
+ "tracing",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "http"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8be7462df143984c4598a256ef469b251d7d7f9e271135073e78fc535414f3d0"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
+[[package]]
+name = "humantime"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"
+
+[[package]]
+name = "hyper"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "h2",
+ "http",
+ "http-body",
+ "httparse",
+ "httpdate",
+ "itoa",
+ "pin-project-lite",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-rustls"
+version = "0.27.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
+dependencies = [
+ "http",
+ "hyper",
+ "hyper-util",
+ "rustls",
+ "rustls-native-certs 0.8.4",
+ "tokio",
+ "tokio-rustls",
+ "tower-service",
+ "webpki-roots",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "http",
+ "http-body",
+ "hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
+ "pin-project-lite",
+ "socket2",
+ "tokio",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "iana-time-zone"
+version = "0.1.65"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
+dependencies = [
+ "android_system_properties",
+ "core-foundation-sys",
+ "iana-time-zone-haiku",
+ "js-sys",
+ "log",
+ "wasm-bindgen",
+ "windows-core",
+]
+
+[[package]]
+name = "iana-time-zone-haiku"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "icu_collections"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"
+
+[[package]]
+name = "icu_properties"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"
+dependencies = [
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"
+
+[[package]]
+name = "icu_provider"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "id-arena"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+
+[[package]]
+name = "ident_case"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "ipnet"
+version = "2.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
+[[package]]
+name = "itertools"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itertools"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "js-sys"
+version = "0.3.99"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "once_cell",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
+[[package]]
+name = "libc"
+version = "0.2.186"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "litemap"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "113b30b4cd05f7c06868fdb2854f66a7b9fece9a48425351cd532e810d74024f"
+
+[[package]]
+name = "lru-slab"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
+
+[[package]]
+name = "macro_rules_attribute"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520"
+dependencies = [
+ "macro_rules_attribute-proc_macro",
+ "paste",
+]
+
+[[package]]
+name = "macro_rules_attribute-proc_macro"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30"
+
+[[package]]
+name = "matchers"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
+dependencies = [
+ "regex-automata",
+]
+
+[[package]]
+name = "md-5"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
+dependencies = [
+ "cfg-if",
+ "digest",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
+
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
+[[package]]
+name = "mio"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "monostate"
+version = "0.1.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3341a273f6c9d5bef1908f17b7267bbab0e95c9bf69a0d4dcf8e9e1b2c76ef67"
+dependencies = [
+ "monostate-impl",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "monostate-impl"
+version = "0.1.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4db6d5580af57bf992f59068d4ea26fd518574ff48d7639b255a36f9de6e7e9"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "nkeys"
+version = "0.4.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "879011babc47a1c7fdf5a935ae3cfe94f34645ca0cac1c7f6424b36fc743d1bf"
+dependencies = [
+ "data-encoding",
+ "ed25519",
+ "ed25519-dalek",
+ "getrandom 0.2.17",
+ "log",
+ "rand 0.8.6",
+ "signatory",
+]
+
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
+[[package]]
+name = "nu-ansi-term"
+version = "0.50.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "nuid"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc895af95856f929163a0aa20c26a78d26bfdc839f51b9d5aa7a5b79e52b7e83"
+dependencies = [
+ "rand 0.8.6",
+]
+
+[[package]]
+name = "num-conv"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "object_store"
+version = "0.11.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3cfccb68961a56facde1163f9319e0d15743352344e7808a11795fb99698dcaf"
+dependencies = [
+ "async-trait",
+ "base64 0.22.1",
+ "bytes",
+ "chrono",
+ "futures",
+ "humantime",
+ "hyper",
+ "itertools 0.13.0",
+ "md-5",
+ "parking_lot",
+ "percent-encoding",
+ "quick-xml",
+ "rand 0.8.6",
+ "reqwest",
+ "ring",
+ "rustls-pemfile",
+ "serde",
+ "serde_json",
+ "snafu",
+ "tokio",
+ "tracing",
+ "url",
+ "walkdir",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+
+[[package]]
+name = "onig"
+version = "6.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cc3cbf698f9438986c11a880c90a6d04b9de27575afd28bbf45b154b6c709e2"
+dependencies = [
+ "bitflags",
+ "libc",
+ "once_cell",
+ "onig_sys",
+]
+
+[[package]]
+name = "onig_sys"
+version = "69.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e68317604e77e53b85896388e1a803c1d21b74c899ec9e5e1112db90735edd7"
+dependencies = [
+ "cc",
+ "pkg-config",
+]
+
+[[package]]
+name = "openssl-probe"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"
+
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
+[[package]]
+name = "pem-rfc7468"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
+dependencies = [
+ "base64ct",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "pin-project"
+version = "1.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924"
+dependencies = [
+ "pin-project-internal",
+]
+
+[[package]]
+name = "pin-project-internal"
+version = "1.1.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "pkcs8"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+dependencies = [
+ "der",
+ "spki",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
+
+[[package]]
+name = "portable-atomic"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
+
+[[package]]
+name = "potential_utf"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
+dependencies = [
+ "zerovec",
+]
+
+[[package]]
+name = "powerfmt"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "procfs"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "731e0d9356b0c25f16f33b5be79b1c57b562f141ebfcdb0ad8ac2c13a24293b4"
+dependencies = [
+ "bitflags",
+ "hex",
+ "lazy_static",
+ "procfs-core",
+ "rustix 0.38.44",
+]
+
+[[package]]
+name = "procfs-core"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d3554923a69f4ce04c4a754260c338f505ce22642d3830e049a399fc2059a29"
+dependencies = [
+ "bitflags",
+ "hex",
+]
+
+[[package]]
+name = "prometheus"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d33c28a30771f7f96db69893f78b857f7450d7e0237e9c8fc6427a81bae7ed1"
+dependencies = [
+ "cfg-if",
+ "fnv",
+ "lazy_static",
+ "libc",
+ "memchr",
+ "parking_lot",
+ "procfs",
+ "protobuf",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "protobuf"
+version = "2.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "106dd99e98437432fed6519dedecfade6a06a73bb7b2a1e019fdd2bee5778d94"
+
+[[package]]
+name = "quick-xml"
+version = "0.37.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"
+dependencies = [
+ "memchr",
+ "serde",
+]
+
+[[package]]
+name = "quinn"
+version = "0.11.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror 2.0.18",
+ "tokio",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-proto"
+version = "0.11.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"
+dependencies = [
+ "bytes",
+ "getrandom 0.3.4",
+ "lru-slab",
+ "rand 0.9.4",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror 2.0.18",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
+dependencies = [
+ "libc",
+ "rand_chacha 0.3.1",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "rand"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
+dependencies = [
+ "rand_chacha 0.9.0",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
+[[package]]
+name = "rayon"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-cond"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2964d0cf57a3e7a06e8183d14a8b527195c706b7983549cd5462d5aa3747438f"
+dependencies = [
+ "either",
+ "itertools 0.14.0",
+ "rayon",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "regex"
+version = "1.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
+
+[[package]]
+name = "reqwest"
+version = "0.12.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures-core",
+ "futures-util",
+ "h2",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-rustls",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "quinn",
+ "rustls",
+ "rustls-native-certs 0.8.4",
+ "rustls-pki-types",
+ "serde",
+ "serde_json",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tokio-rustls",
+ "tokio-util",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wasm-streams",
+ "web-sys",
+ "webpki-roots",
+]
+
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "rmp"
+version = "0.8.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "rmp-serde"
+version = "1.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"
+dependencies = [
+ "rmp",
+ "serde",
+]
+
+[[package]]
+name = "rmpv"
+version = "1.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417"
+dependencies = [
+ "rmp",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "0.38.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.4.15",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys 0.12.1",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls"
+version = "0.23.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b"
+dependencies = [
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki 0.103.13",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5"
+dependencies = [
+ "openssl-probe 0.1.6",
+ "rustls-pemfile",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework 2.11.1",
+]
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
+dependencies = [
+ "openssl-probe 0.2.1",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework 3.7.0",
+]
+
+[[package]]
+name = "rustls-pemfile"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"
+dependencies = [
+ "rustls-pki-types",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9"
+dependencies = [
+ "web-time",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.102.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64ca1bc8749bd4cf37b5ce386cc146580777b4e8572c7b97baf22c83f444bee9"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+
+[[package]]
+name = "ryu"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "schannel"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "security-framework"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
+dependencies = [
+ "bitflags",
+ "core-foundation 0.9.4",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags",
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_bytes"
+version = "0.11.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
+dependencies = [
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.150"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_nanos"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a93142f0367a4cc53ae0fead1bcda39e85beccfad3dcd717656cacab94b12985"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "serde_repr"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_urlencoded"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
+dependencies = [
+ "form_urlencoded",
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest",
+]
+
+[[package]]
+name = "sharded-slab"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
+dependencies = [
+ "lazy_static",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "sie-server-sidecar"
+version = "0.4.2"
+dependencies = [
+ "anyhow",
+ "async-nats",
+ "async-trait",
+ "blake3",
+ "bytes",
+ "clap",
+ "futures-util",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "object_store",
+ "prometheus",
+ "reqwest",
+ "rmp",
+ "rmp-serde",
+ "rmpv",
+ "serde",
+ "serde_bytes",
+ "serde_json",
+ "tempfile",
+ "thiserror 2.0.18",
+ "tokenizers",
+ "tokio",
+ "tracing",
+ "tracing-subscriber",
+ "url",
+ "uuid",
+]
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
+dependencies = [
+ "errno",
+ "libc",
+]
+
+[[package]]
+name = "signatory"
+version = "0.27.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1e303f8205714074f6068773f0e29527e0453937fe837c9717d066635b65f31"
+dependencies = [
+ "pkcs8",
+ "rand_core 0.6.4",
+ "signature",
+ "zeroize",
+]
+
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+dependencies = [
+ "digest",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+
+[[package]]
+name = "snafu"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e84b3f4eacbf3a1ce05eac6763b4d629d60cbc94d632e4092c54ade71f1e1a2"
+dependencies = [
+ "snafu-derive",
+]
+
+[[package]]
+name = "snafu-derive"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "socket2"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "spki"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
+dependencies = [
+ "base64ct",
+ "der",
+]
+
+[[package]]
+name = "spm_precompiled"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5851699c4033c63636f7ea4cf7b7c1f1bf06d0cc03cfb42e711de5a5c46cf326"
+dependencies = [
+ "base64 0.13.1",
+ "nom",
+ "serde",
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "static_assertions"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.2",
+ "once_cell",
+ "rustix 1.1.4",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl 1.0.69",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
+dependencies = [
+ "thiserror-impl 2.0.18",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "thread_local"
+version = "1.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "time"
+version = "0.3.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
+dependencies = [
+ "deranged",
+ "itoa",
+ "num-conv",
+ "powerfmt",
+ "serde_core",
+ "time-core",
+ "time-macros",
+]
+
+[[package]]
+name = "time-core"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
+
+[[package]]
+name = "time-macros"
+version = "0.2.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"
+dependencies = [
+ "num-conv",
+ "time-core",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
+dependencies = [
+ "tinyvec_macros",
+]
+
+[[package]]
+name = "tinyvec_macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+
+[[package]]
+name = "tokenizers"
+version = "0.22.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b238e22d44a15349529690fb07bd645cf58149a1b1e44d6cb5bd1641ff1a6223"
+dependencies = [
+ "ahash",
+ "aho-corasick",
+ "compact_str",
+ "dary_heap",
+ "derive_builder",
+ "esaxx-rs",
+ "getrandom 0.3.4",
+ "itertools 0.14.0",
+ "log",
+ "macro_rules_attribute",
+ "monostate",
+ "onig",
+ "paste",
+ "rand 0.9.4",
+ "rayon",
+ "rayon-cond",
+ "regex",
+ "regex-syntax",
+ "serde",
+ "serde_json",
+ "spm_precompiled",
+ "thiserror 2.0.18",
+ "unicode-normalization-alignments",
+ "unicode-segmentation",
+ "unicode_categories",
+]
+
+[[package]]
+name = "tokio"
+version = "1.52.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "parking_lot",
+ "pin-project-lite",
+ "signal-hook-registry",
+ "socket2",
+ "tokio-macros",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tokio-rustls"
+version = "0.26.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
+dependencies = [
+ "rustls",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-websockets"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f591660438b3038dd04d16c938271c79e7e06260ad2ea2885a4861bfb238605d"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "http",
+ "httparse",
+ "rand 0.8.6",
+ "ring",
+ "rustls-native-certs 0.8.4",
+ "rustls-pki-types",
+ "tokio",
+ "tokio-rustls",
+ "tokio-util",
+]
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
+dependencies = [
+ "bitflags",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "pin-project-lite",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "url",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+ "valuable",
+]
+
+[[package]]
+name = "tracing-log"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
+dependencies = [
+ "log",
+ "once_cell",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-serde"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1"
+dependencies = [
+ "serde",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-subscriber"
+version = "0.3.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
+dependencies = [
+ "matchers",
+ "nu-ansi-term",
+ "once_cell",
+ "regex-automata",
+ "serde",
+ "serde_json",
+ "sharded-slab",
+ "smallvec",
+ "thread_local",
+ "tracing",
+ "tracing-core",
+ "tracing-log",
+ "tracing-serde",
+]
+
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
+[[package]]
+name = "tryhard"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fe58ebd5edd976e0fe0f8a14d2a04b7c81ef153ea9a54eebc42e67c2c23b4e5"
+dependencies = [
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-normalization-alignments"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43f613e4fa046e69818dd287fdc4bc78175ff20331479dab6e1b0f98d57062de"
+dependencies = [
+ "smallvec",
+]
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
+[[package]]
+name = "unicode_categories"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e"
+
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "uuid"
+version = "1.23.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7"
+dependencies = [
+ "getrandom 0.4.2",
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "valuable"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "want"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
+dependencies = [
+ "try-lock",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasip2"
+version = "1.0.3+wasi-0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"
+dependencies = [
+ "wit-bindgen 0.57.1",
+]
+
+[[package]]
+name = "wasip3"
+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
+dependencies = [
+ "wit-bindgen 0.51.0",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.122"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.72"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9473dbd2991ae90b6291c3c32c30c6187ac49aa32f9905d1cce280ec1e110b0f"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.122"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.122"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.122"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "wasm-encoder"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
+dependencies = [
+ "leb128fmt",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-streams"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"
+dependencies = [
+ "futures-util",
+ "js-sys",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.15.5",
+ "indexmap",
+ "semver",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.99"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d621441cfc37b84979402712047321980c178f299193a3589d05b99e8763436"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d"
+dependencies = [
+ "rustls-pki-types",
+]
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "windows-core"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.59.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.5",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm 0.52.6",
+ "windows_aarch64_msvc 0.52.6",
+ "windows_i686_gnu 0.52.6",
+ "windows_i686_gnullvm 0.52.6",
+ "windows_i686_msvc 0.52.6",
+ "windows_x86_64_gnu 0.52.6",
+ "windows_x86_64_gnullvm 0.52.6",
+ "windows_x86_64_msvc 0.52.6",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm 0.53.1",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+dependencies = [
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "prettyplease",
+ "syn",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
+dependencies = [
+ "anyhow",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+ "wasmparser",
+]
+
+[[package]]
+name = "writeable"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
+
+[[package]]
+name = "yoke"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.50"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b065d4f0e55f82fae73202e189638116a87c55ab6b8e6c2721e13dd9d854ad1"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.50"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b631b19d36a892ab55420c92dbc83ccd79274f25be714855d3074aa71cab639"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
+
+[[package]]
+name = "zerotrie"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.toml
new file mode 100644
index 000000000..897ac7d6b
--- /dev/null
+++ b/packages/sie_server_sidecar/Cargo.toml
@@ -0,0 +1,78 @@
+[package]
+name = "sie-server-sidecar"
+version = "0.4.2"
+edition = "2021"
+description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."
+
+[lib]
+name = "sie_server_sidecar"
+path = "src/lib.rs"
+
+[[bin]]
+name = "sie-server-sidecar"
+path = "src/main.rs"
+
+[dependencies]
+tokio = { version = "1", features = ["full"] }
+async-nats = "0.38"
+futures-util = "0.3"
+
+serde = { version = "1", features = ["derive"] }
+# `float_roundtrip` switches serde_json to its IEEE-754 correctly-rounded
+# f64 parser. Required for bit-exact parity with the Python adaptive
+# controller in `scripts/perf/replay-scheduler-trace.py` — without it,
+# serde_json's default "fast" parser can be 1 ULP off for some decimals
+# (e.g. "14.394267984578837" parses 1 bit low), which breaks the
+# shadow-trace ULP diff. Do not drop this feature.
+serde_json = { version = "1", features = ["float_roundtrip"] }
+serde_bytes = "0.11"
+rmp-serde = "1"
+# Low-level msgpack writer. Used to emit byte-for-byte compatible
+# `msgpack_numpy` sentinels on the result path so the Python SDK's
+# `msgpack_numpy.patch()` decoder sees the same wire shape it gets
+# from the Python adapters.
+rmp = "0.8"
+
+clap = { version = "4", features = ["derive", "env"] }
+thiserror = "2"
+anyhow = "1"
+tracing = "0.1"
+tracing-subscriber = { version = "0.3", features = ["json", "env-filter"] }
+
+async-trait = "0.1"
+bytes = "1"
+uuid = { version = "1", features = ["v4"] }
+reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
+
+# Metrics server (matches gateway)
+prometheus = { version = "0.13", features = ["process"] }
+hyper = { version = "1", features = ["server", "http1"] }
+hyper-util = { version = "0.1", features = ["tokio"] }
+http-body-util = "0.1"
+
+# Cloud payload store backends (opt-in, same shape as gateway)
+object_store = { version = "0.11", optional = true, features = ["aws", "gcp"] }
+url = { version = "2", optional = true }
+
+# HF fast-tokenizers. Used by `src/tokenize/` to verify the
+# adapter-provided `tokenizer.json` materialised at the path
+# `ModelDescriptor.tokenizer_path` and to tokenize inbound batches
+# inside the sidecar. Blake3 hashes the canonical bytes
+# for the `tokenizer_id` drift check the adapter populates on
+# `EnsureModelReady`.
+tokenizers = { version = "0.22", default-features = false, features = ["onig"] }
+blake3 = "1"
+
+# NOTE: This crate has no GPU-side dependencies. The sidecar talks to
+# its inference backend strictly over IPC; in-process native backends
+# (if reintroduced later) would land as a sibling crate, not here.
+
+[features]
+default = []
+cloud-storage = ["dep:object_store", "dep:url"]
+
+[dev-dependencies]
+tempfile = "3"
+# Dynamically typed msgpack values for tests that need to walk
+# hand-rolled wire envelopes (e.g. dense-encode numpy sentinel).
+rmpv = "1"
diff --git a/packages/sie_server_sidecar/Dockerfile b/packages/sie_server_sidecar/Dockerfile
new file mode 100644
index 000000000..771879d7e
--- /dev/null
+++ b/packages/sie_server_sidecar/Dockerfile
@@ -0,0 +1,122 @@
+# syntax=docker/dockerfile:1
+#
+# SIE Server Sidecar Image
+#
+# Build from repo root:
+# docker build -f packages/sie_server_sidecar/Dockerfile \
+# -t sie-server-sidecar:latest .
+#
+# The published image is ghcr.io/superlinked/sie-server-sidecar; the runtime
+# binary inside the image is /sie-server-sidecar.
+#
+# The only Cargo feature today is `cloud-storage` (S3/GCS payload modes),
+# which is the default for `ARG FEATURES` below. CI can override with
+# `--build-arg FEATURES=` if you want a leaner build with no remote
+# payload support.
+#
+# Run:
+# The worker expects a Unix socket to a Python `sie_server.ipc_server`.
+# The Helm chart wires the sidecar at /var/run/sie/ipc.sock; for local
+# testing mount a socket path and set SIE_IPC_SOCKET_PATH accordingly.
+
+ARG FEATURES=cloud-storage
+ARG RUST_VERSION=1.96.0
+
+# =============================================================================
+# Dependency planner: capture the Cargo graph only.
+# =============================================================================
+FROM rust:${RUST_VERSION}-slim-bookworm AS chef
+RUN cargo install cargo-chef --locked --version 0.1.77
+WORKDIR /build
+
+FROM chef AS planner
+COPY packages/sie_server_sidecar/Cargo.toml packages/sie_server_sidecar/Cargo.lock ./
+COPY packages/sie_server_sidecar/src/ src/
+RUN cargo chef prepare --recipe-path recipe.json
+
+# =============================================================================
+# Release builder: cook deps, then build the real binary.
+# =============================================================================
+FROM chef AS builder
+ARG FEATURES
+
+# Build deps.
+# * `pkg-config + libssl-dev` - in case any transitive dep uses OpenSSL
+# (async-nats itself uses rustls, but staying safe for feature toggles).
+# * `ca-certificates` - cargo needs these when the network cache misses.
+# * `build-essential` - gcc/cmake/make for `onig_sys` (tokenizers) and
+# `safetensors`. These crates ship C sources and STATICALLY link them
+# so the distroless runtime image can stay minimal.
+RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
+ apt-get update && apt-get install -y --no-install-recommends \
+ pkg-config \
+ libssl-dev \
+ ca-certificates \
+ build-essential \
+ && rm -rf /var/lib/apt/lists/*
+
+# Force `onig_sys` to statically link the bundled Oniguruma instead of
+# trying to dlopen a system libonig at runtime - distroless does not
+# ship libonig and tokenizers would otherwise panic on first use.
+ENV RUSTONIG_STATIC_LIBONIG=1
+
+COPY --from=planner /build/recipe.json recipe.json
+
+# Warm cargo's target cache with JUST the dependency graph. This keeps
+# iteration fast when only worker source changes (deps hash unchanged).
+RUN --mount=type=cache,target=/usr/local/cargo/registry \
+ --mount=type=cache,target=/build/target \
+ cargo chef cook --release \
+ --features "${FEATURES}" \
+ --recipe-path recipe.json
+
+# Restore real source.
+#
+# `cargo chef cook` mutates the crate into dependency-only stubs. Re-copy
+# the real manifest and source before `cargo build` so the final image gets
+# `sie-server-sidecar`, not a cache-warming placeholder binary.
+COPY packages/sie_server_sidecar/Cargo.toml packages/sie_server_sidecar/Cargo.lock ./
+COPY packages/sie_server_sidecar/src/ src/
+
+# Real build.
+#
+# The `/build/target` cache carries compiled deps forward. The size guard
+# catches regressions where the restore step is reordered and a stub binary
+# reaches the runtime image.
+RUN --mount=type=cache,target=/usr/local/cargo/registry \
+ --mount=type=cache,target=/build/target \
+ cargo build --locked --release --bin sie-server-sidecar --features "${FEATURES}" \
+ && ls -lh target/release/sie-server-sidecar \
+ && test "$(wc -c < target/release/sie-server-sidecar)" -gt 5000000 \
+ && cp target/release/sie-server-sidecar /usr/local/bin/sie-server-sidecar
+
+# =============================================================================
+# Runtime image: minimal image, just the static-ish binary.
+# =============================================================================
+# `distroless/cc-debian12` ships glibc + common C runtime libs, matching what
+# the Rust build links against. `nonroot` gives us uid/gid 65532.
+FROM gcr.io/distroless/cc-debian12:nonroot AS runtime
+
+COPY --from=builder /usr/local/bin/sie-server-sidecar /sie-server-sidecar
+
+# Opinionated defaults; override via env in the Pod spec / Helm chart.
+#
+# * SIE_WORKER_METRICS_PORT - Prometheus scrape port (matches the clap arg
+# name; default 9095).
+# * SIE_IPC_SOCKET_PATH - Unix socket to the Python sie-server process. The Helm
+# chart mounts a shared emptyDir at /var/run/sie.
+# * RUST_LOG - structured log level; OTel set at deploy time.
+# * SIE_NATS_URL - required, no default; must be set by the
+# Pod / Helm chart.
+ENV SIE_WORKER_METRICS_PORT=9095 \
+ SIE_IPC_SOCKET_PATH=/var/run/sie/ipc.sock \
+ RUST_LOG=info
+
+EXPOSE 9095
+
+USER nonroot:nonroot
+ENTRYPOINT ["/sie-server-sidecar"]
+
+LABEL org.opencontainers.image.title="sie-server-sidecar" \
+ org.opencontainers.image.description="SIE server sidecar - NATS JetStream consumer + Python IPC forwarder." \
+ org.opencontainers.image.source="https://github.com/superlinked/sie-internal"
diff --git a/packages/sie_server_sidecar/README.md b/packages/sie_server_sidecar/README.md
new file mode 100644
index 000000000..61a5413ee
--- /dev/null
+++ b/packages/sie_server_sidecar/README.md
@@ -0,0 +1,21 @@
+# SIE Server Sidecar
+
+`sie-server-sidecar` builds the `sie-server-sidecar` binary and `sie-server-sidecar`
+container image.
+
+The sidecar owns the queue-mode runtime around an inference adapter pod: NATS
+JetStream consumption, batching and scheduling, IPC to the adapter, payload
+fetching, result framing, ACK/NAK behavior, metrics, and readiness.
+
+It does not load model weights or link GPU libraries. The colocated
+`sie-server` container remains the Python adapter/model-execution process.
+
+Public and runtime names:
+
+- Kubernetes container: `worker-sidecar`
+- Binary: `sie-server-sidecar`
+- Image: `ghcr.io/superlinked/sie-server-sidecar`
+- Metrics: `sie_worker_*` (worker-side runtime metrics)
+
+See [`docs/architecture-guide.md`](docs/architecture-guide.md) for the runtime
+contract and deployment caveats.
diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.md
new file mode 100644
index 000000000..b55c43192
--- /dev/null
+++ b/packages/sie_server_sidecar/docs/architecture-guide.md
@@ -0,0 +1,359 @@
+# SIE Server Sidecar Architecture
+
+This is the canonical reference for `packages/sie_server_sidecar`.
+
+## Status
+
+The package is production-oriented but still deployment-gated by Helm:
+
+- Source package: `packages/sie_server_sidecar`
+- Cargo package: `sie-server-sidecar`
+- Binary: `sie-server-sidecar`
+- Kubernetes container: `worker-sidecar`
+- Container image: `ghcr.io/superlinked/sie-server-sidecar`
+- Prometheus metric prefix: `sie_worker_`
+
+The Kubernetes container is named `worker-sidecar`, while sidecar-only build
+artifacts use the `sie-server-sidecar` family to match the colocated
+`sie-server` adapter process. Prometheus metric families use the
+`sie_worker_*` prefix because they describe worker-side runtime behavior.
+
+GPU-independent preparation code lives in this package:
+
+- `src/protocol/` owns the Rust IPC schema.
+- `src/prep/` owns GPU-independent prep/framing helpers.
+- `src/ipc_types.rs` remains as a re-export so sidecar code can keep using
+ `crate::ipc_types`.
+
+`tools/ci/check_ipc_types_parity.py` checks the Rust protocol schema against
+`packages/sie_server/src/sie_server/ipc_types.py`.
+
+## Runtime Split
+
+A queue-mode worker pod has two cooperating containers:
+
+```text
+gateway -> NATS JetStream -> worker-sidecar -> UDS IPC -> sie-server adapter
+ |
+ +-> NATS Core reply subject
+```
+
+Responsibilities:
+
+| Component | Owns |
+| --- | --- |
+| `sie_gateway` | HTTP/API edge, model and pool resolution, JetStream publish, inbox collection, DLQ listener |
+| `worker-sidecar` | JetStream pull consumer, subject validation, payload fetch, batch formation, adaptive scheduling, Rust tokenization fast path, result framing, ACK/NAK, reply publish, sidecar metrics/readiness |
+| `sie-server` | Python adapter execution, model registry and GPU lifecycle, adapter-specific preprocessing/fallbacks, IPC server, direct HTTP API |
+
+The sidecar never loads model weights and has no GPU dependency. It talks to
+the colocated adapter over a Unix domain socket.
+
+## Request Path
+
+1. Gateway publishes a msgpack `WorkItem` on `sie.work.{model}.{pool}`.
+2. The sidecar's long-lived JetStream pull stream receives messages from
+ stream `WORK_POOL_{pool}`.
+3. The dispatcher extracts the model from the subject and rejects malformed
+ subjects before trusting payload data.
+4. The dispatcher validates `reply_subject`; non-empty values must start with
+ `_INBOX.`.
+5. The sidecar groups by model, calls `EnsureModelReady`, and resolves payload
+ references if present.
+6. The Rust scheduler batches by `(operation, lora_key)` and sends `RunBatch`
+ over UDS IPC when the adapter declares `supports_run_batch`.
+7. Python returns `BatchOutcome` with per-item `ItemOutcome`s.
+8. The sidecar frames/publishes `WorkResult` and ACKs the JetStream message.
+ Publish failure skips ACK so JetStream redelivers.
+
+Failure rules:
+
+- Bad msgpack, malformed subject, transient backend failures, and draining
+ generally NAK with a delay.
+- Unsafe reply subjects are ACK-dropped to avoid publish amplification.
+- Unknown operations publish an error outcome and ACK when the reply publish
+ succeeds.
+- IPC transport errors retry once transparently before the group is NAKed.
+- Gateway owns DLQ publication by listening to JetStream max-delivery
+ advisories; the sidecar only ACKs or NAKs.
+
+## NATS Contract
+
+Worker stream and consumer settings must stay aligned with the gateway and SDK:
+
+| Field | Value |
+| --- | --- |
+| Stream | `WORK_POOL_{pool}` |
+| Subject filter | `sie.work.*.{pool}` |
+| Retention | WorkQueue |
+| Storage | Memory |
+| Consumer | `{bundle}_{pool}` |
+| Ack policy | Explicit |
+| Ack wait | 30 s |
+| Max deliver | `SIE_MAX_DELIVER`, default 20 |
+| Max ack pending | `SIE_MAX_ACK_PENDING`, default 1000 |
+
+The pull stream must be long-lived. Dropping and recreating pull streams inside
+the fetch loop can make async-nats mark unread messages as delivered, causing
+redelivery only after the 30 s `ack_wait`. The implementation creates one pull
+stream and polls it continuously.
+Integration tests guard this with concurrent and sustained-load scenarios that
+watch `sie_worker_nats_redelivery_total`.
+
+The sidecar also runs a slow stream/durable reconciler. It periodically
+re-ensures `WORK_POOL_{pool}` and `{bundle}_{pool}` so NATS metadata drift can
+self-heal without adding reconnect-event work or locks to the fetch loop. It
+does not rebuild the active pull stream; terminal pull-stream errors still use
+the normal pull-loop recovery path.
+
+Generation models use a worker-specific JetStream subject
+`sie.work.{model}.{pool}.{worker_id}`. The sidecar creates and polls that
+worker stream only after Python `WorkerCapabilities` reports at least one
+generation model. If live config reconciliation later adds a generation model
+to an already-running sidecar, a capability reconciler activates the direct
+stream and cancel subscriber exactly once.
+
+When `SIE_GATEWAY_URL` is set, the sidecar runs the pool admission gate before
+pulling from either the pool stream or the generation worker stream. Capped
+named pools fail closed unless `/v1/pools/{pool}` lists this pod in
+`status.assigned_workers`; uncapped pools and profile-uncapped workers continue
+pulling. The default pool fails open during transient gateway/status errors so
+baseline capacity remains available.
+
+On startup the sidecar also performs a best-effort cleanup of empty per-model
+`WORK_<model>` streams whose subjects overlap `sie.work.*.{pool}`. This
+preserves upgrade safety without dropping queued work; non-empty streams must be
+drained or migrated explicitly, and unrelated streams and other pool streams are
+ignored.
+
+## IPC Contract
+
+Framing is:
+
+```text
+[4-byte big-endian length][msgpack named-map body]
+```
+
+The method surface is:
+
+- `Ping`
+- `EnsureModelReady`
+- `ProcessEncodeBatch`
+- `ProcessScoreBatch`
+- `ProcessExtractBatch`
+- `RunBatch`
+- `Drain`
+
+`RunBatch` is the hot scheduler path. It carries a homogeneous-op batch; mixed
+ops are rejected by Python and pinned by parity fixtures under `tests/parity/`.
+Envelope identity fields on `RunBatchItem` preserve `work_item_id`,
+`request_id`, and `item_index` even when the operation-specific payload is
+missing.
+
+`ModelDescriptor` is returned by `EnsureModelReady` and lets the sidecar learn
+per-model capabilities at runtime:
+
+- tokenizer path and tokenizer content hash
+- maximum sequence length
+- supported output types
+- `supports_run_batch`
+
+## Scheduler And Batching
+
+The Rust scheduler is live for queue-mode traffic that reaches this sidecar.
+There is no sidecar-local active model list that gates the path; routing is a
+gateway/pool decision.
+
+Preserved Python semantics:
+
+- cost, count, max-wait, and coalesce-window flush triggers
+- oversize item flushes alone
+- cost-sorted sub-batch packing
+- per-model adaptive controller
+- score runs on the base LoRA path
+- per-item outcomes fan out without dropping the rest of the batch
+
+Production-tuned sidecar defaults:
+
+| Knob | Default | Notes |
+| --- | ---: | --- |
+| `SIE_RUST_PIPELINE_DEPTH` | 2 | one active adapter batch plus one queued behind it |
+| `SIE_BATCHER_COALESCE_MS` | 5 | intentionally lower than Python reference |
+| `SIE_BATCHER_MAX_BATCH_REQUESTS` | 12 | intentionally lower than Python reference |
+| `SIE_ADAPTIVE_MIN_QUANTUM_MS` | 2 | pull-loop coalesce floor |
+| `SIE_ADAPTIVE_MAX_QUANTUM_MS` | 15 | pull-loop coalesce ceiling |
+| `SIE_ADAPTIVE_TARGET_P50_MS` | 50 | pull-loop latency target |
+
+These worker-local defaults cap coalescing and queue depth for CPU-side
+responsiveness; they are locked by Rust tests and should be retuned together.
+
+`SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS=1` opts into controller input that includes
+queue wait. Default is off because saturation queue time can collapse the pull
+quantum even when the pull loop is not the bottleneck.
+
+## Prep And Result Framing
+
+The sidecar owns GPU-independent work:
+
+- text template application for the safe Rust-tokenization path
+- HF fast-tokenizer loading from the adapter-declared tokenizer path
+- `PreparedTokens` attachment for encode IPC items where safe
+- dense, sparse, multivector, and score `RawOutput` framing
+- `msgpack_numpy` sentinel-compatible payload bytes
+
+Python remains the correctness fallback. If tokens are absent or the
+`tokenizer_id` mismatches, Python retokenizes. If a result cannot be represented
+by a typed `RawOutput`, Python-framed `result_msgpack` passes through.
+
+Current worker-side boundaries:
+
+- Encode tokenization fast path exists, but individual text adapters still need
+ byte-identity validation before consuming it everywhere.
+- Score pair construction stays adapter-side because query/document pair policy
+ is model-specific.
+- Extract tokenization stays Python-side.
+- Native Candle/tch-rs adapter work remains future work behind the same IPC boundary.
+
+## Readiness And Metrics
+
+The sidecar serves HTTP on `SIE_WORKER_METRICS_PORT`, default `9095`:
+
+- `/healthz`: always returns 200 while the process is alive.
+- `/readyz`: returns 200 only after a successful IPC `Ping`, while the most
+ recent ping is fresh, and before drain starts.
+- `/metrics`: Prometheus metrics.
+
+In Helm, the `worker-sidecar` container exposes container port `metrics`, the
+worker Service exposes it as service port `worker-metrics`, and the
+ServiceMonitor scrapes that endpoint. Metric families remain `sie_worker_*`
+and `sie_pull_loop_*`; do not rename them with the Kubernetes container.
+
+Freshness is `SIE_WORKER_PING_INTERVAL_MS * SIE_WORKER_READYZ_STALE_MULT`.
+Defaults are 2000 ms and 3.
+
+Helm can route probes to the sidecar with
+`workers.common.workerSidecar.probes.enabled`. This is separate from enabling the
+sidecar container itself.
+
+## Important Environment Variables
+
+| Variable | Purpose |
+| --- | --- |
+| `SIE_NATS_URL` | NATS endpoint; required |
+| `SIE_POOL` | pool segment in `sie.work.*.{pool}` |
+| `SIE_BUNDLE` | consumer-name segment |
+| `SIE_IPC_SOCKET_PATH` | UDS path to the adapter |
+| `SIE_IPC_POOL_SIZE` | concurrent IPC connections, default matches dispatch concurrency |
+| `SIE_NATS_FETCH_BUDGET` | pull-stream credit and fallback model budget |
+| `SIE_NATS_PULL_EXPIRES_S` | server-side pull expiry, default 5 s and must stay below ack wait |
+| `SIE_NATS_CONSUMER_RECONCILE_INTERVAL_MS` | slow stream/durable reconcile interval, default 30000; non-zero values below 10000 are clamped; `0` disables |
+| `SIE_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS` | generation direct-dispatch activation check interval after startup reports no generation models, default 30000; non-zero values below 5000 are clamped; `0` disables |
+| `SIE_STREAM_MAX_AGE_S` | worker stream max age if worker creates the stream first |
+| `SIE_PAYLOAD_STORE_URL` | optional shared payload-store backend (`s3://`, `gs://`, or a local path shared with the gateway) |
+| `SIE_GATEWAY_URL` | optional gateway base URL used by the pool admission gate |
+| `SIE_GATEWAY_API_KEY` | optional bearer token for gateway pool-status reads |
+| `SIE_POOL_ADMISSION_ENABLED` | pool admission gate toggle, default true when `SIE_GATEWAY_URL` is set |
+| `SIE_POOL_ADMISSION_CHECK_INTERVAL_S` | pool admission status check cadence, default 5 s |
+| `SIE_POOL_ADMISSION_PAUSE_S` | sleep while this pod is not admitted to pull, default 1 s |
+| `SIE_POOL_ADMISSION_STALE_AFTER_S` | cached-decision window after transient gateway/status errors, default 30 s |
+| `SIE_WORKER_METRICS_PORT` | sidecar HTTP port |
+| `SIE_HEALTH_PUBLISH_ENABLED` | NATS heartbeat publisher toggle |
+| `SIE_HEALTH_PUBLISH_INTERVAL_MS` | NATS heartbeat publish interval |
+| `SIE_BUNDLE_CONFIG_HASH` | optional initial local bundle hash; normally populated by live apply/export reconciliation |
+| `SIE_CONFIG_SERVICE_URL` | optional `sie-config` base URL for worker-side epoch/export reconciliation |
+| `SIE_ADMIN_TOKEN` | optional bearer token for `GET /v1/configs/export` when config auth is enabled |
+| `SIE_WORKER_CONFIG_POLL_INTERVAL_MS` | worker config epoch poll interval, default 30000 |
+| `SIE_WORKER_CONFIG_FULL_EXPORT_INTERVAL_MS` | slow full-export reconcile interval, default 300000; `0` disables after startup |
+| `SIE_NATS_CONFIG_TRUSTED_PRODUCERS` | comma-separated producer allowlist for `sie.config.models.<bundle>`; binary default `sie-config`; Helm sets the release-scoped config Deployment name |
+| `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` | disables producer validation for local/dev only |
+
+Operator-provided Helm `extraEnv` is rendered after chart defaults so explicit
+overrides still win.
+
+## Live Config Apply
+
+The sidecar subscribes to `sie.config.models.<SIE_BUNDLE>`. Each notification is
+accepted only after producer allowlist, bundle, epoch, and size checks pass.
+Accepted deltas are forwarded to Python over IPC `ApplyModelConfig`; Python
+validates the YAML as `ModelConfig`, mutates its local `ModelRegistry`, clears
+the model descriptor cache, and returns the bundle hash it computes locally.
+
+When `SIE_CONFIG_SERVICE_URL` is set, the sidecar also runs an export
+reconciler. It performs a startup `GET /v1/configs/export`, then polls
+`GET /v1/configs/epoch`. If the control-plane epoch is ahead, or if the slow
+full-export reconcile is due for an epoch-0/no-config-store deployment, it replays
+only export entries whose `affected_bundles` include this worker's bundle. The
+advertised hash advances only after every relevant export entry applies
+successfully, so a partial replay does not produce a false worker ACK.
+
+The NATS health publisher reads that hash dynamically, so the gateway's
+`/v1/configs/models/{id}/status` endpoint observes worker convergence without
+an explicit ACK message. The dispatcher also checks each incoming work item's
+expected `bundle_config_hash` against the current local hash plus a small recent
+hash history. Unknown hashes are NAKed before `EnsureModelReady` or Python IPC,
+so workers behind the gateway redeliver work after their live NATS subscriber or
+export reconciler catches up, while accepted in-flight work remains processable
+after an append-only config advance.
+
+Config apply also nudges the generation capability reconciler. This covers the
+case where a bundle starts encode-only and later receives a generation model:
+the sidecar keeps the encode-only hot path until Python exposes the generation
+task, then creates the worker-specific generation stream.
+
+## Known Caveats
+
+- **Stream `max_age` race.** Gateway and worker can both create the stream.
+ Whichever side creates it first wins. Keep gateway and worker settings aligned
+ when changing retention.
+- **Durable config drift.** The sidecar cleans up overlapping consumers, but a
+ pure durable config change may still need operator cleanup if JetStream
+ rejects an update.
+- **Config replay scope.** Worker-side export reconciliation replays model
+ configs, not bundle definitions or adapter code. Bundle changes still require
+ a matching `sie-config`/worker image rollout; the running sidecar can only
+ apply configs for adapters already present in the co-located Python image.
+- **Subject shape coupling.** The worker extracts the model from subject token
+ `parts[2]`. Gateway subject changes must update worker parsing in lock-step.
+- **Unit integration scope.** Rust integration tests use real NATS and a stub
+ Python IPC server; local Tilt E2E covers the real gateway-to-worker path.
+- **Sidecar enablement changes deployment behavior.** Keeping
+ `workers.common.workerSidecar.enabled` off leaves queue-mode worker pods without
+ a queue consumer. Flipping that default changes Helm behavior and should be a
+ deliberate deployment decision.
+
+## Testing
+
+Use the repo tasks:
+
+```bash
+mise run server-sidecar-check
+mise run server-sidecar-fmt -- --check
+mise run server-sidecar-clippy
+mise run server-sidecar-test
+mise exec -- python tools/ci/check_ipc_types_parity.py
+mise run test -- packages/sie_server/tests/test_parity_run_batch.py
+```
+
+What is covered:
+
+- Rust unit tests for scheduler, adaptive controller, IPC framing/retry,
+ payload confinement, metrics, output framing, tokenizer registry, publisher,
+ shutdown, and NATS helpers. `mise run server-sidecar-test` runs the crate once with
+ default features and once with `cloud-storage` so S3/GCS payload-store code is
+ compiled and tested in the normal worker path.
+- Rust integration smoke tests with real `nats-server`, real `sie-server-sidecar`, and
+ a Python IPC harness.
+- Python parity tests for `RunBatch` fixtures under `tests/parity/`.
+- IPC type parity between Rust and Python schema declarations.
+
+## Architecture Decisions
+
+- Use a sidecar around Python adapters, not a full native rewrite.
+- Keep the adapter boundary over UDS msgpack IPC.
+- Use a long-lived async-nats pull stream.
+- Keep the runtime binary name stable as `sie-server-sidecar`; render the Kubernetes
+ sidecar container as `worker-sidecar`; publish the container image as
+ `sie-server-sidecar`.
+- Keep queue/runtime/prep/framing work in Rust while adapters remain in Python.
+- Treat native Candle/tch-rs backends as future work behind the same adapter
+ boundary.
diff --git a/packages/sie_server_sidecar/examples/print_tokenizer_hash.rs b/packages/sie_server_sidecar/examples/print_tokenizer_hash.rs
new file mode 100644
index 000000000..20163421c
--- /dev/null
+++ b/packages/sie_server_sidecar/examples/print_tokenizer_hash.rs
@@ -0,0 +1,31 @@
+//! Debug/ops helper: print the cross-language `tokenizer_id` hash
+//! for a given `tokenizer.json`.
+//!
+//! Useful when diagnosing a Python ↔ Rust tokenizer-id mismatch at
+//! runtime. The Python companion computes the same value via:
+//!
+//! ```python
+//! from tokenizers import Tokenizer
+//! import blake3
+//! tok = Tokenizer.from_file("/path/to/tokenizer.json")
+//! print(blake3.blake3(tok.to_str(pretty=False).encode()).hexdigest()[:32])
+//! ```
+//!
+//! Usage:
+//!
+//! ```bash
+//! cargo run --example print_tokenizer_hash -- /path/to/tokenizer.json
+//! ```
+
+use std::env;
+
+use sie_server_sidecar::tokenize::tokenizer_content_hash;
+use tokenizers::Tokenizer;
+
+fn main() -> Result<(), Box<dyn std::error::Error>> {
+ let mut args = env::args().skip(1);
+ let path = args.next().ok_or("usage: print_tokenizer_hash <path>")?;
+ let tok = Tokenizer::from_file(&path).map_err(|e| format!("load {path}: {e}"))?;
+ println!("{}", tokenizer_content_hash(&tok));
+ Ok(())
+}
diff --git a/packages/sie_server_sidecar/examples/replay_controller_trace.rs b/packages/sie_server_sidecar/examples/replay_controller_trace.rs
new file mode 100644
index 000000000..77ee3bf35
--- /dev/null
+++ b/packages/sie_server_sidecar/examples/replay_controller_trace.rs
@@ -0,0 +1,230 @@
+//! Replay an adaptive-controller trace through the Rust
+//! [`AdaptiveBatchController`] and emit one `step` output per line on
+//! stdout.
+//!
+//! Used by `scripts/perf/replay-scheduler-trace.py` to validate that
+//! the Rust controller produces byte-identical (actually ULP-identical)
+//! outputs to Python on captured traces.
+//!
+//! ## Trace format (JSONL on stdin)
+//!
+//! Each line is one event of shape:
+//!
+//! ```json
+//! {"event": "step", "observed_p50_ms": 45.2, "fill_ratio": 0.81, "batch_size": 32}
+//! {"event": "record_inference", "inference_ms": 12.5}
+//! ```
+//!
+//! * `step` events advance the controller; the response line carries
+//! the returned `(wait_ms, batch_cost)` plus `starvation_resets`.
+//! * `record_inference` feeds the auto-calibration tracker. Emits no
+//! response line — skipped on the consumer side as well.
+//!
+//! Unknown fields are ignored (`serde(default)`), unknown events are
+//! an error (fail-loud so a typo in the capture doesn't silently
+//! skip events).
+//!
+//! ## CLI
+//!
+//! `--config <path>`: optional JSON file with controller construction
+//! parameters (see `BuilderConfig` below). Defaults to the same
+//! Python-parity defaults used in
+//! `sie_server.config.engine.AdaptiveBatchingConfig`.
+//!
+//! Output is one JSONL line per *step* event (not per input line).
+
+use std::io::{self, BufRead, BufWriter, Write};
+
+use serde::{Deserialize, Serialize};
+use sie_server_sidecar::scheduler::{AdaptiveBatchController, AdaptiveBatchControllerBuilder};
+
+#[derive(Debug, Default, Deserialize)]
+struct BuilderConfig {
+ // Every field mirrors
+ // `sie_server.config.engine.AdaptiveBatchingConfig`. Using double
+ // `Option` for `target_p50_ms` so the JSON `null` explicitly opts
+ // into auto-calibration; omitting the key falls back to the
+ // builder default (None => auto-calibrate as well, so the two are
+ // semantically equivalent — the wrapper exists for trace fidelity
+ // when rolling out from a Python config that explicitly set
+ // `target_p50_ms: null`).
+ target_p50_ms: Option<Option<f64>>,
+ calibration_multiplier: Option<f64>,
+ min_target_p50_ms: Option<f64>,
+ max_target_p50_ms: Option<f64>,
+ min_wait_ms: Option<f64>,
+ max_wait_ms: Option<f64>,
+ min_batch_cost: Option<u64>,
+ max_batch_cost: Option<u64>,
+ gain: Option<f64>,
+ integral_gain: Option<f64>,
+ cost_gain: Option<f64>,
+ update_interval: Option<u32>,
+ fill_ratio_threshold: Option<f64>,
+ starvation_recovery_enabled: Option<bool>,
+ starvation_window: Option<u32>,
+ starvation_batch_size: Option<u32>,
+ initial_wait_ms: Option<f64>,
+ initial_batch_cost: Option<u64>,
+}
+
+impl BuilderConfig {
+ fn into_builder(self) -> AdaptiveBatchControllerBuilder {
+ let mut b = AdaptiveBatchController::builder();
+ if let Some(v) = self.target_p50_ms {
+ b = b.target_p50_ms(v);
+ }
+ if let Some(v) = self.calibration_multiplier {
+ b = b.calibration_multiplier(v);
+ }
+ if let Some(v) = self.min_target_p50_ms {
+ b = b.min_target_p50_ms(v);
+ }
+ if let Some(v) = self.max_target_p50_ms {
+ b = b.max_target_p50_ms(v);
+ }
+ if let Some(v) = self.min_wait_ms {
+ b = b.min_wait_ms(v);
+ }
+ if let Some(v) = self.max_wait_ms {
+ b = b.max_wait_ms(v);
+ }
+ if let Some(v) = self.min_batch_cost {
+ b = b.min_batch_cost(v);
+ }
+ if let Some(v) = self.max_batch_cost {
+ b = b.max_batch_cost(v);
+ }
+ if let Some(v) = self.gain {
+ b = b.gain(v);
+ }
+ if let Some(v) = self.integral_gain {
+ b = b.integral_gain(v);
+ }
+ if let Some(v) = self.cost_gain {
+ b = b.cost_gain(v);
+ }
+ if let Some(v) = self.update_interval {
+ b = b.update_interval(v);
+ }
+ if let Some(v) = self.fill_ratio_threshold {
+ b = b.fill_ratio_threshold(v);
+ }
+ if let Some(v) = self.starvation_recovery_enabled {
+ b = b.starvation_recovery_enabled(v);
+ }
+ if let Some(v) = self.starvation_window {
+ b = b.starvation_window(v);
+ }
+ if let Some(v) = self.starvation_batch_size {
+ b = b.starvation_batch_size(v);
+ }
+ if let Some(v) = self.initial_wait_ms {
+ b = b.initial_wait_ms(v);
+ }
+ if let Some(v) = self.initial_batch_cost {
+ b = b.initial_batch_cost(v);
+ }
+ b
+ }
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(tag = "event", rename_all = "snake_case")]
+enum TraceEvent {
+ Step {
+ /// Elapsed seconds since the previous `step` event. Required
+ /// (not `Option<f64>`) so a trace that forgets to capture
+ /// `dt_s` fails loudly at parse time instead of silently
+ /// driving a zero integrator on one side.
+ dt_s: f64,
+ #[serde(default)]
+ observed_p50_ms: Option<f64>,
+ #[serde(default)]
+ fill_ratio: Option<f64>,
+ #[serde(default)]
+ batch_size: Option<usize>,
+ },
+ RecordInference {
+ inference_ms: f64,
+ },
+}
+
+#[derive(Debug, Serialize)]
+struct StepOutput {
+ wait_ms: f64,
+ batch_cost: u64,
+ /// Cumulative count — lets the diff tool verify starvation events
+ /// landed on the same step index in both implementations, not just
+ /// "the totals agree at the end".
+ starvation_resets: u32,
+}
+
+fn main() -> anyhow::Result<()> {
+ // Minimal CLI: `--config <path>`; everything else is unrecognised
+ // on purpose so trace format stays the public interface.
+ let mut args = std::env::args().skip(1);
+ let mut config: BuilderConfig = BuilderConfig::default();
+ while let Some(arg) = args.next() {
+ match arg.as_str() {
+ "--config" => {
+ let path = args
+ .next()
+ .ok_or_else(|| anyhow::anyhow!("--config requires a path argument"))?;
+ let raw = std::fs::read_to_string(&path)?;
+ config = serde_json::from_str(&raw)?;
+ }
+ "-h" | "--help" => {
+ eprintln!(
+ "replay_controller_trace [--config CONFIG.json]\n\
+ Reads JSONL trace events from stdin, emits one JSONL\n\
+ step-output line per `step` event on stdout."
+ );
+ return Ok(());
+ }
+ other => anyhow::bail!("unknown argument: {other}"),
+ }
+ }
+
+ let mut ctrl = config.into_builder().build();
+
+ let stdin = io::stdin();
+ let stdout = io::stdout();
+ let mut out = BufWriter::new(stdout.lock());
+
+ for (lineno, line) in stdin.lock().lines().enumerate() {
+ let raw = line?;
+ let trimmed = raw.trim();
+ if trimmed.is_empty() || trimmed.starts_with('#') {
+ continue;
+ }
+ let event: TraceEvent = serde_json::from_str(trimmed).map_err(|e| {
+ anyhow::anyhow!("line {}: invalid JSON: {} ({})", lineno + 1, e, trimmed)
+ })?;
+ match event {
+ TraceEvent::Step {
+ dt_s,
+ observed_p50_ms,
+ fill_ratio,
+ batch_size,
+ } => {
+ let (wait_ms, batch_cost) =
+ ctrl.step_replay(dt_s, observed_p50_ms, fill_ratio, batch_size);
+ let snap = ctrl.snapshot(observed_p50_ms, fill_ratio);
+ let output = StepOutput {
+ wait_ms,
+ batch_cost,
+ starvation_resets: snap.starvation_resets,
+ };
+ serde_json::to_writer(&mut out, &output)?;
+ out.write_all(b"\n")?;
+ }
+ TraceEvent::RecordInference { inference_ms } => {
+ ctrl.record_inference_sample(inference_ms);
+ }
+ }
+ }
+
+ out.flush()?;
+ Ok(())
+}
diff --git a/packages/sie_server_sidecar/src/backend/mod.rs b/packages/sie_server_sidecar/src/backend/mod.rs
new file mode 100644
index 000000000..240747f71
--- /dev/null
+++ b/packages/sie_server_sidecar/src/backend/mod.rs
@@ -0,0 +1,228 @@
+//! 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.
+//!
+//! # 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.
+//!
+//! # Not a runtime fallback
+//!
+//! A [`BackendRouter`] composes multiple backends and routes each
+//! operation to the first one that claims the model. Routing is
+//! deterministic and config-driven (order of construction = priority).
+//!
+//! Critically, routing happens at readiness time — it is **not** a
+//! retry-on-error fallback. If a native backend claims a model and
+//! inference fails, the backend is responsible for fanning out
+//! per-item error outcomes in an `Ok(BatchOutcome)` and the dispatcher
+//! ACKs the messages (see the error handling contract below). The
+//! router does **not** silently retry via Python. Numeric divergence
+//! between two embedders is a correctness bug, not a feature, and we
+//! refuse to paper over it.
+//!
+//! # Error handling contract
+//!
+//! The dispatcher's only lever is ACK vs NAK vs per-item publish. It
+//! uses the backend's return value this way:
+//!
+//! * `Ok(BatchOutcome)` → dispatcher honours every [`crate::ipc_types::ItemOutcome`]'s
+//! [`crate::ipc_types::Disposition`]. A well-behaved backend that
+//! handles its own inference failures returns `Ok` with some items
+//! set to `PublishErrorAndAck` — the per-item path.
+//! * `Err(BackendError::Transient)` → NAK the whole group with the
+//! base delay. Use for **infrastructure** failures (broken IPC pipe,
+//! CUDA unavailable, connection reset) where a different pod or the
+//! next redeliver might succeed.
+//! * `Err(BackendError::UnsupportedModel)` → the router falls through
+//! to the next backend; if none claim it, the dispatcher NAKs so a
+//! different pod can pick it up.
+//! * `Err(BackendError::Draining)` → NAK fast; we're shutting down.
+//! * `Err(BackendError::Inference)` → **currently unused at the batch
+//! level.** Reserved for a future protocol where per-batch inference
+//! failure maps to synthetic per-item errors inside the dispatcher.
+//! Do not emit this from new backends — fan out to `PublishErrorAndAck`
+//! items inside `Ok(BatchOutcome)` instead. Emitting `Inference` today
+//! would cause the same retry-storm behaviour as `Transient`.
+//!
+//! # Contract
+//!
+//! * [`InferenceBackend::supports`] is advisory — used by the router
+//! to pick a backend cheaply before any RPC. The authoritative answer
+//! is [`InferenceBackend::ensure_model_ready`].
+//! * [`InferenceBackend::ensure_model_ready`] returns the same
+//! [`EnsureModelReadyResponse`] the dispatcher already handles
+//! (Ready / LoadingStarted / LoadingInProgress / RetryLater plus an
+//! optional `batch_budget`). Backends populate it from their own
+//! load state; the dispatcher's NAK/ACK policy is unchanged.
+//! * `process_*_batch` runs the batch and returns a [`BatchOutcome`]
+//! whose [`crate::ipc_types::ItemOutcome`]s drive per-message publish/ACK/NAK. The
+//! dispatcher has already capped the input at the budget reported
+//! by `ensure_model_ready`, so backends don't need to re-split.
+//! * [`InferenceBackend::drain`] is called once at shutdown. The
+//! deadline is advisory — drains should finish promptly and never
+//! block shutdown indefinitely.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+
+use crate::ipc_types::{
+ BatchOutcome, EnsureModelReadyResponse, ProcessEncodeBatchRequest, ProcessExtractBatchRequest,
+ ProcessScoreBatchRequest, RunBatchRequest,
+};
+
+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
+// under `prep` and `protocol`.
+
+pub use python_ipc::PythonIpcBackend;
+pub use router::BackendRouter;
+
+/// Error taxonomy for backend calls.
+///
+/// See the **Error handling contract** in the module docstring above
+/// for how each variant maps to ACK / NAK / per-item dispatcher
+/// behaviour. In particular: **do not emit [`BackendError::Inference`]
+/// from new backends**; convert per-batch inference failures into
+/// per-item `PublishErrorAndAck` outcomes inside an `Ok(BatchOutcome)`.
+#[derive(Debug, thiserror::Error)]
+pub enum BackendError {
+ /// Transport / infrastructure glitch. Dispatcher NAKs with the
+ /// base delay; JetStream redelivers.
+ #[error("transient: {0}")]
+ Transient(String),
+
+ /// **Reserved.** Batch-level inference failure. Currently no
+ /// dispatcher mapping — emitting this causes NAK-and-redeliver
+ /// (same as [`BackendError::Transient`]), which can retry-storm.
+ /// New backends should fan out per-item errors inside a successful
+ /// [`BatchOutcome`] instead.
+ #[error("inference: {0}")]
+ Inference(String),
+
+ /// No backend in the router claims this model (or the one that
+ /// did later rejected it). Router tries the next; if none
+ /// remain, dispatcher NAKs so another pod can pick it up.
+ #[error("unsupported model: {0}")]
+ UnsupportedModel(String),
+
+ /// Backend is shutting down. NAK fast.
+ #[error("draining")]
+ Draining,
+}
+
+impl BackendError {
+ /// True if the dispatcher should NAK the group rather than error
+ /// out per-item. Transport / readiness / drain failures fall here.
+ pub fn is_retryable(&self) -> bool {
+ matches!(
+ self,
+ BackendError::Transient(_) | BackendError::UnsupportedModel(_) | BackendError::Draining
+ )
+ }
+}
+
+/// Trait object implementing inference for one or more models.
+///
+/// Backends are long-lived, shared across the dispatcher fan-out via
+/// `Arc`, and must be `Send + Sync`. A backend that loads weights
+/// eagerly should do so at construction; one that loads lazily should
+/// surface the load state through [`InferenceBackend::ensure_model_ready`].
+#[async_trait]
+pub trait InferenceBackend: Send + Sync {
+ /// Short, stable name for logs and metrics (e.g. `"python-ipc"`,
+ /// `"native-bert"`). Must be a valid Prometheus label value.
+ fn name(&self) -> &'static str;
+
+ /// Cheap, synchronous check: does this backend handle `model_id`?
+ ///
+ /// The router uses this to pick a backend before issuing any RPC.
+ /// Returning `true` does **not** mean the model is loaded — only
+ /// that this backend is responsible for it.
+ ///
+ /// A backend that serves every model (like [`PythonIpcBackend`])
+ /// returns `true` unconditionally. A specialised backend returns
+ /// `true` only for its allow-list.
+ fn supports(&self, model_id: &str) -> bool;
+
+ /// Ensure the model is loaded (or kick off a load) and report
+ /// readiness + the per-batch budget the dispatcher should honour.
+ ///
+ /// Semantics match the Python `ensure_model_ready` IPC method
+ /// exactly: see [`crate::ipc_types::ReadinessState`] for the
+ /// state machine.
+ async fn ensure_model_ready(
+ &self,
+ model_id: &str,
+ ) -> Result<EnsureModelReadyResponse, BackendError>;
+
+ /// Run an encode batch. Inputs are a flat list of prepared items;
+ /// the backend is responsible for its own internal batching and
+ /// tokenisation.
+ async fn process_encode_batch(
+ &self,
+ req: ProcessEncodeBatchRequest,
+ ) -> Result<BatchOutcome, BackendError>;
+
+ /// Run a score batch (one query vs. N documents, typically).
+ async fn process_score_batch(
+ &self,
+ req: ProcessScoreBatchRequest,
+ ) -> Result<BatchOutcome, BackendError>;
+
+ /// Run an extract batch.
+ async fn process_extract_batch(
+ &self,
+ req: ProcessExtractBatchRequest,
+ ) -> Result<BatchOutcome, BackendError>;
+
+ /// Run a pre-formed batch assembled by the Rust-side scheduler
+ /// (see [`crate::scheduler::Scheduler`]). Every item in the
+ /// batch shares the same `op` (the scheduler's batchers are
+ /// keyed per-`(op, lora)`), so a backend that lacks native
+ /// `RunBatch` support can fan out into the matching
+ /// `process_*_batch` call internally — see
+ /// [`crate::backend::PythonIpcBackend::run_batch`] for the
+ /// reference implementation.
+ ///
+ /// The default implementation returns
+ /// [`BackendError::UnsupportedModel`] so a backend that only
+ /// implements the per-op `process_*_batch` calls doesn't silently
+ /// swallow `RunBatch` requests. The [`crate::backend::BackendRouter`]
+ /// falls through to the next registered backend on this error so
+ /// the Python IPC catch-all still wins.
+ async fn run_batch(&self, req: RunBatchRequest) -> Result<BatchOutcome, BackendError> {
+ let _ = req;
+ Err(BackendError::UnsupportedModel(format!(
+ "run_batch not implemented on {}",
+ self.name()
+ )))
+ }
+
+ /// Graceful shutdown. Called once when the worker has stopped
+ /// pulling from NATS. Backends should:
+ ///
+ /// * Reject new work (return `BackendError::Draining` from
+ /// subsequent `process_*` calls if any race in).
+ /// * Wait for in-flight requests to settle, up to `deadline_ms`.
+ /// * Release resources (close sockets, free GPU memory).
+ ///
+ /// The default implementation is a no-op so native backends can
+ /// opt out when their state lives in-process.
+ async fn drain(&self, _deadline_ms: u64) {}
+}
+
+/// Convenience alias used throughout the dispatcher.
+pub type SharedBackend = Arc<dyn InferenceBackend>;
diff --git a/packages/sie_server_sidecar/src/backend/python_ipc.rs b/packages/sie_server_sidecar/src/backend/python_ipc.rs
new file mode 100644
index 000000000..77342bdfd
--- /dev/null
+++ b/packages/sie_server_sidecar/src/backend/python_ipc.rs
@@ -0,0 +1,152 @@
+//! Default [`InferenceBackend`] — delegates to the Python `sie-server`
+//! over the UDS+msgpack IPC that already exists.
+//!
+//! This is a thin adapter. The on-wire protocol and semantics are
+//! defined in [`crate::ipc_client`] and `sie_server.ipc_server`; this
+//! module just maps the IPC error types to [`BackendError`].
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use tracing::{debug, warn};
+
+use crate::backend::{BackendError, InferenceBackend};
+use crate::ipc_client::{IpcClient, IpcError};
+use crate::ipc_types::{
+ BatchOutcome, EnsureModelReadyResponse, ProcessEncodeBatchRequest, ProcessExtractBatchRequest,
+ ProcessScoreBatchRequest, RunBatchRequest,
+};
+
+/// Routes every call through [`IpcClient`] to the Python sie-server process.
+///
+/// Python is the authoritative adapter registry, so this backend claims
+/// every model (`supports() == true`). When composing multiple
+/// backends via [`crate::backend::BackendRouter`], register this one
+/// last so specialised backends get first refusal.
+pub struct PythonIpcBackend {
+ ipc: Arc<IpcClient>,
+}
+
+impl PythonIpcBackend {
+ pub fn new(ipc: Arc<IpcClient>) -> Self {
+ Self { ipc }
+ }
+}
+
+/// Map an [`IpcError`] to a [`BackendError`].
+///
+/// * Transport-level errors (I/O, timeout, frame-too-large, decode) →
+/// `Transient`: the dispatcher NAKs and JetStream redelivers. The
+/// IPC client already retries once on transport errors internally,
+/// so when we get here the glitch is persistent.
+/// * Protocol-level errors (`Server`, `VersionMismatch`, `Encode`) →
+/// `Transient` as well. These usually indicate a mismatched Python
+/// build or a logical executor error; NAK-and-redeliver lets another
+/// pod take the work while we recover.
+///
+/// Note: the IPC contract does not surface `UnsupportedModel` through
+/// 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 {
+ // 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())
+}
+
+#[async_trait]
+impl InferenceBackend for PythonIpcBackend {
+ fn name(&self) -> &'static str {
+ "python-ipc"
+ }
+
+ fn supports(&self, _model_id: &str) -> bool {
+ true
+ }
+
+ async fn ensure_model_ready(
+ &self,
+ model_id: &str,
+ ) -> Result<EnsureModelReadyResponse, BackendError> {
+ self.ipc
+ .ensure_model_ready(model_id)
+ .await
+ .map_err(map_ipc_error)
+ }
+
+ async fn process_encode_batch(
+ &self,
+ req: ProcessEncodeBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ self.ipc
+ .process_encode_batch(req)
+ .await
+ .map_err(map_ipc_error)
+ }
+
+ async fn process_score_batch(
+ &self,
+ req: ProcessScoreBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ self.ipc
+ .process_score_batch(req)
+ .await
+ .map_err(map_ipc_error)
+ }
+
+ async fn process_extract_batch(
+ &self,
+ req: ProcessExtractBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ self.ipc
+ .process_extract_batch(req)
+ .await
+ .map_err(map_ipc_error)
+ }
+
+ async fn run_batch(&self, req: RunBatchRequest) -> Result<BatchOutcome, BackendError> {
+ // Matches the `METHOD_RUN_BATCH` handler Python registers in
+ // `sie_server/ipc_server.py`. Transport/protocol failures
+ // still map to `Transient` — the dispatcher NAKs and
+ // JetStream redelivers into either the scheduler (if the
+ // model still routes to the worker-sidecar) or the per-op Python path.
+ self.ipc.run_batch(req).await.map_err(map_ipc_error)
+ }
+
+ async fn drain(&self, deadline_ms: u64) {
+ match self.ipc.drain(deadline_ms).await {
+ Ok(resp) => debug!(
+ acknowledged = resp.acknowledged,
+ "python-ipc drain acknowledged"
+ ),
+ Err(e) => warn!(error = %e, "python-ipc drain RPC failed"),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io;
+
+ #[test]
+ fn map_ipc_error_produces_transient_for_io() {
+ let e = IpcError::Io(io::Error::new(io::ErrorKind::BrokenPipe, "pipe"));
+ let be = map_ipc_error(e);
+ assert!(matches!(be, BackendError::Transient(_)));
+ assert!(be.is_retryable());
+ }
+
+ #[test]
+ fn map_ipc_error_produces_transient_for_server() {
+ let e = IpcError::Server("model load failed".into());
+ let be = map_ipc_error(e);
+ assert!(matches!(be, BackendError::Transient(_)));
+ }
+
+ #[test]
+ fn map_ipc_error_produces_transient_for_timeout() {
+ let be = map_ipc_error(IpcError::Timeout);
+ assert!(matches!(be, BackendError::Transient(_)));
+ }
+}
diff --git a/packages/sie_server_sidecar/src/backend/router.rs b/packages/sie_server_sidecar/src/backend/router.rs
new file mode 100644
index 000000000..b40fa3ea1
--- /dev/null
+++ b/packages/sie_server_sidecar/src/backend/router.rs
@@ -0,0 +1,968 @@
+//! [`BackendRouter`] — picks the right [`InferenceBackend`] for a
+//! given `model_id` and forwards the call.
+//!
+//! # Routing rules
+//!
+//! * Backends are tried in **construction order**. The first backend
+//! whose `supports(model_id)` returns `true` wins.
+//! * Routing is cached per `model_id` after the first successful
+//! [`InferenceBackend::ensure_model_ready`] so we don't re-scan on
+//! every batch. A backend that later stops claiming a model is not
+//! handled — restart the worker.
+//! * If `ensure_model_ready` returns [`BackendError::UnsupportedModel`],
+//! the router falls through to the next backend. Any **other** error
+//! short-circuits: we do not silently swap backends on transient
+//! failures (numeric divergence between two embedders = correctness
+//! bug, not feature).
+//!
+//! # Configuration
+//!
+//! Callers construct the router explicitly via
+//! [`BackendRouter::from_backends`]. Priority comes from the caller
+//! (see `lib.rs::run`); this module stays focused on dispatch.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+use std::time::Instant;
+
+use async_trait::async_trait;
+use tokio::sync::RwLock;
+use tracing::{debug, warn};
+
+use crate::backend::{BackendError, InferenceBackend, SharedBackend};
+use crate::ipc_types::{
+ BatchOutcome, Disposition, EnsureModelReadyResponse, ProcessEncodeBatchRequest,
+ ProcessExtractBatchRequest, ProcessScoreBatchRequest, ReadinessState, RunBatchRequest,
+};
+use crate::metrics::MetricsRegistry;
+
+/// Picks a backend per `model_id` and forwards calls to it.
+pub struct BackendRouter {
+ /// Ordered list — first match wins.
+ backends: Vec<SharedBackend>,
+ /// `model_id -> index into backends`. Populated on first
+ /// successful readiness check; avoids re-scanning on every batch.
+ cache: RwLock<HashMap<String, usize>>,
+ /// Optional metrics sink. When set, dispatch records per-backend
+ /// histograms and counters; when unset (tests), dispatch is
+ /// effectively unchanged. Wired by `lib.rs::run`.
+ metrics: Option<Arc<MetricsRegistry>>,
+}
+
+impl BackendRouter {
+ /// Construct from a non-empty, priority-ordered backend list.
+ ///
+ /// # Panics
+ ///
+ /// If `backends` is empty — a router with no backends is always
+ /// wrong, and silently accepting that just moves the error to
+ /// runtime where it'd NAK every message.
+ pub fn from_backends(backends: Vec<SharedBackend>) -> Arc<Self> {
+ Self::from_backends_with_metrics(backends, None)
+ }
+
+ /// Like [`BackendRouter::from_backends`], but also wires a
+ /// metrics registry so dispatch emits per-backend observability
+ /// metrics.
+ pub fn from_backends_with_metrics(
+ backends: Vec<SharedBackend>,
+ metrics: Option<Arc<MetricsRegistry>>,
+ ) -> Arc<Self> {
+ assert!(
+ !backends.is_empty(),
+ "BackendRouter requires at least one backend"
+ );
+ Arc::new(Self {
+ metrics,
+ backends,
+ cache: RwLock::new(HashMap::new()),
+ })
+ }
+
+ /// Convenience for the default (Python-only) deployment.
+ pub fn with_python_only(python: SharedBackend) -> Arc<Self> {
+ Self::from_backends(vec![python])
+ }
+
+ async fn cached_index(&self, model_id: &str) -> Option<usize> {
+ self.cache.read().await.get(model_id).copied()
+ }
+
+ async fn cache_index(&self, model_id: &str, idx: usize) {
+ self.cache.write().await.insert(model_id.to_string(), idx);
+ }
+
+ async fn invalidate_index(&self, model_id: &str) {
+ self.cache.write().await.remove(model_id);
+ }
+
+ /// First backend that claims `model_id` via `supports()`.
+ fn first_supporting(&self, model_id: &str) -> Option<usize> {
+ self.backends.iter().position(|b| b.supports(model_id))
+ }
+
+ /// Resolve a backend for `model_id`, consulting (and populating)
+ /// the cache. Returns `UnsupportedModel` if no backend claims it.
+ ///
+ /// Returns both the index and the backend so callers that need to
+ /// fall through on `UnsupportedModel` at the `process_*_batch`
+ /// level can start the search from the next slot.
+ async fn backend_for(&self, model_id: &str) -> Result<(usize, &SharedBackend), BackendError> {
+ if let Some(idx) = self.cached_index(model_id).await {
+ return Ok((idx, &self.backends[idx]));
+ }
+ let idx = self
+ .first_supporting(model_id)
+ .ok_or_else(|| BackendError::UnsupportedModel(model_id.to_string()))?;
+ Ok((idx, &self.backends[idx]))
+ }
+
+ /// Generic dispatch for a per-op `process_*_batch` call with
+ /// fall-through on `UnsupportedModel`. Mirrors the
+ /// `ensure_model_ready` contract: a backend that claims a model via
+ /// `supports()` but rejects a specific op (e.g. a cross-encoder
+ /// asked to `encode`) is treated as a routing miss, not a hard
+ /// failure — the router tries the next backend. Any other error
+ /// short-circuits.
+ async fn dispatch<F, Fut>(
+ &self,
+ model_id: &str,
+ op_name: &'static str,
+ batch_size: usize,
+ call: F,
+ ) -> Result<BatchOutcome, BackendError>
+ where
+ F: Fn(SharedBackend) -> Fut,
+ Fut: std::future::Future<Output = Result<BatchOutcome, BackendError>>,
+ {
+ let (start_idx, first) = self.backend_for(model_id).await?;
+ let first_name = first.name();
+ match self
+ .call_instrumented(Arc::clone(first), model_id, op_name, batch_size, &call)
+ .await
+ {
+ Ok(resp) => return Ok(resp),
+ Err(BackendError::UnsupportedModel(_)) => {
+ // The backend claimed the model via `supports()` but
+ // rejected this specific op (classic shape: a native
+ // encoder asked to `score` — delegate to Python IPC).
+ // Do NOT invalidate the cached binding: the cache is
+ // per-model, so wiping it would also reroute future
+ // `encode` calls through Python and defeat the native
+ // fast path.
+ debug!(
+ model = %model_id,
+ backend = first_name,
+ op = op_name,
+ "router: backend doesn't serve this op, falling through"
+ );
+ }
+ Err(e) => return Err(e),
+ }
+
+ for (_idx, backend) in self.backends.iter().enumerate().skip(start_idx + 1) {
+ if !backend.supports(model_id) {
+ continue;
+ }
+ match self
+ .call_instrumented(Arc::clone(backend), model_id, op_name, batch_size, &call)
+ .await
+ {
+ Ok(resp) => {
+ if let Some(m) = &self.metrics {
+ m.router_fallthrough_total
+ .with_label_values(&[first_name, backend.name(), op_name])
+ .inc();
+ }
+ // NOTE: Do NOT promote this backend in the cache. The
+ // model cache is per-model, not per-(model, op). A
+ // common deployment has a native encoder serve
+ // `encode` for a given model_id and Python IPC serve
+ // `score` / `extract` for the same model_id — if we
+ // cached the Python backend after the first score
+ // call, subsequent `encode` calls would also route
+ // to Python, silently losing the native fast path.
+ // Re-resolving from `first_supporting` on every miss
+ // keeps ops routing correct at the cost of a cheap
+ // O(backends) scan per op-level miss.
+ return Ok(resp);
+ }
+ Err(BackendError::UnsupportedModel(_)) => continue,
+ Err(e) => return Err(e),
+ }
+ }
+
+ Err(BackendError::UnsupportedModel(model_id.to_string()))
+ }
+
+ async fn ensure_ready_instrumented(
+ &self,
+ backend: &SharedBackend,
+ model_id: &str,
+ ) -> Result<EnsureModelReadyResponse, BackendError> {
+ let start = Instant::now();
+ let result = backend.ensure_model_ready(model_id).await;
+ if let Some(m) = &self.metrics {
+ let elapsed = start.elapsed().as_secs_f64();
+ let outcome_label: &str = match &result {
+ Ok(resp) => match resp.state {
+ ReadinessState::Ready => "ready",
+ ReadinessState::LoadingStarted => "loading_started",
+ ReadinessState::LoadingInProgress => "loading_in_progress",
+ ReadinessState::RetryLater => "retry_later",
+ },
+ Err(BackendError::UnsupportedModel(_)) => "unsupported",
+ Err(BackendError::Draining) => "draining",
+ Err(BackendError::Transient(_)) => "transient",
+ Err(BackendError::Inference(_)) => "inference",
+ };
+ let model_lbl = m.model_label(model_id);
+ m.backend_ensure_ready_seconds
+ .with_label_values(&[backend.name(), &model_lbl, outcome_label])
+ .observe(elapsed);
+ // Count loading transitions so operators can see "model loads"
+ // driven by the Python executor.
+ if matches!(
+ &result,
+ Ok(resp) if resp.state == ReadinessState::LoadingStarted
+ ) {
+ m.pull_model_loads_total
+ .with_label_values(&[&model_lbl])
+ .inc();
+ }
+ }
+ result
+ }
+
+ /// Invoke one backend and record the per-backend observability
+ /// metrics around it. Keeps `dispatch` readable while ensuring
+ /// every call site gets uniform instrumentation.
+ async fn call_instrumented<F, Fut>(
+ &self,
+ backend: SharedBackend,
+ model_id: &str,
+ op_name: &'static str,
+ batch_size: usize,
+ call: &F,
+ ) -> Result<BatchOutcome, BackendError>
+ where
+ F: Fn(SharedBackend) -> Fut,
+ Fut: std::future::Future<Output = Result<BatchOutcome, BackendError>>,
+ {
+ let backend_name = backend.name();
+ if let Some(m) = &self.metrics {
+ m.backend_batch_items
+ .with_label_values(&[backend_name, op_name])
+ .observe(batch_size as f64);
+ }
+ let start = Instant::now();
+ let result = call(backend).await;
+ let elapsed = start.elapsed().as_secs_f64();
+
+ if let Some(m) = &self.metrics {
+ let model_lbl = m.model_label(model_id);
+ let outcome_label: &str = match &result {
+ Ok(_) => "ok",
+ Err(BackendError::UnsupportedModel(_)) => "unsupported",
+ Err(BackendError::Draining) => "draining",
+ Err(BackendError::Transient(_)) => "transient",
+ Err(BackendError::Inference(_)) => "inference",
+ };
+ m.backend_process_seconds
+ .with_label_values(&[backend_name, op_name, &model_lbl, outcome_label])
+ .observe(elapsed);
+
+ if let Err(err) = &result {
+ let kind = match err {
+ BackendError::UnsupportedModel(_) => "unsupported",
+ BackendError::Draining => "draining",
+ BackendError::Transient(_) => "transient",
+ BackendError::Inference(_) => "inference",
+ };
+ m.backend_process_errors_total
+ .with_label_values(&[backend_name, op_name, kind])
+ .inc();
+ } else if let Ok(outcome) = &result {
+ // Count per-item dispositions; this is where the
+ // fanout of "publish success" vs "publish error"
+ // vs "ack-to-drop" becomes visible on the dashboard.
+ for item in &outcome.outcomes {
+ let disp = match item.disposition {
+ Disposition::PublishAndAck => "publish_and_ack",
+ Disposition::PublishErrorAndAck => "publish_error_and_ack",
+ Disposition::NakRetry => "nak_retry",
+ };
+ m.backend_item_outcomes_total
+ .with_label_values(&[backend_name, op_name, disp])
+ .inc();
+ }
+ }
+ }
+
+ result
+ }
+
+ /// Total number of registered backends. Always `>= 1` —
+ /// [`BackendRouter::from_backends`] panics on empty input, so
+ /// the `is_empty` sibling that clippy would like us to expose
+ /// would always return `false`.
+ #[allow(clippy::len_without_is_empty)]
+ pub fn len(&self) -> usize {
+ self.backends.len()
+ }
+
+ /// Drain every registered backend concurrently; one slow drain
+ /// can't block the others.
+ ///
+ /// Dedupes by `Arc` pointer identity as a defensive measure in
+ /// case the same backend was registered twice (e.g. an ops misconfig).
+ pub async fn drain_all(&self, deadline_ms: u64) {
+ use std::collections::HashSet;
+ // Arc pointer identity as `usize` so the set is `Send`.
+ let mut seen: HashSet<usize> = HashSet::new();
+ let mut unique: Vec<Arc<dyn InferenceBackend>> = Vec::with_capacity(self.backends.len());
+ for b in &self.backends {
+ let id = Arc::as_ptr(b) as *const () as usize;
+ if seen.insert(id) {
+ unique.push(Arc::clone(b));
+ }
+ }
+ // Drop `seen` before the await so the future stays Send.
+ drop(seen);
+ let futs: Vec<_> = unique
+ .into_iter()
+ .map(|b| async move { b.drain(deadline_ms).await })
+ .collect();
+ futures_util::future::join_all(futs).await;
+ }
+
+ /// Backend names, in priority order. For logging at startup.
+ pub fn names(&self) -> Vec<&'static str> {
+ self.backends.iter().map(|b| b.name()).collect()
+ }
+}
+
+/// The router itself satisfies [`InferenceBackend`], so the dispatcher
+/// can hold an `Arc<BackendRouter>` or `Arc<dyn InferenceBackend>`
+/// interchangeably.
+#[async_trait]
+impl InferenceBackend for BackendRouter {
+ fn name(&self) -> &'static str {
+ "router"
+ }
+
+ fn supports(&self, model_id: &str) -> bool {
+ self.backends.iter().any(|b| b.supports(model_id))
+ }
+
+ async fn ensure_model_ready(
+ &self,
+ model_id: &str,
+ ) -> Result<EnsureModelReadyResponse, BackendError> {
+ let mut start_idx = 0;
+ if let Some(idx) = self.cached_index(model_id).await {
+ match self
+ .ensure_ready_instrumented(&self.backends[idx], model_id)
+ .await
+ {
+ Ok(resp) => return Ok(resp),
+ Err(BackendError::UnsupportedModel(_)) => {
+ self.invalidate_index(model_id).await;
+ start_idx = idx + 1;
+ }
+ Err(e) => return Err(e),
+ }
+ }
+
+ for (idx, backend) in self.backends.iter().enumerate().skip(start_idx) {
+ if !backend.supports(model_id) {
+ continue;
+ }
+ match self.ensure_ready_instrumented(backend, model_id).await {
+ Ok(resp) => {
+ debug!(
+ model = %model_id,
+ backend = backend.name(),
+ state = ?resp.state,
+ "router: bound model to backend"
+ );
+ self.cache_index(model_id, idx).await;
+ return Ok(resp);
+ }
+ Err(BackendError::UnsupportedModel(_)) => continue,
+ Err(e) => {
+ // Hard error on the first claimant — do NOT silently
+ // fall through to the next backend. Surface so the
+ // dispatcher NAKs and ops can diagnose.
+ warn!(
+ model = %model_id,
+ backend = backend.name(),
+ error = %e,
+ "router: backend readiness failed, not falling through"
+ );
+ return Err(e);
+ }
+ }
+ }
+
+ Err(BackendError::UnsupportedModel(model_id.to_string()))
+ }
+
+ async fn process_encode_batch(
+ &self,
+ req: ProcessEncodeBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ let model_id = req.model_id.clone();
+ let batch_size = req.items.len();
+ // Cheap to clone in the common (single-backend) case; the clone
+ // only matters if we fall through, which is the rare path.
+ let result = self
+ .dispatch(&model_id, "encode", batch_size, move |backend| {
+ let req = req.clone();
+ async move { backend.process_encode_batch(req).await }
+ })
+ .await;
+ result
+ }
+
+ async fn process_score_batch(
+ &self,
+ req: ProcessScoreBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ let model_id = req.model_id.clone();
+ let batch_size = req.items.len();
+ let result = self
+ .dispatch(&model_id, "score", batch_size, move |backend| {
+ let req = req.clone();
+ async move { backend.process_score_batch(req).await }
+ })
+ .await;
+ result
+ }
+
+ async fn process_extract_batch(
+ &self,
+ req: ProcessExtractBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ let model_id = req.model_id.clone();
+ let batch_size = req.items.len();
+ let result = self
+ .dispatch(&model_id, "extract", batch_size, move |backend| {
+ let req = req.clone();
+ async move { backend.process_extract_batch(req).await }
+ })
+ .await;
+ result
+ }
+
+ async fn run_batch(&self, req: RunBatchRequest) -> Result<BatchOutcome, BackendError> {
+ // `run_batch` uses the same fall-through semantics as the
+ // per-op dispatchers: the first backend whose `supports()`
+ // claims `model_id` handles it; `UnsupportedModel` trips the
+ // next backend in order. A native backend that only implements
+ // the per-op `process_*_batch` calls returns `UnsupportedModel`
+ // from `run_batch` (the default impl), so this path lets the
+ // Python IPC catch-all (tail of the router chain) pick up the
+ // batch without forcing every native backend to implement
+ // `run_batch`.
+ let model_id = req.model_id.clone();
+ let batch_size = req.items.len();
+ let result = self
+ .dispatch(&model_id, "run_batch", batch_size, move |backend| {
+ let req = req.clone();
+ async move { backend.run_batch(req).await }
+ })
+ .await;
+ result
+ }
+
+ async fn drain(&self, deadline_ms: u64) {
+ self.drain_all(deadline_ms).await;
+ }
+}
+
+// -----------------------------------------------------------------------------
+// Tests
+// -----------------------------------------------------------------------------
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ipc_types::ReadinessState;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ /// Test double — claims a configurable set of models and counts calls.
+ ///
+ /// `supports_all` makes it claim every model (mimicking Python).
+ struct MockBackend {
+ name: &'static str,
+ supported: Vec<String>,
+ supports_all: bool,
+ ready_err: Option<BackendError>,
+ process_err: Option<BackendError>,
+ score_err: Option<BackendError>,
+ extract_err: Option<BackendError>,
+ ready_calls: AtomicUsize,
+ process_calls: AtomicUsize,
+ score_calls: AtomicUsize,
+ extract_calls: AtomicUsize,
+ drain_calls: AtomicUsize,
+ }
+
+ impl MockBackend {
+ fn scoped(name: &'static str, supported: &[&str]) -> Self {
+ Self {
+ name,
+ supported: supported.iter().map(|s| s.to_string()).collect(),
+ supports_all: false,
+ ready_err: None,
+ process_err: None,
+ score_err: None,
+ extract_err: None,
+ ready_calls: AtomicUsize::new(0),
+ process_calls: AtomicUsize::new(0),
+ score_calls: AtomicUsize::new(0),
+ extract_calls: AtomicUsize::new(0),
+ drain_calls: AtomicUsize::new(0),
+ }
+ }
+ fn all(name: &'static str) -> Self {
+ Self {
+ name,
+ supported: vec![],
+ supports_all: true,
+ ready_err: None,
+ process_err: None,
+ score_err: None,
+ extract_err: None,
+ ready_calls: AtomicUsize::new(0),
+ process_calls: AtomicUsize::new(0),
+ score_calls: AtomicUsize::new(0),
+ extract_calls: AtomicUsize::new(0),
+ drain_calls: AtomicUsize::new(0),
+ }
+ }
+ fn with_ready_error(mut self, err: BackendError) -> Self {
+ self.ready_err = Some(err);
+ self
+ }
+ fn with_process_error(mut self, err: BackendError) -> Self {
+ self.process_err = Some(err);
+ self
+ }
+ fn with_score_error(mut self, err: BackendError) -> Self {
+ self.score_err = Some(err);
+ self
+ }
+ fn with_extract_error(mut self, err: BackendError) -> Self {
+ self.extract_err = Some(err);
+ self
+ }
+ }
+
+ fn clone_err(err: &BackendError) -> BackendError {
+ match err {
+ BackendError::Transient(m) => BackendError::Transient(m.clone()),
+ BackendError::Inference(m) => BackendError::Inference(m.clone()),
+ BackendError::UnsupportedModel(m) => BackendError::UnsupportedModel(m.clone()),
+ BackendError::Draining => BackendError::Draining,
+ }
+ }
+
+ #[async_trait]
+ impl InferenceBackend for MockBackend {
+ fn name(&self) -> &'static str {
+ self.name
+ }
+ fn supports(&self, model_id: &str) -> bool {
+ self.supports_all || self.supported.iter().any(|m| m == model_id)
+ }
+ async fn ensure_model_ready(
+ &self,
+ _model_id: &str,
+ ) -> Result<EnsureModelReadyResponse, BackendError> {
+ self.ready_calls.fetch_add(1, Ordering::SeqCst);
+ if let Some(err) = &self.ready_err {
+ return Err(clone_err(err));
+ }
+ Ok(EnsureModelReadyResponse {
+ state: ReadinessState::Ready,
+ batch_budget: Some(32),
+ descriptor: None,
+ })
+ }
+ async fn process_encode_batch(
+ &self,
+ _req: ProcessEncodeBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ self.process_calls.fetch_add(1, Ordering::SeqCst);
+ if let Some(err) = &self.process_err {
+ return Err(clone_err(err));
+ }
+ Ok(BatchOutcome { outcomes: vec![] })
+ }
+ async fn process_score_batch(
+ &self,
+ _req: ProcessScoreBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ self.score_calls.fetch_add(1, Ordering::SeqCst);
+ if let Some(err) = self.score_err.as_ref().or(self.process_err.as_ref()) {
+ return Err(clone_err(err));
+ }
+ Ok(BatchOutcome { outcomes: vec![] })
+ }
+ async fn process_extract_batch(
+ &self,
+ _req: ProcessExtractBatchRequest,
+ ) -> Result<BatchOutcome, BackendError> {
+ self.extract_calls.fetch_add(1, Ordering::SeqCst);
+ if let Some(err) = self.extract_err.as_ref().or(self.process_err.as_ref()) {
+ return Err(clone_err(err));
+ }
+ Ok(BatchOutcome { outcomes: vec![] })
+ }
+ async fn drain(&self, _deadline_ms: u64) {
+ self.drain_calls.fetch_add(1, Ordering::SeqCst);
+ }
+ }
+
+ fn encode_req(model: &str) -> ProcessEncodeBatchRequest {
+ ProcessEncodeBatchRequest {
+ model_id: model.into(),
+ items: vec![],
+ }
+ }
+
+ #[tokio::test]
+ async fn single_backend_owns_everything() {
+ let b = Arc::new(MockBackend::all("python")) as SharedBackend;
+ let router = BackendRouter::with_python_only(b);
+ let resp = router.ensure_model_ready("any-model").await.unwrap();
+ assert!(matches!(resp.state, ReadinessState::Ready));
+ assert_eq!(router.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn native_backend_wins_over_python_when_it_supports_model() {
+ let native = Arc::new(MockBackend::scoped("native", &["bge-base"]));
+ let python = Arc::new(MockBackend::all("python"));
+ let router = BackendRouter::from_backends(vec![
+ Arc::clone(&native) as SharedBackend,
+ Arc::clone(&python) as SharedBackend,
+ ]);
+
+ let resp = router.ensure_model_ready("bge-base").await.unwrap();
+ assert!(matches!(resp.state, ReadinessState::Ready));
+ assert_eq!(native.ready_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(python.ready_calls.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test]
+ async fn falls_through_to_python_when_native_does_not_support() {
+ let native = Arc::new(MockBackend::scoped("native", &["bge-base"]));
+ let python = Arc::new(MockBackend::all("python"));
+ let router = BackendRouter::from_backends(vec![
+ Arc::clone(&native) as SharedBackend,
+ Arc::clone(&python) as SharedBackend,
+ ]);
+
+ let resp = router.ensure_model_ready("gpt-neo").await.unwrap();
+ assert!(matches!(resp.state, ReadinessState::Ready));
+ assert_eq!(native.ready_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(python.ready_calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn native_hard_error_does_not_fall_through_to_python() {
+ // Correctness invariant: if a native backend claims a model
+ // and then its readiness call fails with a non-Unsupported
+ // error, we MUST surface that error. Silently retrying via
+ // Python would let numeric drift leak into production.
+ let native = Arc::new(
+ MockBackend::scoped("native", &["bge-base"])
+ .with_ready_error(BackendError::Transient("cuda oom".into())),
+ );
+ let python = Arc::new(MockBackend::all("python"));
+ let router = BackendRouter::from_backends(vec![
+ Arc::clone(&native) as SharedBackend,
+ Arc::clone(&python) as SharedBackend,
+ ]);
+
+ let err = router.ensure_model_ready("bge-base").await.unwrap_err();
+ assert!(matches!(err, BackendError::Transient(_)));
+ assert_eq!(python.ready_calls.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test]
+ async fn native_unsupported_falls_through_to_next_backend() {
+ // If a backend claims via supports() but then returns
+ // UnsupportedModel at readiness time (e.g. the weights hash
+ // didn't match), the router should try the next backend.
+ let native = Arc::new(
+ MockBackend::scoped("native", &["bge-base"])
+ .with_ready_error(BackendError::UnsupportedModel("bge-base".into())),
+ );
+ let python = Arc::new(MockBackend::all("python"));
+ let router = BackendRouter::from_backends(vec![
+ Arc::clone(&native) as SharedBackend,
+ Arc::clone(&python) as SharedBackend,
+ ]);
+
+ let resp = router.ensure_model_ready("bge-base").await.unwrap();
+ assert!(matches!(resp.state, ReadinessState::Ready));
+ assert_eq!(native.ready_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(python.ready_calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn cached_backend_unsupported_falls_through_to_next_backend() {
+ let native = Arc::new(
+ MockBackend::scoped("native", &["bge-base"])
+ .with_ready_error(BackendError::UnsupportedModel("bge-base".into())),
+ );
+ let python = Arc::new(MockBackend::all("python"));
+ let router = BackendRouter::from_backends(vec![
+ Arc::clone(&native) as SharedBackend,
+ Arc::clone(&python) as SharedBackend,
+ ]);
+ router.cache_index("bge-base", 0).await;
+
+ let resp = router.ensure_model_ready("bge-base").await.unwrap();
+ assert!(matches!(resp.state, ReadinessState::Ready));
+ assert_eq!(native.ready_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(python.ready_calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn unsupported_when_no_backend_claims() {
+ let native = Arc::new(MockBackend::scoped("native", &["bge-base"])) as SharedBackend;
+ let router = BackendRouter::from_backends(vec![native]);
+ let err = router.ensure_model_ready("unknown").await.unwrap_err();
+ assert!(matches!(err, BackendError::UnsupportedModel(_)));
+ }
+
+ #[tokio::test]
+ async fn routes_process_encode_to_cached_backend() {
+ let native = Arc::new(MockBackend::scoped("native", &["bge-base"]));
+ let python = Arc::new(MockBackend::all("python"));
+ let router = BackendRouter::from_backends(vec![
+ Arc::clone(&native) as SharedBackend,
+ Arc::clone(&python) as SharedBackend,
+ ]);
+
+ router.ensure_model_ready("bge-base").await.unwrap();
+ let _ = router
+ .process_encode_batch(encode_req("bge-base"))
+ .await
+ .unwrap();
+
+ assert_eq!(native.process_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(python.process_calls.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test]
+ async fn process_without_prior_ready_still_routes_by_supports() {
+ // Callers may hit process_* before ensure_model_ready (on
+ // restart, or in tests). The router should still resolve via
+ // supports() — just without caching the binding.
+ let native = Arc::new(MockBackend::scoped("native", &["bge-base"]));
+ let router = BackendRouter::from_backends(vec![Arc::clone(&native) as SharedBackend]);
+ let _ = router
+ .process_encode_batch(encode_req("bge-base"))
+ .await
+ .unwrap();
+ assert_eq!(native.process_calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn process_unknown_model_returns_unsupported() {
+ let native = Arc::new(MockBackend::scoped("native", &["bge-base"])) as SharedBackend;
+ let router = BackendRouter::from_backends(vec![native]);
+ let err = router
+ .process_encode_batch(encode_req("unknown"))
+ .await
+ .unwrap_err();
+ assert!(matches!(err, BackendError::UnsupportedModel(_)));
+ }
+
+ #[tokio::test]
+ async fn drain_all_calls_every_backend() {
+ let a = Arc::new(MockBackend::all("a"));
+ let b = Arc::new(MockBackend::all("b"));
+ let router = BackendRouter::from_backends(vec![
+ Arc::clone(&a) as SharedBackend,
+ Arc::clone(&b) as SharedBackend,
+ ]);
+ router.drain_all(1000).await;
+ assert_eq!(a.drain_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(b.drain_calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn supports_is_union_over_backends() {
+ let native = Arc::new(MockBackend::scoped("native", &["bge-base"])) as SharedBackend;
+ let python = Arc::new(MockBackend::all("python")) as SharedBackend;
+ let router = BackendRouter::from_backends(vec![Arc::clone(&native), Arc::clone(&python)]);
+ // Both the specific and arbitrary models are supported, thanks
+ // to Python claiming everything.
+ assert!(router.supports("bge-base"));
+ assert!(router.supports("anything-at-all"));
+ }
+
+ #[test]
+ #[should_panic(expected = "at least one backend")]
+ fn empty_router_panics() {
+ let _ = BackendRouter::from_backends(Vec::new());
+ }
+
+ #[tokio::test]
+ async fn process_falls_through_on_unsupported_op() {
+ // Concrete case: a cross-encoder backend claims reranker
+ // `model_id` via supports() (because it serves score for it),
+ // but when asked to encode returns UnsupportedModel. The
+ // router must try the next backend instead of surfacing the
+ // error, which would cause a spurious NAK.
+ let cross_encoder = Arc::new(
+ MockBackend::scoped("xencoder", &["BAAI/bge-reranker-v2-m3"]).with_process_error(
+ BackendError::UnsupportedModel("BAAI/bge-reranker-v2-m3".into()),
+ ),
+ );
+ let python = Arc::new(MockBackend::all("python"));
+ let router = BackendRouter::from_backends(vec![
+ Arc::clone(&cross_encoder) as SharedBackend,
+ Arc::clone(&python) as SharedBackend,
+ ]);
+
+ let _ = router
+ .process_encode_batch(encode_req("BAAI/bge-reranker-v2-m3"))
+ .await
+ .unwrap();
+
+ assert_eq!(cross_encoder.process_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(python.process_calls.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn process_hard_error_does_not_fall_through() {
+ // Inference / Transient errors must short-circuit — silently
+ // retrying on the next backend would hide numeric drift.
+ let cross_encoder = Arc::new(
+ MockBackend::scoped("xencoder", &["reranker"])
+ .with_process_error(BackendError::Transient("cuda oom".into())),
+ );
+ let python = Arc::new(MockBackend::all("python"));
+ let router = BackendRouter::from_backends(vec![
+ Arc::clone(&cross_encoder) as SharedBackend,
+ Arc::clone(&python) as SharedBackend,
+ ]);
+
+ let err = router
+ .process_encode_batch(encode_req("reranker"))
+ .await
+ .unwrap_err();
+ assert!(matches!(err, BackendError::Transient(_)));
+ assert_eq!(cross_encoder.process_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(python.process_calls.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test]
+ async fn encode_stays_on_native_after_score_falls_through_to_python() {
+ // Deployment shape: the native encoder serves `encode` for a
+ // model_id; the same model_id's `score` / `extract` must fall
+ // through to Python IPC. Crucially, after the first `score`
+ // call falls through, a subsequent `encode` call MUST still
+ // land on the native backend — otherwise we silently lose the
+ // native fast path for the remainder of the pod's lifetime.
+ use crate::ipc_types::{ProcessExtractBatchRequest, ProcessScoreBatchRequest};
+
+ let model = "BAAI/bge-base-en-v1.5";
+ let native = Arc::new(
+ MockBackend::scoped("native", &[model])
+ .with_score_error(BackendError::UnsupportedModel(model.into()))
+ .with_extract_error(BackendError::UnsupportedModel(model.into())),
+ );
+ let python = Arc::new(MockBackend::all("python"));
+ let router = BackendRouter::from_backends(vec![
+ Arc::clone(&native) as SharedBackend,
+ Arc::clone(&python) as SharedBackend,
+ ]);
+
+ // First encode goes to native.
+ router
+ .process_encode_batch(encode_req(model))
+ .await
+ .unwrap();
+ assert_eq!(native.process_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(python.process_calls.load(Ordering::SeqCst), 0);
+
+ // Score falls through to python.
+ let score_req = ProcessScoreBatchRequest {
+ model_id: model.into(),
+ items: vec![],
+ };
+ router.process_score_batch(score_req).await.unwrap();
+ assert_eq!(native.score_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(python.score_calls.load(Ordering::SeqCst), 1);
+
+ // Extract also falls through to python.
+ let extract_req = ProcessExtractBatchRequest {
+ model_id: model.into(),
+ items: vec![],
+ };
+ router.process_extract_batch(extract_req).await.unwrap();
+ assert_eq!(native.extract_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(python.extract_calls.load(Ordering::SeqCst), 1);
+
+ // Subsequent encode must STILL go to the native backend — the
+ // fall-through for score / extract must NOT have promoted
+ // python in the per-model cache.
+ router
+ .process_encode_batch(encode_req(model))
+ .await
+ .unwrap();
+ assert_eq!(
+ native.process_calls.load(Ordering::SeqCst),
+ 2,
+ "encode regressed to python after score fall-through"
+ );
+ assert_eq!(
+ python.process_calls.load(Ordering::SeqCst),
+ 0,
+ "encode should not have hit python"
+ );
+ }
+
+ #[tokio::test]
+ async fn process_no_other_claimant_surfaces_unsupported() {
+ // Only the cross-encoder claims the id and only it would be
+ // asked; if it rejects and no other backend supports the id,
+ // we return UnsupportedModel to the dispatcher.
+ let cross_encoder = Arc::new(
+ MockBackend::scoped("xencoder", &["reranker"])
+ .with_process_error(BackendError::UnsupportedModel("reranker".into())),
+ );
+ let router =
+ BackendRouter::from_backends(vec![Arc::clone(&cross_encoder) as SharedBackend]);
+
+ let err = router
+ .process_encode_batch(encode_req("reranker"))
+ .await
+ .unwrap_err();
+ assert!(matches!(err, BackendError::UnsupportedModel(_)));
+ assert_eq!(cross_encoder.process_calls.load(Ordering::SeqCst), 1);
+ }
+
+ /// Repeated readiness checks re-handshake with the selected backend.
+ /// The router caches model-to-backend binding, not the readiness
+ /// response itself, so descriptor/batch-budget metadata can change
+ /// safely after live config reconciliation.
+ #[tokio::test]
+ async fn repeated_ready_checks_call_backend() {
+ let python = Arc::new(MockBackend::all("python"));
+ let router = BackendRouter::from_backends(vec![Arc::clone(&python) as SharedBackend]);
+
+ router.ensure_model_ready("model-a").await.unwrap();
+ router.ensure_model_ready("model-a").await.unwrap();
+ assert_eq!(python.ready_calls.load(Ordering::SeqCst), 2);
+ }
+}
diff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rs
new file mode 100644
index 000000000..0541fe136
--- /dev/null
+++ b/packages/sie_server_sidecar/src/config.rs
@@ -0,0 +1,224 @@
+//! Worker runtime configuration.
+//!
+//! All runtime knobs flow through CLI args / env vars in `main.rs`; this
+//! struct is the one-shot snapshot passed into `run()`.
+
+use std::path::PathBuf;
+
+#[derive(Debug, Clone)]
+pub struct WorkerConfig {
+ /// NATS server URL (e.g. `nats://localhost:4222`).
+ pub nats_url: String,
+
+ /// Pool name — drives the stream (`WORK_POOL_{pool}`), consumer
+ /// (`{bundle}_{pool}`), and subject filter.
+ pub pool: String,
+
+ /// Bundle ID — forms part of the durable consumer name so multiple
+ /// bundles on the same pool don't step on each other.
+ pub bundle: String,
+
+ /// Unix domain socket used to talk to the Python `ipc_server.py`.
+ pub ipc_socket_path: PathBuf,
+
+ /// Number of concurrent IPC connections to the Python sie-server process. `1`
+ /// preserves the legacy single-socket behaviour; higher values let
+ /// the dispatcher's `SIE_MAX_CONCURRENT_BATCHES` actually drive
+ /// parallel Python-side batches. Sourced from `SIE_IPC_POOL_SIZE`
+ /// (see `main.rs`); when unset we default to
+ /// `SIE_MAX_CONCURRENT_BATCHES`'s default (4).
+ pub ipc_pool_size: usize,
+
+ /// Optional payload store URL — if unset, workers expect items inline
+ /// (large items will be rejected by the gateway's offload). Local paths
+ /// point at a shared directory; `s3://…` / `gs://…` use cloud stores
+ /// when built with `--features cloud-storage`.
+ pub payload_store_url: Option<String>,
+
+ /// Optional gateway URL used by the worker-side pool admission gate.
+ /// When set and admission is enabled, the sidecar asks
+ /// `/v1/pools/{pool}` before pulling from NATS.
+ pub gateway_url: Option<String>,
+
+ /// Optional bearer token for gateway pool-status reads.
+ pub gateway_api_key: Option<String>,
+
+ /// Whether the pool admission gate is enabled. The gate still no-ops
+ /// when `gateway_url` is unset so local NATS-only harnesses continue to
+ /// work.
+ pub pool_admission_enabled: bool,
+
+ /// Pool admission status check cadence.
+ pub pool_admission_check_interval_ms: u64,
+
+ /// Sleep duration while this worker is not admitted to pull.
+ pub pool_admission_pause_ms: u64,
+
+ /// How long to reuse the last successful admission decision after
+ /// transient gateway/status errors.
+ pub pool_admission_stale_after_ms: u64,
+
+ /// Prometheus metrics HTTP port.
+ pub metrics_port: u16,
+
+ /// Stable worker identifier surfaced in logs / `WorkResult.worker_id` /
+ /// IPC `Ping`.
+ pub worker_id: String,
+
+ /// How often to send `Ping` RPCs to the Python sie-server process.
+ pub ping_interval_ms: u64,
+
+ /// Multiplier applied to `ping_interval_ms` to compute the
+ /// `/readyz` heartbeat-staleness threshold. The sidecar's
+ /// readiness flips red once the most recent successful `Ping`
+ /// is older than `ping_interval_ms * ready_stale_mult`.
+ ///
+ /// 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).
+ /// `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.
+ pub ready_stale_mult: u32,
+
+ /// Machine-profile label this pod advertises in NATS
+ /// heartbeats (e.g. `l4`, `a100`). Surfaced to the gateway
+ /// only — the `X-SIE-MACHINE-PROFILE` route filter compares
+ /// case-insensitively against this value. Empty disables the
+ /// filter (route by bundle alone). Sourced from
+ /// `SIE_MACHINE_PROFILE`; falls back to `pool` to preserve
+ /// the historical convention where pool name == GPU type.
+ pub machine_profile: String,
+
+ /// GPU count surfaced in heartbeats. Informational —
+ /// `WorkerRegistry::update_worker` coerces `0 -> 1` so an
+ /// unset value still routes. Sourced from `SIE_GPU_COUNT`.
+ pub gpu_count: i32,
+
+ /// Optional bundle-config hash echoed in heartbeats so admin
+ /// tooling can correlate the worker's bundle revision with
+ /// the gateway's model registry epoch. Empty is fine.
+ pub bundle_config_hash: String,
+
+ /// Optional URL for the `sie-config` control plane. When set, the
+ /// sidecar polls `/v1/configs/epoch` and reconciles missed deltas from
+ /// `/v1/configs/export`.
+ pub config_service_url: Option<String>,
+
+ /// Optional bearer token for `sie-config` export reads. Helm wires this
+ /// from `SIE_ADMIN_TOKEN` when config auth is enabled because
+ /// `/v1/configs/export` is admin-authenticated.
+ pub config_service_token: Option<String>,
+
+ /// Cadence for worker-side `/v1/configs/epoch` polling.
+ pub config_poll_interval_ms: u64,
+
+ /// Slow full-export reconciliation cadence. This covers no-config-store
+ /// deployments where `sie-config` keeps epoch at `0`; `0` disables the
+ /// periodic export audit after startup.
+ pub config_full_export_interval_ms: u64,
+
+ /// Trusted producer allowlist for `sie.config.models.<bundle>`
+ /// notifications. Empty means trust any producer and is intended only for
+ /// local/dev clusters.
+ pub nats_config_trusted_producers: Vec<String>,
+
+ /// Heartbeat interval for the NATS health publisher.
+ /// Defaults to 5 s — same cadence as the gateway's
+ /// `start_heartbeat_loop` so the staleness check has a 6×
+ /// margin against the 30 s `heartbeat_timeout`.
+ pub health_publish_interval_ms: u64,
+}
+
+impl WorkerConfig {
+ pub fn stream_name(&self) -> String {
+ format!("WORK_POOL_{}", self.pool)
+ }
+
+ pub fn consumer_name(&self) -> String {
+ // Matches `sie_sdk.queue_types.work_consumer_name(bundle, pool)` so
+ // Rust and Python adapter processes converge on the same durable consumer.
+ format!("{}_{}", self.bundle, self.pool)
+ }
+
+ pub fn subject_filter(&self) -> String {
+ format!("sie.work.*.{}", self.pool)
+ }
+
+ pub fn worker_stream_name(&self) -> String {
+ format!(
+ "WORK_WORKER_{}",
+ crate::subject::normalize_model_id(&self.worker_id)
+ )
+ }
+
+ pub fn worker_consumer_name(&self) -> String {
+ format!(
+ "gen-{}",
+ crate::subject::normalize_model_id(&self.worker_id)
+ )
+ }
+
+ pub fn worker_subject_filter(&self) -> String {
+ format!(
+ "sie.work.*.{}.{}",
+ self.pool,
+ crate::subject::normalize_model_id(&self.worker_id)
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sample() -> WorkerConfig {
+ WorkerConfig {
+ nats_url: "nats://localhost:4222".into(),
+ pool: "l4".into(),
+ bundle: "default".into(),
+ ipc_socket_path: PathBuf::from("/tmp/sie-ipc.sock"),
+ ipc_pool_size: 1,
+ payload_store_url: None,
+ gateway_url: None,
+ gateway_api_key: None,
+ pool_admission_enabled: true,
+ pool_admission_check_interval_ms: 5_000,
+ pool_admission_pause_ms: 1_000,
+ pool_admission_stale_after_ms: 30_000,
+ metrics_port: 9095,
+ worker_id: "worker-test".into(),
+ ping_interval_ms: 2000,
+ ready_stale_mult: 3,
+ machine_profile: "l4".into(),
+ gpu_count: 1,
+ bundle_config_hash: String::new(),
+ config_service_url: None,
+ config_service_token: None,
+ config_poll_interval_ms: 30_000,
+ config_full_export_interval_ms: 300_000,
+ nats_config_trusted_producers: vec!["sie-config".into()],
+ health_publish_interval_ms: 5_000,
+ }
+ }
+
+ #[test]
+ fn stream_and_consumer_names_match_gateway_contract() {
+ let c = sample();
+ // Must agree with sie_gateway's NATS naming so publisher and
+ // consumer land on the same stream/consumer.
+ assert_eq!(c.stream_name(), "WORK_POOL_l4");
+ assert_eq!(c.consumer_name(), "default_l4");
+ assert_eq!(c.subject_filter(), "sie.work.*.l4");
+ assert_eq!(c.worker_stream_name(), "WORK_WORKER_worker-test");
+ assert_eq!(c.worker_consumer_name(), "gen-worker-test");
+ assert_eq!(c.worker_subject_filter(), "sie.work.*.l4.worker-test");
+ }
+
+ #[test]
+ fn subject_filter_contains_pool() {
+ let mut c = sample();
+ c.pool = "eval-h100".into();
+ assert!(c.subject_filter().ends_with(".eval-h100"));
+ }
+}
diff --git a/packages/sie_server_sidecar/src/config_reconciler.rs b/packages/sie_server_sidecar/src/config_reconciler.rs
new file mode 100644
index 000000000..99a46a6b6
--- /dev/null
+++ b/packages/sie_server_sidecar/src/config_reconciler.rs
@@ -0,0 +1,790 @@
+//! Periodic worker-side reconciliation against `sie-config`.
+//!
+//! Core NATS gives the sidecar a fast live path for
+//! `sie.config.models.<bundle>`, but it does not replay messages that were
+//! published while a worker was disconnected. This module closes that gap by
+//! polling `GET /v1/configs/epoch` and fetching `GET /v1/configs/export` when
+//! the control plane is ahead. A slower full-export pass also covers
+//! no-config-store deployments where `sie-config` keeps epoch at `0`.
+
+use std::collections::HashMap;
+use std::future::Future;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use serde::Deserialize;
+use tokio::sync::Notify;
+use tokio::task::JoinHandle;
+use tokio::time::interval;
+use tracing::{debug, info, warn};
+
+use crate::config_subscriber::{
+ apply_via_ipc_with_retry, ConfigApplyState, MAX_MODEL_CONFIG_BYTES,
+};
+use crate::ipc_client::{IpcClient, IpcError};
+use crate::ipc_types::{ApplyModelConfigRequest, ApplyModelConfigResponse};
+use crate::metrics::MetricsRegistry;
+use crate::shutdown::Shutdown;
+
+const HTTP_TIMEOUT: Duration = Duration::from_secs(10);
+pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_secs(30);
+pub const DEFAULT_FULL_EXPORT_INTERVAL: Duration = Duration::from_secs(5 * 60);
+
+#[derive(Debug, Clone)]
+pub struct ReconcilerConfig {
+ pub base_url: String,
+ pub admin_token: Option<String>,
+ pub bundle: String,
+ pub poll_interval: Duration,
+ pub full_export_interval: Option<Duration>,
+}
+
+#[derive(Debug, Deserialize)]
+struct EpochResponse {
+ #[serde(default)]
+ epoch: u64,
+}
+
+#[derive(Debug, Deserialize)]
+struct ExportSnapshot {
+ #[serde(default)]
+ epoch: u64,
+ #[serde(default)]
+ bundle_config_hashes: HashMap<String, String>,
+ #[serde(default)]
+ models: Vec<ExportedModel>,
+}
+
+#[derive(Debug, Deserialize)]
+struct ExportedModel {
+ #[serde(default)]
+ model_id: String,
+ #[serde(default)]
+ raw_yaml: Option<String>,
+ #[serde(default)]
+ model_config: Option<serde_json::Value>,
+ #[serde(default)]
+ affected_bundles: Vec<String>,
+}
+
+impl ExportedModel {
+ fn targets_bundle(&self, bundle: &str) -> bool {
+ self.affected_bundles.iter().any(|b| b == bundle)
+ }
+
+ fn config_body(&self) -> Result<Option<String>, serde_json::Error> {
+ if let Some(raw) = self.raw_yaml.as_deref() {
+ let trimmed = raw.trim();
+ if !trimmed.is_empty() {
+ return Ok(Some(trimmed.to_string()));
+ }
+ }
+ match &self.model_config {
+ Some(value) if !value.is_null() => serde_json::to_string(value).map(Some),
+ _ => Ok(None),
+ }
+ }
+}
+
+#[derive(Debug, thiserror::Error)]
+enum ReconcileError {
+ #[error("http error: {0}")]
+ Http(#[from] reqwest::Error),
+ #[error("unexpected status {status} from {url}: {body}")]
+ BadStatus {
+ status: u16,
+ url: String,
+ body: String,
+ },
+}
+
+#[derive(Debug)]
+struct ExportOutcome {
+ epoch: u64,
+ applied: usize,
+ failed: usize,
+ skipped: usize,
+ shutdown: bool,
+ state_updated: bool,
+}
+
+struct ReconcileClient {
+ base_url: String,
+ admin_token: Option<String>,
+ http: reqwest::Client,
+}
+
+struct ReconcileRuntime<'a> {
+ client: &'a ReconcileClient,
+ bundle: &'a str,
+ ipc: Arc<IpcClient>,
+ state: Arc<ConfigApplyState>,
+ metrics: Arc<MetricsRegistry>,
+ shutdown: Arc<Shutdown>,
+}
+
+impl ReconcileClient {
+ fn new(base_url: String, admin_token: Option<String>) -> Result<Self, reqwest::Error> {
+ let http = reqwest::Client::builder().timeout(HTTP_TIMEOUT).build()?;
+ Ok(Self {
+ base_url,
+ admin_token,
+ http,
+ })
+ }
+
+ async fn fetch_epoch(&self) -> Result<u64, ReconcileError> {
+ let url = format!("{}/v1/configs/epoch", self.base_url.trim_end_matches('/'));
+ let mut req = self.http.get(&url);
+ if let Some(token) = &self.admin_token {
+ req = req.bearer_auth(token);
+ }
+ let resp = req.send().await?;
+ let status = resp.status();
+ if !status.is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ return Err(ReconcileError::BadStatus {
+ status: status.as_u16(),
+ url,
+ body,
+ });
+ }
+ let payload: EpochResponse = resp.json().await?;
+ Ok(payload.epoch)
+ }
+
+ async fn fetch_export(&self) -> Result<ExportSnapshot, ReconcileError> {
+ let url = format!("{}/v1/configs/export", self.base_url.trim_end_matches('/'));
+ let mut req = self.http.get(&url);
+ if let Some(token) = &self.admin_token {
+ req = req.bearer_auth(token);
+ }
+ let resp = req.send().await?;
+ let status = resp.status();
+ if !status.is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ return Err(ReconcileError::BadStatus {
+ status: status.as_u16(),
+ url,
+ body,
+ });
+ }
+ Ok(resp.json().await?)
+ }
+}
+
+fn record_reconcile(metrics: &MetricsRegistry, result: &str) {
+ metrics
+ .config_deltas_total
+ .with_label_values(&["export", result])
+ .inc();
+}
+
+/// Spawn the optional export reconciler.
+///
+/// The task is disabled when `config.base_url` is empty. The caller owns the
+/// returned handle and aborts it on shutdown, matching the config subscriber
+/// and health publisher lifecycle.
+pub fn spawn(
+ config: Option<ReconcilerConfig>,
+ ipc: Arc<IpcClient>,
+ state: Arc<ConfigApplyState>,
+ metrics: Arc<MetricsRegistry>,
+ shutdown: Arc<Shutdown>,
+ generation_reconcile: Option<Arc<Notify>>,
+) -> Option<JoinHandle<()>> {
+ let config = config?;
+ if config.base_url.trim().is_empty() {
+ return None;
+ }
+
+ Some(tokio::spawn(async move {
+ let client = match ReconcileClient::new(config.base_url.clone(), config.admin_token) {
+ Ok(c) => c,
+ Err(e) => {
+ warn!(error = %e, "worker-config: failed to build export reconciler client");
+ record_reconcile(&metrics, "client_error");
+ return;
+ }
+ };
+
+ info!(
+ base_url = %config.base_url,
+ bundle = %config.bundle,
+ poll_interval_ms = config.poll_interval.as_millis() as u64,
+ full_export_interval_ms = config.full_export_interval.map(|d| d.as_millis() as u64),
+ "worker-config: export reconciler started"
+ );
+
+ let runtime = ReconcileRuntime {
+ client: &client,
+ bundle: &config.bundle,
+ ipc: Arc::clone(&ipc),
+ state: Arc::clone(&state),
+ metrics: Arc::clone(&metrics),
+ shutdown: Arc::clone(&shutdown),
+ };
+ let mut last_successful_export: Option<Instant> = None;
+ match reconcile_export(&runtime, false, "startup").await {
+ Ok(outcome) if outcome.shutdown => return,
+ Ok(outcome) if outcome.failed == 0 => {
+ last_successful_export = Some(Instant::now());
+ if outcome.applied > 0 {
+ if let Some(notify) = generation_reconcile.as_ref() {
+ notify.notify_one();
+ }
+ }
+ info!(
+ epoch = outcome.epoch,
+ applied = outcome.applied,
+ skipped = outcome.skipped,
+ state_updated = outcome.state_updated,
+ "worker-config: startup export reconcile complete"
+ );
+ }
+ Ok(outcome) => {
+ warn!(
+ epoch = outcome.epoch,
+ applied = outcome.applied,
+ failed = outcome.failed,
+ skipped = outcome.skipped,
+ "worker-config: startup export reconcile partial; will retry"
+ );
+ }
+ Err(e) => {
+ warn!(error = %e, "worker-config: startup export reconcile failed; will retry");
+ record_reconcile(&metrics, "fetch_error");
+ }
+ }
+
+ let mut ticker = interval(config.poll_interval);
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ ticker.tick().await;
+
+ loop {
+ tokio::select! {
+ biased;
+ _ = shutdown.wait() => return,
+ _ = ticker.tick() => {
+ let local_epoch = state.epoch();
+ let remote_epoch = match client.fetch_epoch().await {
+ Ok(epoch) => epoch,
+ Err(e) => {
+ warn!(error = %e, "worker-config: epoch poll failed");
+ record_reconcile(&metrics, "epoch_error");
+ continue;
+ }
+ };
+
+ let full_export_due = config.full_export_interval.is_some_and(|interval| {
+ last_successful_export
+ .map(|last| last.elapsed() >= interval)
+ .unwrap_or(true)
+ });
+ let needs_export =
+ remote_epoch != local_epoch || (remote_epoch == 0 && full_export_due);
+
+ if !needs_export {
+ debug!(
+ local_epoch,
+ remote_epoch,
+ "worker-config: epoch poll in sync"
+ );
+ continue;
+ }
+
+ let force_epoch = remote_epoch < local_epoch;
+ let reason = if remote_epoch > local_epoch {
+ "epoch_ahead"
+ } else if remote_epoch < local_epoch {
+ "epoch_rewind"
+ } else {
+ "periodic_export"
+ };
+ if force_epoch {
+ warn!(
+ local_epoch,
+ remote_epoch,
+ "worker-config: local epoch ahead of sie-config; export reconcile will force epoch after successful apply"
+ );
+ } else {
+ info!(
+ local_epoch,
+ remote_epoch,
+ reason,
+ "worker-config: drift detected; fetching export"
+ );
+ }
+
+ match reconcile_export(&runtime, force_epoch, reason)
+ .await
+ {
+ Ok(outcome) if outcome.shutdown => return,
+ Ok(outcome) if outcome.failed == 0 => {
+ last_successful_export = Some(Instant::now());
+ if outcome.applied > 0 {
+ if let Some(notify) = generation_reconcile.as_ref() {
+ notify.notify_one();
+ }
+ }
+ info!(
+ epoch = outcome.epoch,
+ applied = outcome.applied,
+ skipped = outcome.skipped,
+ state_updated = outcome.state_updated,
+ reason,
+ "worker-config: export reconcile complete"
+ );
+ }
+ Ok(outcome) => {
+ warn!(
+ epoch = outcome.epoch,
+ applied = outcome.applied,
+ failed = outcome.failed,
+ skipped = outcome.skipped,
+ reason,
+ "worker-config: export reconcile partial; epoch/hash not advanced"
+ );
+ }
+ Err(e) => {
+ warn!(error = %e, reason, "worker-config: export reconcile failed");
+ record_reconcile(&metrics, "fetch_error");
+ }
+ }
+ }
+ }
+ }
+ }))
+}
+
+async fn reconcile_export(
+ runtime: &ReconcileRuntime<'_>,
+ force_epoch: bool,
+ reason: &str,
+) -> Result<ExportOutcome, ReconcileError> {
+ let snapshot = runtime.client.fetch_export().await?;
+ let ipc = Arc::clone(&runtime.ipc);
+ let shutdown = Arc::clone(&runtime.shutdown);
+ Ok(reconcile_export_snapshot(
+ snapshot,
+ runtime.bundle,
+ &runtime.state,
+ &runtime.metrics,
+ force_epoch,
+ reason,
+ move |req, model_id, epoch| {
+ let ipc = Arc::clone(&ipc);
+ let shutdown = Arc::clone(&shutdown);
+ async move { apply_via_ipc_with_retry(ipc, shutdown, req, &model_id, epoch).await }
+ },
+ )
+ .await)
+}
+
+async fn reconcile_export_snapshot<F, Fut>(
+ snapshot: ExportSnapshot,
+ bundle: &str,
+ state: &ConfigApplyState,
+ metrics: &MetricsRegistry,
+ force_epoch: bool,
+ reason: &str,
+ mut apply: F,
+) -> ExportOutcome
+where
+ F: FnMut(ApplyModelConfigRequest, String, u64) -> Fut,
+ Fut: Future<Output = Result<Option<ApplyModelConfigResponse>, IpcError>>,
+{
+ let _apply_guard = state.lock_apply().await;
+
+ if !force_epoch && snapshot.epoch < state.epoch() {
+ record_reconcile(metrics, "stale_export");
+ return ExportOutcome {
+ epoch: snapshot.epoch,
+ applied: 0,
+ failed: 0,
+ skipped: snapshot.models.len(),
+ shutdown: false,
+ state_updated: false,
+ };
+ }
+
+ let mut applied = 0usize;
+ let mut failed = 0usize;
+ let mut skipped = 0usize;
+ let control_plane_hash = snapshot
+ .bundle_config_hashes
+ .get(bundle)
+ .filter(|hash| !hash.is_empty())
+ .cloned();
+ let mut last_bundle_hash: Option<String> = None;
+ let mut first_hash_mismatch: Option<String> = None;
+
+ for model in snapshot.models {
+ if !model.targets_bundle(bundle) {
+ skipped += 1;
+ continue;
+ }
+
+ let model_config = match model.config_body() {
+ Ok(Some(body)) => body,
+ Ok(None) => {
+ skipped += 1;
+ continue;
+ }
+ Err(e) => {
+ warn!(
+ model = %model.model_id,
+ error = %e,
+ "worker-config: exported model_config could not be serialized"
+ );
+ failed += 1;
+ continue;
+ }
+ };
+
+ if model_config.len() > MAX_MODEL_CONFIG_BYTES {
+ warn!(
+ model = %model.model_id,
+ bytes = model_config.len(),
+ max_bytes = MAX_MODEL_CONFIG_BYTES,
+ "worker-config: exported model_config is oversized"
+ );
+ failed += 1;
+ continue;
+ }
+
+ let req = ApplyModelConfigRequest {
+ bundle_id: bundle.to_string(),
+ model_id: model.model_id.clone(),
+ epoch: snapshot.epoch,
+ bundle_config_hash: String::new(),
+ profiles_added: vec![],
+ model_config,
+ };
+
+ let resp = match apply(req, model.model_id.clone(), snapshot.epoch).await {
+ Ok(Some(resp)) => resp,
+ Ok(None) => {
+ record_reconcile(metrics, "shutdown");
+ return ExportOutcome {
+ epoch: snapshot.epoch,
+ applied,
+ failed,
+ skipped,
+ shutdown: true,
+ state_updated: false,
+ };
+ }
+ Err(e) => {
+ warn!(
+ model = %model.model_id,
+ epoch = snapshot.epoch,
+ error = %e,
+ "worker-config: exported model apply failed"
+ );
+ failed += 1;
+ continue;
+ }
+ };
+
+ if !resp.applied {
+ warn!(
+ model = %model.model_id,
+ epoch = snapshot.epoch,
+ "worker-config: exported model apply returned applied=false"
+ );
+ failed += 1;
+ continue;
+ }
+
+ if let Some(hash) = &control_plane_hash {
+ if !resp.bundle_config_hash.is_empty()
+ && resp.bundle_config_hash != *hash
+ && first_hash_mismatch.is_none()
+ {
+ first_hash_mismatch = Some(resp.bundle_config_hash.clone());
+ }
+ last_bundle_hash = Some(hash.clone());
+ } else if !resp.bundle_config_hash.is_empty() {
+ last_bundle_hash = Some(resp.bundle_config_hash);
+ }
+ applied += 1;
+ }
+
+ let state_updated = if failed == 0 {
+ if let (Some(control_hash), Some(applied_hash)) = (
+ control_plane_hash.as_deref(),
+ first_hash_mismatch.as_deref(),
+ ) {
+ warn!(
+ epoch = snapshot.epoch,
+ advertised_hash = %control_hash,
+ applied_hash = %applied_hash,
+ "worker-config: Python registry hash differs from control-plane export hash; advertising control-plane hash"
+ );
+ }
+ let state_updated =
+ state.mark_export_reconciled(snapshot.epoch, last_bundle_hash, force_epoch);
+ if state_updated {
+ metrics.config_epoch.set(snapshot.epoch as i64);
+ }
+ record_reconcile(
+ metrics,
+ if applied == 0 {
+ "no_relevant_models"
+ } else if state_updated {
+ "applied"
+ } else {
+ "stale_export"
+ },
+ );
+ state_updated
+ } else {
+ record_reconcile(metrics, "partial");
+ false
+ };
+
+ debug!(
+ epoch = snapshot.epoch,
+ applied,
+ failed,
+ skipped,
+ reason,
+ state_updated,
+ "worker-config: export reconcile attempt finished"
+ );
+
+ ExportOutcome {
+ epoch: snapshot.epoch,
+ applied,
+ failed,
+ skipped,
+ shutdown: false,
+ state_updated,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Arc;
+
+ use tokio::sync::Mutex;
+
+ fn exported_model(model_id: &str, bundles: &[&str]) -> ExportedModel {
+ ExportedModel {
+ model_id: model_id.into(),
+ raw_yaml: Some(format!("sie_id: {model_id}\nprofiles:\n default: {{}}\n")),
+ model_config: None,
+ affected_bundles: bundles.iter().map(|b| (*b).to_string()).collect(),
+ }
+ }
+
+ fn metrics() -> MetricsRegistry {
+ MetricsRegistry::new().expect("metrics registry")
+ }
+
+ #[test]
+ fn exported_model_targets_exact_bundle_only() {
+ let model = ExportedModel {
+ model_id: "m".into(),
+ raw_yaml: Some("sie_id: m\n".into()),
+ model_config: None,
+ affected_bundles: vec!["default".into(), "vision".into()],
+ };
+ assert!(model.targets_bundle("default"));
+ assert!(!model.targets_bundle("def"));
+ assert!(!model.targets_bundle("DEFAULT"));
+ }
+
+ #[test]
+ fn raw_yaml_wins_over_structured_model_config() {
+ let model = ExportedModel {
+ model_id: "m".into(),
+ raw_yaml: Some("sie_id: raw\n".into()),
+ model_config: Some(serde_json::json!({"sie_id": "json"})),
+ affected_bundles: vec!["default".into()],
+ };
+ assert_eq!(model.config_body().unwrap().as_deref(), Some("sie_id: raw"));
+ }
+
+ #[test]
+ fn structured_model_config_falls_back_to_json_yaml_subset() {
+ let model = ExportedModel {
+ model_id: "m".into(),
+ raw_yaml: None,
+ model_config: Some(serde_json::json!({"sie_id": "json"})),
+ affected_bundles: vec!["default".into()],
+ };
+ assert_eq!(
+ model.config_body().unwrap().as_deref(),
+ Some("{\"sie_id\":\"json\"}")
+ );
+ }
+
+ #[tokio::test]
+ async fn export_reconcile_applies_target_bundle_and_updates_epoch_hash() {
+ let snapshot = ExportSnapshot {
+ epoch: 7,
+ bundle_config_hashes: HashMap::new(),
+ models: vec![
+ exported_model("target-model", &["default"]),
+ exported_model("other-model", &["vision"]),
+ ],
+ };
+ let state = ConfigApplyState::new("old".into());
+ let metrics = metrics();
+ let applied = Arc::new(Mutex::new(Vec::new()));
+
+ let outcome =
+ reconcile_export_snapshot(snapshot, "default", &state, &metrics, false, "test", {
+ let applied = Arc::clone(&applied);
+ move |req, _model_id, _epoch| {
+ let applied = Arc::clone(&applied);
+ async move {
+ applied.lock().await.push(req);
+ Ok(Some(ApplyModelConfigResponse {
+ applied: true,
+ bundle_config_hash: "hash-7".into(),
+ config_version: 7,
+ }))
+ }
+ }
+ })
+ .await;
+
+ assert_eq!(outcome.applied, 1);
+ assert_eq!(outcome.failed, 0);
+ assert_eq!(outcome.skipped, 1);
+ assert!(outcome.state_updated);
+ assert_eq!(state.epoch(), 7);
+ assert_eq!(
+ state.bundle_config_hash().read().unwrap().as_str(),
+ "hash-7"
+ );
+
+ let applied = applied.lock().await;
+ assert_eq!(applied.len(), 1);
+ assert_eq!(applied[0].model_id, "target-model");
+ assert_eq!(applied[0].bundle_id, "default");
+ assert_eq!(applied[0].epoch, 7);
+ }
+
+ #[tokio::test]
+ async fn export_reconcile_partial_failure_does_not_advance_state() {
+ let snapshot = ExportSnapshot {
+ epoch: 8,
+ bundle_config_hashes: HashMap::new(),
+ models: vec![
+ exported_model("ok-model", &["default"]),
+ exported_model("bad-model", &["default"]),
+ ],
+ };
+ let state = ConfigApplyState::new("old".into());
+ let metrics = metrics();
+
+ let outcome = reconcile_export_snapshot(
+ snapshot,
+ "default",
+ &state,
+ &metrics,
+ false,
+ "test",
+ |req, _model_id, _epoch| async move {
+ if req.model_id == "bad-model" {
+ Err(IpcError::Server("apply failed".into()))
+ } else {
+ Ok(Some(ApplyModelConfigResponse {
+ applied: true,
+ bundle_config_hash: "hash-8".into(),
+ config_version: 8,
+ }))
+ }
+ },
+ )
+ .await;
+
+ assert_eq!(outcome.applied, 1);
+ assert_eq!(outcome.failed, 1);
+ assert!(!outcome.state_updated);
+ assert_eq!(state.epoch(), 0);
+ assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "old");
+ }
+
+ #[tokio::test]
+ async fn export_reconcile_forced_epoch_rewind_only_after_success() {
+ let snapshot = ExportSnapshot {
+ epoch: 3,
+ bundle_config_hashes: HashMap::new(),
+ models: vec![exported_model("target-model", &["default"])],
+ };
+ let state = ConfigApplyState::new("old".into());
+ state.force_epoch(9);
+ let metrics = metrics();
+
+ let outcome = reconcile_export_snapshot(
+ snapshot,
+ "default",
+ &state,
+ &metrics,
+ true,
+ "test",
+ |_req, _model_id, _epoch| async move {
+ Ok(Some(ApplyModelConfigResponse {
+ applied: true,
+ bundle_config_hash: "hash-3".into(),
+ config_version: 3,
+ }))
+ },
+ )
+ .await;
+
+ assert_eq!(outcome.applied, 1);
+ assert_eq!(outcome.failed, 0);
+ assert!(outcome.state_updated);
+ assert_eq!(state.epoch(), 3);
+ assert_eq!(
+ state.bundle_config_hash().read().unwrap().as_str(),
+ "hash-3"
+ );
+ }
+
+ #[tokio::test]
+ async fn export_reconcile_prefers_control_plane_bundle_hash() {
+ let snapshot = ExportSnapshot {
+ epoch: 11,
+ bundle_config_hashes: HashMap::from([(
+ "default".to_string(),
+ "control-hash".to_string(),
+ )]),
+ models: vec![exported_model("target-model", &["default"])],
+ };
+ let state = ConfigApplyState::new("old".into());
+ let metrics = metrics();
+
+ let outcome = reconcile_export_snapshot(
+ snapshot,
+ "default",
+ &state,
+ &metrics,
+ false,
+ "test",
+ |_req, _model_id, _epoch| async move {
+ Ok(Some(ApplyModelConfigResponse {
+ applied: true,
+ bundle_config_hash: "python-hash".into(),
+ config_version: 11,
+ }))
+ },
+ )
+ .await;
+
+ assert_eq!(outcome.failed, 0);
+ assert!(outcome.state_updated);
+ assert_eq!(state.epoch(), 11);
+ assert_eq!(
+ state.bundle_config_hash().read().unwrap().as_str(),
+ "control-hash"
+ );
+ }
+}
diff --git a/packages/sie_server_sidecar/src/config_subscriber.rs b/packages/sie_server_sidecar/src/config_subscriber.rs
new file mode 100644
index 000000000..a511e5d61
--- /dev/null
+++ b/packages/sie_server_sidecar/src/config_subscriber.rs
@@ -0,0 +1,779 @@
+//! Bundle-scoped config-delta subscriber.
+//!
+//! `sie-config` publishes validated model config deltas to both
+//! `sie.config.models._all` (gateway replicas) and
+//! `sie.config.models.<bundle>` (workers). The gateway applies `_all` into its
+//! Rust registry; this module consumes the bundle-scoped subject in the
+//! worker-sidecar and forwards the validated YAML to Python over IPC so the
+//! adapter-local `ModelRegistry` changes in the process that serves inference.
+
+use std::collections::VecDeque;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, RwLock};
+
+use async_nats::Client;
+use futures_util::StreamExt;
+use serde::{Deserialize, Serialize};
+use tokio::sync::{Mutex, MutexGuard, Notify};
+use tokio::task::JoinHandle;
+use tokio::time::{sleep, Duration};
+use tracing::{debug, info, warn};
+
+use crate::health_publisher::SharedBundleConfigHash;
+use crate::ipc_client::{IpcClient, IpcError};
+use crate::ipc_types::ApplyModelConfigRequest;
+use crate::metrics::MetricsRegistry;
+use crate::shutdown::Shutdown;
+
+const SUBJECT_PREFIX: &str = "sie.config.models";
+pub const MAX_MODEL_CONFIG_BYTES: usize = 1_048_576;
+const RETRY_BASE_DELAY: Duration = Duration::from_millis(250);
+const RETRY_MAX_DELAY: Duration = Duration::from_secs(5);
+const MAX_ACCEPTED_BUNDLE_HASHES: usize = 64;
+
+/// Default publisher allowlist. Matches the gateway config subscriber.
+pub const DEFAULT_TRUSTED_PRODUCERS: &[&str] = &["sie-config"];
+
+#[derive(Debug)]
+pub struct ConfigApplyState {
+ epoch: AtomicU64,
+ bundle_config_hash: SharedBundleConfigHash,
+ accepted_bundle_config_hashes: RwLock<VecDeque<String>>,
+ /// Serializes Python registry mutations from live NATS deltas and export
+ /// replay so an older snapshot cannot clobber a newer live apply.
+ apply_lock: Mutex<()>,
+}
+
+impl ConfigApplyState {
+ pub fn new(initial_bundle_config_hash: String) -> Self {
+ let mut accepted_bundle_config_hashes = VecDeque::new();
+ if !initial_bundle_config_hash.is_empty() {
+ accepted_bundle_config_hashes.push_back(initial_bundle_config_hash.clone());
+ }
+ Self {
+ epoch: AtomicU64::new(0),
+ bundle_config_hash: Arc::new(RwLock::new(initial_bundle_config_hash)),
+ accepted_bundle_config_hashes: RwLock::new(accepted_bundle_config_hashes),
+ apply_lock: Mutex::new(()),
+ }
+ }
+
+ pub fn epoch(&self) -> u64 {
+ self.epoch.load(Ordering::Acquire)
+ }
+
+ pub fn bundle_config_hash(&self) -> SharedBundleConfigHash {
+ Arc::clone(&self.bundle_config_hash)
+ }
+
+ pub fn current_bundle_config_hash(&self) -> String {
+ self.bundle_config_hash
+ .read()
+ .expect("bundle config hash lock poisoned")
+ .clone()
+ }
+
+ pub fn accepts_bundle_config_hash(&self, expected_hash: &str) -> bool {
+ if expected_hash.is_empty() {
+ return true;
+ }
+ if self.current_bundle_config_hash() == expected_hash {
+ return true;
+ }
+ self.accepted_bundle_config_hashes
+ .read()
+ .expect("accepted bundle config hashes lock poisoned")
+ .iter()
+ .any(|hash| hash == expected_hash)
+ }
+
+ pub async fn lock_apply(&self) -> MutexGuard<'_, ()> {
+ self.apply_lock.lock().await
+ }
+
+ pub fn set_epoch_max(&self, epoch: u64) -> bool {
+ let mut current = self.epoch();
+ while epoch > current {
+ match self
+ .epoch
+ .compare_exchange(current, epoch, Ordering::AcqRel, Ordering::Acquire)
+ {
+ Ok(_) => return true,
+ Err(observed) => current = observed,
+ }
+ }
+ false
+ }
+
+ pub fn force_epoch(&self, epoch: u64) {
+ self.epoch.store(epoch, Ordering::Release);
+ }
+
+ pub fn set_bundle_hash(&self, hash: String) {
+ self.remember_bundle_hash(&hash);
+ let mut guard = self
+ .bundle_config_hash
+ .write()
+ .expect("bundle config hash lock poisoned");
+ *guard = hash;
+ }
+
+ fn remember_bundle_hash(&self, hash: &str) {
+ if hash.is_empty() {
+ return;
+ }
+ let mut accepted = self
+ .accepted_bundle_config_hashes
+ .write()
+ .expect("accepted bundle config hashes lock poisoned");
+ if accepted.iter().any(|known| known == hash) {
+ return;
+ }
+ accepted.push_back(hash.to_string());
+ while accepted.len() > MAX_ACCEPTED_BUNDLE_HASHES {
+ accepted.pop_front();
+ }
+ }
+
+ fn mark_applied(&self, epoch: u64, bundle_config_hash: String) {
+ if epoch == 0 {
+ if !bundle_config_hash.is_empty() {
+ self.set_bundle_hash(bundle_config_hash);
+ }
+ return;
+ }
+
+ let mut current = self.epoch();
+ while epoch > current {
+ match self
+ .epoch
+ .compare_exchange(current, epoch, Ordering::AcqRel, Ordering::Acquire)
+ {
+ Ok(_) => {
+ if !bundle_config_hash.is_empty() {
+ self.set_bundle_hash(bundle_config_hash);
+ }
+ return;
+ }
+ Err(observed) => current = observed,
+ }
+ }
+ }
+
+ pub fn mark_export_reconciled(
+ &self,
+ epoch: u64,
+ bundle_config_hash: Option<String>,
+ force_epoch: bool,
+ ) -> bool {
+ if force_epoch {
+ self.force_epoch(epoch);
+ } else {
+ let current = self.epoch();
+ if epoch < current {
+ return false;
+ }
+ self.set_epoch_max(epoch);
+ }
+ if let Some(hash) = bundle_config_hash {
+ if !hash.is_empty() {
+ self.set_bundle_hash(hash);
+ }
+ }
+ true
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ConfigNotification {
+ /// Publisher identity. Python emits this field as `router_id`; keep the
+ /// alias for the wire contract shared with the gateway.
+ #[serde(alias = "router_id")]
+ pub producer_id: String,
+ pub bundle_id: String,
+ pub epoch: u64,
+ pub bundle_config_hash: String,
+ #[serde(default)]
+ pub model_id: String,
+ #[serde(default)]
+ pub profiles_added: Vec<String>,
+ #[serde(default)]
+ pub model_config: String,
+ #[serde(default)]
+ pub affected_bundles: Vec<String>,
+}
+
+fn env_bool(name: &str) -> bool {
+ std::env::var(name).ok().is_some_and(|v| {
+ matches!(
+ v.trim().to_ascii_lowercase().as_str(),
+ "1" | "true" | "yes" | "on"
+ )
+ })
+}
+
+pub fn trusted_producers_from_env() -> Vec<String> {
+ if env_bool("SIE_NATS_CONFIG_TRUST_ANY_PRODUCER") {
+ return Vec::new();
+ }
+ let custom: Vec<String> = std::env::var("SIE_NATS_CONFIG_TRUSTED_PRODUCERS")
+ .unwrap_or_default()
+ .split(',')
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(ToString::to_string)
+ .collect();
+ if custom.is_empty() {
+ DEFAULT_TRUSTED_PRODUCERS
+ .iter()
+ .map(|s| (*s).to_string())
+ .collect()
+ } else {
+ custom
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct ConfigSubscriberOptions {
+ pub trusted_producers: Vec<String>,
+ pub generation_reconcile: Option<Arc<Notify>>,
+}
+
+struct SubscriberRuntime {
+ bundle: String,
+ trusted_producers: Vec<String>,
+ ipc: Arc<IpcClient>,
+ state: Arc<ConfigApplyState>,
+ metrics: Arc<MetricsRegistry>,
+ shutdown: Arc<Shutdown>,
+ generation_reconcile: Option<Arc<Notify>>,
+}
+
+pub fn bundle_subject(bundle: &str) -> Result<String, String> {
+ let trimmed = bundle.trim();
+ if trimmed.is_empty() {
+ return Err("bundle is empty".to_string());
+ }
+ if trimmed.contains('.') || trimmed.contains('*') || trimmed.contains('>') {
+ return Err(format!(
+ "bundle {trimmed:?} is not a single safe NATS subject token"
+ ));
+ }
+ Ok(format!("{SUBJECT_PREFIX}.{trimmed}"))
+}
+
+pub fn is_trusted_producer(producer_id: &str, trusted_producers: &[String]) -> bool {
+ if trusted_producers.is_empty() {
+ return true;
+ }
+ trusted_producers.iter().any(|trusted| {
+ trusted == producer_id
+ || producer_id
+ .strip_prefix(trusted.as_str())
+ .is_some_and(|rest| rest.starts_with('-'))
+ })
+}
+
+fn notification_targets_bundle(notification: &ConfigNotification, bundle: &str) -> bool {
+ notification.bundle_id == bundle
+}
+
+fn notification_is_stale(epoch: u64, current_epoch: u64) -> bool {
+ epoch < current_epoch || (epoch == current_epoch && epoch != 0)
+}
+
+fn record_delta(metrics: &MetricsRegistry, kind: &str, result: &str) {
+ metrics
+ .config_deltas_total
+ .with_label_values(&[kind, result])
+ .inc();
+}
+
+fn retryable_ipc_error(e: &IpcError) -> bool {
+ match e {
+ IpcError::Io(io_err) => matches!(
+ io_err.kind(),
+ std::io::ErrorKind::BrokenPipe
+ | std::io::ErrorKind::ConnectionRefused
+ | std::io::ErrorKind::ConnectionReset
+ | std::io::ErrorKind::ConnectionAborted
+ | std::io::ErrorKind::UnexpectedEof
+ | std::io::ErrorKind::NotFound
+ | std::io::ErrorKind::NotConnected
+ | std::io::ErrorKind::WouldBlock
+ ),
+ IpcError::Timeout => true,
+ _ => false,
+ }
+}
+
+fn next_retry_delay(current: Duration) -> Duration {
+ std::cmp::min(current.saturating_mul(2), RETRY_MAX_DELAY)
+}
+
+async fn wait_retry_or_shutdown(shutdown: &Shutdown, delay: Duration) -> bool {
+ tokio::select! {
+ biased;
+ _ = shutdown.wait() => true,
+ _ = sleep(delay) => false,
+ }
+}
+
+fn authoritative_bundle_hash(notification_hash: &str, applied_hash: &str) -> String {
+ if notification_hash.is_empty() {
+ applied_hash.to_string()
+ } else {
+ notification_hash.to_string()
+ }
+}
+
+/// Spawn the long-lived subscription task. Failures are logged and leave the
+/// worker serving its startup config; inference should not crash just because
+/// live config apply is temporarily unavailable.
+pub fn spawn(
+ nats: Client,
+ bundle: String,
+ ipc: Arc<IpcClient>,
+ state: Arc<ConfigApplyState>,
+ metrics: Arc<MetricsRegistry>,
+ shutdown: Arc<Shutdown>,
+ options: ConfigSubscriberOptions,
+) -> JoinHandle<()> {
+ tokio::spawn(async move {
+ let subject = match bundle_subject(&bundle) {
+ Ok(s) => s,
+ Err(e) => {
+ warn!(bundle = %bundle, error = %e, "worker-config: subscription disabled");
+ return;
+ }
+ };
+
+ let runtime = SubscriberRuntime {
+ bundle,
+ trusted_producers: options.trusted_producers,
+ ipc,
+ state,
+ metrics,
+ shutdown,
+ generation_reconcile: options.generation_reconcile,
+ };
+
+ if runtime.trusted_producers.is_empty() {
+ warn!(
+ subject = %subject,
+ "worker-config: producer validation disabled; intended only for local/dev clusters"
+ );
+ } else {
+ info!(
+ subject = %subject,
+ trusted_producers = ?runtime.trusted_producers,
+ "worker-config: subscription started"
+ );
+ }
+
+ let mut subscribe_delay = RETRY_BASE_DELAY;
+ loop {
+ if runtime.shutdown.is_fired() {
+ debug!(subject = %subject, "worker-config: shutdown observed; stopping subscriber");
+ return;
+ }
+
+ let mut subscriber = match nats.subscribe(subject.clone()).await {
+ Ok(s) => {
+ subscribe_delay = RETRY_BASE_DELAY;
+ s
+ }
+ Err(e) => {
+ warn!(
+ subject = %subject,
+ error = %e,
+ retry_delay_ms = subscribe_delay.as_millis() as u64,
+ "worker-config: subscribe failed; retrying"
+ );
+ if wait_retry_or_shutdown(&runtime.shutdown, subscribe_delay).await {
+ return;
+ }
+ subscribe_delay = next_retry_delay(subscribe_delay);
+ continue;
+ }
+ };
+
+ loop {
+ let wait = runtime.shutdown.wait();
+ tokio::select! {
+ biased;
+ _ = wait => {
+ debug!(subject = %subject, "worker-config: shutdown observed; stopping subscriber");
+ return;
+ }
+ maybe_msg = subscriber.next() => {
+ let Some(msg) = maybe_msg else {
+ warn!(
+ subject = %subject,
+ retry_delay_ms = subscribe_delay.as_millis() as u64,
+ "worker-config: subscription ended; resubscribing"
+ );
+ if wait_retry_or_shutdown(&runtime.shutdown, subscribe_delay).await {
+ return;
+ }
+ subscribe_delay = next_retry_delay(subscribe_delay);
+ break;
+ };
+ let notification: ConfigNotification = match serde_json::from_slice(&msg.payload) {
+ Ok(n) => n,
+ Err(e) => {
+ warn!(subject = %subject, error = %e, "worker-config: invalid notification JSON");
+ record_delta(&runtime.metrics, "unknown", "parse_error");
+ continue;
+ }
+ };
+ apply_notification(&runtime, notification).await;
+ }
+ }
+ }
+ }
+ })
+}
+
+pub(crate) async fn apply_via_ipc_with_retry(
+ ipc: Arc<IpcClient>,
+ shutdown: Arc<Shutdown>,
+ req: ApplyModelConfigRequest,
+ model_id: &str,
+ epoch: u64,
+) -> Result<Option<crate::ipc_types::ApplyModelConfigResponse>, IpcError> {
+ let mut retry_delay = RETRY_BASE_DELAY;
+ let mut attempt = 0_u64;
+ loop {
+ match ipc.apply_model_config(req.clone()).await {
+ Ok(resp) => 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: transient Python registry apply failure; retrying"
+ );
+ } else {
+ debug!(
+ model = %model_id,
+ epoch,
+ attempt,
+ error = %e,
+ "worker-config: Python registry apply 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),
+ }
+ }
+}
+
+async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotification) {
+ let bundle = runtime.bundle.as_str();
+ let trusted_producers = runtime.trusted_producers.as_slice();
+ let state = runtime.state.as_ref();
+ let metrics = runtime.metrics.as_ref();
+ let kind = if notification.model_config.trim().is_empty() {
+ "epoch_bump"
+ } else {
+ "model_config"
+ };
+
+ if !is_trusted_producer(&notification.producer_id, trusted_producers) {
+ warn!(
+ producer_id = %notification.producer_id,
+ trusted_producers = ?trusted_producers,
+ epoch = notification.epoch,
+ model = %notification.model_id,
+ "worker-config: rejecting notification from untrusted producer"
+ );
+ record_delta(metrics, kind, "rejected_untrusted");
+ return;
+ }
+
+ if !notification_targets_bundle(&notification, bundle) {
+ warn!(
+ notification_bundle = %notification.bundle_id,
+ worker_bundle = %bundle,
+ affected_bundles = ?notification.affected_bundles,
+ epoch = notification.epoch,
+ "worker-config: rejecting notification for another bundle"
+ );
+ record_delta(metrics, kind, "rejected_bundle");
+ return;
+ }
+
+ let current_epoch = state.epoch();
+ if notification_is_stale(notification.epoch, current_epoch) {
+ debug!(
+ epoch = notification.epoch,
+ current_epoch,
+ model = %notification.model_id,
+ "worker-config: dropping stale notification"
+ );
+ record_delta(metrics, kind, "stale");
+ return;
+ }
+
+ if kind == "epoch_bump" {
+ let _apply_guard = state.lock_apply().await;
+ let current_epoch = state.epoch();
+ if notification_is_stale(notification.epoch, current_epoch) {
+ debug!(
+ epoch = notification.epoch,
+ current_epoch,
+ model = %notification.model_id,
+ "worker-config: dropping stale notification"
+ );
+ record_delta(metrics, kind, "stale");
+ return;
+ }
+ state.set_epoch_max(notification.epoch);
+ metrics.config_epoch.set(notification.epoch as i64);
+ record_delta(metrics, kind, "applied");
+ return;
+ }
+
+ if notification.model_config.len() > MAX_MODEL_CONFIG_BYTES {
+ warn!(
+ model = %notification.model_id,
+ bytes = notification.model_config.len(),
+ max_bytes = MAX_MODEL_CONFIG_BYTES,
+ "worker-config: rejecting oversized model_config"
+ );
+ record_delta(metrics, kind, "rejected_oversized");
+ return;
+ }
+
+ let _apply_guard = state.lock_apply().await;
+ let current_epoch = state.epoch();
+ if notification_is_stale(notification.epoch, current_epoch) {
+ debug!(
+ epoch = notification.epoch,
+ current_epoch,
+ model = %notification.model_id,
+ "worker-config: dropping stale notification"
+ );
+ record_delta(metrics, kind, "stale");
+ return;
+ }
+
+ info!(
+ from = %notification.producer_id,
+ bundle = %notification.bundle_id,
+ model = %notification.model_id,
+ epoch = notification.epoch,
+ profiles_added = ?notification.profiles_added,
+ "worker-config: applying model config via IPC"
+ );
+
+ let req = ApplyModelConfigRequest {
+ bundle_id: notification.bundle_id.clone(),
+ model_id: notification.model_id.clone(),
+ epoch: notification.epoch,
+ bundle_config_hash: notification.bundle_config_hash.clone(),
+ profiles_added: notification.profiles_added.clone(),
+ model_config: notification.model_config.clone(),
+ };
+
+ let resp = match apply_via_ipc_with_retry(
+ Arc::clone(&runtime.ipc),
+ Arc::clone(&runtime.shutdown),
+ req,
+ &notification.model_id,
+ notification.epoch,
+ )
+ .await
+ {
+ Ok(Some(r)) => r,
+ Ok(None) => {
+ record_delta(metrics, kind, "shutdown");
+ return;
+ }
+ Err(e) => {
+ warn!(
+ model = %notification.model_id,
+ epoch = notification.epoch,
+ error = %e,
+ "worker-config: Python registry apply failed; epoch not advanced"
+ );
+ record_delta(metrics, kind, "apply_error");
+ return;
+ }
+ };
+
+ if !resp.applied {
+ warn!(
+ model = %notification.model_id,
+ epoch = notification.epoch,
+ "worker-config: Python registry reported applied=false; epoch not advanced"
+ );
+ record_delta(metrics, kind, "apply_rejected");
+ return;
+ }
+
+ let applied_bundle_hash =
+ authoritative_bundle_hash(&notification.bundle_config_hash, &resp.bundle_config_hash);
+
+ if !notification.bundle_config_hash.is_empty()
+ && !resp.bundle_config_hash.is_empty()
+ && notification.bundle_config_hash != resp.bundle_config_hash
+ {
+ warn!(
+ model = %notification.model_id,
+ epoch = notification.epoch,
+ advertised_hash = %notification.bundle_config_hash,
+ applied_hash = %resp.bundle_config_hash,
+ "worker-config: Python registry hash differs from control-plane hash; advertising control-plane hash"
+ );
+ record_delta(metrics, kind, "hash_mismatch");
+ } else {
+ record_delta(metrics, kind, "applied");
+ }
+
+ state.mark_applied(notification.epoch, applied_bundle_hash);
+ metrics.config_epoch.set(notification.epoch as i64);
+ if let Some(notify) = runtime.generation_reconcile.as_ref() {
+ notify.notify_one();
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn bundle_subject_requires_single_safe_token() {
+ assert_eq!(
+ bundle_subject("default").unwrap(),
+ "sie.config.models.default"
+ );
+ assert!(bundle_subject("").is_err());
+ assert!(bundle_subject("bad.bundle").is_err());
+ assert!(bundle_subject("bad*").is_err());
+ assert!(bundle_subject("bad>").is_err());
+ }
+
+ #[test]
+ fn trusted_producer_matches_exact_and_pod_prefix() {
+ let trusted = vec!["sie-config".to_string()];
+ assert!(is_trusted_producer("sie-config", &trusted));
+ assert!(is_trusted_producer("sie-config-5f7b6d8c-kxwvr", &trusted));
+ assert!(is_trusted_producer("sie-config-0", &trusted));
+ assert!(!is_trusted_producer("sie-configuration", &trusted));
+ assert!(!is_trusted_producer("other", &trusted));
+ assert!(is_trusted_producer("other", &[]));
+ }
+
+ #[test]
+ fn notification_targets_bundle_requires_payload_bundle_match() {
+ let mut notification = ConfigNotification {
+ producer_id: "sie-config".into(),
+ bundle_id: "default".into(),
+ epoch: 1,
+ bundle_config_hash: "h".into(),
+ model_id: "m".into(),
+ profiles_added: vec![],
+ model_config: "x".into(),
+ affected_bundles: vec![],
+ };
+ assert!(notification_targets_bundle(&notification, "default"));
+ assert!(!notification_targets_bundle(&notification, "other"));
+ notification.affected_bundles.push("other".into());
+ assert!(!notification_targets_bundle(&notification, "other"));
+ }
+
+ #[test]
+ fn config_notification_accepts_router_id_alias() {
+ let json = r#"{
+ "router_id": "sie-config-0",
+ "bundle_id": "default",
+ "epoch": 3,
+ "bundle_config_hash": "hash",
+ "model_id": "test/model",
+ "profiles_added": ["default"],
+ "model_config": "sie_id: test/model\n",
+ "affected_bundles": ["default"]
+ }"#;
+ let parsed: ConfigNotification = serde_json::from_str(json).unwrap();
+ assert_eq!(parsed.producer_id, "sie-config-0");
+ assert_eq!(parsed.bundle_id, "default");
+ assert_eq!(parsed.epoch, 3);
+ }
+
+ #[test]
+ fn apply_state_tracks_epoch_monotonically_and_hash() {
+ let state = ConfigApplyState::new("initial".into());
+ state.mark_applied(10, "h10".into());
+ state.mark_applied(7, "h7".into());
+ assert_eq!(state.epoch(), 10);
+ assert_eq!(
+ state.bundle_config_hash().read().unwrap().as_str(),
+ "h10",
+ "stale apply results must not roll the advertised hash backward"
+ );
+ }
+
+ #[test]
+ fn epoch_zero_model_config_is_not_stale_for_no_store_mode() {
+ assert!(!notification_is_stale(0, 0));
+ assert!(notification_is_stale(1, 1));
+ assert!(notification_is_stale(0, 1));
+ }
+
+ #[test]
+ fn epoch_zero_apply_updates_hash_without_advancing_epoch() {
+ let state = ConfigApplyState::new("initial".into());
+ state.mark_applied(0, "h0".into());
+ assert_eq!(state.epoch(), 0);
+ assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "h0");
+ }
+
+ #[test]
+ fn accepted_hash_history_keeps_inflight_work_processable() {
+ let state = ConfigApplyState::new("h0".into());
+ assert!(state.accepts_bundle_config_hash(""));
+ assert!(state.accepts_bundle_config_hash("h0"));
+ assert!(!state.accepts_bundle_config_hash("h1"));
+
+ state.mark_applied(1, "h1".into());
+ assert!(state.accepts_bundle_config_hash("h0"));
+ assert!(state.accepts_bundle_config_hash("h1"));
+ assert!(!state.accepts_bundle_config_hash("missing"));
+ }
+
+ #[test]
+ fn advertised_notification_hash_wins_after_successful_apply() {
+ assert_eq!(
+ authoritative_bundle_hash("control-plane", "python-local"),
+ "control-plane"
+ );
+ assert_eq!(
+ authoritative_bundle_hash("", "python-local"),
+ "python-local"
+ );
+ }
+
+ #[test]
+ fn retryable_ipc_errors_are_transport_or_timeout_only() {
+ let refused = IpcError::Io(std::io::Error::from(std::io::ErrorKind::ConnectionRefused));
+ let missing = IpcError::Io(std::io::Error::from(std::io::ErrorKind::NotFound));
+ let server = IpcError::Server("bad config".into());
+ let version = IpcError::VersionMismatch { got: 0 };
+
+ assert!(retryable_ipc_error(&refused));
+ assert!(retryable_ipc_error(&missing));
+ assert!(retryable_ipc_error(&IpcError::Timeout));
+ assert!(!retryable_ipc_error(&server));
+ assert!(!retryable_ipc_error(&version));
+ }
+}
diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rs
new file mode 100644
index 000000000..e19ac2e06
--- /dev/null
+++ b/packages/sie_server_sidecar/src/dispatcher.rs
@@ -0,0 +1,3145 @@
+//! Per-batch dispatcher: decode NATS JetStream messages into WorkItems,
+//! fan out to the Python inference core over IPC, publish results, and
+//! ACK/NAK each message.
+//!
+//! fetch -> decode + validate (subject, reply_subject, model_id)
+//! -> group by model_id
+//! -> per model (concurrent, capped by batch_semaphore):
+//! EnsureModelReady
+//! apply per-model batch_budget (overflow -> NAK fast)
+//! fan out encode/score/extract concurrently:
+//! resolve payload -> IPC ProcessXxxBatch -> publish + ACK
+//! on IPC failure -> NAK group with transient delay
+
+use std::collections::{BTreeMap, HashMap, HashSet};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::Instant;
+
+use async_nats::jetstream::Message;
+use futures_util::future::join_all;
+use serde_json::Value as Json;
+use thiserror::Error;
+use tokio::sync::{Mutex, Semaphore};
+use tokio::task::JoinHandle;
+use tracing::{debug, info, warn};
+
+use crate::backend::{BackendError, SharedBackend};
+use crate::config_subscriber::ConfigApplyState;
+use crate::ipc_client::{IpcClient, IpcError};
+use crate::ipc_types::{
+ BatchOutcome, Disposition, EncodeBatchItem, ExtractBatchItem, GenerateEvent, ItemOutcome,
+ PreparedTokens, ProcessEncodeBatchRequest, ProcessExtractBatchRequest, ProcessGenerateRequest,
+ ProcessScoreBatchRequest, ReadinessState, RunBatchRequest, ScoreBatchItem,
+};
+use crate::latency::LatencyTracker;
+use crate::log_util::ErrChain;
+use crate::metrics::MetricsRegistry;
+use crate::payload_store::{PayloadError, PayloadStore};
+use crate::publisher::{should_publish, Timings, WorkPublisher};
+use crate::scheduler::{
+ lora_from_options, Op as SchedOp, ProductionScheduler, ProductionSchedulerRegistry,
+ SchedulerItem, SchedulerMeta,
+};
+use crate::shutdown::Shutdown;
+use crate::subject::extract_model_id;
+use crate::tokenize::TokenizerRegistry;
+use crate::work_types::WorkItem;
+
+/// Base NAK delay in milliseconds. Mirrors Python's `_NAK_DELAY_S`
+/// (default 5 000 ms, overridable via `SIE_NAK_DELAY_S`). Used for:
+///
+/// * `loading_started` readiness (just kicked off a load)
+/// * `retry_later` readiness (unknown error path)
+/// * generic transient IPC / executor failures
+///
+/// `loading_in_progress` uses `2 × base`.
+pub(crate) fn base_nak_delay_ms() -> u64 {
+ std::env::var("SIE_NAK_DELAY_S")
+ .ok()
+ .and_then(|s| s.parse::<f64>().ok())
+ .filter(|v| *v > 0.0)
+ .map(|s| (s * 1000.0) as u64)
+ .unwrap_or(5_000)
+}
+
+/// NAK delay on fair-dispatch overflow — we want fast redelivery because
+/// the item is otherwise ready, we're just flow-controlling. Matches
+/// Python's hardcoded 0.1 s overflow NAK.
+const NAK_DELAY_OVERFLOW_MS: u64 = 100;
+
+/// NAK delay used when the backend reports `BackendError::Draining`. The
+/// local backend is going away — another worker should pick the message
+/// up promptly, so we use a short delay (100ms) instead of the generic
+/// `base_nak_delay_ms` (~5s) that is intended for transient retryable
+/// errors. Holding the message back longer just starves redelivery.
+const NAK_DELAY_DRAINING_MS: u64 = 100;
+
+/// Pick the right NAK delay for a given backend error — `Draining` is
+/// fast because we want redelivery to another worker, everything else
+/// uses the shared base delay.
+pub(crate) fn nak_delay_for_backend_error(err: &BackendError) -> u64 {
+ match err {
+ BackendError::Draining => NAK_DELAY_DRAINING_MS,
+ _ => base_nak_delay_ms(),
+ }
+}
+
+/// Reply subjects must live under `_INBOX.` (NATS conventions). Non-empty
+/// subjects outside this prefix are rejected as a crude anti-injection
+/// check — a malicious producer could otherwise aim results at an
+/// arbitrary subject. Empty reply_subjects are allowed (fire-and-forget).
+const INBOX_PREFIX: &str = "_INBOX.";
+
+/// True if `reply_subject` is acceptable for use on a `WorkItem`.
+/// Empty is allowed (fire-and-forget). Non-empty subjects must start
+/// with `_INBOX.` so malicious producers can't redirect results.
+pub(crate) fn reply_subject_is_safe(reply_subject: &str) -> bool {
+ reply_subject.is_empty() || reply_subject.starts_with(INBOX_PREFIX)
+}
+
+/// Bind each outcome (in order) to a `resolved` index by `work_item_id`,
+/// consuming duplicate ids in FIFO arrival order. Returns a vector the
+/// same length as `outcomes`, where `Some(idx)` means "outcome[i]
+/// handles resolved[idx]" and `None` means "ghost outcome — no matching
+/// work item remaining to consume".
+///
+/// Factored out of [`Dispatcher::apply_outcomes`] so the bookkeeping is
+/// unit-testable without mocking JetStream `Message`s.
+pub(crate) fn resolve_outcome_indices<'a, I>(
+ resolved_wiids: &[&'a str],
+ outcomes_wiids: I,
+) -> Vec<Option<usize>>
+where
+ I: IntoIterator<Item = &'a str>,
+{
+ use std::collections::HashMap;
+
+ let mut by_wiid: HashMap<&str, Vec<usize>> = HashMap::with_capacity(resolved_wiids.len());
+ for (idx, wiid) in resolved_wiids.iter().enumerate() {
+ by_wiid.entry(*wiid).or_default().push(idx);
+ }
+ // Reverse so `pop()` yields earliest-inserted index first.
+ for v in by_wiid.values_mut() {
+ v.reverse();
+ }
+ outcomes_wiids
+ .into_iter()
+ .map(|wiid| by_wiid.get_mut(wiid).and_then(|v| v.pop()))
+ .collect()
+}
+
+/// Fallback per-model batch budget when the Python side doesn't report
+/// one on EnsureModelReady (for example, while the model is not loaded).
+/// Reads `SIE_NATS_FETCH_BUDGET` (default
+/// 64), the same env var that the pull loop uses for its per-fetch
+/// credit — so operators have one knob that means "how many messages a
+/// worker should grab at a time" across both layers (matches Python's
+/// historical `_DEFAULT_BATCH_BUDGET`).
+fn default_batch_budget() -> u32 {
+ std::env::var("SIE_NATS_FETCH_BUDGET")
+ .ok()
+ .and_then(|s| s.parse::<u32>().ok())
+ .unwrap_or(64)
+}
+
+/// Cap on concurrent model-group processing per worker. Matches Python's
+/// `_MAX_CONCURRENT_BATCHES = 4` — enough to keep the IPC pipeline full
+/// without risking ACK-timeout storms under backpressure. Override with
+/// `SIE_MAX_CONCURRENT_BATCHES`.
+///
+/// Exposed publicly so `main.rs` can use the same value as the fallback
+/// for `SIE_IPC_POOL_SIZE` when it's unset — the IPC pool should never
+/// be smaller than the dispatcher's concurrency cap or it becomes the
+/// binding constraint.
+pub fn default_max_concurrent_batches() -> usize {
+ std::env::var("SIE_MAX_CONCURRENT_BATCHES")
+ .ok()
+ .and_then(|s| s.parse::<usize>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or(4)
+}
+
+#[derive(Debug, Error)]
+pub enum DispatchError {
+ /// Backend-layer error — IPC transport, native inference failure,
+ /// or backend-level drain. Wraps [`BackendError`].
+ #[error("backend: {0}")]
+ Backend(#[from] BackendError),
+ #[error("payload: {0}")]
+ Payload(#[from] PayloadError),
+ #[error("publish: {0}")]
+ Publish(#[from] crate::publisher::PublishError),
+ #[error("ipc: {0}")]
+ Ipc(#[from] IpcError),
+ #[error("nats ack: {0}")]
+ Ack(String),
+}
+
+/// Pre-bundled handles the dispatcher needs — avoids a giant fn signature.
+pub struct Dispatcher {
+ /// Inference backend — typically a [`crate::backend::BackendRouter`]
+ /// composing a native backend and/or [`crate::backend::PythonIpcBackend`].
+ /// 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
+ /// trait remains outcome-oriented; generation is event-streaming, so
+ /// the dispatcher talks to Python's `ProcessGenerate` RPC directly.
+ pub ipc: Arc<IpcClient>,
+ pub payload_store: Arc<dyn PayloadStore>,
+ pub publisher: Arc<WorkPublisher>,
+ pub metrics: Arc<MetricsRegistry>,
+ /// Rolling latency tracker shared with the pull loop. On every
+ /// successful publish we record `inference_ms + postprocess_ms`
+ /// (default) or `queue_ms + inference_ms + postprocess_ms` when
+ /// `SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS=1`. See
+ /// `crate::pull_quantum_includes_queue_ms` for the rationale.
+ pub latency_tracker: Arc<Mutex<LatencyTracker>>,
+ /// Caps concurrent model-group processing. Acquired once per group,
+ /// held for the lifetime of the encode/score/extract fan-out.
+ pub batch_semaphore: Arc<Semaphore>,
+ /// Rust-side tokenizer registry. Always present; an empty
+ /// registry means "no model has registered a tokeniser yet" and
+ /// every `get(model_id)` returns `None`, which collapses the
+ /// dispatcher to the Python-tokenise fallback path.
+ ///
+ /// Tokenisers are ingested lazily on the first
+ /// [`crate::backend::InferenceBackend::ensure_model_ready`]
+ /// response that carries a populated [`crate::ipc_types::ModelDescriptor`] for the
+ /// model — see `Dispatcher::handle_model_group`.
+ pub tokenizer_registry: Arc<TokenizerRegistry>,
+ /// Optional Rust-side scheduler registry. When `Some`, every model
+ /// is routed through the Rust scheduler
+ /// (batch formation + adaptive control) with flushed batches
+ /// shipped to the backend via `run_batch`. When `None`, the
+ /// dispatcher falls back to the op-scoped `process_*_batch`
+ /// path for every request — this mode is kept for unit tests
+ /// that don't need the scheduler plumbing.
+ ///
+ /// The [`Shutdown`] signal below is observed by the per-model
+ /// drain loops which are spawned lazily on first traffic by
+ /// `Dispatcher::resolve_scheduler`.
+ pub scheduler_registry: Option<Arc<ProductionSchedulerRegistry>>,
+ /// Shutdown signal the per-model scheduler drain loops observe.
+ /// `None` when no [`Self::scheduler_registry`] is configured —
+ /// keeps the field inert for the Python-only topology.
+ pub shutdown: Option<Arc<Shutdown>>,
+ /// Current sidecar-applied bundle config state. Shared with the live config
+ /// subscriber/reconciler and NATS health publisher.
+ pub config_apply_state: Option<Arc<ConfigApplyState>>,
+ /// Per-model scheduler drain handles, populated lazily when a
+ /// new scheduler is materialised on first traffic. The shutdown
+ /// path in `lib.rs` drains this map and awaits every handle so
+ /// final-drain windows have a chance to complete.
+ pub scheduler_drain_handles: Arc<Mutex<HashMap<String, JoinHandle<()>>>>,
+ pub generation_handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
+}
+
+impl Dispatcher {
+ /// Construct with a default-sized concurrency semaphore from env.
+ ///
+ /// `scheduler_registry` + `shutdown` together gate the scheduler
+ /// path: if both are `Some`, every model routes
+ /// through `Self::enqueue_encode_into_scheduler` (and the
+ /// score / extract twins) with per-model drain loops spawned
+ /// lazily on first traffic by `Self::resolve_scheduler`.
+ /// Otherwise every model keeps the legacy
+ /// `Self::handle_encode` / `Self::handle_score` /
+ /// `Self::handle_extract` flow. It's a programming error to
+ /// pass exactly one as `Some` — we assert it below rather than
+ /// carry a half-wired state through the hot path.
+ #[allow(clippy::too_many_arguments)] // each arg is a distinct dependency
+ pub fn new(
+ backend: SharedBackend,
+ ipc: Arc<IpcClient>,
+ payload_store: Arc<dyn PayloadStore>,
+ publisher: Arc<WorkPublisher>,
+ metrics: Arc<MetricsRegistry>,
+ latency_tracker: Arc<Mutex<LatencyTracker>>,
+ tokenizer_registry: Arc<TokenizerRegistry>,
+ scheduler_registry: Option<Arc<ProductionSchedulerRegistry>>,
+ shutdown: Option<Arc<Shutdown>>,
+ config_apply_state: Option<Arc<ConfigApplyState>>,
+ ) -> Self {
+ debug_assert_eq!(
+ scheduler_registry.is_some(),
+ shutdown.is_some(),
+ "scheduler_registry and shutdown must be wired together — one half invalidates the drain-loop lifecycle"
+ );
+ Self {
+ backend,
+ ipc,
+ payload_store,
+ publisher,
+ metrics,
+ latency_tracker,
+ batch_semaphore: Arc::new(Semaphore::new(default_max_concurrent_batches())),
+ tokenizer_registry,
+ scheduler_registry,
+ shutdown,
+ config_apply_state,
+ scheduler_drain_handles: Arc::new(Mutex::new(HashMap::new())),
+ generation_handles: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+}
+
+impl Dispatcher {
+ fn current_bundle_config_hash(&self) -> Option<String> {
+ self.config_apply_state
+ .as_ref()
+ .map(|state| state.current_bundle_config_hash())
+ }
+}
+
+fn unknown_bundle_config_hash<'a>(
+ items: impl IntoIterator<Item = &'a WorkItem>,
+ state: Option<&ConfigApplyState>,
+) -> Option<(&'a str, usize)> {
+ let state = state?;
+ let mut first_unknown: Option<&'a str> = None;
+ let mut count = 0usize;
+ for wi in items {
+ if !state.accepts_bundle_config_hash(&wi.bundle_config_hash) {
+ count += 1;
+ if first_unknown.is_none() {
+ first_unknown = Some(wi.bundle_config_hash.as_str());
+ }
+ }
+ }
+ first_unknown.map(|hash| (hash, count))
+}
+
+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).
+ ///
+ /// Model-id routing: derived from the NATS **subject**, falling back
+ /// to `WorkItem.model_id` when the subject is malformed. On
+ /// disagreement the subject wins (that's what JetStream used to
+ /// dispatch us) and we warn.
+ ///
+ /// Concurrency:
+ /// * group by `model_id` only.
+ /// * model groups run concurrently, capped by `batch_semaphore` to
+ /// 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>) {
+ let batch_started = Instant::now();
+ let batch_size = messages.len();
+ self.metrics
+ .messages_received_total
+ .inc_by(batch_size as u64);
+ 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 {
+ // 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
+ // in tests return Err and are quietly skipped.
+ if let Ok(info) = msg.info() {
+ // Operation is part of the WorkItem, not the subject; use
+ // "all" here and rely on `sie_pull_loop_batch_process_seconds`
+ // (already labelled by operation) for per-op breakdowns.
+ self.metrics
+ .nats_deliver_count
+ .with_label_values(&["all"])
+ .observe(info.delivered as f64);
+ if info.delivered > 1 {
+ self.metrics.nats_redelivery_total.inc();
+ }
+ }
+ // Source of truth for routing is the NATS subject (JetStream
+ // already used it to dispatch to this consumer). If the subject
+ // doesn't yield a model_id, we can't trust the payload either,
+ // so NAK for redelivery and let max_deliver → DLQ handle it.
+ let subject_model = match extract_model_id(&msg.subject) {
+ Some(m) => m,
+ None => {
+ warn!(
+ subject = %msg.subject,
+ "could not extract model_id from subject — NAKing for redelivery",
+ );
+ nak_one(&msg, base_delay_ms, &self.metrics).await;
+ continue;
+ }
+ };
+ match rmp_serde::from_slice::<WorkItem>(&msg.payload) {
+ Ok(mut wi) => {
+ if !reply_subject_is_safe(&wi.reply_subject) {
+ // ACK-to-drop (not NAK): the subject is attacker-
+ // controlled; retrying just amplifies the attempt.
+ warn!(
+ work_item_id = %wi.work_item_id,
+ reply_subject = %truncate(&wi.reply_subject, 60),
+ "rejecting WorkItem with suspicious reply_subject — ACKing to drop",
+ );
+ match ack(&msg).await {
+ Ok(()) => self.metrics.messages_acked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "ack failed on drop");
+ self.metrics.jetstream_ack_failures_total.inc();
+ }
+ }
+ continue;
+ }
+ if wi.model_id != subject_model {
+ warn!(
+ work_item_id = %wi.work_item_id,
+ subject = %msg.subject,
+ wi_model_id = %wi.model_id,
+ subject_model_id = %subject_model,
+ "WorkItem.model_id disagrees with subject — trusting subject",
+ );
+ wi.model_id = subject_model;
+ }
+ decoded.push((wi, msg));
+ }
+ Err(e) => {
+ // NAK so JetStream redelivers (possibly to a worker on a
+ // newer wire version) and eventually DLQs after
+ // 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;
+ }
+ }
+ }
+ if decoded.is_empty() {
+ info!(
+ batch_size,
+ elapsed_ms = batch_started.elapsed().as_millis() as u64,
+ "handle_batch: done (all messages rejected before dispatch)"
+ );
+ return;
+ }
+
+ let mut generate_items = Vec::new();
+ let mut regular_items = Vec::with_capacity(decoded.len());
+ for (wi, msg) in decoded {
+ if wi.operation == "generate" {
+ generate_items.push((wi, msg));
+ } else {
+ regular_items.push((wi, msg));
+ }
+ }
+ let generate_count = generate_items.len();
+ if generate_count > 0 {
+ self.spawn_generate_items(generate_items).await;
+ }
+ if regular_items.is_empty() {
+ info!(
+ batch_size,
+ generate = generate_count,
+ elapsed_ms = batch_started.elapsed().as_millis() as u64,
+ "handle_batch: done (generation items handed off)"
+ );
+ return;
+ }
+
+ let model_groups = group_by_model_only(regular_items);
+ let group_count = model_groups.len();
+ let mut futs = Vec::with_capacity(group_count);
+ for (model_id, items) in model_groups {
+ let this = Arc::clone(self);
+ futs.push(async move {
+ let permit = match this.batch_semaphore.clone().acquire_owned().await {
+ Ok(p) => p,
+ Err(_) => {
+ warn!(model = %model_id, "batch semaphore closed — dropping group");
+ return;
+ }
+ };
+ this.metrics.inflight_batches.inc();
+ let result = this.handle_model_group(&model_id, items).await;
+ this.metrics.inflight_batches.dec();
+ drop(permit);
+ if let Err(e) = result {
+ warn!(model = %model_id, error = %ErrChain(&e), "model group handling failed");
+ }
+ });
+ }
+ join_all(futs).await;
+ info!(
+ batch_size,
+ group_count,
+ elapsed_ms = batch_started.elapsed().as_millis() as u64,
+ "handle_batch: done"
+ );
+ }
+
+ async fn spawn_generate_items(self: &Arc<Self>, items: Vec<(WorkItem, Message)>) {
+ let mut handles = self.generation_handles.lock().await;
+ handles.retain(|h| !h.is_finished());
+ for (wi, msg) in items {
+ let this = Arc::clone(self);
+ handles.push(tokio::spawn(async move {
+ this.handle_generate_item(wi, msg).await;
+ }));
+ }
+ }
+
+ async fn handle_generate_item(self: Arc<Self>, wi: WorkItem, msg: Message) {
+ let model_id = wi.model_id.clone();
+ let model_lbl = self.metrics.model_label(&model_id).into_owned();
+ let _timer = self
+ .metrics
+ .pull_batch_process_seconds
+ .with_label_values(&[&model_lbl, "generate"])
+ .start_timer();
+ let base_delay_ms = base_nak_delay_ms();
+
+ let readiness_resp = match self.backend.ensure_model_ready(&model_id).await {
+ Ok(r) => r,
+ Err(e) => {
+ warn!(
+ model = %model_id,
+ error = %ErrChain(&e),
+ "EnsureModelReady failed for generate — NAKing"
+ );
+ nak_one(&msg, nak_delay_for_backend_error(&e), &self.metrics).await;
+ return;
+ }
+ };
+ match readiness_resp.state {
+ ReadinessState::Ready => {}
+ ReadinessState::LoadingStarted | ReadinessState::RetryLater => {
+ nak_one(&msg, base_delay_ms, &self.metrics).await;
+ return;
+ }
+ ReadinessState::LoadingInProgress => {
+ nak_one(&msg, base_delay_ms.saturating_mul(2), &self.metrics).await;
+ return;
+ }
+ }
+
+ let work_item_msgpack = match rmp_serde::to_vec_named(&wi) {
+ Ok(bytes) => bytes,
+ Err(e) => {
+ warn!(
+ work_item_id = %wi.work_item_id,
+ request_id = %wi.request_id,
+ error = %e,
+ "failed to re-encode generate WorkItem — publishing error + ACK"
+ );
+ match self
+ .publish_error(&wi, "internal_error", "failed to encode generate work item")
+ .await
+ {
+ Ok(_) => match ack(&msg).await {
+ Ok(()) => self.metrics.messages_acked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "ack after generate encode error failed");
+ self.metrics.jetstream_ack_failures_total.inc();
+ }
+ },
+ Err(_) => nak_one(&msg, base_delay_ms, &self.metrics).await,
+ }
+ return;
+ }
+ };
+
+ let settled = Arc::new(AtomicBool::new(false));
+ let msg = Arc::new(msg);
+ 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 result = self
+ .ipc
+ .process_generate(
+ ProcessGenerateRequest {
+ model_id: model_id.clone(),
+ work_item_msgpack,
+ },
+ move |event| {
+ let publisher = Arc::clone(&publisher);
+ let metrics = Arc::clone(&metrics);
+ let settled = Arc::clone(&settled_for_events);
+ let msg = Arc::clone(&msg_for_events);
+ async move {
+ handle_generate_event(event, publisher, metrics, settled, msg)
+ .await
+ .map_err(|e| IpcError::Server(e.to_string()))
+ }
+ },
+ )
+ .await;
+
+ match result {
+ Ok(()) => {
+ if !settled.load(Ordering::SeqCst) {
+ warn!(
+ work_item_id = %wi.work_item_id,
+ request_id = %wi.request_id,
+ "ProcessGenerate ended without ACK/NAK event — NAKing"
+ );
+ nak_one(&msg, base_delay_ms, &self.metrics).await;
+ }
+ }
+ Err(e) => {
+ warn!(
+ work_item_id = %wi.work_item_id,
+ request_id = %wi.request_id,
+ model = %model_id,
+ error = %e,
+ "ProcessGenerate failed — NAKing if unsettled"
+ );
+ if !settled.swap(true, Ordering::SeqCst) {
+ nak_one(&msg, base_delay_ms, &self.metrics).await;
+ }
+ }
+ }
+ }
+
+ async fn handle_model_group(
+ self: &Arc<Self>,
+ model_id: &str,
+ items: Vec<(WorkItem, Message)>,
+ ) -> Result<(), DispatchError> {
+ let group_started = Instant::now();
+ let group_size = items.len();
+ let base_delay_ms = base_nak_delay_ms();
+ if let Some((expected_hash, unknown_hash_count)) = unknown_bundle_config_hash(
+ items.iter().map(|(wi, _)| wi),
+ self.config_apply_state.as_deref(),
+ ) {
+ let local_hash = self.current_bundle_config_hash().unwrap_or_default();
+ info!(
+ model = %model_id,
+ unknown_hash_count,
+ group_size,
+ local_hash = %local_hash,
+ expected_hash,
+ "request bundle config hash is unknown locally — NAKing group"
+ );
+ nak_all(&items, base_delay_ms, &self.metrics).await;
+ return Ok(());
+ }
+ // `ipc_requests_total` / `ipc_failures_total` identify the IPC
+ // transport counters even though the backend trait is generic (see
+ // `crate::backend::InferenceBackend`).
+ self.metrics.ipc_requests_total.inc();
+ let readiness_resp = match self.backend.ensure_model_ready(model_id).await {
+ Ok(r) => r,
+ Err(e) => {
+ self.metrics.ipc_failures_total.inc();
+ warn!(
+ model = %model_id,
+ group_size,
+ error = %ErrChain(&e),
+ "EnsureModelReady failed — NAKing group"
+ );
+ nak_all(&items, base_delay_ms, &self.metrics).await;
+ return Err(e.into());
+ }
+ };
+ match readiness_resp.state {
+ ReadinessState::Ready => {
+ // Adapter handshake: fold the adapter's `ModelDescriptor`
+ // (if any) into our local registries. Idempotent on
+ // re-handshake — the registry hashes the loaded
+ // tokenizer.json and short-circuits if the declared
+ // `tokenizer_id` already matches what's cached.
+ if let Some(descriptor) = readiness_resp.descriptor.as_ref() {
+ match self
+ .tokenizer_registry
+ .register_from_descriptor(model_id, descriptor)
+ {
+ Ok(true) => {
+ debug!(
+ model = %model_id,
+ "rust-tokenize: registered tokeniser from EnsureModelReady descriptor"
+ );
+ }
+ Ok(false) => {} // no path, idempotent, or hash mismatch (warning logged inside)
+ Err(e) => {
+ // Non-fatal: model just falls back to Python
+ // tokenisation, exactly the same as if no
+ // descriptor had been declared at all.
+ warn!(
+ model = %model_id,
+ error = %e,
+ "rust-tokenize: descriptor load failed — Python will tokenise this model"
+ );
+ }
+ }
+ }
+ }
+ ReadinessState::LoadingStarted => {
+ info!(model = %model_id, "model load started — NAKing group for retry");
+ nak_all(&items, base_delay_ms, &self.metrics).await;
+ return Ok(());
+ }
+ ReadinessState::LoadingInProgress => {
+ // 2× base so we don't burn through max_deliver while a slow
+ // model is loading (Python uses the same multiplier).
+ info!(model = %model_id, "model load in progress — NAKing group with 2x delay");
+ nak_all(&items, base_delay_ms.saturating_mul(2), &self.metrics).await;
+ return Ok(());
+ }
+ ReadinessState::RetryLater => {
+ info!(model = %model_id, "model not available — NAKing group");
+ nak_all(&items, base_delay_ms, &self.metrics).await;
+ return Ok(());
+ }
+ }
+
+ // Cap the group at the per-model batch budget reported by Python.
+ // Overflow gets NAK'd with a short delay so it redelivers to
+ // (possibly) another worker — keeps one hot model from starving
+ // the others on this worker's GPU.
+ let budget = readiness_resp
+ .batch_budget
+ .filter(|&b| b > 0)
+ .unwrap_or_else(default_batch_budget) as usize;
+ let (dispatch, overflow) = split_by_budget(items, budget);
+ if !overflow.is_empty() {
+ debug!(
+ model = %model_id,
+ budget,
+ overflow = overflow.len(),
+ "fair dispatch: NAKing overflow"
+ );
+ nak_all(&overflow, NAK_DELAY_OVERFLOW_MS, &self.metrics).await;
+ }
+ if dispatch.is_empty() {
+ return Ok(());
+ }
+ let model_lbl = self.metrics.model_label(model_id);
+ self.metrics
+ .pull_items_fetched
+ .with_label_values(&[&model_lbl])
+ .observe(dispatch.len() as f64);
+
+ // Fan out by operation; each op runs concurrently below. The IPC
+ // client serialises at the socket but payload resolution, NATS
+ // ACKs and publishes all overlap across ops.
+ 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 {
+ 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)),
+ }
+ }
+
+ for (wi, msg) in &unknown_items {
+ warn!(op = %wi.operation, "unknown operation — publishing error + ACK");
+ match self
+ .publish_error(wi, "bad_operation", "unknown operation")
+ .await
+ {
+ Ok(_) => match ack(msg).await {
+ Ok(()) => self.metrics.messages_acked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "ack after bad_operation error-publish failed");
+ self.metrics.jetstream_ack_failures_total.inc();
+ }
+ },
+ Err(_) => {
+ // Error publish failed — NAK so JetStream redelivers
+ // 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;
+ }
+ }
+ }
+
+ let encode_n = encode_items.len();
+ let score_n = score_items.len();
+ let extract_n = extract_items.len();
+ let unknown_n = unknown_items.len();
+
+ // When `scheduler_registry` is wired, every op routes through
+ // the scheduler's submit-then-drain path instead of the per-op
+ // `process_*_batch` path. The scheduler owns batch formation +
+ // adaptive control and hands flushed batches to the backend via
+ // `run_batch`; the per-model drain loop (spawned lazily on first
+ // traffic inside [`Self::resolve_scheduler`]) handles inference
+ // + publish + ACK/NAK.
+ //
+ // Registry absent ⇒ legacy path unchanged. Only unit tests
+ // exercise that branch today.
+ let scheduler_opt = self.resolve_scheduler(model_id).await;
+ let encode_fut = async {
+ if encode_items.is_empty() {
+ return Ok(());
+ }
+ if let Some(sched) = scheduler_opt.as_ref() {
+ self.enqueue_encode_into_scheduler(model_id, sched, encode_items)
+ .await;
+ return Ok(());
+ }
+ self.handle_encode(model_id, encode_items).await
+ };
+ let score_fut = async {
+ if score_items.is_empty() {
+ return Ok(());
+ }
+ if let Some(sched) = scheduler_opt.as_ref() {
+ self.enqueue_score_into_scheduler(model_id, sched, score_items)
+ .await;
+ return Ok(());
+ }
+ self.handle_score(model_id, score_items).await
+ };
+ let extract_fut = async {
+ if extract_items.is_empty() {
+ return Ok(());
+ }
+ if let Some(sched) = scheduler_opt.as_ref() {
+ self.enqueue_extract_into_scheduler(model_id, sched, extract_items)
+ .await;
+ return Ok(());
+ }
+ self.handle_extract(model_id, extract_items).await
+ };
+ let (r_enc, r_score, r_ext) = tokio::join!(encode_fut, score_fut, extract_fut);
+ if let Err(e) = &r_enc {
+ warn!(model = %model_id, error = %ErrChain(e), "encode batch failed");
+ }
+ if let Err(e) = &r_score {
+ warn!(model = %model_id, error = %ErrChain(e), "score batch failed");
+ }
+ if let Err(e) = &r_ext {
+ warn!(model = %model_id, error = %ErrChain(e), "extract batch failed");
+ }
+ info!(
+ model = %model_id,
+ group_size,
+ encode = encode_n,
+ score = score_n,
+ extract = extract_n,
+ unknown = unknown_n,
+ encode_ok = r_enc.is_ok(),
+ score_ok = r_score.is_ok(),
+ extract_ok = r_ext.is_ok(),
+ elapsed_ms = group_started.elapsed().as_millis() as u64,
+ "handle_model_group: done"
+ );
+ Ok(())
+ }
+
+ // -- encode -----------------------------------------------------------
+
+ async fn handle_encode(
+ &self,
+ model_id: &str,
+ items: Vec<(WorkItem, Message)>,
+ ) -> Result<(), DispatchError> {
+ let model_lbl = self.metrics.model_label(model_id);
+ let _timer = self
+ .metrics
+ .pull_batch_process_seconds
+ .with_label_values(&[&model_lbl, "encode"])
+ .start_timer();
+ let mut resolved: Vec<(WorkItem, Message, Json, f64)> = Vec::with_capacity(items.len());
+ for (wi, msg) in items {
+ let (item_json, fetch_ms) = match self.resolve_item(&wi).await {
+ Ok(v) => v,
+ Err(e) => {
+ warn!(
+ error = %ErrChain(&e),
+ work_item_id = %wi.work_item_id,
+ request_id = %wi.request_id,
+ model = %wi.model_id,
+ "failed to resolve encode item"
+ );
+ match self
+ .publish_error(&wi, "payload_error", "failed to resolve item")
+ .await
+ {
+ Ok(_) => match ack(&msg).await {
+ Ok(()) => self.metrics.messages_acked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "ack after error-publish failed");
+ self.metrics.jetstream_ack_failures_total.inc();
+ }
+ },
+ Err(_) => {
+ // NATS publish failed — NAK so redelivery
+ // 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;
+ }
+ }
+ continue;
+ }
+ };
+ resolved.push((wi, msg, item_json, fetch_ms));
+ }
+ if resolved.is_empty() {
+ return Ok(());
+ }
+
+ let batch_items: Vec<EncodeBatchItem> = resolved
+ .iter()
+ .map(|(wi, _msg, item, fm)| {
+ let prepared_tokens = self.maybe_prepare_encode_tokens(model_id, wi, item);
+ EncodeBatchItem {
+ work_item_id: wi.work_item_id.clone(),
+ request_id: wi.request_id.clone(),
+ item_index: wi.item_index,
+ total_items: wi.total_items,
+ timestamp: wi.timestamp,
+ item: item.clone(),
+ output_types: wi.output_types.clone(),
+ instruction: wi.instruction.clone(),
+ is_query: wi.is_query,
+ options: wi.options.clone(),
+ profile_id: opt_non_empty(&wi.profile_id),
+ bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
+ payload_fetch_ms: *fm,
+ prepared_tokens,
+ }
+ })
+ .collect();
+
+ self.metrics.ipc_requests_total.inc();
+ let outcome = match self
+ .backend
+ .process_encode_batch(ProcessEncodeBatchRequest {
+ model_id: model_id.to_string(),
+ items: batch_items,
+ })
+ .await
+ {
+ Ok(o) => o,
+ Err(e) => {
+ self.metrics.ipc_failures_total.inc();
+ let delay = nak_delay_for_backend_error(&e);
+ warn!(
+ model = %model_id,
+ error = %ErrChain(&e),
+ nak_delay_ms = delay,
+ batch_size = resolved.len(),
+ "ProcessEncodeBatch failed — NAKing group"
+ );
+ let msgs_only: Vec<(WorkItem, Message)> =
+ resolved.into_iter().map(|(wi, m, _, _)| (wi, m)).collect();
+ nak_all(&msgs_only, delay, &self.metrics).await;
+ return Err(e.into());
+ }
+ };
+
+ self.apply_outcomes(
+ outcome,
+ resolved
+ .into_iter()
+ .map(|(wi, m, _, fm)| (wi, m, fm))
+ .collect(),
+ )
+ .await;
+ Ok(())
+ }
+
+ // -- score ------------------------------------------------------------
+
+ async fn handle_score(
+ &self,
+ model_id: &str,
+ items: Vec<(WorkItem, Message)>,
+ ) -> Result<(), DispatchError> {
+ let model_lbl = self.metrics.model_label(model_id);
+ let _timer = self
+ .metrics
+ .pull_batch_process_seconds
+ .with_label_values(&[&model_lbl, "score"])
+ .start_timer();
+ let mut prepared: Vec<(WorkItem, Message, Json, Vec<Json>, f64)> =
+ Vec::with_capacity(items.len());
+ for (wi, msg) in items {
+ let (query, score_items, fetch_ms) = match self.resolve_score(&wi).await {
+ Ok(v) => v,
+ Err(e) => {
+ warn!(
+ error = %ErrChain(&e),
+ work_item_id = %wi.work_item_id,
+ request_id = %wi.request_id,
+ model = %wi.model_id,
+ "failed to resolve score payload"
+ );
+ match self
+ .publish_error(&wi, "payload_error", "failed to resolve score payload")
+ .await
+ {
+ Ok(_) => match ack(&msg).await {
+ Ok(()) => self.metrics.messages_acked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "ack after error-publish failed");
+ self.metrics.jetstream_ack_failures_total.inc();
+ }
+ },
+ Err(_) => {
+ nak_one(&msg, base_nak_delay_ms(), &self.metrics).await;
+ }
+ }
+ continue;
+ }
+ };
+ prepared.push((wi, msg, query, score_items, fetch_ms));
+ }
+ if prepared.is_empty() {
+ return Ok(());
+ }
+
+ // Rust-tokenisation wire-noop on score: Python's
+ // `_process_single_score` does not consume `prepared_tokens`
+ // — the cross-encoder adapter tokenises query+doc pairs
+ // internally using model-specific pair-building policy
+ // (`[CLS] q [SEP] d [SEP]`, pair padding, etc.) that lives
+ // adapter-side. We always set `prepared_tokens = None` here
+ // so the Python path stays the source of truth. See the
+ // score-path note in `docs/architecture-guide.md`.
+ let batch_items: Vec<ScoreBatchItem> = prepared
+ .iter()
+ .map(|(wi, _, q, it, fm)| ScoreBatchItem {
+ work_item_id: wi.work_item_id.clone(),
+ request_id: wi.request_id.clone(),
+ item_index: wi.item_index,
+ total_items: wi.total_items,
+ timestamp: wi.timestamp,
+ query_item: q.clone(),
+ score_items: it.clone(),
+ instruction: wi.instruction.clone(),
+ options: wi.options.clone(),
+ profile_id: opt_non_empty(&wi.profile_id),
+ payload_fetch_ms: *fm,
+ prepared_tokens: None,
+ })
+ .collect();
+
+ self.metrics.ipc_requests_total.inc();
+ let outcome = match self
+ .backend
+ .process_score_batch(ProcessScoreBatchRequest {
+ model_id: model_id.to_string(),
+ items: batch_items,
+ })
+ .await
+ {
+ Ok(o) => o,
+ Err(e) => {
+ self.metrics.ipc_failures_total.inc();
+ let delay = nak_delay_for_backend_error(&e);
+ warn!(
+ model = %model_id,
+ error = %ErrChain(&e),
+ nak_delay_ms = delay,
+ batch_size = prepared.len(),
+ "ProcessScoreBatch failed — NAKing group"
+ );
+ let msgs_only: Vec<(WorkItem, Message)> = prepared
+ .into_iter()
+ .map(|(wi, m, _, _, _)| (wi, m))
+ .collect();
+ nak_all(&msgs_only, delay, &self.metrics).await;
+ return Err(e.into());
+ }
+ };
+
+ self.apply_outcomes(
+ outcome,
+ prepared
+ .into_iter()
+ .map(|(wi, m, _, _, fm)| (wi, m, fm))
+ .collect(),
+ )
+ .await;
+ Ok(())
+ }
+
+ // -- extract ----------------------------------------------------------
+
+ async fn handle_extract(
+ &self,
+ model_id: &str,
+ items: Vec<(WorkItem, Message)>,
+ ) -> Result<(), DispatchError> {
+ let model_lbl = self.metrics.model_label(model_id);
+ let _timer = self
+ .metrics
+ .pull_batch_process_seconds
+ .with_label_values(&[&model_lbl, "extract"])
+ .start_timer();
+ let mut resolved: Vec<(WorkItem, Message, Json, f64)> = Vec::with_capacity(items.len());
+ for (wi, msg) in items {
+ let (item_json, fetch_ms) = match self.resolve_item(&wi).await {
+ Ok(v) => v,
+ Err(e) => {
+ warn!(
+ error = %ErrChain(&e),
+ work_item_id = %wi.work_item_id,
+ request_id = %wi.request_id,
+ model = %wi.model_id,
+ "failed to resolve extract item"
+ );
+ match self
+ .publish_error(&wi, "payload_error", "failed to resolve item")
+ .await
+ {
+ Ok(_) => match ack(&msg).await {
+ Ok(()) => self.metrics.messages_acked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "ack after error-publish failed");
+ self.metrics.jetstream_ack_failures_total.inc();
+ }
+ },
+ Err(_) => {
+ nak_one(&msg, base_nak_delay_ms(), &self.metrics).await;
+ }
+ }
+ continue;
+ }
+ };
+ resolved.push((wi, msg, item_json, fetch_ms));
+ }
+ if resolved.is_empty() {
+ return Ok(());
+ }
+
+ let batch_items: Vec<ExtractBatchItem> = resolved
+ .iter()
+ .map(|(wi, _, item, fm)| ExtractBatchItem {
+ work_item_id: wi.work_item_id.clone(),
+ request_id: wi.request_id.clone(),
+ item_index: wi.item_index,
+ total_items: wi.total_items,
+ timestamp: wi.timestamp,
+ item: item.clone(),
+ labels: wi.labels.clone(),
+ output_schema: wi.output_schema.clone(),
+ instruction: wi.instruction.clone(),
+ options: wi.options.clone(),
+ profile_id: opt_non_empty(&wi.profile_id),
+ bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
+ payload_fetch_ms: *fm,
+ })
+ .collect();
+
+ self.metrics.ipc_requests_total.inc();
+ let outcome = match self
+ .backend
+ .process_extract_batch(ProcessExtractBatchRequest {
+ model_id: model_id.to_string(),
+ items: batch_items,
+ })
+ .await
+ {
+ Ok(o) => o,
+ Err(e) => {
+ self.metrics.ipc_failures_total.inc();
+ let delay = nak_delay_for_backend_error(&e);
+ warn!(
+ model = %model_id,
+ error = %ErrChain(&e),
+ nak_delay_ms = delay,
+ batch_size = resolved.len(),
+ "ProcessExtractBatch failed — NAKing group"
+ );
+ let msgs_only: Vec<(WorkItem, Message)> =
+ resolved.into_iter().map(|(wi, m, _, _)| (wi, m)).collect();
+ nak_all(&msgs_only, delay, &self.metrics).await;
+ return Err(e.into());
+ }
+ };
+
+ self.apply_outcomes(
+ outcome,
+ resolved
+ .into_iter()
+ .map(|(wi, m, _, fm)| (wi, m, fm))
+ .collect(),
+ )
+ .await;
+ Ok(())
+ }
+
+ // -- outcome / publish helpers ---------------------------------------
+
+ async fn apply_outcomes(&self, outcome: BatchOutcome, resolved: Vec<(WorkItem, Message, 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".
+ let wiids: Vec<&str> = resolved
+ .iter()
+ .map(|(wi, _, _)| wi.work_item_id.as_str())
+ .collect();
+ let bindings = resolve_outcome_indices(
+ &wiids,
+ outcome.outcomes.iter().map(|o| o.work_item_id.as_str()),
+ );
+
+ let mut resolved: Vec<Option<(WorkItem, Message, f64)>> =
+ resolved.into_iter().map(Some).collect();
+
+ for (outcome_idx, item_outcome) in outcome.outcomes.into_iter().enumerate() {
+ let Some(idx) = bindings[outcome_idx] else {
+ warn!(
+ work_item_id = %item_outcome.work_item_id,
+ "outcome for unknown or already-consumed work_item_id — ignoring"
+ );
+ continue;
+ };
+ let Some((wi, msg, fetch_ms)) = resolved[idx].take() else {
+ continue;
+ };
+ self.apply_outcome(&wi, &msg, &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 {
+ continue;
+ };
+ warn!(
+ subject = %msg.subject,
+ "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();
+ }
+ }
+ }
+
+ async fn apply_outcome(
+ &self,
+ wi: &WorkItem,
+ msg: &Message,
+ outcome: &ItemOutcome,
+ payload_fetch_ms: f64,
+ ) {
+ match outcome.disposition {
+ Disposition::PublishAndAck | Disposition::PublishErrorAndAck => {
+ if should_publish(&outcome.disposition) {
+ let queue_ms = queue_ms_from(wi.timestamp);
+ let timings = Some(Timings {
+ queue_ms,
+ payload_fetch_ms,
+ });
+ match self
+ .publisher
+ .publish_result(&wi.reply_subject, outcome, timings)
+ .await
+ {
+ Ok(()) => {
+ // Record latency only on the success path —
+ // sampling error-path latency would bias the
+ // FetchExpiry controller toward shrinking the
+ // pull-loop quantum.
+ //
+ // By default `queue_ms_from(wi.timestamp)`
+ // (gateway-publish → NATS-pull) is **excluded**:
+ // including it would feed upstream queue depth
+ // into the tracker that drives the pull-loop
+ // quantum, collapsing the quantum to its floor
+ // under saturation even though the pull-loop
+ // itself isn't the bottleneck. Mirrors the semantics applied
+ // to the scheduler's adaptive-batch tracker
+ // (see `dispatch_batch_inner` per_item_total_ms).
+ //
+ // Operators can opt in to whole-path latency
+ // feedback (queue + inference + postprocess) via
+ // `SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS=1`. See
+ // [`crate::pull_quantum_includes_queue_ms`] and
+ // `docs/architecture-guide.md`.
+ if matches!(outcome.disposition, Disposition::PublishAndAck) {
+ let inference_ms = outcome.inference_ms.unwrap_or(0.0);
+ let postprocess_ms = outcome.postprocessing_ms.unwrap_or(0.0);
+ let mut total = inference_ms + postprocess_ms;
+ if crate::pull_quantum_includes_queue_ms() {
+ total += queue_ms;
+ }
+ self.latency_tracker.lock().await.record(total);
+
+ // Prometheus backend timing histograms. Observations
+ // are per-item (one outcome == one source request), so
+ // each completed backend batch contributes N samples
+ // per timing bucket. Only the success path is sampled
+ // to match the rationale above on latency_tracker.
+ //
+ // A zero field means "backend didn't report this phase"
+ // (e.g. tokenize time for image-only models, or
+ // postprocess when no postprocessor ran) — skip those
+ // so the histograms reflect reality rather than
+ // adding a pile of 0-bucket samples that bias p50.
+ //
+ // Cardinality: `operation` is a free-form String on
+ // WorkItem, but PublishAndAck is only produced by the
+ // encode/score/extract code paths (unknown ops route
+ // to publish_error_and_ack and get filtered by the
+ // outer match). We still check against the known set
+ // defensively — a future refactor shouldn't be able
+ // to sneak a new label value into Prometheus without
+ // touching this list. If it's somehow not one of the
+ // three, skip the observation (don't `return` — that
+ // would bypass the ACK below and cause redelivery).
+ if let op @ ("encode" | "score" | "extract") = wi.operation.as_str()
+ {
+ let model_label =
+ self.metrics.model_label(&wi.model_id).into_owned();
+ let record_phase = |phase: &str, ms: f64| {
+ if ms > 0.0 {
+ self.metrics
+ .backend_phase_seconds
+ .with_label_values(&[
+ op,
+ model_label.as_str(),
+ phase,
+ ])
+ .observe(ms / 1_000.0);
+ }
+ };
+ record_phase(
+ "tokenize",
+ outcome.tokenization_ms.unwrap_or(0.0),
+ );
+ record_phase("inference", inference_ms);
+ record_phase("postprocess", postprocess_ms);
+ }
+ }
+ }
+ Err(crate::publisher::PublishError::EmptyReplySubject) => {
+ // Fire-and-forget work item — ACK anyway so
+ // JetStream doesn't redeliver forever.
+ debug!(
+ work_item_id = %wi.work_item_id,
+ "skipping publish — empty reply_subject; will still ACK"
+ );
+ }
+ Err(e) => {
+ // NATS publish failed — skip ACK so JetStream
+ // redelivers (caller may still NAK explicitly).
+ warn!(
+ work_item_id = %wi.work_item_id,
+ error = %e,
+ "failed to publish WorkResult — skipping ACK",
+ );
+ return;
+ }
+ }
+ }
+ match ack(msg).await {
+ Ok(()) => self.metrics.messages_acked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "ack failed");
+ self.metrics.jetstream_ack_failures_total.inc();
+ }
+ }
+ }
+ Disposition::NakRetry => {
+ let delay = std::time::Duration::from_millis(
+ outcome.nak_delay_ms.unwrap_or_else(base_nak_delay_ms),
+ );
+ match msg
+ .ack_with(async_nats::jetstream::AckKind::Nak(Some(delay)))
+ .await
+ {
+ Ok(()) => self.metrics.messages_naked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "nak failed");
+ self.metrics.jetstream_nak_failures_total.inc();
+ }
+ }
+ }
+ }
+ }
+
+ /// Publish a synthetic error `WorkResult` on `wi.reply_subject`.
+ ///
+ /// Returns:
+ /// * `Ok(true)` — published (or fire-and-forget: empty reply_subject).
+ /// The caller may safely ACK the NATS message.
+ /// * `Ok(false)` — (reserved) never returned today, kept for future
+ /// cases where the caller should NAK without logging.
+ /// * `Err(_)` — NATS publish itself failed. The caller MUST NOT ACK:
+ /// the client never got the error reply, so we rely on redelivery
+ /// to give another worker (or this one, later) a chance to surface
+ /// the failure.
+ async fn publish_error(
+ &self,
+ wi: &WorkItem,
+ code: &str,
+ message: &str,
+ ) -> 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,
+ };
+ match self
+ .publisher
+ .publish_result(&wi.reply_subject, &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)
+ }
+ }
+ }
+
+ // -- scheduler -------------------------------------------------------
+
+ /// Return the per-model [`ProductionScheduler`] when
+ /// [`Self::scheduler_registry`] is present. `None` means
+ /// "legacy path: submit straight to `process_*_batch`" — used
+ /// only in unit tests that don't wire the scheduler.
+ ///
+ /// Lazily materialises the scheduler on first touch. When a new
+ /// one is created, also spawns that model's drain loop so the
+ /// submitted items get consumed — that's the counterpart to the
+ /// old eager-at-startup `spawn_scheduler_drains`. Schedulers are
+ /// now materialised only for active models that land on a sidecar
+ /// worker, so boot does not need a model list to iterate.
+ async fn resolve_scheduler(
+ self: &Arc<Self>,
+ model_id: &str,
+ ) -> Option<Arc<ProductionScheduler>> {
+ let registry = self.scheduler_registry.as_ref()?;
+ let shutdown = self.shutdown.as_ref()?;
+ let (sched, created) = registry.get_or_create(model_id).await;
+ if created {
+ let mut handles = self.scheduler_drain_handles.lock().await;
+ // Double-check under the lock: a concurrent `resolve_scheduler`
+ // for the same model could have won the `get_or_create` race
+ // and already inserted a handle. Without this guard we'd spawn
+ // two drain loops racing the same scheduler queue.
+ if !handles.contains_key(model_id) {
+ let disp = Arc::clone(self);
+ let sched_c = Arc::clone(&sched);
+ let shutdown_c = Arc::clone(shutdown);
+ let model_id_s = model_id.to_owned();
+ let model_id_log = model_id.to_owned();
+ let handle = tokio::spawn(async move {
+ scheduler_drain_loop(model_id_s, disp, sched_c, shutdown_c).await;
+ });
+ handles.insert(model_id.to_owned(), handle);
+ // Increment the live `models_total` gauge the first time
+ // we materialise a scheduler for this model. Dashboards
+ // and the shutdown log both read this; we deliberately
+ // keep it monotonic-per-process (schedulers never get
+ // dropped mid-run) so a decrement path isn't needed.
+ self.metrics.scheduler.models_total.inc();
+ info!(
+ model = %model_id_log,
+ "rust-scheduler: drain loop spawned on first traffic",
+ );
+ }
+ }
+ Some(sched)
+ }
+
+ /// Remove and return every scheduler drain handle registered so
+ /// far. Called at shutdown from `lib.rs` so the main shutdown
+ /// path can `await` each task to completion (bounded inside the
+ /// loop by `DEFAULT_SCHEDULER_DRAIN_DEADLINE_MS`, overridable via
+ /// `SIE_SCHEDULER_DRAIN_DEADLINE_MS`).
+ pub async fn take_scheduler_drain_handles(&self) -> Vec<JoinHandle<()>> {
+ let mut guard = self.scheduler_drain_handles.lock().await;
+ guard.drain().map(|(_, h)| h).collect()
+ }
+
+ /// Remove and return all in-flight generation task handles. Called
+ /// during shutdown after the pull loops stop so long-running streams can
+ /// settle before the backend drain RPC closes Python-side state.
+ pub async fn take_generation_handles(&self) -> Vec<JoinHandle<()>> {
+ let mut guard = self.generation_handles.lock().await;
+ guard.drain(..).collect()
+ }
+
+ /// Resolve every encode item's payload then submit it into the
+ /// model scheduler under its `options["lora"]` key. Items whose
+ /// payload resolution fails follow the same publish_error + ACK
+ /// (or NAK on publish failure) path as [`Self::handle_encode`];
+ /// the scheduler never sees them.
+ ///
+ /// Returns immediately once all items are enqueued — the drain
+ /// loop owns the actual backend call + outcome publish.
+ async fn enqueue_encode_into_scheduler(
+ &self,
+ model_id: &str,
+ scheduler: &Arc<ProductionScheduler>,
+ items: Vec<(WorkItem, Message)>,
+ ) {
+ 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 (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")
+ .await;
+ continue;
+ }
+ };
+ let prepared_tokens = self.maybe_prepare_encode_tokens(model_id, &wi, &item_json);
+ let lora = lora_from_options(&wi.options);
+ let ebi = EncodeBatchItem {
+ work_item_id: wi.work_item_id.clone(),
+ request_id: wi.request_id.clone(),
+ item_index: wi.item_index,
+ total_items: wi.total_items,
+ timestamp: wi.timestamp,
+ item: item_json,
+ output_types: wi.output_types.clone(),
+ instruction: wi.instruction.clone(),
+ is_query: wi.is_query,
+ options: wi.options.clone(),
+ profile_id: opt_non_empty(&wi.profile_id),
+ bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
+ payload_fetch_ms: fetch_ms,
+ prepared_tokens,
+ };
+ let meta = SchedulerMeta::new(wi, msg, fetch_ms);
+ scheduler
+ .submit(SchedOp::Encode, lora, SchedulerItem::Encode(ebi), meta)
+ .await;
+ }
+ }
+
+ /// Score twin of [`Self::enqueue_encode_into_scheduler`]. See
+ /// [`Self::handle_score`] for the Rust-tokenisation note on
+ /// `prepared_tokens` being `None` (cross-encoder tokenisation
+ /// stays Python-side for now).
+ ///
+ /// Routing policy: score always goes to `LoraKey::base`
+ /// regardless of what's on `options["lora"]`. That's enforced
+ /// inside [`crate::scheduler::Scheduler::submit`] so the call
+ /// here passes the parsed key through transparently.
+ async fn enqueue_score_into_scheduler(
+ &self,
+ model_id: &str,
+ scheduler: &Arc<ProductionScheduler>,
+ items: Vec<(WorkItem, Message)>,
+ ) {
+ 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 (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")
+ .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(),
+ item_index: wi.item_index,
+ total_items: wi.total_items,
+ timestamp: wi.timestamp,
+ query_item: query,
+ score_items,
+ instruction: wi.instruction.clone(),
+ options: wi.options.clone(),
+ profile_id: opt_non_empty(&wi.profile_id),
+ payload_fetch_ms: fetch_ms,
+ prepared_tokens: None,
+ };
+ let meta = SchedulerMeta::new(wi, msg, fetch_ms);
+ scheduler
+ .submit(SchedOp::Score, lora, SchedulerItem::Score(sbi), meta)
+ .await;
+ }
+ }
+
+ /// Extract twin of [`Self::enqueue_encode_into_scheduler`].
+ /// Extract items don't emit `prepared_tokens` on the Rust side
+ /// (Python owns extract tokenisation in v1), so the outgoing
+ /// [`ExtractBatchItem`] matches the current
+ /// [`Self::handle_extract`] shape.
+ async fn enqueue_extract_into_scheduler(
+ &self,
+ model_id: &str,
+ scheduler: &Arc<ProductionScheduler>,
+ items: Vec<(WorkItem, Message)>,
+ ) {
+ 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 (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")
+ .await;
+ continue;
+ }
+ };
+ let lora = lora_from_options(&wi.options);
+ let xbi = ExtractBatchItem {
+ work_item_id: wi.work_item_id.clone(),
+ request_id: wi.request_id.clone(),
+ item_index: wi.item_index,
+ total_items: wi.total_items,
+ timestamp: wi.timestamp,
+ item: item_json,
+ labels: wi.labels.clone(),
+ output_schema: wi.output_schema.clone(),
+ instruction: wi.instruction.clone(),
+ options: wi.options.clone(),
+ profile_id: opt_non_empty(&wi.profile_id),
+ bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),
+ payload_fetch_ms: fetch_ms,
+ };
+ let meta = SchedulerMeta::new(wi, msg, fetch_ms);
+ scheduler
+ .submit(SchedOp::Extract, lora, SchedulerItem::Extract(xbi), meta)
+ .await;
+ }
+ }
+
+ /// 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) {
+ warn!(
+ error = %ErrChain(err),
+ work_item_id = %wi.work_item_id,
+ request_id = %wi.request_id,
+ model = %wi.model_id,
+ "{log_msg}"
+ );
+ match self
+ .publish_error(wi, "payload_error", "failed to resolve item")
+ .await
+ {
+ Ok(_) => match ack(msg).await {
+ Ok(()) => self.metrics.messages_acked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "ack after error-publish failed");
+ self.metrics.jetstream_ack_failures_total.inc();
+ }
+ },
+ Err(_) => {
+ nak_one(msg, base_nak_delay_ms(), &self.metrics).await;
+ }
+ }
+ }
+
+ // -- payload resolution ----------------------------------------------
+
+ async fn resolve_item(&self, wi: &WorkItem) -> Result<(Json, f64), PayloadError> {
+ if let Some(item) = &wi.item {
+ return Ok((item.clone(), 0.0));
+ }
+ let Some(payload_ref) = &wi.payload_ref else {
+ return Err(PayloadError::InvalidRef(format!(
+ "work item {} has neither item nor payload_ref",
+ wi.work_item_id
+ )));
+ };
+ let start = std::time::Instant::now();
+ let bytes = self.payload_store.get(payload_ref).await?;
+ let ms = start.elapsed().as_secs_f64() * 1000.0;
+ let item: Json = rmp_serde::from_slice(&bytes)
+ .map_err(|e| PayloadError::InvalidRef(format!("decode payload: {e}")))?;
+ Ok((item, ms))
+ }
+
+ // -- Rust-side tokenisation -------------------------------------------
+ //
+ // `maybe_prepare_encode_tokens` consults the tokenizer registry
+ // and returns `Some(PreparedTokens)` when the v2 safety rules
+ // hold:
+ //
+ // 1. Registry has an entry for `model_id` (the adapter declared
+ // a tokeniser on `EnsureModelReady`).
+ // 2. The `item` JSON payload has a populated string `text`
+ // field. Image / audio / multimodal items fall through to
+ // Python as today.
+ //
+ // The registry-backed path no longer bails out on `is_query=true`
+ // or `instruction!=""`: when a model has shipped its template
+ // defaults via `ModelDescriptor.default_query_template` /
+ // `default_doc_template`, the sidecar applies the template via
+ // [`crate::prep::text_prep::TextPrep`] before tokenising — bit-exact
+ // with Python's `_utils.extract_texts` for the two known
+ // placeholders. Per-request `options.query_template` /
+ // `options.doc_template` overrides still win.
+ //
+ // Any tokenise error at runtime returns `None` and the Python
+ // adapter tokenises from `item` exactly like today. Failures are
+ // logged at `debug` so they don't drown out real incidents.
+ //
+ // Score path: there is no Rust-side fast path. The cross-encoder
+ // adapter on the Python side owns pair-building + tokenisation
+ // (model-specific `[CLS] q [SEP] d [SEP]` policies plus pair
+ // padding), so Rust always sets `ScoreBatchItem.prepared_tokens =
+ // None`. Re-introducing a `maybe_prepare_score_tokens` helper
+ // is straightforward when the Python score path grows a
+ // `prepared_tokens` consumer; until then the dead helper has
+ // been removed to keep the surface honest.
+ fn maybe_prepare_encode_tokens(
+ &self,
+ model_id: &str,
+ wi: &WorkItem,
+ item: &Json,
+ ) -> Option<PreparedTokens> {
+ let entry = self.tokenizer_registry.get(model_id)?;
+
+ // Text-only inputs. Treat absent / non-string / empty text as
+ // "not a fast-path request" and defer to Python. An empty
+ // string would tokenise to a 2-token `[CLS][SEP]` padding
+ // sequence — harmless but pure IPC overhead vs letting Python
+ // short-circuit on its own empty-text guard.
+ let raw_text = item
+ .get("text")
+ .and_then(|v| v.as_str())
+ .filter(|s| !s.is_empty())?;
+
+ // Resolve per-request template overrides; fall back to the
+ // adapter's defaults from the handshake. Same precedence as
+ // Python's `resolve_embedding_options`.
+ let (query_template, doc_template) = crate::prep::text_prep::extract_templates_from_options(
+ wi.options.as_ref(),
+ entry.default_query_template(),
+ entry.default_doc_template(),
+ );
+
+ // Apply the template / instruction transform. Borrowing-style
+ // `apply` so plain (non-templated, non-instructed) text is a
+ // no-op pass-through with no allocation beyond the input.
+ let prep = crate::prep::text_prep::TextPrep {
+ instruction: wi.instruction.as_deref(),
+ is_query: wi.is_query,
+ query_template,
+ doc_template,
+ };
+ let prepared_text = prep.apply(raw_text);
+ let text: &str = prepared_text.as_str();
+
+ let rag = match entry.tokenize(&[text]) {
+ Ok(r) if r.len() == 1 => r,
+ Ok(_) => return None, // empty/unexpected — defer
+ Err(e) => {
+ tracing::debug!(
+ model = %model_id,
+ error = %e,
+ "rust-tokenize: encode tokenise failed; deferring to Python"
+ );
+ return None;
+ }
+ };
+
+ Some(rag_to_wire(entry.tokenizer_id(), entry.max_seq_len(), rag))
+ }
+
+ async fn resolve_score(&self, wi: &WorkItem) -> Result<(Json, Vec<Json>, f64), PayloadError> {
+ // Inline path: both query + items provided on the WorkItem.
+ if let (Some(q), Some(items)) = (&wi.query_item, &wi.score_items) {
+ return Ok((q.clone(), items.clone(), 0.0));
+ }
+
+ // Offloaded path: query_payload_ref points at a msgpack-encoded
+ // `{"query": ..., "items": [...]}` blob.
+ let Some(ref_key) = &wi.query_payload_ref else {
+ return Err(PayloadError::InvalidRef(format!(
+ "score item {} missing query/items and query_payload_ref",
+ wi.work_item_id
+ )));
+ };
+ let start = std::time::Instant::now();
+ let bytes = self.payload_store.get(ref_key).await?;
+ let ms = start.elapsed().as_secs_f64() * 1000.0;
+ let decoded: Json = rmp_serde::from_slice(&bytes)
+ .map_err(|e| PayloadError::InvalidRef(format!("decode score payload: {e}")))?;
+ let query = decoded
+ .get("query")
+ .cloned()
+ .ok_or_else(|| PayloadError::InvalidRef("score payload missing 'query'".into()))?;
+ let items = decoded
+ .get("items")
+ .and_then(|v| v.as_array())
+ .cloned()
+ .ok_or_else(|| {
+ PayloadError::InvalidRef("score payload missing 'items' array".into())
+ })?;
+ Ok((query, items, ms))
+ }
+}
+
+// -----------------------------------------------------------------------------
+// Grouping (pure logic, tested independently)
+// -----------------------------------------------------------------------------
+
+/// Group by `(model_id, operation)`. Retained for tests and callers
+/// that want explicit per-op grouping; the hot path uses
+/// [`group_by_model_only`] so encode/score/extract for the same model
+/// can run concurrently under a single readiness check.
+pub fn group_by_model<T>(
+ items: Vec<(WorkItem, T)>,
+) -> BTreeMap<(String, String), Vec<(WorkItem, T)>> {
+ let mut groups: BTreeMap<(String, String), Vec<(WorkItem, T)>> = BTreeMap::new();
+ for (wi, extra) in items {
+ let key = (wi.model_id.clone(), wi.operation.clone());
+ groups.entry(key).or_default().push((wi, extra));
+ }
+ groups
+}
+
+/// Group decoded messages by `model_id` only — hot-path grouping.
+pub fn group_by_model_only<T>(items: Vec<(WorkItem, T)>) -> BTreeMap<String, Vec<(WorkItem, T)>> {
+ let mut groups: BTreeMap<String, Vec<(WorkItem, T)>> = BTreeMap::new();
+ for (wi, extra) in items {
+ let key = wi.model_id.clone();
+ groups.entry(key).or_default().push((wi, extra));
+ }
+ groups
+}
+
+/// Split a per-model group at the batch budget. First `budget` items go
+/// to dispatch, the rest to overflow (the caller NAKs with a short delay).
+pub(crate) type DispatchSplit<T> = (Vec<(WorkItem, T)>, Vec<(WorkItem, T)>);
+
+pub(crate) fn split_by_budget<T>(items: Vec<(WorkItem, T)>, budget: usize) -> DispatchSplit<T> {
+ if items.len() <= budget {
+ return (items, Vec::new());
+ }
+ let mut it = items.into_iter();
+ let dispatch: Vec<(WorkItem, T)> = it.by_ref().take(budget).collect();
+ let overflow: Vec<(WorkItem, T)> = it.collect();
+ (dispatch, overflow)
+}
+
+/// Compute `queue_ms` for a `WorkItem` given its embedded `timestamp`
+/// (unix seconds, set by the gateway publisher). Returns 0 for
+/// missing/future timestamps so we never report a negative latency.
+/// Compute one `total_ms` sample per *unique* `request_id` in the
+/// batch. Mirrors Python's `_complete_requests` dedup pattern (see
+/// `model_worker.py:947-976` on main `bbe409c3`):
+///
+/// ```python
+/// completed_metadata: set[int] = set()
+/// for metadata in batch.metadata:
+/// meta_id = id(metadata)
+/// if meta_id in completed_metadata:
+/// continue
+/// completed_metadata.add(meta_id)
+/// ...
+/// self._latency_tracker.record(metadata.timing.total_ms)
+/// ```
+///
+/// In the Rust scheduler each NATS message is its own
+/// [`SchedulerMeta`] with its own `submitted_at`; when the gateway
+/// fans out a multi-item client request it produces N work-items with
+/// the same `request_id` and distinct `item_index`es. We pick the
+/// **first** occurrence's `submitted_at` (lowest `item_index` is not
+/// guaranteed because the BatchFormer sorts by cost, but all items in
+/// a request share the same gateway publish time so any of them is a
+/// fair stand-in for Python's request-level `_start_time`).
+///
+/// Items are skipped if:
+/// * the IPC reply marked them anything other than `PublishAndAck`
+/// (errors / NAK paths shouldn't bias the controller toward fast
+/// no-op replies);
+/// * `total_ms` came out non-positive — represents IPC error paths
+/// where the per-item timing fields were left at zero. Letting
+/// these in would bias `observed_p50_ms` toward zero and pin the
+/// wait knob at the floor.
+///
+/// Takes an iterator of `(request_id, submitted_at, outcome)` triples
+/// rather than a `&[SchedulerMeta]` so unit tests don't need to
+/// fabricate a `jetstream::Message` (which has no public constructor).
+fn dedupe_per_request_totals<'a, I>(rows: I, now: Instant) -> Vec<f64>
+where
+ I: IntoIterator<Item = (&'a str, Instant, &'a ItemOutcome)>,
+{
+ let iter = rows.into_iter();
+ let (lower, _) = iter.size_hint();
+ let mut seen: HashSet<&str> = HashSet::with_capacity(lower);
+ let mut out: Vec<f64> = Vec::with_capacity(lower);
+ for (request_id, submitted_at, o) in iter {
+ if !matches!(o.disposition, Disposition::PublishAndAck) {
+ continue;
+ }
+ if !seen.insert(request_id) {
+ continue;
+ }
+ // Saturating subtract: in tests / replays where
+ // `submitted_at` could be set in the future relative to
+ // `now`, treat it as zero wait rather than panicking.
+ let batcher_wait_ms = now.saturating_duration_since(submitted_at).as_secs_f64() * 1000.0;
+ let inf = o.inference_ms.unwrap_or(0.0);
+ let post = o.postprocessing_ms.unwrap_or(0.0);
+ let total = batcher_wait_ms + inf + post;
+ if total > 0.0 {
+ out.push(total);
+ }
+ }
+ out
+}
+
+fn queue_ms_from(timestamp_s: f64) -> f64 {
+ if timestamp_s <= 0.0 {
+ return 0.0;
+ }
+ let now_s = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs_f64())
+ .unwrap_or(timestamp_s);
+ let delta_ms = (now_s - timestamp_s) * 1000.0;
+ if delta_ms < 0.0 {
+ 0.0
+ } else {
+ delta_ms
+ }
+}
+
+/// Convert a [`crate::tokenize::RaggedTokens`] bundle into the wire
+/// [`PreparedTokens`] form. Wrapping here (rather than inline at each
+/// call site) keeps the "what to elide to save bytes" policy in one
+/// place: BERT-style all-zero `token_type_ids` skip the wire, since
+/// Python treats an empty outer vec as "all zeros".
+fn rag_to_wire(
+ tokenizer_id: &str,
+ max_seq_len: usize,
+ rag: crate::tokenize::RaggedTokens,
+) -> PreparedTokens {
+ let token_type_ids = if rag.token_type_ids_all_zero() {
+ Vec::new()
+ } else {
+ rag.token_type_ids
+ };
+ PreparedTokens {
+ input_ids: rag.input_ids,
+ attention_mask: rag.attention_mask,
+ token_type_ids,
+ tokenizer_id: tokenizer_id.to_string(),
+ max_seq_len: max_seq_len as u32,
+ }
+}
+
+fn opt_non_empty(s: &str) -> Option<String> {
+ if s.is_empty() {
+ None
+ } else {
+ Some(s.to_string())
+ }
+}
+
+fn truncate(s: &str, n: usize) -> &str {
+ match s.char_indices().nth(n) {
+ Some((idx, _)) => &s[..idx],
+ None => s,
+ }
+}
+
+async fn handle_generate_event(
+ event: GenerateEvent,
+ publisher: Arc<WorkPublisher>,
+ metrics: Arc<MetricsRegistry>,
+ settled: Arc<AtomicBool>,
+ msg: Arc<Message>,
+) -> Result<(), DispatchError> {
+ match event.kind.as_str() {
+ "publish" => {
+ publisher
+ .publish_raw(&event.reply_subject, event.payload)
+ .await?;
+ }
+ "ack" => {
+ if !settled.swap(true, Ordering::SeqCst) {
+ match ack(&msg).await {
+ Ok(()) => metrics.messages_acked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "generate ACK failed");
+ metrics.jetstream_ack_failures_total.inc();
+ }
+ }
+ }
+ }
+ "nak" => {
+ if !settled.swap(true, Ordering::SeqCst) {
+ let delay_ms = event.delay_ms.unwrap_or_else(base_nak_delay_ms);
+ nak_one(&msg, delay_ms, &metrics).await;
+ }
+ }
+ "in_progress" => {
+ if !settled.load(Ordering::SeqCst) {
+ match msg.ack_with(async_nats::jetstream::AckKind::Progress).await {
+ Ok(()) => {}
+ Err(e) => {
+ debug!(error = %e, "generate in-progress ACK failed");
+ metrics.jetstream_ack_failures_total.inc();
+ }
+ }
+ }
+ }
+ other => {
+ warn!(event = %other, "unknown ProcessGenerate event from Python");
+ }
+ }
+ Ok(())
+}
+
+async fn ack(msg: &Message) -> Result<(), DispatchError> {
+ msg.ack()
+ .await
+ .map_err(|e| DispatchError::Ack(e.to_string()))
+}
+
+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();
+ }
+ }
+ }
+ 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
+ {
+ Ok(()) => metrics.messages_naked_total.inc(),
+ Err(e) => {
+ warn!(error = %e, "nak failed");
+ metrics.jetstream_nak_failures_total.inc();
+ }
+ }
+}
+
+// -----------------------------------------------------------------------------
+// Scheduler drain loop
+// -----------------------------------------------------------------------------
+
+/// Default deadline (ms) for the shutdown-time drain of a model's
+/// scheduler queue. After this the loop exits and any residual items
+/// redeliver via JetStream's `ack_wait` — correct but slower. Tuned
+/// to stay well under `DRAIN_DEADLINE_MS` on the backend so the
+/// overall shutdown budget isn't exceeded. Overridable with
+/// `SIE_SCHEDULER_DRAIN_DEADLINE_MS` for ops; see
+/// [`scheduler_drain_deadline_ms`].
+const DEFAULT_SCHEDULER_DRAIN_DEADLINE_MS: u64 = 10_000;
+
+/// Resolved drain deadline honouring the `SIE_SCHEDULER_DRAIN_DEADLINE_MS`
+/// env override. Parsed per call (the drain loop reads it exactly
+/// once, at shutdown-time) so tests + ops can nudge it without
+/// restarting threads. Invalid / non-positive values fall back to
+/// the default rather than silently producing a zero deadline.
+fn scheduler_drain_deadline_ms() -> u64 {
+ std::env::var("SIE_SCHEDULER_DRAIN_DEADLINE_MS")
+ .ok()
+ .and_then(|s| s.parse::<u64>().ok())
+ .filter(|v| *v > 0)
+ .unwrap_or(DEFAULT_SCHEDULER_DRAIN_DEADLINE_MS)
+}
+
+/// Process-wide monotonic batch id. Shared across every per-model
+/// drain loop so a batch id collision across models can't happen,
+/// which keeps log-correlation unambiguous on the Python side.
+static SCHEDULER_BATCH_ID_COUNTER: std::sync::atomic::AtomicU64 =
+ std::sync::atomic::AtomicU64::new(0);
+
+/// Role of a batch within a scheduler wave.
+///
+/// A wave starts with one **primary** batch and may continue with zero
+/// or more **drain** batches from the same `(op, lora)` queue. The
+/// adaptive controller must step exactly once per wave, using the
+/// primary batch size. Drains still feed inference-time and per-request
+/// latency samples, but they do not trigger efficiency records or PI
+/// controller steps; otherwise the controller sees a stream of smaller
+/// drain batches and drives the wait knob too low under saturation.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum WaveRole {
+ /// First batch in a wave (or shutdown final-drain — every
+ /// flush there is its own degenerate wave with no following
+ /// drains). Drives a full `record_completion` →
+ /// efficiency-record + controller step + cap propagation.
+ Primary,
+ /// Continuation batch produced by `try_drain_same` on the same
+ /// `(op, lora)` queue as the wave's primary. Feeds the
+ /// inference-calibration tracker (one sample) + the per-request
+ /// latency tracker, but does **not** step the controller and
+ /// does **not** record an efficiency sample. The caps from the
+ /// preceding primary's step stay in effect for the rest of the
+ /// wave; adaptive Prometheus gauges retain the primary's value
+ /// (`gauge.set` is idempotent), so dashboards show one update
+ /// per wave instead of one per IPC roundtrip.
+ Drain,
+}
+
+/// 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
+/// the adaptive controller with one completion sample.
+///
+/// Factored out of [`scheduler_drain_loop`] so the happy-path + the
+/// shutdown final-drain share the same code. Pure async fn with no
+/// hidden state: the scheduler is borrowed and the dispatcher is
+/// [`Arc`]'d.
+///
+/// `role` decides whether this batch's completion triggers a
+/// controller step (see [`WaveRole`] for the cadence rules).
+async fn process_scheduler_batch(
+ model_id: &str,
+ dispatcher: &Arc<Dispatcher>,
+ scheduler: &Arc<ProductionScheduler>,
+ op: SchedOp,
+ lora: crate::scheduler::LoraKey,
+ batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,
+ role: WaveRole,
+) {
+ if batch.items.is_empty() {
+ return;
+ }
+ let batch_size = batch.items.len();
+ let total_cost = batch.total_cost;
+ let op_label = match op {
+ SchedOp::Encode => "encode",
+ SchedOp::Score => "score",
+ SchedOp::Extract => "extract",
+ };
+ // `lora.as_str()` yields `None` for the base key; on the wire
+ // we send an empty string so Python's `lora_key or None` chain
+ // roundtrips to the same value.
+ let lora_str = lora.as_str().unwrap_or("").to_string();
+ // Worker-local monotonic batch id. `Relaxed` is fine: the value
+ // is log-only (Python writes it on METHOD_RUN_BATCH) and no
+ // ordering guarantees hang off it across threads.
+ let batch_id = SCHEDULER_BATCH_ID_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+
+ let rb_items: Vec<crate::ipc_types::RunBatchItem> = batch
+ .items
+ .into_iter()
+ .map(SchedulerItem::into_run_batch_item)
+ .collect();
+ let req = RunBatchRequest {
+ model_id: model_id.to_string(),
+ batch_id,
+ lora_key: lora_str,
+ total_cost,
+ items: rb_items,
+ };
+
+ let model_lbl = dispatcher.metrics.model_label(model_id);
+ // Basic scheduler observability: one sample per flushed batch of
+ // (items, total_cost) against `(model, operation, lora)`. Record
+ // *before* the RPC so we capture the batch shape even if the
+ // backend call ends up failing and the batch gets NAKed — the
+ // shape itself is what the scheduler produced.
+ //
+ // On the wire `lora_str` is `""` (matches Python's `lora_key or
+ // None` contract) but for dashboards we prefer the explicit
+ // `"base"` sentinel so PromQL doesn't need `lora=""` predicates.
+ // `lora.as_str()` yields `None` for the base key too, so this
+ // doesn't duplicate logic — we just pick a clearer label.
+ let lora_metric_label = lora.as_str().unwrap_or("base");
+ dispatcher
+ .metrics
+ .scheduler
+ .batch_items
+ .with_label_values(&[&model_lbl, op_label, lora_metric_label])
+ .observe(batch_size as f64);
+ dispatcher
+ .metrics
+ .scheduler
+ .batch_cost
+ .with_label_values(&[&model_lbl, op_label, lora_metric_label])
+ .observe(total_cost as f64);
+ let _timer = dispatcher
+ .metrics
+ .pull_batch_process_seconds
+ .with_label_values(&[&model_lbl, op_label])
+ .start_timer();
+ let started = Instant::now();
+ dispatcher.metrics.ipc_requests_total.inc();
+
+ let outcome = match dispatcher.backend.run_batch(req).await {
+ Ok(o) => o,
+ Err(e) => {
+ dispatcher.metrics.ipc_failures_total.inc();
+ let delay = nak_delay_for_backend_error(&e);
+ warn!(
+ model = %model_id,
+ op = op_label,
+ error = %ErrChain(&e),
+ nak_delay_ms = delay,
+ batch_size,
+ "scheduler RunBatch failed — NAKing batch",
+ );
+ let msgs_only: Vec<(WorkItem, Message)> =
+ batch.metadata.into_iter().map(|m| (m.wi, m.msg)).collect();
+ nak_all(&msgs_only, delay, &dispatcher.metrics).await;
+ return;
+ }
+ };
+
+ // Collect per-item timings BEFORE we move the metadata into
+ // `apply_outcomes`. Two telemetry flows out of this loop:
+ //
+ // 1. `inference_ms_sample` — first reported inference_ms (all
+ // items in a GPU batch share the forward pass so any one is
+ // representative). Feeds the auto-calibration tracker so
+ // `target_p50_ms` derives from GPU forward time, not the
+ // batcher+post sum.
+ // 2. `per_item_total_ms` — one entry per `PublishAndAck`
+ // outcome, value = `batcher_wait + inference + postprocess`
+ // for *that* item. Fed verbatim into the controller's
+ // latency tracker so `observed_p50_ms` matches Python
+ // `RequestTiming.total_ms` semantics. The signal must include
+ // the Rust BatchFormer wait, must exclude upstream NATS queue
+ // depth, and must not collapse a batch to its max item latency;
+ // each of those alternatives biases the PI loop enough to pin
+ // the wait knob at a floor or ceiling.
+ //
+ // The semantically correct mirror of Python's `total_ms` is
+ // `(now - submitted_at) + inference + post`. `submitted_at`
+ // (`SchedulerMeta.submitted_at`) is stamped when the dispatcher
+ // enqueues the item into our scheduler — equivalent to when
+ // Python's `RequestTiming()` is constructed at the top of
+ // `EncodePipeline.run_encode`, which is *after* the NATS pull
+ // but *before* batch formation. The delta (`now -
+ // submitted_at`) covers the time the item spent inside our
+ // own (Rust) `BatchFormer` waiting to flush — the analogue
+ // of Python's `total_ms` via `metadata.timing._start_time`
+ // getting set in `EncodePipeline.run_encode`. Note: in
+ // passthrough mode Python no longer has a per-LoRA BatchFormer,
+ // so the entire batch-form delta is observed here on the Rust
+ // side instead of being split across Rust and Python batchers.
+ let now = Instant::now();
+ let inference_ms_sample = outcome
+ .outcomes
+ .iter()
+ .find_map(|o| o.inference_ms)
+ .unwrap_or_else(|| started.elapsed().as_secs_f64() * 1000.0);
+ // Per-request totals (deduped by `request_id`). When the gateway
+ // splits a multi-item client request into N NATS work-items they
+ // share the same `request_id` but get distinct `item_index`es —
+ // they may all land in one Rust batch. Python's
+ // `_complete_requests` dedupes via a `seen: set[id(metadata)]` so a
+ // multi-item request deposits **one** latency sample, not N (see
+ // `model_worker.py:947-976` on main `bbe409c3`). The tracker p50 is
+ // a per-request signal, not a per-item one — recording N samples
+ // here would let a single 10-item request dominate `observed_p50_ms`
+ // 10× more than ten 1-item requests at the same throughput, which
+ // is exactly the bias the calibration tracker is designed to avoid.
+ // Picking the first occurrence's
+ // `submitted_at` keeps `batcher_wait_ms` aligned with Python's
+ // `RequestTiming._start_time`, which is set once when the request
+ // enters the worker process and shared across all its items.
+ let per_request_total_ms: Vec<f64> = dedupe_per_request_totals(
+ batch
+ .metadata
+ .iter()
+ .zip(outcome.outcomes.iter())
+ .map(|(m, o)| (m.wi.request_id.as_str(), m.submitted_at, o)),
+ now,
+ );
+
+ let resolved: Vec<(WorkItem, Message, f64)> = batch
+ .metadata
+ .into_iter()
+ .map(|m| (m.wi, m.msg, m.fetch_ms))
+ .collect();
+ dispatcher.apply_outcomes(outcome, resolved).await;
+
+ // Feed the adaptive controller. Only record completion when we
+ // actually saw a successful item — a batch of all-errors would
+ // bias the controller toward shrinking caps based on fast
+ // no-op replies.
+ //
+ // Calibration sample rate: **one sample per batch** (not per
+ // item). Feeding one sample per item can make Rust's calibration
+ // latch from a single cold-start batch, pinning the target and
+ // wait knob before the GPU reaches steady state. Per-batch
+ // sampling keeps calibration aging across multiple batches while
+ // the GPU warms.
+ //
+ // PI signal sample rate: per **unique request_id** (deduped).
+ // The tracker p50 is a per-request signal — a single 10-item
+ // request shouldn't dominate `observed_p50_ms` 10× more than ten
+ // 1-item requests at the same throughput. For typical bench
+ // workloads (1 item per request) dedup is a no-op.
+ //
+ // Cadence (per [`WaveRole`]): Primary triggers
+ // `record_completion` (efficiency record + controller step +
+ // cap propagation + Prometheus push). Drain feeds inference +
+ // latency samples only; the controller is **not** stepped — the
+ // wave's caps were already updated by the primary, and Python's
+ // `_process_loop` likewise steps once per wave with the primary
+ // batch size (`model_worker.py:828, 855-870`).
+ //
+ // `SIE_RUST_WAVE_CADENCE=off` flips back to per-batch stepping
+ // (every Drain also calls `record_completion`). Off-by-default;
+ // see [`crate::wave_cadence_enabled`] for the rationale and the
+ // p50/p99 trade-off.
+ if !per_request_total_ms.is_empty() {
+ scheduler.record_inference_sample(inference_ms_sample).await;
+ scheduler
+ .record_latency_samples(&per_request_total_ms)
+ .await;
+ if matches!(role, WaveRole::Primary) || !crate::wave_cadence_enabled() {
+ let snapshot = scheduler.record_completion(total_cost, batch_size).await;
+
+ // Push the controller snapshot to Prometheus. In passthrough
+ // mode the Python adaptive controller never runs, so the Rust
+ // scheduler is the sole source of these metrics. `model_lbl`
+ // is already in scope from the pre-RPC path; re-using it keeps
+ // the label string stable across the
+ // batch_items / batch_cost / adaptive_* families so a
+ // PromQL `on(model)` join works.
+ let m = &dispatcher.metrics.scheduler;
+ m.adaptive_wait_ms
+ .with_label_values(&[&model_lbl])
+ .set(snapshot.new_wait_ms);
+ m.adaptive_cost
+ .with_label_values(&[&model_lbl])
+ .set(snapshot.new_batch_cost as f64);
+ if let Some(o) = snapshot.observed_p50_ms {
+ m.adaptive_observed_p50_ms
+ .with_label_values(&[&model_lbl])
+ .set(o);
+ }
+ if let Some(t) = snapshot.target_p50_ms {
+ m.adaptive_target_p50_ms
+ .with_label_values(&[&model_lbl])
+ .set(t);
+ }
+ if let Some(f) = snapshot.fill_ratio {
+ m.adaptive_fill_ratio
+ .with_label_values(&[&model_lbl])
+ .set(f);
+ }
+ if snapshot.starvation_resets_delta > 0 {
+ m.starvation_resets_total
+ .with_label_values(&[&model_lbl])
+ .inc_by(u64::from(snapshot.starvation_resets_delta));
+ }
+ }
+ }
+
+ debug!(
+ model = %model_id,
+ op = op_label,
+ batch_id,
+ batch_size,
+ total_cost,
+ role = ?role,
+ elapsed_ms = started.elapsed().as_millis() as u64,
+ "scheduler batch complete",
+ );
+}
+
+/// 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
+/// window; any items still in the scheduler when the deadline
+/// expires redeliver via JetStream `ack_wait`.
+///
+/// Maximum number of in-flight `process_scheduler_batch` invocations
+/// per model scheduler. This controls the depth of the IPC dispatch
+/// pipeline.
+///
+/// Default is **2**: one batch can be on the GPU while the next has
+/// already crossed the IPC boundary and is waiting on Python's
+/// passthrough lock. That preserves the dual-buffer behaviour the
+/// Python batcher used to provide before batch formation moved into
+/// Rust.
+///
+/// `1` is still useful as a regression-bisect and high-saturation
+/// escape hatch: it forces strict serial dispatch and removes queued
+/// IPC frames from the request's tail. The default stays at `2` because
+/// normal saturated loads benefit from hiding IPC roundtrip/decode time
+/// behind the current forward pass.
+///
+/// Values are clamped to `[1, 8]`. The upper bound is intentionally
+/// conservative: Python inference is still serialized by the adapter's
+/// single CUDA stream, so large depths mainly park decoded batches on
+/// the lock and inflate per-batch latency.
+fn pipeline_depth() -> usize {
+ std::env::var("SIE_RUST_PIPELINE_DEPTH")
+ .ok()
+ .and_then(|v| v.parse::<usize>().ok())
+ .map(|v| v.clamp(1, 8))
+ .unwrap_or(2)
+}
+
+/// 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
+/// independent task. The task releases its permit when it returns.
+///
+/// Backpressure direction: if the pipeline is saturated, the
+/// `acquire_owned` here yields the consume loop, which means the
+/// underlying `BatchFormer` keeps accumulating items. The next
+/// `consume_next` call therefore sees a fuller batch — net positive
+/// at saturation.
+// Each argument is independently sourced from the consume loop's
+// stack frame (model_id from the per-model task, dispatcher +
+// scheduler are shared Arcs, pipeline_sem is loop-local, op/lora/
+// batch come from the just-flushed scheduler tick, role comes from
+// the wave's primary-vs-drain role assignment). Bundling them into a
+// struct would introduce a one-shot wrapper type whose only purpose
+// is to satisfy this lint — net less readable, so explicit allow.
+#[allow(clippy::too_many_arguments)]
+async fn spawn_pipelined_batch(
+ model_id: &str,
+ dispatcher: &Arc<Dispatcher>,
+ scheduler: &Arc<ProductionScheduler>,
+ pipeline_sem: &Arc<Semaphore>,
+ op: SchedOp,
+ lora: crate::scheduler::LoraKey,
+ batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,
+ role: WaveRole,
+) {
+ if batch.items.is_empty() {
+ return;
+ }
+ let permit = match pipeline_sem.clone().acquire_owned().await {
+ Ok(p) => p,
+ Err(_) => {
+ // Semaphore closed. Should be impossible while the loop
+ // owns it, but log loudly and fall back to a serial
+ // dispatch on the consume loop's task so we don't drop
+ // the batch on the floor.
+ warn!(
+ model = %model_id,
+ "rust-scheduler: pipeline semaphore closed; running batch inline",
+ );
+ process_scheduler_batch(model_id, dispatcher, scheduler, op, lora, batch, role).await;
+ return;
+ }
+ };
+ let model_id_c = model_id.to_owned();
+ let disp_c = Arc::clone(dispatcher);
+ let sched_c = Arc::clone(scheduler);
+ tokio::spawn(async move {
+ process_scheduler_batch(&model_id_c, &disp_c, &sched_c, op, lora, batch, role).await;
+ drop(permit);
+ });
+}
+
+pub(crate) async fn scheduler_drain_loop(
+ model_id: String,
+ dispatcher: Arc<Dispatcher>,
+ scheduler: Arc<ProductionScheduler>,
+ shutdown: Arc<Shutdown>,
+) {
+ let depth = pipeline_depth();
+ info!(
+ model = %model_id,
+ pipeline_depth = depth,
+ "rust-scheduler: drain loop started",
+ );
+
+ // Python runs in passthrough mode here: there is no per-LoRA
+ // BatchFormer and every IPC frame is one GPU forward pass,
+ // serialized by `_passthrough_lock`. All batching now lives in
+ // the Rust scheduler (`ProductionScheduler` -> `BatchFormer`).
+ //
+ // What `depth = 2` still buys us in this regime: the Python IPC
+ // server (`ipc_server.py::_handle_request`) spawns each `RUN_BATCH`
+ // as an `asyncio.create_task` (non-blocking on the read loop), so
+ // shipping batch N+1 while N is on the GPU lets N+1 cross the IPC
+ // boundary, msgpack-decode, and park on the contended
+ // `_passthrough_lock`. When N's forward pass finishes the lock
+ // releases, N+1 enters the forward pass without paying the IPC
+ // roundtrip + decode on the critical path.
+ //
+ // We cap depth at 2 by default — Python's adapter is still single-
+ // CUDA-stream so true concurrent inference isn't possible; depth
+ // > 2 just inflates per-batch latency by parking more frames on
+ // the lock without any throughput gain. Operators can override
+ // via `SIE_RUST_PIPELINE_DEPTH`: `1` falls back to strict serial
+ // dispatch (one outstanding IPC roundtrip). At very high
+ // concurrency, operators may prefer `1` to avoid parking a second
+ // frame behind a long GPU forward pass.
+ let pipeline_sem = Arc::new(Semaphore::new(depth));
+
+ // Idle-bypass + continuous-batching state. In passthrough mode,
+ // `model_worker.py::_process_loop` is bypassed and the Rust scheduler
+ // is the sole batcher in the system, so the logic below 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.
+ //
+ // * After every consumed batch we loop on `try_drain_same` for
+ // the same `(op, lora)` until it returns `None`. With
+ // pipelining this is still useful: items that landed in the
+ // Rust `BatchFormer` between the timer firing and us reaching
+ // this point get shipped immediately rather than waiting for
+ // the next coalesce window. Each drained sub-batch goes
+ // through the same permit-bounded spawn, so total in-flight
+ // stays capped by `depth`.
+ //
+ // * `was_idle` is reset to true only when the just-finished
+ // wave produced no drained tail and the kicking batch was a
+ // singleton — i.e. real evidence the worker outran demand.
+ // Multi-item batches or non-empty drain tails mean traffic
+ // is steady and the next iteration should accumulate (no
+ // immediate flush).
+ let mut was_idle = true;
+ loop {
+ tokio::select! {
+ (op, lora, batch) = scheduler.consume_next(was_idle) => {
+ let initial_batch_size = batch.items.len();
+ // First batch in the wave drives the controller step.
+ spawn_pipelined_batch(
+ &model_id,
+ &dispatcher,
+ &scheduler,
+ &pipeline_sem,
+ op,
+ lora.clone(),
+ batch,
+ WaveRole::Primary,
+ ).await;
+
+ let mut drained_any = false;
+ while let Some(drain_batch) =
+ scheduler.try_drain_same(op, lora.clone()).await
+ {
+ if drain_batch.items.is_empty() {
+ break;
+ }
+ drained_any = true;
+ // Drains continue the wave: feed inference +
+ // latency samples, but no controller step.
+ spawn_pipelined_batch(
+ &model_id,
+ &dispatcher,
+ &scheduler,
+ &pipeline_sem,
+ op,
+ lora.clone(),
+ drain_batch,
+ WaveRole::Drain,
+ ).await;
+ }
+
+ was_idle = !drained_any && initial_batch_size <= 1;
+ }
+ _ = shutdown.wait() => {
+ info!(
+ model = %model_id,
+ "rust-scheduler: shutdown observed — entering final drain",
+ );
+ break;
+ }
+ }
+ }
+
+ // Quiesce the pipeline: acquire all `depth` permits so every
+ // spawned dispatch task has finished its IPC roundtrip and
+ // released its permit. Only then do we enter synchronous shutdown
+ // drain below. Without this the final-drain loop
+ // could race with still-in-flight pipelined batches and double-
+ // submit work to Python.
+ if let Ok(permits) = pipeline_sem.clone().acquire_many_owned(depth as u32).await {
+ // Hold the permits for the rest of the function so no further
+ // spawns can sneak in (`spawn_pipelined_batch` is no longer
+ // called past this point, but defence-in-depth).
+ std::mem::forget(permits);
+ }
+
+ // Shutdown drain: flush whatever's still enqueued, up to a
+ // deadline. `try_consume_next` is non-blocking; a `None` return
+ // with `total_pending_count() > 0` means flush triggers haven't
+ // fired yet — we sleep briefly to let coalesce windows expire
+ // then try again.
+ let started = Instant::now();
+ let deadline = std::time::Duration::from_millis(scheduler_drain_deadline_ms());
+ loop {
+ if started.elapsed() >= deadline {
+ let remaining = scheduler.total_pending_count().await;
+ if remaining > 0 {
+ warn!(
+ model = %model_id,
+ remaining,
+ elapsed_ms = started.elapsed().as_millis() as u64,
+ "rust-scheduler: drain deadline exceeded — residual items will redeliver via JetStream ack_wait",
+ );
+ }
+ break;
+ }
+ match scheduler.try_consume_next().await {
+ Some((op, lora, batch)) => {
+ // Final-drain flushes are standalone waves (no
+ // following `try_drain_same` loop here), so each
+ // counts as its own primary.
+ process_scheduler_batch(
+ &model_id,
+ &dispatcher,
+ &scheduler,
+ op,
+ lora,
+ batch,
+ WaveRole::Primary,
+ )
+ .await;
+ }
+ None => {
+ if scheduler.total_pending_count().await == 0 {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;
+ }
+ }
+ }
+ info!(
+ model = %model_id,
+ elapsed_ms = started.elapsed().as_millis() as u64,
+ "rust-scheduler: drain loop exited",
+ );
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn wi(request: &str, idx: u32, model: &str, op: &str) -> WorkItem {
+ WorkItem {
+ work_item_id: format!("{}.{}", request, idx),
+ request_id: request.into(),
+ item_index: idx,
+ total_items: 1,
+ operation: op.into(),
+ model_id: model.into(),
+ profile_id: String::new(),
+ engine: String::new(),
+ pool_name: "l4".into(),
+ machine_profile: String::new(),
+ item: Some(serde_json::json!({"text": "x"})),
+ payload_ref: None,
+ output_types: None,
+ 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: String::new(),
+ reply_subject: "_INBOX.r.a".into(),
+ traceparent: None,
+ tracestate: None,
+ timestamp: 0.0,
+ }
+ }
+
+ #[test]
+ fn groups_by_model_and_operation() {
+ let items = vec![
+ (wi("r1", 0, "A", "encode"), ()),
+ (wi("r1", 1, "A", "encode"), ()),
+ (wi("r2", 0, "B", "encode"), ()),
+ (wi("r3", 0, "A", "score"), ()),
+ ];
+ let groups = group_by_model(items);
+ assert_eq!(groups[&("A".to_string(), "encode".to_string())].len(), 2);
+ assert_eq!(groups[&("A".to_string(), "score".to_string())].len(), 1);
+ assert_eq!(groups[&("B".to_string(), "encode".to_string())].len(), 1);
+ assert_eq!(groups.len(), 3);
+ }
+
+ #[test]
+ fn group_by_model_only_collapses_ops() {
+ // For the hot path: all ops for a single model should land together
+ // so they can be dispatched concurrently within the group.
+ let items = vec![
+ (wi("r1", 0, "A", "encode"), ()),
+ (wi("r1", 1, "A", "score"), ()),
+ (wi("r2", 0, "A", "extract"), ()),
+ (wi("r3", 0, "B", "encode"), ()),
+ ];
+ let groups = group_by_model_only(items);
+ assert_eq!(groups["A"].len(), 3);
+ assert_eq!(groups["B"].len(), 1);
+ assert_eq!(groups.len(), 2);
+ }
+
+ #[test]
+ fn opt_non_empty_maps_empty_to_none() {
+ assert_eq!(opt_non_empty(""), None);
+ assert_eq!(opt_non_empty("x"), Some("x".to_string()));
+ }
+
+ #[test]
+ fn unknown_bundle_config_hash_accepts_current_recent_and_empty_hashes() {
+ let state = ConfigApplyState::new("hash-1".into());
+ state.set_bundle_hash("hash-2".into());
+
+ let mut current = wi("r1", 0, "A", "encode");
+ current.bundle_config_hash = "hash-2".into();
+ let mut recent = wi("r1", 1, "A", "encode");
+ recent.bundle_config_hash = "hash-1".into();
+ let legacy = wi("r1", 2, "A", "encode");
+
+ let items = [current, recent, legacy];
+ let unknown = unknown_bundle_config_hash(items.iter(), Some(&state));
+ assert!(unknown.is_none());
+ }
+
+ #[test]
+ fn unknown_bundle_config_hash_reports_first_unknown_and_count() {
+ let state = ConfigApplyState::new("hash-1".into());
+
+ let mut first = wi("r1", 0, "A", "encode");
+ first.bundle_config_hash = "missing-a".into();
+ let mut accepted = wi("r1", 1, "A", "encode");
+ accepted.bundle_config_hash = "hash-1".into();
+ let mut second = wi("r1", 2, "A", "encode");
+ second.bundle_config_hash = "missing-b".into();
+
+ let items = [first, accepted, second];
+ let unknown = unknown_bundle_config_hash(items.iter(), Some(&state));
+ assert_eq!(unknown, Some(("missing-a", 2)));
+ }
+
+ #[test]
+ fn reply_subject_is_safe_rules() {
+ assert!(reply_subject_is_safe(""));
+ assert!(reply_subject_is_safe("_INBOX.ab"));
+ assert!(reply_subject_is_safe("_INBOX.a.b.c"));
+ assert!(!reply_subject_is_safe("sie.work.foo.l4"));
+ assert!(!reply_subject_is_safe("something.evil"));
+ assert!(!reply_subject_is_safe("_INBOX")); // no trailing dot
+ }
+
+ #[test]
+ fn truncate_respects_char_boundaries() {
+ assert_eq!(truncate("hello", 3), "hel");
+ assert_eq!(truncate("hi", 10), "hi");
+ // 'é' is two bytes — truncate should not split it.
+ assert_eq!(truncate("café", 3), "caf");
+ assert_eq!(truncate("café", 4), "café");
+ }
+
+ #[test]
+ fn queue_ms_from_zero_timestamp_is_zero() {
+ assert_eq!(queue_ms_from(0.0), 0.0);
+ assert_eq!(queue_ms_from(-1.0), 0.0);
+ }
+
+ #[test]
+ fn queue_ms_from_past_timestamp_is_positive() {
+ let one_second_ago = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64()
+ - 1.0;
+ let ms = queue_ms_from(one_second_ago);
+ // Allow ±200ms wobble for test scheduling; we mostly want to verify
+ // "not zero, not negative, in the right ballpark".
+ assert!((800.0..=1200.0).contains(&ms), "expected ~1000ms, got {ms}");
+ }
+
+ #[test]
+ fn split_by_budget_under_limit_passes_through() {
+ let items = vec![
+ (wi("r", 0, "m", "encode"), ()),
+ (wi("r", 1, "m", "encode"), ()),
+ ];
+ let (dispatch, overflow) = split_by_budget(items, 5);
+ assert_eq!(dispatch.len(), 2);
+ assert!(overflow.is_empty());
+ }
+
+ #[test]
+ fn split_by_budget_over_limit_splits() {
+ let items: Vec<(WorkItem, ())> = (0..10).map(|i| (wi("r", i, "m", "encode"), ())).collect();
+ let (dispatch, overflow) = split_by_budget(items, 3);
+ assert_eq!(dispatch.len(), 3);
+ assert_eq!(overflow.len(), 7);
+ // Original order preserved across the split.
+ assert_eq!(dispatch[0].0.item_index, 0);
+ assert_eq!(dispatch[2].0.item_index, 2);
+ assert_eq!(overflow[0].0.item_index, 3);
+ assert_eq!(overflow[6].0.item_index, 9);
+ }
+
+ #[test]
+ fn split_by_budget_zero_sends_all_to_overflow() {
+ let items: Vec<(WorkItem, ())> = (0..3).map(|i| (wi("r", i, "m", "encode"), ())).collect();
+ let (dispatch, overflow) = split_by_budget(items, 0);
+ assert!(dispatch.is_empty());
+ assert_eq!(overflow.len(), 3);
+ }
+
+ #[test]
+ fn default_max_concurrent_batches_env_parsing() {
+ // Env-free default should be 4. We only assert the env-free
+ // branch here to avoid polluting global state for other tests.
+ //
+ // SAFETY: this is a #[test] in a cfg(test) module and we don't
+ // actually mutate env here — we just check the function is sane
+ // when the variable is absent in CI.
+ assert!(default_max_concurrent_batches() >= 1);
+ }
+
+ #[test]
+ fn pipeline_depth_default_is_two() {
+ // Env-free assertion only. We can't safely mutate env vars
+ // in unit tests without polluting other tests running in
+ // the same process.
+ if std::env::var("SIE_RUST_PIPELINE_DEPTH").is_err() {
+ assert_eq!(pipeline_depth(), 2);
+ }
+ }
+
+ #[test]
+ fn queue_ms_from_future_timestamp_clamps_to_zero() {
+ let in_the_future = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64()
+ + 60.0;
+ assert_eq!(queue_ms_from(in_the_future), 0.0);
+ }
+
+ #[test]
+ fn base_nak_delay_ms_env_free_default() {
+ // Env-free default must match Python's `_NAK_DELAY_S = 5.0` (5000ms)
+ // so Rust and Python adapter processes produce the same JetStream delivery
+ // pressure under back-off. We don't mutate the environment here to
+ // avoid cross-test flakiness; we just assert the lower bound.
+ //
+ // If `SIE_NAK_DELAY_S` is set in the surrounding environment the
+ // value may differ, but the function must always yield a positive
+ // delay.
+ let v = base_nak_delay_ms();
+ assert!(v >= 1, "base_nak_delay_ms must be > 0, got {v}");
+ }
+
+ #[test]
+ fn nak_delay_for_draining_is_short_not_base() {
+ // Draining must NOT use the generic base delay (~5s). Another
+ // worker needs the redelivery now; a long NAK would starve
+ // throughput while the draining pod walks through shutdown.
+ let delay = nak_delay_for_backend_error(&BackendError::Draining);
+ assert_eq!(delay, NAK_DELAY_DRAINING_MS);
+ assert!(
+ delay < base_nak_delay_ms(),
+ "draining delay ({delay}ms) must be tighter than base ({}ms)",
+ base_nak_delay_ms()
+ );
+ }
+
+ #[test]
+ fn nak_delay_for_transient_and_inference_uses_base() {
+ // Everything except Draining shares the base delay so Rust and
+ // Python adapter processes throttle retries identically.
+ assert_eq!(
+ nak_delay_for_backend_error(&BackendError::Transient("x".into())),
+ base_nak_delay_ms()
+ );
+ assert_eq!(
+ nak_delay_for_backend_error(&BackendError::Inference("y".into())),
+ base_nak_delay_ms()
+ );
+ assert_eq!(
+ nak_delay_for_backend_error(&BackendError::UnsupportedModel("z".into())),
+ base_nak_delay_ms()
+ );
+ }
+
+ #[test]
+ fn resolve_outcome_indices_matches_by_wiid_in_arrival_order() {
+ // Happy path: every outcome lines up with exactly one resolved
+ // row, same order.
+ let resolved = vec!["a", "b", "c"];
+ let outcomes = ["a", "b", "c"];
+ let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
+ assert_eq!(bindings, vec![Some(0), Some(1), Some(2)]);
+ }
+
+ #[test]
+ fn resolve_outcome_indices_handles_out_of_order_outcomes() {
+ // The executor may reorder outcomes within a batch (adapter
+ // dedup / parallelism). Binding is by wiid, not slot.
+ let resolved = vec!["a", "b", "c"];
+ let outcomes = ["c", "a", "b"];
+ let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
+ assert_eq!(bindings, vec![Some(2), Some(0), Some(1)]);
+ }
+
+ #[test]
+ fn resolve_outcome_indices_handles_duplicate_wiids_fifo() {
+ // Two messages with the same wiid (pathological redelivery or
+ // upstream bug) must each bind to a *different* resolved slot
+ // in arrival order, so neither is silently dropped.
+ let resolved = vec!["dup", "dup", "uniq"];
+ let outcomes = ["dup", "uniq", "dup"];
+ let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
+ assert_eq!(
+ bindings,
+ vec![Some(0), Some(2), Some(1)],
+ "duplicate 'dup' outcomes must consume resolved slots 0 then 1"
+ );
+ }
+
+ #[test]
+ fn resolve_outcome_indices_extra_outcome_is_ghost() {
+ // Executor emitted more outcomes than items. The surplus must
+ // be flagged (`None`) so the caller can log + drop it instead
+ // of silently ACKing a phantom item.
+ let resolved = vec!["a"];
+ let outcomes = ["a", "ghost"];
+ let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
+ assert_eq!(bindings, vec![Some(0), None]);
+ }
+
+ #[test]
+ fn resolve_outcome_indices_missing_outcome_leaves_orphan() {
+ // Executor dropped an outcome. Returned bindings cover just
+ // what was supplied; the caller walks `resolved` to NAK any
+ // index not present in any `Some(idx)` binding.
+ let resolved = vec!["a", "b", "c"];
+ let outcomes = ["a", "c"];
+ let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
+ assert_eq!(bindings, vec![Some(0), Some(2)]);
+ // Verifying the orphan-detection contract at the call site:
+ let used: std::collections::HashSet<usize> = bindings.iter().filter_map(|o| *o).collect();
+ let orphans: Vec<usize> = (0..resolved.len()).filter(|i| !used.contains(i)).collect();
+ assert_eq!(orphans, vec![1], "index 1 ('b') should be the sole orphan");
+ }
+
+ #[test]
+ fn resolve_outcome_indices_unknown_wiid_is_ghost() {
+ // Outcome for a wiid that isn't in the batch at all.
+ let resolved = vec!["a"];
+ let outcomes = ["unknown"];
+ let bindings = resolve_outcome_indices(&resolved, outcomes.iter().copied());
+ assert_eq!(bindings, vec![None]);
+ }
+
+ // ----- dedupe_per_request_totals ----------------------------------------
+
+ fn outcome(
+ request_id: &str,
+ item_index: u32,
+ disposition: Disposition,
+ inference_ms: Option<f64>,
+ post_ms: Option<f64>,
+ ) -> ItemOutcome {
+ ItemOutcome {
+ work_item_id: format!("{request_id}.{item_index}"),
+ request_id: request_id.into(),
+ item_index,
+ disposition,
+ nak_delay_ms: None,
+ result_msgpack: Vec::new(),
+ error: None,
+ error_code: None,
+ inference_ms,
+ tokenization_ms: None,
+ postprocessing_ms: post_ms,
+ raw_output: None,
+ }
+ }
+
+ #[test]
+ fn dedupe_collapses_multiple_items_of_same_request() {
+ // Three NATS work-items for `req-A` (multi-item /encode) plus
+ // one solo `req-B` land in the same batch. Python's
+ // `_complete_requests` records 2 latency samples (one per
+ // unique `id(metadata)`); Rust must do the same so a 10-item
+ // request doesn't pull `observed_p50_ms` 10× harder than ten
+ // 1-item requests at matched throughput.
+ let now = Instant::now();
+ let t0 = now - std::time::Duration::from_millis(50);
+ let oa0 = outcome(
+ "req-A",
+ 0,
+ Disposition::PublishAndAck,
+ Some(20.0),
+ Some(2.0),
+ );
+ let oa1 = outcome(
+ "req-A",
+ 1,
+ Disposition::PublishAndAck,
+ Some(20.0),
+ Some(2.0),
+ );
+ let oa2 = outcome(
+ "req-A",
+ 2,
+ Disposition::PublishAndAck,
+ Some(20.0),
+ Some(2.0),
+ );
+ let ob0 = outcome(
+ "req-B",
+ 0,
+ Disposition::PublishAndAck,
+ Some(20.0),
+ Some(2.0),
+ );
+
+ let totals = dedupe_per_request_totals(
+ [
+ ("req-A", t0, &oa0),
+ ("req-A", t0, &oa1),
+ ("req-A", t0, &oa2),
+ ("req-B", t0, &ob0),
+ ],
+ now,
+ );
+
+ assert_eq!(totals.len(), 2, "one sample per unique request_id");
+ // Each sample is wait(50) + inf(20) + post(2) = 72 ms within
+ // a tight tolerance for the test scheduler.
+ for s in &totals {
+ assert!(
+ (70.0..=80.0).contains(s),
+ "sample {s} should be ~72ms (50 wait + 20 inf + 2 post)"
+ );
+ }
+ }
+
+ #[test]
+ fn dedupe_skips_non_publish_dispositions() {
+ // Errors / NAK paths must not bias the controller toward fast
+ // no-op replies (they often have inference_ms = 0). Mirrors
+ // Python's per-item `if not metadata.future.done()` gate.
+ let now = Instant::now();
+ let t0 = now - std::time::Duration::from_millis(10);
+ let nak = outcome("req-X", 0, Disposition::NakRetry, Some(20.0), Some(0.0));
+ let err = outcome(
+ "req-Y",
+ 0,
+ Disposition::PublishErrorAndAck,
+ Some(20.0),
+ Some(0.0),
+ );
+ let ok = outcome(
+ "req-Z",
+ 0,
+ Disposition::PublishAndAck,
+ Some(20.0),
+ Some(0.0),
+ );
+
+ let totals = dedupe_per_request_totals(
+ [("req-X", t0, &nak), ("req-Y", t0, &err), ("req-Z", t0, &ok)],
+ now,
+ );
+
+ assert_eq!(totals.len(), 1, "only PublishAndAck contributes");
+ }
+
+ #[test]
+ fn dedupe_skips_zero_or_negative_totals() {
+ // IPC failure with no timing fields populated — both `inf` and
+ // `post` default to 0 and `submitted_at == now` makes the wait
+ // 0 too. A zero sample would pin `observed_p50_ms` at the
+ // floor and starve the wait knob.
+ let now = Instant::now();
+ let zero = outcome("req-zero", 0, Disposition::PublishAndAck, None, None);
+ let totals = dedupe_per_request_totals([("req-zero", now, &zero)], now);
+ assert!(totals.is_empty(), "zero-total samples must be dropped");
+ }
+
+ #[test]
+ fn dedupe_keeps_first_occurrence_submitted_at() {
+ // BatchFormer sorts items by cost so the first item we see for
+ // a given request_id may not be `item_index == 0`. The dedup
+ // should latch onto whichever submitted_at appears first in
+ // iteration order (parity with Python, which uses the
+ // request-level _start_time set once at request entry).
+ let now = Instant::now();
+ let early = now - std::time::Duration::from_millis(100);
+ let late = now - std::time::Duration::from_millis(10);
+ let o_late = outcome("req-A", 5, Disposition::PublishAndAck, Some(0.0), Some(0.0));
+ let o_early = outcome("req-A", 0, Disposition::PublishAndAck, Some(0.0), Some(0.0));
+
+ // Late item appears first (BatchFormer sorted by cost).
+ let totals =
+ dedupe_per_request_totals([("req-A", late, &o_late), ("req-A", early, &o_early)], now);
+
+ assert_eq!(totals.len(), 1);
+ let s = totals[0];
+ assert!(
+ (5.0..=20.0).contains(&s),
+ "sample {s} should reflect the first-seen submitted_at (~10ms wait)"
+ );
+ }
+
+ #[test]
+ fn dedupe_empty_input_yields_empty_output() {
+ let totals = dedupe_per_request_totals(std::iter::empty(), Instant::now());
+ assert!(totals.is_empty());
+ }
+}
diff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rs
new file mode 100644
index 000000000..07e744e42
--- /dev/null
+++ b/packages/sie_server_sidecar/src/health_publisher.rs
@@ -0,0 +1,346 @@
+//! NATS health-heartbeat publisher.
+//!
+//! In `health_mode=nats` the gateway expects every worker to
+//! periodically publish a [`WorkerStatusMessage`]-shaped payload to
+//! `sie.health.<worker_id>` so its `WorkerRegistry` knows the worker
+//! exists, which `bundle` it serves, and which `pool_name` to route
+//! NATS work to. Without this signal the gateway returns
+//! `202 provisioning` for every request.
+//!
+//! See `packages/sie_gateway/src/discovery/nats_health.rs` for the
+//! consumer side and `docs/queue-based-routing.md` for the routing
+//! contract.
+//!
+//! # What the gateway actually reads
+//!
+//! Only a small subset of fields is load-bearing for routing:
+//!
+//! * `bundle` — must match the bundle resolved by the gateway's
+//! model registry (lowercase compared); routes only consider
+//! workers whose bundle index entry contains them.
+//! * `pool_name` — non-empty so [`resolve_queue_pool`] can return
+//! the pool the dispatcher publishes work onto. An empty
+//! `pool_name` makes the worker invisible to the queue path.
+//! * `machine_profile` — only consulted when the request carries
+//! `X-SIE-MACHINE-PROFILE`; ignored otherwise.
+//! * `ready` — drives the `WorkerHealth::Healthy` transition. We
+//! gate on the local [`Readiness`] state so the heartbeat agrees
+//! with `/readyz`.
+//!
+//! `loaded_models` and the GPU memory fields are informational; the
+//! sidecar does not own a list of model IDs (the adapter does), so
+//! we publish an empty list and let the gateway's per-model state
+//! reflect what it observes from successful work-result publishes
+//! plus its own model registry.
+//!
+//! [`WorkerStatusMessage`]: https://github.com/search?q=WorkerStatusMessage+repo%3Asie-internal
+//! [`resolve_queue_pool`]: https://github.com/search?q=resolve_queue_pool+repo%3Asie-internal
+
+use std::sync::Arc;
+use std::sync::RwLock;
+use std::time::Duration;
+
+use async_nats::Client;
+use serde::Serialize;
+use tokio::task::JoinHandle;
+use tokio::time::interval;
+use tracing::{debug, info, warn};
+
+use crate::readiness::Readiness;
+use crate::shutdown::Shutdown;
+
+pub type SharedBundleConfigHash = Arc<RwLock<String>>;
+
+/// Default subject prefix used by the gateway. Workers always
+/// publish to `sie.health.<worker_id>` because the gateway's
+/// `extract_worker_url_from_status` reads `splitn(3, '.')` on the
+/// subject, so any sub-token segments would confuse URL extraction.
+pub const HEALTH_SUBJECT_PREFIX: &str = "sie.health";
+
+/// Default interval between heartbeats. Matches the gateway's
+/// `NatsHealthManager::start_heartbeat_loop` 5 s tick — anything
+/// faster wastes NATS bandwidth and anything slower risks the
+/// 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);
+
+/// 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)]
+pub struct HealthPublisherConfig {
+ /// Stable identifier used as the subject leaf and as the
+ /// fallback URL the gateway constructs. Should match
+ /// `WorkerConfig::worker_id`.
+ pub worker_id: String,
+ /// The bundle this pod's adapter is serving. The gateway's
+ /// per-bundle index keys on this (lowercased), so it must
+ /// match `BundleConfig.id`. Sourced from `SIE_BUNDLE`.
+ pub bundle: String,
+ /// Pool name. The gateway publishes work onto
+ /// `sie.work.<model>.<pool_name>`; the worker must echo the
+ /// same pool here or `resolve_queue_pool` returns `None` and
+ /// requests 202-provision forever. Sourced from `SIE_POOL`.
+ pub pool_name: String,
+ /// Optional machine-profile label (e.g. `l4`, `a100`).
+ /// Consulted only when the inbound request carries
+ /// `X-SIE-MACHINE-PROFILE`. Empty means "any GPU".
+ pub machine_profile: String,
+ /// Reported GPU count. The registry coerces `0 -> 1` so a
+ /// missing value still routes; we still want to surface the
+ /// real count when known so admin views show accurate totals.
+ pub gpu_count: i32,
+ /// Bundle-config hash so the gateway can correlate against its own
+ /// model registry epoch. Updated by the config subscriber after a
+ /// successful Python registry apply.
+ pub bundle_config_hash: SharedBundleConfigHash,
+ /// How often to publish. Defaults to [`DEFAULT_PUBLISH_INTERVAL`].
+ pub interval: Duration,
+}
+
+impl HealthPublisherConfig {
+ /// Subject this pod publishes to. Kept as a method so the
+ /// gateway-side parser (`splitn(3, '.')`) and this side stay
+ /// in lockstep — change the prefix here and the gateway will
+ /// see no health messages.
+ pub fn subject(&self) -> String {
+ format!("{}.{}", HEALTH_SUBJECT_PREFIX, self.worker_id)
+ }
+}
+
+/// Wire shape published to NATS. Mirrors the gateway's
+/// [`crate::types::WorkerStatusMessage`] subset that's actually
+/// load-bearing for routing.
+///
+/// Serialised as JSON because the gateway's
+/// `handle_nats_message` tries msgpack first and falls back to
+/// JSON; JSON keeps the payload trivially `nats sub`-debuggable
+/// from a shell, which matters for the post-deploy smoke test
+/// we do every time. Both formats are accepted, so we can switch
+/// to msgpack later without a flag day on either side.
+#[derive(Debug, Serialize)]
+struct WorkerStatusPayload<'a> {
+ name: &'a str,
+ ready: bool,
+ gpu_count: i32,
+ machine_profile: &'a str,
+ pool_name: &'a str,
+ bundle: &'a str,
+ bundle_config_hash: &'a str,
+ /// Empty — the sidecar has no authoritative list of loaded
+ /// models. The adapter knows; surfacing that would require a
+ /// new IPC round-trip per heartbeat which isn't worth the
+ /// cost for an informational field.
+ loaded_models: &'a [&'a str],
+}
+
+/// Spawn the heartbeat-publisher loop. The returned [`JoinHandle`]
+/// is owned by `run()` so shutdown can `.abort()` it after the
+/// pull loop exits — same lifecycle as `crate::spawn_heartbeat`.
+///
+/// Failure modes (non-fatal):
+///
+/// * NATS publish errors — logged, counter bumped via WARN every
+/// 5 / 30 / 120 ticks (same backoff pattern as the IPC heartbeat
+/// to avoid spamming during a NATS outage).
+/// * Serde encode errors — should be unreachable for a static
+/// payload shape; logged and skipped.
+pub fn spawn(
+ nats: Client,
+ config: HealthPublisherConfig,
+ readiness: Arc<Readiness>,
+ shutdown: Arc<Shutdown>,
+) -> JoinHandle<()> {
+ let subject = config.subject();
+ info!(
+ subject = %subject,
+ bundle = %config.bundle,
+ pool = %config.pool_name,
+ machine_profile = %config.machine_profile,
+ gpu_count = config.gpu_count,
+ interval_ms = config.interval.as_millis() as u64,
+ "nats-health: heartbeat publisher starting"
+ );
+
+ tokio::spawn(async move {
+ let mut tick = interval(config.interval);
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+
+ let mut consecutive_failures: u64 = 0;
+ loop {
+ let wait = shutdown.wait();
+ tokio::select! {
+ biased;
+ _ = wait => {
+ debug!(subject = %subject, "nats-health: shutdown observed; stopping publisher");
+ return;
+ }
+ _ = tick.tick() => {
+ let snap = readiness.snapshot();
+ let ready = snap.is_ready();
+ let bytes = {
+ let hash = config
+ .bundle_config_hash
+ .read()
+ .expect("bundle config hash lock poisoned");
+ let payload = WorkerStatusPayload {
+ name: &config.worker_id,
+ ready,
+ gpu_count: config.gpu_count,
+ machine_profile: &config.machine_profile,
+ pool_name: &config.pool_name,
+ bundle: &config.bundle,
+ bundle_config_hash: hash.as_str(),
+ loaded_models: &[],
+ };
+ match serde_json::to_vec(&payload) {
+ Ok(b) => b,
+ Err(e) => {
+ warn!(
+ error = %e,
+ "nats-health: serde_json encode failed (unexpected for static shape)"
+ );
+ continue;
+ }
+ }
+ };
+ match nats.publish(subject.clone(), bytes.into()).await {
+ Ok(_) => {
+ if consecutive_failures > 0 {
+ info!(
+ consecutive_failures,
+ subject = %subject,
+ "nats-health: publish recovered"
+ );
+ }
+ consecutive_failures = 0;
+ debug!(subject = %subject, ready, "nats-health: heartbeat published");
+ }
+ Err(e) => {
+ consecutive_failures = consecutive_failures.saturating_add(1);
+ // Same warn cadence as `spawn_heartbeat`:
+ // first failure, then 5 / 30 / every 120
+ // so a sustained NATS outage doesn't
+ // drown the log file.
+ if consecutive_failures == 1
+ || consecutive_failures == 5
+ || consecutive_failures == 30
+ || consecutive_failures.is_multiple_of(120)
+ {
+ warn!(
+ consecutive_failures,
+ subject = %subject,
+ error = %e,
+ "nats-health: publish failed"
+ );
+ } else {
+ debug!(
+ consecutive_failures,
+ subject = %subject,
+ error = %e,
+ "nats-health: publish still failing"
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn cfg() -> HealthPublisherConfig {
+ HealthPublisherConfig {
+ worker_id: "worker-l4-0".into(),
+ bundle: "default".into(),
+ pool_name: "l4".into(),
+ machine_profile: "l4".into(),
+ gpu_count: 1,
+ bundle_config_hash: Arc::new(RwLock::new("hash-abc".into())),
+ interval: DEFAULT_PUBLISH_INTERVAL,
+ }
+ }
+
+ #[test]
+ fn subject_is_prefix_dot_worker_id() {
+ // Gateway's `extract_worker_url_from_status` does
+ // `splitn(3, '.')` so the worker_id must occupy a single
+ // subject token. We don't enforce that here (NATS
+ // tolerates more dots) but the convention is one token.
+ assert_eq!(cfg().subject(), "sie.health.worker-l4-0");
+ }
+
+ #[test]
+ fn payload_roundtrips_to_gateway_shape() {
+ // Serialises to the exact field set
+ // `WorkerStatusMessage::deserialize` reads — every
+ // load-bearing field present, nothing extra.
+ let c = cfg();
+ let json = {
+ let hash = c.bundle_config_hash.read().unwrap();
+ let payload = WorkerStatusPayload {
+ name: &c.worker_id,
+ ready: true,
+ gpu_count: c.gpu_count,
+ machine_profile: &c.machine_profile,
+ pool_name: &c.pool_name,
+ bundle: &c.bundle,
+ bundle_config_hash: hash.as_str(),
+ loaded_models: &[],
+ };
+ serde_json::to_value(&payload).unwrap()
+ };
+ assert_eq!(json["name"], "worker-l4-0");
+ assert_eq!(json["ready"], true);
+ assert_eq!(json["gpu_count"], 1);
+ assert_eq!(json["machine_profile"], "l4");
+ assert_eq!(json["pool_name"], "l4");
+ assert_eq!(json["bundle"], "default");
+ assert_eq!(json["bundle_config_hash"], "hash-abc");
+ assert_eq!(json["loaded_models"], serde_json::json!([]));
+ }
+
+ #[test]
+ fn payload_reads_updated_bundle_config_hash() {
+ let c = cfg();
+ {
+ let mut hash = c.bundle_config_hash.write().unwrap();
+ *hash = "hash-next".into();
+ }
+ let json = {
+ let hash = c.bundle_config_hash.read().unwrap();
+ let payload = WorkerStatusPayload {
+ name: &c.worker_id,
+ ready: true,
+ gpu_count: c.gpu_count,
+ machine_profile: &c.machine_profile,
+ pool_name: &c.pool_name,
+ bundle: &c.bundle,
+ bundle_config_hash: hash.as_str(),
+ loaded_models: &[],
+ };
+ serde_json::to_value(&payload).unwrap()
+ };
+ assert_eq!(json["bundle_config_hash"], "hash-next");
+ }
+
+ #[test]
+ fn payload_uses_local_readiness_for_ready_flag() {
+ // Heartbeat must reflect /readyz state — once draining
+ // we publish ready=false so the gateway transitions us
+ // to Unhealthy ASAP rather than waiting for the 30 s
+ // heartbeat_timeout to elapse.
+ let r = Readiness::new(2_000, 3);
+ r.record_ping_success();
+ assert!(r.snapshot().is_ready());
+
+ r.mark_draining();
+ assert!(!r.snapshot().is_ready());
+ }
+}
diff --git a/packages/sie_server_sidecar/src/ipc_client.rs b/packages/sie_server_sidecar/src/ipc_client.rs
new file mode 100644
index 000000000..97596258a
--- /dev/null
+++ b/packages/sie_server_sidecar/src/ipc_client.rs
@@ -0,0 +1,2052 @@
+//! Async IPC client over a Unix domain socket, speaking the length-prefixed
+//! msgpack protocol defined by `sie_server.ipc_server`.
+//!
+//! # Concurrency model: connection pool
+//!
+//! Each IPC RPC is a strictly synchronous `write_frame → read_frame`
+//! round-trip on one connection. A single connection therefore admits at
+//! most one in-flight RPC; any second caller blocks behind the first.
+//!
+//! To let `SIE_MAX_CONCURRENT_BATCHES` actually translate into parallel
+//! IPC calls — and thus let the Python-side adaptive batcher / GPU
+//! pipeline overlap CPU preprocessing on one batch with GPU inference on
+//! another — we run a small **pool** of N independent connections to the
+//! same `ipc_server.py`.
+//!
+//! * The Python server already accepts many connections concurrently
+//! (`asyncio.start_unix_server`) and spawns an `asyncio.create_task`
+//! per incoming frame, so no Python-side change is required; each
+//! Rust slot just looks like another sidecar.
+//! * Callers `acquire()` a `SlotGuard` — a fair FIFO checkout — do
+//! their round-trip, and drop it to return the slot. If all N slots
+//! are checked out the caller waits on a [`tokio::sync::Semaphore`],
+//! which avoids the head-of-line blocking a round-robin scheme would
+//! suffer when one slot has a slow in-flight RPC.
+//! * A transport error on slot K only resets slot K's socket, so one
+//! broken connection doesn't wipe the other N-1 sessions.
+//!
+//! Sizing: 1 is the legacy behaviour (restored by `IpcClient::new`).
+//! Real deployments set `SIE_IPC_POOL_SIZE` (see `main.rs`) to match
+//! `SIE_MAX_CONCURRENT_BATCHES` so the dispatcher's concurrency limit
+//! is the binding one, not this socket mutex.
+
+use std::collections::VecDeque;
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex as StdMutex};
+use std::time::Duration;
+
+use serde::{de::DeserializeOwned, Serialize};
+use thiserror::Error;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::UnixStream;
+use tokio::sync::{OwnedSemaphorePermit, Semaphore};
+use tokio::time::timeout;
+use tracing::{debug, info, warn};
+
+use crate::ipc_mux::{mux_enabled, MuxClient, MuxError};
+use crate::ipc_types::{
+ ApplyModelConfigRequest, ApplyModelConfigResponse, BatchOutcome, DrainRequest, DrainResponse,
+ EnsureModelReadyRequest, EnsureModelReadyResponse, GenerateEvent, PingRequest, PingResponse,
+ ProcessEncodeBatchRequest, ProcessExtractBatchRequest, ProcessGenerateRequest,
+ ProcessScoreBatchRequest, RequestEnvelope, ResponseEnvelope, RunBatchRequest,
+ SignalGenerateCancelRequest, SignalGenerateCancelResponse, WorkerCapabilitiesRequest,
+ WorkerCapabilitiesResponse, IPC_VERSION, METHOD_APPLY_MODEL_CONFIG, METHOD_DRAIN,
+ METHOD_ENSURE_MODEL_READY, METHOD_PING, METHOD_PROCESS_ENCODE_BATCH,
+ METHOD_PROCESS_EXTRACT_BATCH, METHOD_PROCESS_GENERATE, METHOD_PROCESS_SCORE_BATCH,
+ METHOD_RUN_BATCH, METHOD_SIGNAL_GENERATE_CANCEL, METHOD_WORKER_CAPABILITIES,
+};
+use crate::log_util::ErrChain;
+use crate::metrics::MetricsRegistry;
+
+const MAX_FRAME_BYTES: usize = 32 * 1024 * 1024;
+
+/// Default pool size when the caller doesn't specify one. Matches the
+/// legacy single-connection behaviour — production deployments override
+/// via [`IpcClient::with_pool_size`] / `SIE_IPC_POOL_SIZE`.
+const DEFAULT_POOL_SIZE: usize = 1;
+
+/// WARN threshold for "slow" RPCs — emits one structured line per slow
+/// call so an operator scanning `kubectl logs` sees Python-side
+/// stalls without having to open Grafana. The `ipc_request_seconds`
+/// histogram is the primary source of truth; this is the ergonomic
+/// shortcut for live debugging. Keep the budget generous: model
+/// loading (ensure_model_ready) can legitimately take 10+ seconds, so
+/// we deliberately do NOT pick a threshold low enough to flag that
+/// path; it'd be pure noise. We do flag ping / per-batch inference.
+const SLOW_RPC_WARN_MS: u128 = 2_000;
+
+/// A bounded label for the `result` dimension on `ipc_request_seconds`.
+/// Keeps cardinality low (no raw messages).
+fn error_label(e: &IpcError) -> &'static str {
+ match e {
+ IpcError::Io(_) => "io",
+ IpcError::Encode(_) => "encode",
+ IpcError::Decode(_) => "decode",
+ IpcError::Timeout => "timeout",
+ IpcError::FrameTooLarge(_) => "frame_too_large",
+ IpcError::Server(_) => "server",
+ IpcError::VersionMismatch { .. } => "version_mismatch",
+ }
+}
+
+/// Classify an `IpcError` as a transport glitch (`true`) or a logical /
+/// protocol error (`false`). Only transport glitches are worth retrying.
+fn is_transport_error(e: &IpcError) -> bool {
+ match e {
+ IpcError::Io(io_err) => matches!(
+ io_err.kind(),
+ std::io::ErrorKind::BrokenPipe
+ | std::io::ErrorKind::ConnectionReset
+ | std::io::ErrorKind::ConnectionAborted
+ | std::io::ErrorKind::UnexpectedEof
+ | std::io::ErrorKind::NotFound
+ | std::io::ErrorKind::NotConnected
+ | std::io::ErrorKind::WouldBlock
+ ),
+ _ => false,
+ }
+}
+
+fn generate_frame_timeout() -> Duration {
+ let secs = std::env::var("SIE_GENERATE_IPC_FRAME_TIMEOUT_S")
+ .ok()
+ .and_then(|s| s.parse::<u64>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or(300);
+ Duration::from_secs(secs)
+}
+
+async fn read_frame(stream: &mut UnixStream) -> Result<Vec<u8>, IpcError> {
+ let mut len_buf = [0u8; 4];
+ stream.read_exact(&mut len_buf).await?;
+ let resp_len = u32::from_be_bytes(len_buf);
+ if resp_len as usize > MAX_FRAME_BYTES {
+ return Err(IpcError::FrameTooLarge(resp_len));
+ }
+ let mut resp_buf = vec![0u8; resp_len as usize];
+ stream.read_exact(&mut resp_buf).await?;
+ Ok(resp_buf)
+}
+
+#[derive(Debug, Error)]
+pub enum IpcError {
+ #[error("io: {0}")]
+ Io(#[from] std::io::Error),
+ #[error("encode: {0}")]
+ Encode(#[from] rmp_serde::encode::Error),
+ #[error("decode: {0}")]
+ Decode(#[from] rmp_serde::decode::Error),
+ #[error("timeout waiting for IPC response")]
+ Timeout,
+ #[error("frame too large: {0} > {MAX_FRAME_BYTES}")]
+ FrameTooLarge(u32),
+ #[error("server returned error: {0}")]
+ Server(String),
+ #[error("envelope version mismatch: got {got}, expected {IPC_VERSION}")]
+ VersionMismatch { got: u32 },
+}
+
+/// One physical UDS connection, identified by its slot index. Only ever
+/// accessed by whichever task currently holds it (enforced by the pool's
+/// checkout semantics), so no internal synchronization is needed.
+struct Slot {
+ id: usize,
+ stream: Option<UnixStream>,
+}
+
+impl Slot {
+ fn new(id: usize) -> Self {
+ Self { id, stream: None }
+ }
+}
+
+/// Fair-FIFO pool of [`Slot`]s backed by a [`Semaphore`].
+///
+/// Invariants:
+/// * The semaphore's permit count equals `capacity - live_checkouts`.
+/// * Permit release is paired with the slot push: we always push the
+/// slot back onto the queue **before** the permit is released. A
+/// waiter that subsequently wakes therefore always finds a slot
+/// ready to pop, so [`Self::acquire`]'s `expect` can never fire.
+///
+/// We use a `std::sync::Mutex` (not `tokio::sync::Mutex`) for the slot
+/// queue because:
+/// 1. The critical section is a single `VecDeque::{push_back, pop_front}`
+/// — sub-microsecond, no `.await` points, so Tokio's async mutex
+/// brings no benefit and its async-only API prevents using it from
+/// inside `Drop` (which is where the push-back happens).
+/// 2. Holding a blocking lock for that span does not starve the
+/// executor — it's shorter than a scheduling quantum.
+///
+/// Why not round-robin by index? A slow RPC on slot K would block every
+/// Kth caller that wrapped back to that slot, even if N-1 others were
+/// idle. Checkout-and-return gives strict fairness and head-of-line
+/// isolation.
+struct Pool {
+ capacity: usize,
+ slots: StdMutex<VecDeque<Slot>>,
+ permits: Arc<Semaphore>,
+ metrics: Option<Arc<MetricsRegistry>>,
+}
+
+impl Pool {
+ fn new(capacity: usize, metrics: Option<Arc<MetricsRegistry>>) -> Self {
+ assert!(capacity >= 1, "IPC pool capacity must be ≥ 1");
+ let mut slots = VecDeque::with_capacity(capacity);
+ for id in 0..capacity {
+ slots.push_back(Slot::new(id));
+ }
+ if let Some(m) = &metrics {
+ m.ipc_pool_size.set(capacity as i64);
+ m.ipc_pool_inflight.set(0);
+ }
+ Self {
+ capacity,
+ slots: StdMutex::new(slots),
+ permits: Arc::new(Semaphore::new(capacity)),
+ metrics,
+ }
+ }
+
+ /// Wait for a free slot. Returns an RAII guard that returns the slot
+ /// to the pool on drop. If the caller wishes to discard a slot (e.g.
+ /// after an unrecoverable error) they can still drop the guard —
+ /// the slot's socket is either still usable or already `None`.
+ async fn acquire(self: &Arc<Self>) -> SlotGuard {
+ let start = std::time::Instant::now();
+ let permit = Arc::clone(&self.permits)
+ .acquire_owned()
+ .await
+ .expect("IPC pool semaphore closed");
+ let slot = {
+ let mut q = self.slots.lock().expect("pool slot mutex poisoned");
+ q.pop_front().expect(
+ "pool invariant violated: permit acquired but no slot available \
+ (indicates the SlotGuard Drop order is wrong — the permit is \
+ being released before the slot is pushed back)",
+ )
+ };
+ if let Some(m) = &self.metrics {
+ m.ipc_pool_acquire_wait_seconds
+ .observe(start.elapsed().as_secs_f64());
+ m.ipc_pool_inflight.inc();
+ }
+ SlotGuard {
+ slot: Some(slot),
+ pool: Arc::clone(self),
+ dirty: false,
+ _permit: permit,
+ }
+ }
+
+ /// Drop every idle slot's socket. Slots currently checked out will
+ /// reset themselves when the caller's `call_inner` observes the
+ /// transport error; this only clobbers the ones sitting in the
+ /// queue. Used by [`IpcClient::reset`] for shutdown / pathological
+ /// recovery.
+ fn reset_idle(&self) {
+ let mut q = self.slots.lock().expect("pool slot mutex poisoned");
+ for s in q.iter_mut() {
+ s.stream = None;
+ }
+ }
+}
+
+/// RAII handle to a single [`Slot`] checked out of a [`Pool`]. Dropping
+/// the guard returns the slot to the back of the pool and releases the
+/// semaphore permit.
+///
+/// ## Cancellation safety
+///
+/// The IPC protocol is a strict `write_frame → read_frame` round-trip.
+/// If a caller's `call(…)` Future is dropped mid-I/O (e.g. because a
+/// gateway-imposed request deadline fires, or the caller wrapped us in
+/// `tokio::time::timeout` and hit it), the underlying `UnixStream` may
+/// have:
+/// * a half-written length prefix but no body, or
+/// * a fully written frame but no response read yet.
+///
+/// Either way the socket is **protocol-desynchronized**: the next
+/// request's bytes would be misinterpreted by the Python server as a
+/// continuation of the aborted one, producing either a silent hang or
+/// a corrupt decode.
+///
+/// To prevent that we arm a "dirty" flag on the guard before any I/O
+/// `.await` and only disarm it on successful protocol completion. If
+/// `Drop` runs while the flag is armed (cancellation, panic, early
+/// return), the slot's stream is cleared so the next `call_inner` on
+/// it reconnects from scratch.
+///
+/// Field order matters: Rust drops struct fields in declaration order,
+/// so `slot` is taken first in our [`Drop`] impl, and the permit in
+/// `_permit` is released afterwards. This ordering is what upholds the
+/// pool invariant that a waiter waking on the semaphore always finds a
+/// slot to pop.
+struct SlotGuard {
+ slot: Option<Slot>,
+ pool: Arc<Pool>,
+ /// Set to `true` while I/O is in flight. If the guard is dropped
+ /// while armed, the slot's socket is forcibly reset on the way
+ /// back into the pool. Reset on success via [`Self::disarm`].
+ dirty: bool,
+ _permit: OwnedSemaphorePermit,
+}
+
+impl SlotGuard {
+ fn slot_mut(&mut self) -> &mut Slot {
+ self.slot.as_mut().expect("slot taken before guard dropped")
+ }
+
+ /// Mark the slot's stream as mid-I/O — any non-clean exit will
+ /// force a reconnect on next use. Paired with [`Self::disarm`] on
+ /// successful protocol completion, or an explicit
+ /// `slot.stream = None` for errors the caller classifies as
+ /// transport glitches.
+ fn arm(&mut self) {
+ self.dirty = true;
+ }
+
+ /// Mark the current call as cleanly completed — no stream reset
+ /// needed on drop.
+ fn disarm(&mut self) {
+ self.dirty = false;
+ }
+}
+
+impl Drop for SlotGuard {
+ fn drop(&mut self) {
+ // Push the slot back *synchronously* before our `_permit` field
+ // is dropped below. A std::sync::Mutex over a VecDeque makes
+ // this a handful of instructions — we can't use a Tokio async
+ // mutex here because Drop is sync. After this scope, the
+ // compiler drops `_permit`, which bumps the semaphore and
+ // wakes the next waiter; they then pop the slot we just
+ // pushed. Reordering would reintroduce the "permit but no
+ // slot" race the old async-spawn version suffered.
+ if let Some(mut slot) = self.slot.take() {
+ if self.dirty {
+ // Cancellation / panic / early-return path: the
+ // stream may be protocol-desynchronized. Clobber it
+ // so the next user reconnects cleanly.
+ slot.stream = None;
+ }
+ let mut q = self.pool.slots.lock().expect("pool slot mutex poisoned");
+ q.push_back(slot);
+ if let Some(m) = &self.pool.metrics {
+ m.ipc_pool_inflight.dec();
+ }
+ }
+ }
+}
+
+/// Shared IPC client — a pool of UDS connections to `ipc_server.py`.
+///
+/// Created with either [`IpcClient::new`] (single connection, legacy)
+/// or [`IpcClient::new_pool`] / [`IpcClient::with_pool_size`] for
+/// multi-connection deployments. Connections are established lazily on
+/// first use per slot.
+///
+/// The transport can be switched to a multiplexed single-connection
+/// design by setting `SIE_IPC_MUX=1` (see [`crate::ipc_mux`]). The
+/// public API is identical; only the wire-level concurrency model
+/// differs (slot pool vs. id-multiplexing).
+pub struct IpcClient {
+ socket_path: PathBuf,
+ pool: Arc<Pool>,
+ next_request_id: AtomicU64,
+ request_timeout: Duration,
+ metrics: Option<Arc<MetricsRegistry>>,
+ /// When `Some`, every `call(…)` is delegated to the multiplexed
+ /// transport instead of acquiring a slot from the pool. Lazily
+ /// initialised so unit tests that never opt in pay no cost.
+ mux: Option<Arc<MuxClient>>,
+}
+
+impl IpcClient {
+ /// Create a single-connection client. Equivalent to the pre-pool
+ /// behaviour — kept for tests and simple callers; production
+ /// configuration should prefer [`IpcClient::new_pool`].
+ pub fn new(socket_path: impl Into<PathBuf>) -> Self {
+ Self::new_pool(socket_path, DEFAULT_POOL_SIZE)
+ }
+
+ /// Create an N-connection client. `pool_size` is clamped to `>= 1`.
+ pub fn new_pool(socket_path: impl Into<PathBuf>, pool_size: usize) -> Self {
+ let capacity = pool_size.max(1);
+ let socket_path = socket_path.into();
+ let mux = if mux_enabled() {
+ info!(
+ socket = %socket_path.display(),
+ "ipc_client: SIE_IPC_MUX=1 — using multiplexed transport"
+ );
+ Some(Arc::new(MuxClient::spawn(socket_path.clone())))
+ } else {
+ None
+ };
+ Self {
+ socket_path,
+ pool: Arc::new(Pool::new(capacity, None)),
+ next_request_id: AtomicU64::new(1),
+ request_timeout: Duration::from_secs(60),
+ metrics: None,
+ mux,
+ }
+ }
+
+ pub fn with_timeout(mut self, timeout: Duration) -> Self {
+ self.request_timeout = timeout;
+ self
+ }
+
+ /// Attach a metrics registry so each RPC records per-method latency,
+ /// frame sizes, and connect/reconnect events — plus pool saturation
+ /// (`ipc_pool_inflight`, `ipc_pool_acquire_wait_seconds`). No-op if
+ /// unset.
+ pub fn with_metrics(mut self, metrics: Arc<MetricsRegistry>) -> Self {
+ // Rebuild the pool so the metrics handle threads all the way
+ // down to the pool-side gauges. We haven't started serving any
+ // RPCs yet (this is a builder), so dropping the old pool is
+ // cheap and correctness-preserving.
+ self.pool = Arc::new(Pool::new(self.pool.capacity, Some(Arc::clone(&metrics))));
+ // Re-spawn the multiplexer with metrics threaded through so
+ // its connect/reconnect counters land on the same registry
+ // as the pool variant.
+ if self.mux.is_some() {
+ self.mux = Some(Arc::new(MuxClient::spawn_with_metrics(
+ self.socket_path.clone(),
+ Some(Arc::clone(&metrics)),
+ )));
+ }
+ self.metrics = Some(metrics);
+ self
+ }
+
+ /// Override pool size post-construction. Useful when the size is
+ /// parsed from env in `main.rs` after `IpcClient::new` was chosen
+ /// for a reasonable default. Clamped to `>= 1`.
+ pub fn with_pool_size(mut self, pool_size: usize) -> Self {
+ let capacity = pool_size.max(1);
+ let metrics = self.metrics.clone();
+ self.pool = Arc::new(Pool::new(capacity, metrics));
+ self
+ }
+
+ pub fn socket_path(&self) -> &Path {
+ &self.socket_path
+ }
+
+ /// Configured pool capacity (≥ 1). Observable via the
+ /// `sie_worker_ipc_pool_size` gauge as well.
+ pub fn pool_size(&self) -> usize {
+ self.pool.capacity
+ }
+
+ /// Drop every idle pooled socket. Used on shutdown or after a hard
+ /// protocol error. Individual transport glitches during a live RPC
+ /// are handled in [`IpcClient::call`] and only affect the slot they
+ /// happened on. Slots currently checked out are left alone; they
+ /// will be reconnected lazily by their caller's `call_inner` on
+ /// next use after it has observed the transport error.
+ pub async fn reset(&self) {
+ self.pool.reset_idle();
+ }
+
+ fn next_id(&self) -> String {
+ let n = self.next_request_id.fetch_add(1, Ordering::Relaxed);
+ format!("w-{n}")
+ }
+
+ /// Low-level request/response — send one frame, read one frame.
+ ///
+ /// Resilience: on an I/O-layer error (broken pipe / reset / UDS EOF /
+ /// msgpack decode on a half-read buffer) we reset **the offending
+ /// slot only** and transparently retry exactly once, preferring a
+ /// fresh slot from the pool so the retry isn't gated on the still-
+ /// breaking connection. This avoids NAKing an entire batch just
+ /// because the Python side restarted between two fetches, while
+ /// also not taking out the other N-1 slots.
+ ///
+ /// We do *not* retry:
+ /// * `Timeout` — if Python is slow once, it'll likely be slow again,
+ /// and a retry would double our tail latency.
+ /// * `Server` / `VersionMismatch` — these are logical errors that
+ /// won't go away on retry.
+ /// * `FrameTooLarge` — signals a bug, not a transport glitch.
+ /// * `Encode` — serialization on our side; retry won't help.
+ ///
+ /// We serialize the request envelope exactly once at the top of `call`
+ /// and reuse those bytes for the retry. The previous implementation
+ /// took `body: Req` by value and `body.clone()`d before the first send
+ /// "just in case" a retry was needed — an O(batch) allocation on every
+ /// successful RPC. Trait bound `Req: Clone` was removed with this
+ /// refactor; only `Serialize` remains.
+ pub async fn call<Req, Resp>(&self, method: &str, body: Req) -> Result<Resp, IpcError>
+ where
+ Req: Serialize,
+ Resp: DeserializeOwned,
+ {
+ let request_id = self.next_id();
+ let envelope = RequestEnvelope {
+ version: IPC_VERSION,
+ method,
+ request_id: request_id.clone(),
+ body,
+ };
+ let payload = rmp_serde::to_vec_named(&envelope)?;
+ if let Some(m) = &self.metrics {
+ m.ipc_request_bytes
+ .with_label_values(&[method])
+ .observe(payload.len() as f64);
+ }
+ debug!(method, request_id = %request_id, bytes = payload.len(), "ipc request");
+
+ let start = std::time::Instant::now();
+
+ // Multiplexed transport (SIE_IPC_MUX=1): single shared
+ // connection with id-based response demuxing. The mux actor
+ // owns reconnect; we still wrap the call in our own timeout
+ // and apply a single transport-class retry to mirror the
+ // pool path's "fresh slot" recovery semantics. The retry
+ // reuses the same payload bytes (and request_id): the actor
+ // drained its inflight map on disconnect, so the original
+ // id is no longer registered and the new attempt won't be
+ // confused with a stale response.
+ if let Some(mux) = &self.mux {
+ let first = self
+ .mux_call::<Resp>(mux, method, request_id.clone(), &payload)
+ .await;
+ return match first {
+ Ok(v) => {
+ self.record_rpc(method, start, "ok");
+ Ok(v)
+ }
+ Err(e) if is_transport_error(&e) => {
+ info!(
+ method,
+ error = %ErrChain(&e),
+ "mux IPC transport error — retrying once"
+ );
+ if let Some(m) = &self.metrics {
+ m.ipc_reconnect_total.inc();
+ }
+ match self
+ .mux_call::<Resp>(mux, method, request_id, &payload)
+ .await
+ {
+ Ok(v) => {
+ self.record_rpc(method, start, "ok_after_retry");
+ Ok(v)
+ }
+ Err(e) => {
+ self.record_rpc(method, start, error_label(&e));
+ Err(e)
+ }
+ }
+ }
+ Err(e) => {
+ self.record_rpc(method, start, error_label(&e));
+ Err(e)
+ }
+ };
+ }
+
+ // First attempt on some slot. We arm() before the I/O starts
+ // so a cancellation/panic between here and disarm() forces a
+ // reconnect on that slot (protocol-resync safety).
+ let mut slot_guard = self.pool.acquire().await;
+ slot_guard.arm();
+ let first = timeout(
+ self.request_timeout,
+ self.call_inner::<Resp>(method, &payload, slot_guard.slot_mut()),
+ )
+ .await;
+ let first = match first {
+ Ok(r) => r,
+ Err(_) => {
+ // Timeout → the slot's UDS is in an indeterminate state
+ // (we may be mid-write, or Python may have stalled mid-
+ // read). The guard is still armed so Drop will clear
+ // the stream; drop() now to release the slot.
+ drop(slot_guard);
+ self.record_rpc(method, start, "timeout");
+ return Err(IpcError::Timeout);
+ }
+ };
+ match first {
+ Ok(v) => {
+ // Clean protocol completion — don't reset the socket.
+ slot_guard.disarm();
+ drop(slot_guard);
+ self.record_rpc(method, start, "ok");
+ Ok(v)
+ }
+ Err(e) if is_transport_error(&e) => {
+ info!(
+ method,
+ slot = slot_guard.slot_mut().id,
+ error = %ErrChain(&e),
+ "IPC transport error — resetting slot and retrying once"
+ );
+ // Leave armed so Drop clears the stream; checkout
+ // again for the retry so we preferentially land on a
+ // different slot. With pool_size=1 this is the same
+ // slot (will reconnect on the retry's ensure path).
+ drop(slot_guard);
+ if let Some(m) = &self.metrics {
+ m.ipc_reconnect_total.inc();
+ }
+ let mut retry_guard = self.pool.acquire().await;
+ retry_guard.arm();
+ let second = timeout(
+ self.request_timeout,
+ self.call_inner::<Resp>(method, &payload, retry_guard.slot_mut()),
+ )
+ .await;
+ match second {
+ Ok(Ok(v)) => {
+ retry_guard.disarm();
+ drop(retry_guard);
+ self.record_rpc(method, start, "ok_after_retry");
+ Ok(v)
+ }
+ Ok(Err(e)) => {
+ // Armed → Drop clears the stream.
+ drop(retry_guard);
+ self.record_rpc(method, start, error_label(&e));
+ Err(e)
+ }
+ Err(_) => {
+ // Armed → Drop clears the stream.
+ drop(retry_guard);
+ self.record_rpc(method, start, "timeout");
+ Err(IpcError::Timeout)
+ }
+ }
+ }
+ Err(e) => {
+ // Non-transport error from call_inner (Server /
+ // VersionMismatch / Decode / FrameTooLarge / Encode).
+ // For Decode / FrameTooLarge the stream may be
+ // desynchronized, so leave the guard armed → Drop
+ // clears it. For Server / VersionMismatch / Encode
+ // the protocol completed cleanly, so disarm.
+ if !matches!(e, IpcError::Decode(_) | IpcError::FrameTooLarge(_)) {
+ slot_guard.disarm();
+ }
+ drop(slot_guard);
+ self.record_rpc(method, start, error_label(&e));
+ Err(e)
+ }
+ }
+ }
+
+ /// Send one request through the multiplexed transport and decode
+ /// the typed response. Mirrors `call_inner` for the pool path:
+ /// returns the same [`IpcError`] taxonomy so the caller's error
+ /// handling is identical regardless of transport.
+ async fn mux_call<Resp>(
+ &self,
+ mux: &MuxClient,
+ method: &str,
+ request_id: String,
+ payload: &[u8],
+ ) -> Result<Resp, IpcError>
+ where
+ Resp: DeserializeOwned,
+ {
+ let raw = match timeout(
+ self.request_timeout,
+ mux.call_raw(request_id, payload.to_vec()),
+ )
+ .await
+ {
+ Ok(r) => r,
+ Err(_) => return Err(IpcError::Timeout),
+ };
+ let frame = match raw {
+ Ok(f) => f,
+ Err(MuxError::Io(e)) => return Err(IpcError::Io(e)),
+ Err(MuxError::FrameTooLarge(n)) => return Err(IpcError::FrameTooLarge(n)),
+ Err(MuxError::ConnectionLost) => {
+ return Err(IpcError::Io(std::io::Error::new(
+ std::io::ErrorKind::ConnectionReset,
+ "mux: connection lost while waiting for response",
+ )));
+ }
+ Err(MuxError::Shutdown) => {
+ return Err(IpcError::Io(std::io::Error::new(
+ std::io::ErrorKind::NotConnected,
+ "mux: actor exited",
+ )));
+ }
+ };
+ if let Some(m) = &self.metrics {
+ m.ipc_response_bytes
+ .with_label_values(&[method])
+ .observe(frame.len() as f64);
+ }
+ let envelope: ResponseEnvelope<Resp> = rmp_serde::from_slice(&frame)?;
+ if envelope.version != IPC_VERSION {
+ return Err(IpcError::VersionMismatch {
+ got: envelope.version,
+ });
+ }
+ if !envelope.ok {
+ return Err(IpcError::Server(envelope.error.unwrap_or_default()));
+ }
+ envelope
+ .body
+ .ok_or_else(|| IpcError::Server("response ok=true but body missing".to_string()))
+ }
+
+ fn record_rpc(&self, method: &str, start: std::time::Instant, result: &str) {
+ let elapsed = start.elapsed();
+ if let Some(m) = &self.metrics {
+ m.ipc_request_seconds
+ .with_label_values(&[method, result])
+ .observe(elapsed.as_secs_f64());
+ }
+ let elapsed_ms = elapsed.as_millis();
+ if elapsed_ms >= SLOW_RPC_WARN_MS && (result == "ok" || result == "ok_after_retry") {
+ warn!(
+ method,
+ result,
+ elapsed_ms = elapsed_ms as u64,
+ threshold_ms = SLOW_RPC_WARN_MS as u64,
+ "slow IPC RPC — Python side took longer than expected"
+ );
+ }
+ }
+
+ async fn call_inner<Resp>(
+ &self,
+ method: &str,
+ payload: &[u8],
+ slot: &mut Slot,
+ ) -> Result<Resp, IpcError>
+ where
+ Resp: DeserializeOwned,
+ {
+ // The slot is checked out exclusively to this call, so no lock
+ // is needed around the I/O. Lazy-connect on first use (or after
+ // a prior transport error cleared the stream).
+ if slot.stream.is_none() {
+ match UnixStream::connect(&self.socket_path).await {
+ Ok(s) => {
+ info!(
+ socket = %self.socket_path.display(),
+ slot = slot.id,
+ "connected IPC socket"
+ );
+ if let Some(m) = &self.metrics {
+ m.ipc_connect_total.with_label_values(&["ok"]).inc();
+ }
+ slot.stream = Some(s);
+ }
+ Err(e) => {
+ if let Some(m) = &self.metrics {
+ m.ipc_connect_total.with_label_values(&["error"]).inc();
+ }
+ warn!(
+ socket = %self.socket_path.display(),
+ slot = slot.id,
+ error = %ErrChain(&e),
+ "IPC connect failed — will surface to caller for retry"
+ );
+ return Err(IpcError::Io(e));
+ }
+ }
+ }
+ let stream = slot
+ .stream
+ .as_mut()
+ .expect("stream was just populated under exclusive slot ownership");
+
+ let len = u32::try_from(payload.len()).map_err(|_| IpcError::FrameTooLarge(u32::MAX))?;
+ stream.write_all(&len.to_be_bytes()).await?;
+ stream.write_all(payload).await?;
+ stream.flush().await?;
+
+ let mut len_buf = [0u8; 4];
+ stream.read_exact(&mut len_buf).await?;
+ let resp_len = u32::from_be_bytes(len_buf);
+ if resp_len as usize > MAX_FRAME_BYTES {
+ return Err(IpcError::FrameTooLarge(resp_len));
+ }
+ let mut resp_buf = vec![0u8; resp_len as usize];
+ stream.read_exact(&mut resp_buf).await?;
+ if let Some(m) = &self.metrics {
+ m.ipc_response_bytes
+ .with_label_values(&[method])
+ .observe(resp_buf.len() as f64);
+ }
+
+ let envelope: ResponseEnvelope<Resp> = rmp_serde::from_slice(&resp_buf)?;
+ if envelope.version != IPC_VERSION {
+ return Err(IpcError::VersionMismatch {
+ got: envelope.version,
+ });
+ }
+ if !envelope.ok {
+ return Err(IpcError::Server(envelope.error.unwrap_or_default()));
+ }
+ envelope
+ .body
+ .ok_or_else(|| IpcError::Server("response ok=true but body missing".to_string()))
+ }
+
+ /// Process one streaming generation request. Unlike normal IPC RPCs,
+ /// this method receives a sequence of response envelopes:
+ /// `publish` / `in_progress` / `ack` / `nak` events followed by
+ /// `done`. The Rust sidecar owns the real NATS client and JetStream
+ /// message settlement; Python owns generation adapter execution and
+ /// chunk encoding.
+ pub async fn process_generate<F, Fut>(
+ &self,
+ req: ProcessGenerateRequest,
+ mut on_event: F,
+ ) -> Result<(), IpcError>
+ where
+ F: FnMut(GenerateEvent) -> Fut,
+ Fut: std::future::Future<Output = Result<(), IpcError>>,
+ {
+ let request_id = self.next_id();
+ let envelope = RequestEnvelope {
+ version: IPC_VERSION,
+ method: METHOD_PROCESS_GENERATE,
+ request_id: request_id.clone(),
+ body: req,
+ };
+ let payload = rmp_serde::to_vec_named(&envelope)?;
+ if let Some(m) = &self.metrics {
+ m.ipc_request_bytes
+ .with_label_values(&[METHOD_PROCESS_GENERATE])
+ .observe(payload.len() as f64);
+ }
+ let start = std::time::Instant::now();
+ let result = self
+ .process_generate_inner(&request_id, &payload, &mut on_event)
+ .await;
+ let label = match &result {
+ Ok(()) => "ok",
+ Err(e) => error_label(e),
+ };
+ self.record_rpc(METHOD_PROCESS_GENERATE, start, label);
+ result
+ }
+
+ async fn process_generate_inner<F, Fut>(
+ &self,
+ request_id: &str,
+ payload: &[u8],
+ on_event: &mut F,
+ ) -> Result<(), IpcError>
+ where
+ F: FnMut(GenerateEvent) -> Fut,
+ Fut: std::future::Future<Output = Result<(), IpcError>>,
+ {
+ let mut stream = UnixStream::connect(&self.socket_path).await?;
+ if let Some(m) = &self.metrics {
+ m.ipc_connect_total.with_label_values(&["ok"]).inc();
+ }
+ let len = u32::try_from(payload.len()).map_err(|_| IpcError::FrameTooLarge(u32::MAX))?;
+ stream.write_all(&len.to_be_bytes()).await?;
+ stream.write_all(payload).await?;
+ stream.flush().await?;
+
+ loop {
+ let frame = timeout(generate_frame_timeout(), read_frame(&mut stream)).await;
+ let resp_buf = match frame {
+ Ok(Ok(bytes)) => bytes,
+ Ok(Err(e)) => return Err(e),
+ Err(_) => return Err(IpcError::Timeout),
+ };
+ if let Some(m) = &self.metrics {
+ m.ipc_response_bytes
+ .with_label_values(&[METHOD_PROCESS_GENERATE])
+ .observe(resp_buf.len() as f64);
+ }
+ let envelope: ResponseEnvelope<GenerateEvent> = rmp_serde::from_slice(&resp_buf)?;
+ if envelope.version != IPC_VERSION {
+ return Err(IpcError::VersionMismatch {
+ got: envelope.version,
+ });
+ }
+ if envelope.request_id != request_id {
+ return Err(IpcError::Server(format!(
+ "generate stream response request_id mismatch: got {}, expected {}",
+ envelope.request_id, request_id
+ )));
+ }
+ if !envelope.ok {
+ return Err(IpcError::Server(envelope.error.unwrap_or_default()));
+ }
+ let event = envelope.body.ok_or_else(|| {
+ IpcError::Server("generate stream ok=true but body missing".to_string())
+ })?;
+ if event.kind == "done" {
+ return Ok(());
+ }
+ on_event(event).await?;
+ }
+ }
+
+ // -- Typed method wrappers -------------------------------------------
+
+ pub async fn ping(&self, timestamp_ms: f64) -> Result<PingResponse, IpcError> {
+ self.call(METHOD_PING, PingRequest { timestamp_ms }).await
+ }
+
+ pub async fn ensure_model_ready(
+ &self,
+ model_id: impl Into<String>,
+ ) -> Result<EnsureModelReadyResponse, IpcError> {
+ self.call(
+ METHOD_ENSURE_MODEL_READY,
+ EnsureModelReadyRequest {
+ model_id: model_id.into(),
+ },
+ )
+ .await
+ }
+
+ pub async fn worker_capabilities(&self) -> Result<WorkerCapabilitiesResponse, IpcError> {
+ self.call(METHOD_WORKER_CAPABILITIES, WorkerCapabilitiesRequest {})
+ .await
+ }
+
+ pub async fn signal_generate_cancel(
+ &self,
+ request_id: impl Into<String>,
+ ) -> Result<SignalGenerateCancelResponse, IpcError> {
+ self.call(
+ METHOD_SIGNAL_GENERATE_CANCEL,
+ SignalGenerateCancelRequest {
+ request_id: request_id.into(),
+ },
+ )
+ .await
+ }
+
+ pub async fn process_encode_batch(
+ &self,
+ req: ProcessEncodeBatchRequest,
+ ) -> Result<BatchOutcome, IpcError> {
+ self.call(METHOD_PROCESS_ENCODE_BATCH, req).await
+ }
+
+ pub async fn process_score_batch(
+ &self,
+ req: ProcessScoreBatchRequest,
+ ) -> Result<BatchOutcome, IpcError> {
+ self.call(METHOD_PROCESS_SCORE_BATCH, req).await
+ }
+
+ pub async fn process_extract_batch(
+ &self,
+ req: ProcessExtractBatchRequest,
+ ) -> Result<BatchOutcome, IpcError> {
+ self.call(METHOD_PROCESS_EXTRACT_BATCH, req).await
+ }
+
+ /// Dispatch a pre-formed batch through the `RunBatch` RPC. Every
+ /// batch that comes out of the Rust-side
+ /// scheduler is shipped through this path; legacy per-op paths
+ /// (`process_*_batch`) stay available for backends that don't
+ /// implement `run_batch` and for unit tests that don't wire a
+ /// scheduler.
+ pub async fn run_batch(&self, req: RunBatchRequest) -> Result<BatchOutcome, IpcError> {
+ self.call(METHOD_RUN_BATCH, req).await
+ }
+
+ pub async fn apply_model_config(
+ &self,
+ req: ApplyModelConfigRequest,
+ ) -> Result<ApplyModelConfigResponse, IpcError> {
+ self.call(METHOD_APPLY_MODEL_CONFIG, req).await
+ }
+
+ pub async fn drain(&self, deadline_ms: u64) -> Result<DrainResponse, IpcError> {
+ self.call(METHOD_DRAIN, DrainRequest { deadline_ms }).await
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::AtomicUsize;
+ use std::sync::Arc;
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::net::UnixListener;
+ use tokio::time::Instant;
+
+ fn short_sock_path() -> PathBuf {
+ // Match the Python test helper — AF_UNIX paths on macOS are <=104 chars.
+ let base = std::env::var("TMPDIR").unwrap_or_else(|_| "/tmp".to_string());
+ let base = if base.len() > 20 {
+ "/tmp".to_string()
+ } else {
+ base
+ };
+ let name = format!("sie-w-{}.sock", uuid::Uuid::new_v4().simple());
+ PathBuf::from(base).join(name)
+ }
+
+ /// Tiny in-process echo server: reads a request frame and replies with
+ /// a fixed response envelope. Enough to exercise framing + typed call.
+ async fn spawn_echo<F>(path: PathBuf, handler: F) -> tokio::task::JoinHandle<()>
+ where
+ F: Fn(&[u8]) -> Vec<u8> + Send + Sync + 'static,
+ {
+ let _ = tokio::fs::remove_file(&path).await;
+ let listener = UnixListener::bind(&path).unwrap();
+ let handler = Arc::new(handler);
+ tokio::spawn(async move {
+ loop {
+ let (mut sock, _) = match listener.accept().await {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ let handler = Arc::clone(&handler);
+ tokio::spawn(async move {
+ loop {
+ let mut len_buf = [0u8; 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![0u8; n];
+ if sock.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ let resp = (handler)(&buf);
+ 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;
+ }
+ }
+ });
+ }
+ })
+ }
+
+ /// Echo server variant whose per-frame handler can await — lets tests
+ /// inject artificial per-request latency to exercise concurrency.
+ async fn spawn_echo_async<F, Fut>(path: PathBuf, handler: F) -> tokio::task::JoinHandle<()>
+ where
+ F: Fn(Vec<u8>) -> Fut + Send + Sync + 'static,
+ Fut: std::future::Future<Output = Vec<u8>> + Send + 'static,
+ {
+ let _ = tokio::fs::remove_file(&path).await;
+ let listener = UnixListener::bind(&path).unwrap();
+ let handler = Arc::new(handler);
+ tokio::spawn(async move {
+ loop {
+ let (mut sock, _) = match listener.accept().await {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ let handler = Arc::clone(&handler);
+ tokio::spawn(async move {
+ loop {
+ let mut len_buf = [0u8; 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![0u8; n];
+ if sock.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ let resp = (handler)(buf).await;
+ 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 ping_reply_bytes(req_bytes: &[u8], worker_id: &str) -> Vec<u8> {
+ let req: serde_json::Value = rmp_serde::from_slice(req_bytes).unwrap();
+ let request_id = req["request_id"].as_str().unwrap().to_string();
+ let envelope = serde_json::json!({
+ "version": IPC_VERSION,
+ "request_id": request_id,
+ "ok": true,
+ "body": serde_json::json!({"timestamp_ms": 0.0, "worker_id": worker_id}),
+ "error": serde_json::Value::Null,
+ });
+ rmp_serde::to_vec_named(&envelope).unwrap()
+ }
+
+ #[tokio::test]
+ async fn ping_roundtrips_typed() {
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let _server = spawn_echo(path_clone, |req_bytes| {
+ let req: serde_json::Value = rmp_serde::from_slice(req_bytes).unwrap();
+ let request_id = req["request_id"].as_str().unwrap().to_string();
+ let body = rmp_serde::to_vec_named(&serde_json::json!({
+ "timestamp_ms": 999.0,
+ "worker_id": "echo",
+ }))
+ .unwrap();
+ let envelope = serde_json::json!({
+ "version": IPC_VERSION,
+ "request_id": request_id,
+ "ok": true,
+ "body": rmp_serde::from_slice::<serde_json::Value>(&body).unwrap(),
+ "error": serde_json::Value::Null,
+ });
+ rmp_serde::to_vec_named(&envelope).unwrap()
+ })
+ .await;
+
+ tokio::task::yield_now().await;
+ let client = IpcClient::new(path);
+ let resp = client.ping(42.0).await.unwrap();
+ assert_eq!(resp.worker_id, "echo");
+ assert_eq!(resp.timestamp_ms, 999.0);
+ }
+
+ #[tokio::test]
+ async fn server_error_surfaces_as_ipc_server() {
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let _server = spawn_echo(path_clone, |req_bytes| {
+ let req: serde_json::Value = rmp_serde::from_slice(req_bytes).unwrap();
+ let request_id = req["request_id"].as_str().unwrap().to_string();
+ let envelope = serde_json::json!({
+ "version": IPC_VERSION,
+ "request_id": request_id,
+ "ok": false,
+ "body": serde_json::Value::Null,
+ "error": "boom",
+ });
+ rmp_serde::to_vec_named(&envelope).unwrap()
+ })
+ .await;
+
+ tokio::task::yield_now().await;
+ let client = IpcClient::new(path);
+ let err = client.ping(1.0).await.unwrap_err();
+ match err {
+ IpcError::Server(msg) => assert_eq!(msg, "boom"),
+ other => panic!("expected Server error, got {other:?}"),
+ }
+ }
+
+ #[tokio::test]
+ async fn reconnect_retry_after_broken_pipe() {
+ // Server drops the connection on the very first accepted frame, then
+ // replies normally on subsequent connections. We expect the client
+ // to transparently retry once and succeed.
+ use std::sync::atomic::{AtomicU32, Ordering};
+
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let _ = tokio::fs::remove_file(&path_clone).await;
+ let listener = UnixListener::bind(&path_clone).unwrap();
+ let connections = Arc::new(AtomicU32::new(0));
+ let connections_clone = Arc::clone(&connections);
+
+ let _server = tokio::spawn(async move {
+ loop {
+ let (mut sock, _) = match listener.accept().await {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ let n = connections_clone.fetch_add(1, Ordering::SeqCst);
+ tokio::spawn(async move {
+ let mut len_buf = [0u8; 4];
+ if sock.read_exact(&mut len_buf).await.is_err() {
+ return;
+ }
+ let frame_len = u32::from_be_bytes(len_buf) as usize;
+ let mut buf = vec![0u8; frame_len];
+ if sock.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ if n == 0 {
+ drop(sock);
+ return;
+ }
+ let req: serde_json::Value = rmp_serde::from_slice(&buf).unwrap();
+ let request_id = req["request_id"].as_str().unwrap().to_string();
+ let envelope = serde_json::json!({
+ "version": IPC_VERSION,
+ "request_id": request_id,
+ "ok": true,
+ "body": serde_json::json!({"timestamp_ms": 1.0, "worker_id": "after-retry"}),
+ "error": serde_json::Value::Null,
+ });
+ let resp = rmp_serde::to_vec_named(&envelope).unwrap();
+ let len = (resp.len() as u32).to_be_bytes();
+ let _ = sock.write_all(&len).await;
+ let _ = sock.write_all(&resp).await;
+ let _ = sock.flush().await;
+ });
+ }
+ });
+
+ tokio::task::yield_now().await;
+ let client = IpcClient::new(path);
+ let resp = client.ping(1.0).await.expect("retry should succeed");
+ assert_eq!(resp.worker_id, "after-retry");
+ assert_eq!(connections.load(Ordering::SeqCst), 2);
+ }
+
+ #[tokio::test]
+ async fn server_error_is_not_retried() {
+ // A protocol-level `ok=false` response is a logical error — retrying
+ // would just repeat the same error, so we should surface it on the
+ // first attempt and leave the connection alive.
+ use std::sync::atomic::{AtomicU32, Ordering};
+
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let _ = tokio::fs::remove_file(&path_clone).await;
+ let listener = UnixListener::bind(&path_clone).unwrap();
+ let connections = Arc::new(AtomicU32::new(0));
+ let connections_clone = Arc::clone(&connections);
+
+ let _server = tokio::spawn(async move {
+ loop {
+ let (mut sock, _) = match listener.accept().await {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ connections_clone.fetch_add(1, Ordering::SeqCst);
+ tokio::spawn(async move {
+ loop {
+ let mut len_buf = [0u8; 4];
+ if sock.read_exact(&mut len_buf).await.is_err() {
+ return;
+ }
+ let frame_len = u32::from_be_bytes(len_buf) as usize;
+ let mut buf = vec![0u8; frame_len];
+ if sock.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ let req: serde_json::Value = rmp_serde::from_slice(&buf).unwrap();
+ let request_id = req["request_id"].as_str().unwrap().to_string();
+ let envelope = serde_json::json!({
+ "version": IPC_VERSION,
+ "request_id": request_id,
+ "ok": false,
+ "body": serde_json::Value::Null,
+ "error": "logic error",
+ });
+ let resp = rmp_serde::to_vec_named(&envelope).unwrap();
+ 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;
+ }
+ let _ = sock.flush().await;
+ }
+ });
+ }
+ });
+
+ tokio::task::yield_now().await;
+ let client = IpcClient::new(path);
+ let err = client.ping(1.0).await.unwrap_err();
+ assert!(matches!(err, IpcError::Server(_)));
+ assert_eq!(connections.load(Ordering::SeqCst), 1);
+ }
+
+ #[tokio::test]
+ async fn is_transport_error_classifies_correctly() {
+ let io_broken = IpcError::Io(std::io::Error::from(std::io::ErrorKind::BrokenPipe));
+ assert!(is_transport_error(&io_broken));
+ let io_reset = IpcError::Io(std::io::Error::from(std::io::ErrorKind::ConnectionReset));
+ assert!(is_transport_error(&io_reset));
+ let io_eof = IpcError::Io(std::io::Error::from(std::io::ErrorKind::UnexpectedEof));
+ assert!(is_transport_error(&io_eof));
+ let server = IpcError::Server("x".into());
+ assert!(!is_transport_error(&server));
+ let ver = IpcError::VersionMismatch { got: 99 };
+ assert!(!is_transport_error(&ver));
+ let timeout = IpcError::Timeout;
+ assert!(!is_transport_error(&timeout));
+ }
+
+ #[tokio::test]
+ async fn concurrent_reset_does_not_panic_on_connect() {
+ // Regression for a TOCTOU that existed in the single-socket
+ // version. With the pool, reset() nukes idle slots' streams and
+ // any live call just lazily reconnects on its own slot — never
+ // panics, never deadlocks. This test hammers reset() against 32
+ // concurrent pings and asserts neither.
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let _server = spawn_echo(path_clone, |req_bytes| ping_reply_bytes(req_bytes, "x")).await;
+
+ tokio::task::yield_now().await;
+ let client = Arc::new(IpcClient::new(path));
+ let stop = Arc::new(AtomicBool::new(false));
+
+ let resetter = {
+ let client = Arc::clone(&client);
+ let stop = Arc::clone(&stop);
+ tokio::spawn(async move {
+ while !stop.load(Ordering::Relaxed) {
+ client.reset().await;
+ tokio::task::yield_now().await;
+ }
+ })
+ };
+
+ let mut pings = Vec::with_capacity(32);
+ for _ in 0..32 {
+ let client = Arc::clone(&client);
+ pings.push(tokio::spawn(async move { client.ping(1.0).await }));
+ }
+ for p in pings {
+ let _ = p.await;
+ }
+
+ stop.store(true, Ordering::Relaxed);
+ let _ = resetter.await;
+ }
+
+ #[tokio::test]
+ async fn version_mismatch_is_detected() {
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let _server = spawn_echo(path_clone, |req_bytes| {
+ let req: serde_json::Value = rmp_serde::from_slice(req_bytes).unwrap();
+ let request_id = req["request_id"].as_str().unwrap().to_string();
+ let envelope = serde_json::json!({
+ "version": 999,
+ "request_id": request_id,
+ "ok": true,
+ "body": serde_json::json!({"timestamp_ms": 0.0, "worker_id": "x"}),
+ "error": serde_json::Value::Null,
+ });
+ rmp_serde::to_vec_named(&envelope).unwrap()
+ })
+ .await;
+
+ tokio::task::yield_now().await;
+ let client = IpcClient::new(path);
+ let err = client.ping(1.0).await.unwrap_err();
+ assert!(matches!(err, IpcError::VersionMismatch { got: 999 }));
+ }
+
+ // -----------------------------------------------------------------
+ // Pool-specific tests (new).
+ // -----------------------------------------------------------------
+
+ #[tokio::test]
+ async fn pool_opens_independent_connections_per_slot() {
+ // With pool_size=N and N concurrent blocking RPCs, the server must
+ // accept exactly N connections — proving the client did not
+ // serialize them on a single socket.
+ use std::sync::atomic::{AtomicU32, Ordering};
+
+ const N: usize = 4;
+ const HOLD: Duration = Duration::from_millis(200);
+
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let _ = tokio::fs::remove_file(&path_clone).await;
+ let listener = UnixListener::bind(&path_clone).unwrap();
+ let accepted = Arc::new(AtomicU32::new(0));
+ let accepted_clone = Arc::clone(&accepted);
+
+ let _server = tokio::spawn(async move {
+ loop {
+ let (mut sock, _) = match listener.accept().await {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ accepted_clone.fetch_add(1, Ordering::SeqCst);
+ tokio::spawn(async move {
+ loop {
+ let mut len_buf = [0u8; 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![0u8; n];
+ if sock.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ // Artificial latency so overlap is observable.
+ tokio::time::sleep(HOLD).await;
+ let resp = ping_reply_bytes(&buf, "pooled");
+ let len = (resp.len() as u32).to_be_bytes();
+ let _ = sock.write_all(&len).await;
+ let _ = sock.write_all(&resp).await;
+ let _ = sock.flush().await;
+ }
+ });
+ }
+ });
+
+ tokio::task::yield_now().await;
+ let client = Arc::new(IpcClient::new_pool(path, N));
+ assert_eq!(client.pool_size(), N);
+
+ let start = Instant::now();
+ let mut handles = Vec::with_capacity(N);
+ for _ in 0..N {
+ let client = Arc::clone(&client);
+ handles.push(tokio::spawn(async move { client.ping(1.0).await }));
+ }
+ for h in handles {
+ h.await.unwrap().expect("ping");
+ }
+ let elapsed = start.elapsed();
+
+ // Upper bound: if requests were serialized on one socket it
+ // would be ≥ N * HOLD = 800ms. With the pool they run in
+ // parallel and should finish in ~HOLD + scheduling jitter.
+ assert!(
+ elapsed < HOLD * 2,
+ "pooled pings took {:?}, expected ~{:?} (serialized would be ~{:?})",
+ elapsed,
+ HOLD,
+ HOLD * N as u32,
+ );
+
+ // The server must have accepted one connection per slot.
+ // `>= N` covers the benign case where a slot's reconnect
+ // handler is still pending on shutdown, but on the steady
+ // state path we expect exactly N.
+ let n = accepted.load(Ordering::SeqCst);
+ assert_eq!(n, N as u32, "expected exactly one accept per slot, got {n}",);
+ }
+
+ #[tokio::test]
+ async fn pool_isolates_slow_rpcs_from_fast_ones() {
+ // One slot is artificially slow (5s). Fire N-1 other calls; they
+ // must complete on the other slots and must NOT wait for the
+ // slow one. This is the head-of-line isolation guarantee that
+ // rules out a naive round-robin scheme.
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ const N: usize = 4;
+ const FAST: usize = N - 1;
+ const SLOW_HOLD: Duration = Duration::from_secs(3);
+ const FAST_BUDGET: Duration = Duration::from_millis(500);
+
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let first_slot = Arc::new(AtomicBool::new(true));
+ let first_slot_clone = Arc::clone(&first_slot);
+
+ let _server = spawn_echo_async(path_clone, move |buf| {
+ let is_first = first_slot_clone.swap(false, Ordering::SeqCst);
+ async move {
+ if is_first {
+ tokio::time::sleep(SLOW_HOLD).await;
+ }
+ ping_reply_bytes(&buf, if is_first { "slow" } else { "fast" })
+ }
+ })
+ .await;
+
+ tokio::task::yield_now().await;
+ let client = Arc::new(IpcClient::new_pool(path, N));
+
+ // Kick off the slow one first so it grabs slot 0.
+ let slow_client = Arc::clone(&client);
+ let slow = tokio::spawn(async move { slow_client.ping(1.0).await });
+
+ // Give the slow ping a moment to be in-flight on its slot.
+ tokio::time::sleep(Duration::from_millis(50)).await;
+
+ // Now fire FAST concurrent pings; they must all return inside
+ // FAST_BUDGET even though the slow slot is still holding.
+ let start = Instant::now();
+ let mut fasts = Vec::with_capacity(FAST);
+ for _ in 0..FAST {
+ let client = Arc::clone(&client);
+ fasts.push(tokio::spawn(async move { client.ping(2.0).await }));
+ }
+ for h in fasts {
+ h.await.unwrap().expect("fast ping");
+ }
+ let fast_elapsed = start.elapsed();
+ assert!(
+ fast_elapsed < FAST_BUDGET,
+ "fast pings took {:?}, expected < {:?} — slow RPC was blocking the pool",
+ fast_elapsed,
+ FAST_BUDGET,
+ );
+
+ // Let the slow one finish so we don't leak its task.
+ let _ = slow.await;
+ }
+
+ #[tokio::test]
+ async fn pool_saturation_blocks_n_plus_one_until_a_slot_frees() {
+ // Pool size = 2 with two in-flight slow RPCs. A third caller
+ // must wait until one of the first two returns. This exercises
+ // the Semaphore-based fair-FIFO acquire.
+ const N: usize = 2;
+ const HOLD: Duration = Duration::from_millis(300);
+
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let _server = spawn_echo_async(path_clone, |buf| async move {
+ tokio::time::sleep(HOLD).await;
+ ping_reply_bytes(&buf, "held")
+ })
+ .await;
+
+ tokio::task::yield_now().await;
+ let client = Arc::new(IpcClient::new_pool(path, N));
+
+ let c1 = Arc::clone(&client);
+ let c2 = Arc::clone(&client);
+ let h1 = tokio::spawn(async move { c1.ping(1.0).await });
+ let h2 = tokio::spawn(async move { c2.ping(2.0).await });
+
+ // Let h1 / h2 acquire the two slots.
+ tokio::time::sleep(Duration::from_millis(30)).await;
+
+ // Third caller — must be forced to wait at acquire() for >= (HOLD - 30ms).
+ let c3 = Arc::clone(&client);
+ let third_start = Instant::now();
+ let h3 = tokio::spawn(async move { c3.ping(3.0).await });
+
+ h1.await.unwrap().expect("h1");
+ h2.await.unwrap().expect("h2");
+ h3.await.unwrap().expect("h3");
+ let third_elapsed = third_start.elapsed();
+ assert!(
+ third_elapsed >= HOLD.saturating_sub(Duration::from_millis(80)),
+ "third caller returned in {:?}; expected to wait at least ~{:?} \
+ for a pool slot to free",
+ third_elapsed,
+ HOLD,
+ );
+ }
+
+ #[tokio::test]
+ async fn pool_reset_on_transport_error_is_scoped_to_one_slot() {
+ // Force a transport error on exactly one connection: the per-
+ // connection handler drops the socket on its first frame. With
+ // pool_size=4, reset semantics must keep the other 3 slots'
+ // sockets alive (no `reset_all`), and the client's one-shot
+ // retry must succeed on a fresh slot.
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ const N: usize = 4;
+
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let _ = tokio::fs::remove_file(&path_clone).await;
+ let listener = UnixListener::bind(&path_clone).unwrap();
+ let connections = Arc::new(AtomicUsize::new(0));
+ let connections_clone = Arc::clone(&connections);
+
+ let _server = tokio::spawn(async move {
+ loop {
+ let (mut sock, _) = match listener.accept().await {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ let n = connections_clone.fetch_add(1, Ordering::SeqCst);
+ tokio::spawn(async move {
+ if n == 0 {
+ // Read one frame then drop — simulate a mid-
+ // session EOF on slot 0.
+ let mut len_buf = [0u8; 4];
+ if sock.read_exact(&mut len_buf).await.is_err() {
+ return;
+ }
+ let frame_len = u32::from_be_bytes(len_buf) as usize;
+ let mut buf = vec![0u8; frame_len];
+ let _ = sock.read_exact(&mut buf).await;
+ drop(sock);
+ return;
+ }
+ loop {
+ let mut len_buf = [0u8; 4];
+ if sock.read_exact(&mut len_buf).await.is_err() {
+ return;
+ }
+ let frame_len = u32::from_be_bytes(len_buf) as usize;
+ let mut buf = vec![0u8; frame_len];
+ if sock.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ let resp = ping_reply_bytes(&buf, "ok");
+ let len = (resp.len() as u32).to_be_bytes();
+ let _ = sock.write_all(&len).await;
+ let _ = sock.write_all(&resp).await;
+ let _ = sock.flush().await;
+ }
+ });
+ }
+ });
+
+ tokio::task::yield_now().await;
+ let client = Arc::new(IpcClient::new_pool(path, N));
+
+ // First ping: hits slot 0, triggers retry after the drop, retry
+ // lands on a different slot and succeeds.
+ let resp = client.ping(1.0).await.expect("retry should succeed");
+ assert_eq!(resp.worker_id, "ok");
+
+ // Fire three more pings back-to-back — each should succeed on
+ // first try using the healthy slots (1..N).
+ for _ in 0..3 {
+ let r = client.ping(2.0).await.expect("healthy slots keep working");
+ assert_eq!(r.worker_id, "ok");
+ }
+
+ // Connection budget: 1 failed + at least 1 healthy for the
+ // retry + up to 3 more for subsequent pings landing on already-
+ // connected slots. The exact accept count is scheduling-order
+ // dependent so we only assert the key bound: we did NOT take
+ // out every slot (which would look like N+1 accepts at minimum,
+ // one per slot's reconnect after a reset_all).
+ let accepted = connections.load(Ordering::SeqCst);
+ assert!(
+ accepted >= 2,
+ "expected at least 2 connections (1 failing + 1 retry), got {accepted}"
+ );
+ assert!(
+ accepted < N * 2,
+ "accept count {accepted} suggests reset_all fired; should be scoped to one slot"
+ );
+ }
+
+ #[tokio::test]
+ async fn pool_size_one_preserves_legacy_semantics() {
+ // Belt-and-suspenders: `new()` must behave exactly like the
+ // pre-pool version — single connection, strict serialization
+ // of concurrent callers. This test locks the contract in.
+ const HOLD: Duration = Duration::from_millis(150);
+
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let accepted = Arc::new(AtomicUsize::new(0));
+ let accepted_clone = Arc::clone(&accepted);
+ let _ = tokio::fs::remove_file(&path_clone).await;
+ let listener = UnixListener::bind(&path_clone).unwrap();
+
+ let _server = tokio::spawn(async move {
+ loop {
+ let (mut sock, _) = match listener.accept().await {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ accepted_clone.fetch_add(1, Ordering::SeqCst);
+ tokio::spawn(async move {
+ loop {
+ let mut len_buf = [0u8; 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![0u8; n];
+ if sock.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ tokio::time::sleep(HOLD).await;
+ let resp = ping_reply_bytes(&buf, "single");
+ let len = (resp.len() as u32).to_be_bytes();
+ let _ = sock.write_all(&len).await;
+ let _ = sock.write_all(&resp).await;
+ let _ = sock.flush().await;
+ }
+ });
+ }
+ });
+
+ tokio::task::yield_now().await;
+ let client = Arc::new(IpcClient::new(path));
+ assert_eq!(client.pool_size(), 1);
+
+ let start = Instant::now();
+ let h1 = {
+ let c = Arc::clone(&client);
+ tokio::spawn(async move { c.ping(1.0).await })
+ };
+ let h2 = {
+ let c = Arc::clone(&client);
+ tokio::spawn(async move { c.ping(2.0).await })
+ };
+ h1.await.unwrap().expect("h1");
+ h2.await.unwrap().expect("h2");
+ let elapsed = start.elapsed();
+
+ // Serialized: should take ~2 * HOLD.
+ assert!(
+ elapsed >= HOLD * 2 - Duration::from_millis(40),
+ "legacy single-connection client should serialize; took only {:?}",
+ elapsed,
+ );
+ // Exactly one connection opened (serialized sharing).
+ assert_eq!(accepted.load(Ordering::SeqCst), 1);
+ }
+
+ // =====================================================================
+ // Stress, cancellation, and invariant tests
+ // =====================================================================
+ //
+ // The tests above lock in the happy-path pool semantics. The ones
+ // below stress it the way production will: hundreds of concurrent
+ // callers, futures being cancelled mid-RPC by caller-side
+ // deadlines, oversubscribed pools, and post-burst metric
+ // consistency. If any of these regress we will get correctness
+ // bugs in prod — particularly the cancellation tests.
+ // =====================================================================
+
+ /// Stress: N=8 pool, 256 concurrent callers, every one must
+ /// complete successfully. Exercises semaphore contention, FIFO
+ /// slot queueing, and metric correctness under heavy load.
+ #[tokio::test]
+ async fn stress_many_concurrent_callers_all_complete() {
+ const POOL: usize = 8;
+ const CONCURRENCY: usize = 256;
+ const SERVER_DELAY: Duration = Duration::from_millis(5);
+
+ let path = short_sock_path();
+ let _server = spawn_echo_async(path.clone(), |req| async move {
+ tokio::time::sleep(SERVER_DELAY).await;
+ ping_reply_bytes(&req, "stress")
+ })
+ .await;
+ tokio::task::yield_now().await;
+
+ let metrics = Arc::new(MetricsRegistry::new().unwrap());
+ let client = Arc::new(IpcClient::new_pool(path, POOL).with_metrics(Arc::clone(&metrics)));
+ assert_eq!(client.pool_size(), POOL);
+
+ let mut handles = Vec::with_capacity(CONCURRENCY);
+ for i in 0..CONCURRENCY {
+ let c = Arc::clone(&client);
+ handles.push(tokio::spawn(async move { c.ping(i as f64).await }));
+ }
+ for (i, h) in handles.into_iter().enumerate() {
+ h.await
+ .unwrap_or_else(|e| panic!("task {i} panicked: {e:?}"))
+ .unwrap_or_else(|e| panic!("task {i} ping failed: {e:?}"));
+ }
+
+ // After full drain: pool_inflight must be back to 0 and
+ // pool_size must still equal POOL.
+ assert_eq!(
+ metrics.ipc_pool_inflight.get(),
+ 0,
+ "inflight gauge leaked after {CONCURRENCY} completed calls"
+ );
+ assert_eq!(metrics.ipc_pool_size.get(), POOL as i64);
+
+ // Same client still works after the storm — slots weren't
+ // corrupted.
+ client.ping(9999.0).await.expect("post-stress ping");
+ }
+
+ /// Cancellation safety: if the caller drops the `call` Future
+ /// mid-RPC (what happens on a Tokio timeout wrapper, or gateway
+ /// deadline), the slot MUST be returned to the pool and the
+ /// next caller on that slot must not get a corrupted socket.
+ ///
+ /// This is the single most important concurrency invariant. A
+ /// regression here silently poisons the pool in production and
+ /// every subsequent request on the recycled slot sees either a
+ /// decode error or a stall.
+ #[tokio::test]
+ async fn dropping_future_mid_rpc_does_not_poison_slot() {
+ const POOL: usize = 2;
+ // Server holds responses just long enough that our 20ms
+ // caller deadline fires first. 150ms picked to dwarf any
+ // scheduler jitter.
+ const SERVER_HOLD: Duration = Duration::from_millis(150);
+
+ let path = short_sock_path();
+ let _server = spawn_echo_async(path.clone(), |req| async move {
+ tokio::time::sleep(SERVER_HOLD).await;
+ ping_reply_bytes(&req, "cancel-harness")
+ })
+ .await;
+ tokio::task::yield_now().await;
+
+ let metrics = Arc::new(MetricsRegistry::new().unwrap());
+ let client = Arc::new(IpcClient::new_pool(path, POOL).with_metrics(Arc::clone(&metrics)));
+
+ // Burn both pool slots with calls that will be cancelled.
+ for i in 0..POOL {
+ let c = Arc::clone(&client);
+ let res = tokio::time::timeout(Duration::from_millis(20), c.ping(i as f64)).await;
+ assert!(
+ res.is_err(),
+ "iter {i}: expected caller-side timeout, got {res:?}"
+ );
+ }
+ // Let Drop run and any server-side IO settle.
+ tokio::task::yield_now().await;
+ tokio::time::sleep(Duration::from_millis(30)).await;
+
+ // Key invariants:
+ // 1. inflight gauge back to zero → no slot leaked.
+ // 2. Subsequent calls succeed → slots were reconnected
+ // cleanly despite mid-I/O cancellation.
+ assert_eq!(
+ metrics.ipc_pool_inflight.get(),
+ 0,
+ "slot leaked after cancelled futures"
+ );
+
+ // Fire POOL+2 sequential calls on the "poisoned" slots — each
+ // must get a clean response, not a stale half-frame.
+ for i in 0..(POOL + 2) {
+ client
+ .ping((1000 + i) as f64)
+ .await
+ .unwrap_or_else(|e| panic!("post-cancel ping {i} got stale/corrupt slot: {e:?}"));
+ }
+ }
+
+ /// Timeout path: when `request_timeout` elapses the call returns
+ /// `IpcError::Timeout`, but the slot must be returned and
+ /// reusable. The socket is cleared so the next call reconnects.
+ #[tokio::test]
+ async fn timeout_returns_slot_and_allows_reuse() {
+ const POOL: usize = 1;
+ // Server: first request hangs forever, later requests answer
+ // immediately. Count accepted connections so we can assert
+ // that the post-timeout call reconnected on a fresh socket.
+ let path = short_sock_path();
+ let path_clone = path.clone();
+ let accept_count = Arc::new(AtomicUsize::new(0));
+ let accept_count_clone = Arc::clone(&accept_count);
+ let _ = tokio::fs::remove_file(&path_clone).await;
+ let listener = UnixListener::bind(&path_clone).unwrap();
+ let conn_idx = Arc::new(AtomicUsize::new(0));
+ let _server = tokio::spawn(async move {
+ loop {
+ let (mut sock, _) = match listener.accept().await {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ accept_count_clone.fetch_add(1, Ordering::SeqCst);
+ let idx = conn_idx.fetch_add(1, Ordering::SeqCst);
+ tokio::spawn(async move {
+ loop {
+ let mut len_buf = [0u8; 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![0u8; n];
+ if sock.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ if idx == 0 {
+ // Hang: never reply. The client-side
+ // request_timeout will fire.
+ std::future::pending::<()>().await;
+ return;
+ }
+ let resp = ping_reply_bytes(&buf, "timeout-reuse");
+ let len = (resp.len() as u32).to_be_bytes();
+ let _ = sock.write_all(&len).await;
+ let _ = sock.write_all(&resp).await;
+ let _ = sock.flush().await;
+ }
+ });
+ }
+ });
+
+ tokio::task::yield_now().await;
+ let metrics = Arc::new(MetricsRegistry::new().unwrap());
+ let client = Arc::new(
+ IpcClient::new_pool(path, POOL)
+ .with_timeout(Duration::from_millis(50))
+ .with_metrics(Arc::clone(&metrics)),
+ );
+
+ // First call: times out inside IpcClient::call.
+ let err = client.ping(1.0).await.unwrap_err();
+ assert!(matches!(err, IpcError::Timeout), "got {err:?}");
+ // Slot returned; no leak.
+ assert_eq!(metrics.ipc_pool_inflight.get(), 0);
+
+ // Second call: must get a brand new connection (the hung
+ // socket was clobbered by arm+Drop), not hang on the
+ // still-alive but desynchronized old stream.
+ let ok = client.ping(2.0).await.expect("post-timeout ping");
+ // Worker id baked into the reply proves we reached the
+ // "later connection" branch of the server.
+ assert_eq!(ok.worker_id, "timeout-reuse");
+ assert_eq!(metrics.ipc_pool_inflight.get(), 0);
+ // We should have seen at least two connections: the
+ // original (hung) and the reconnect.
+ assert!(
+ accept_count.load(Ordering::SeqCst) >= 2,
+ "expected reconnection after timeout, but server only saw {} connections",
+ accept_count.load(Ordering::SeqCst)
+ );
+ }
+
+ /// Fairness / no-starvation: with K callers >> N slots, every
+ /// caller must eventually complete. Catches scheduler bugs where
+ /// a single slot monopolizes the semaphore or the wake-chain
+ /// gets broken.
+ #[tokio::test]
+ async fn oversubscribed_pool_drains_without_starvation() {
+ const POOL: usize = 4;
+ const CALLERS: usize = 64;
+ const SERVER_DELAY: Duration = Duration::from_millis(20);
+
+ let path = short_sock_path();
+ let _server = spawn_echo_async(path.clone(), |req| async move {
+ tokio::time::sleep(SERVER_DELAY).await;
+ ping_reply_bytes(&req, "fair")
+ })
+ .await;
+ tokio::task::yield_now().await;
+
+ let client = Arc::new(IpcClient::new_pool(path, POOL));
+
+ // Fan out all callers simultaneously.
+ let mut handles = Vec::with_capacity(CALLERS);
+ let start = Instant::now();
+ for i in 0..CALLERS {
+ let c = Arc::clone(&client);
+ handles.push(tokio::spawn(async move { c.ping(i as f64).await }));
+ }
+
+ // Serial lower bound: CALLERS / POOL * SERVER_DELAY = 16 * 20ms = 320ms
+ // Generous upper bound: 3x the theoretical lower bound.
+ let budget = (SERVER_DELAY * CALLERS as u32 / POOL as u32) * 3;
+
+ for (i, h) in handles.into_iter().enumerate() {
+ let res = tokio::time::timeout(budget, h).await.unwrap_or_else(|_| {
+ panic!(
+ "caller {i} did not complete within {:?} — starvation or deadlock",
+ budget
+ )
+ });
+ res.unwrap()
+ .unwrap_or_else(|e| panic!("caller {i} failed: {e:?}"));
+ }
+ let elapsed = start.elapsed();
+ // Should NOT be fully serial — with POOL=4, ~4x speedup.
+ let fully_serial = SERVER_DELAY * CALLERS as u32;
+ assert!(
+ elapsed < fully_serial,
+ "oversubscribed pool looks serialized: elapsed {:?} >= fully_serial {:?}",
+ elapsed,
+ fully_serial
+ );
+ }
+
+ /// Metric invariant: `sie_worker_ipc_pool_inflight` must never go
+ /// negative, and must return to exactly 0 after every burst
+ /// (including bursts containing errors). Decrements happen
+ /// inside `SlotGuard::Drop`; an extra decrement on an error
+ /// path would cause an underflow that Prometheus would silently
+ /// clamp, hiding the bug in prod.
+ #[tokio::test]
+ async fn inflight_metric_returns_to_zero_after_mixed_burst() {
+ const POOL: usize = 4;
+ let path = short_sock_path();
+
+ // Echo server that randomly returns valid / invalid frames,
+ // triggering the full spectrum of result labels (ok, decode
+ // error, transport close).
+ let path_clone = path.clone();
+ let _ = tokio::fs::remove_file(&path_clone).await;
+ let listener = UnixListener::bind(&path_clone).unwrap();
+ let counter = Arc::new(AtomicUsize::new(0));
+ let counter_clone = Arc::clone(&counter);
+ let _server = tokio::spawn(async move {
+ loop {
+ let (mut sock, _) = match listener.accept().await {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ let counter = Arc::clone(&counter_clone);
+ tokio::spawn(async move {
+ loop {
+ let mut len_buf = [0u8; 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![0u8; n];
+ if sock.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ let idx = counter.fetch_add(1, Ordering::SeqCst);
+ let bucket = idx % 3;
+ if bucket == 0 {
+ // Valid reply.
+ let resp = ping_reply_bytes(&buf, "mixed");
+ let len = (resp.len() as u32).to_be_bytes();
+ let _ = sock.write_all(&len).await;
+ let _ = sock.write_all(&resp).await;
+ let _ = sock.flush().await;
+ } else if bucket == 1 {
+ // Close the socket mid-protocol → transport error on client.
+ return;
+ } else {
+ // Junk body → client Decode error.
+ let junk = b"\x00\x00\x00\x04junk";
+ let _ = sock.write_all(junk).await;
+ let _ = sock.flush().await;
+ return;
+ }
+ }
+ });
+ }
+ });
+
+ tokio::task::yield_now().await;
+ let metrics = Arc::new(MetricsRegistry::new().unwrap());
+ let client = Arc::new(IpcClient::new_pool(path, POOL).with_metrics(Arc::clone(&metrics)));
+
+ // Fire 32 concurrent calls. We don't care about individual
+ // outcomes — we care that the gauge reconciles at the end.
+ let mut handles = Vec::new();
+ for i in 0..32 {
+ let c = Arc::clone(&client);
+ handles.push(tokio::spawn(async move {
+ let _ = c.ping(i as f64).await;
+ }));
+ }
+ for h in handles {
+ let _ = h.await;
+ }
+ // Let all Drops settle.
+ tokio::time::sleep(Duration::from_millis(50)).await;
+
+ let inflight = metrics.ipc_pool_inflight.get();
+ assert_eq!(
+ inflight, 0,
+ "inflight gauge did not reconcile to zero after mixed burst: {inflight}"
+ );
+ assert!(inflight >= 0, "inflight gauge went negative: {inflight}");
+ }
+}
diff --git a/packages/sie_server_sidecar/src/ipc_mux.rs b/packages/sie_server_sidecar/src/ipc_mux.rs
new file mode 100644
index 000000000..22ed6d959
--- /dev/null
+++ b/packages/sie_server_sidecar/src/ipc_mux.rs
@@ -0,0 +1,843 @@
+//! Multiplexed IPC connection — single UDS, many in-flight RPCs.
+//!
+//! Drop-in alternative to the slot-pool transport in [`crate::ipc_client`].
+//! The two designs converge on the same `ipc_server.py` (which already
+//! accepts pipelined frames on one connection — process methods run in
+//! independent `asyncio.Task`s, see `ipc_server.py:271-286`); the
+//! difference is purely on the Rust side:
+//!
+//! * **Pool transport**: N independent UDS connections, each strictly
+//! single-flight (`write → read`). Concurrency caps at N. A slow RPC
+//! pins one slot for its full duration; if all N slots are busy a
+//! new caller waits on a semaphore even though Python is idle.
+//! * **Mux transport** (this module): one UDS connection, one writer
+//! task, one reader task, an inflight map keyed by `request_id`.
+//! `N` concurrent RPCs are limited only by the inflight cap (default
+//! 1024) and by Python's own concurrency. No head-of-line stalls
+//! between unrelated methods (e.g. `EnsureModelReady` no longer
+//! queues behind a heavy `RunBatch`).
+//!
+//! # Activation
+//!
+//! Disabled by default. Set `SIE_IPC_MUX=1` to opt in. The pool
+//! transport stays the legacy fallback so any deployment-specific
+//! regression can be reverted with an env-var flip, no rebuild.
+//!
+//! # Cancellation safety
+//!
+//! The actor pattern owns all I/O. Caller futures only ever see two
+//! awaits: a `mpsc::Sender::send` (drops the command if cancelled —
+//! safe) and a `oneshot::Receiver::await` (drops the receiver if
+//! cancelled — the actor's send fails silently when the response
+//! arrives later, which is a no-op). At no point can a cancelled
+//! caller leave the wire in a half-written state.
+//!
+//! # Reconnect
+//!
+//! On any I/O error the actor:
+//! 1. Sends `IpcError::Io` to every still-in-flight oneshot.
+//! 2. Drops the read/write halves and sleeps a small backoff.
+//! 3. Reconnects and resumes processing the command channel.
+//!
+//! Callers that want retry-on-transport-error get it for free: they
+//! see one error, the next call proceeds against the new connection.
+
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::{Arc, Mutex as StdMutex};
+use std::time::Duration;
+
+use serde::Deserialize;
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::UnixStream;
+use tokio::sync::{mpsc, oneshot};
+use tracing::{debug, info, warn};
+
+use crate::log_util::ErrChain;
+use crate::metrics::MetricsRegistry;
+
+/// Same upper bound the pool transport uses; matches Python's
+/// `_MAX_FRAME_BYTES` so a misconfigured caller can't OOM either side.
+const MAX_FRAME_BYTES: usize = 32 * 1024 * 1024;
+
+/// Maximum simultaneously-in-flight RPCs. The mpsc channel is bounded
+/// at this size so that backpressure shows up at `MuxClient::call`
+/// instead of inside the actor's HashMap. 1024 is large enough to
+/// never bind under realistic NATS pull rates and small enough that a
+/// stuck Python adapter can't pin unbounded heap.
+const MAX_INFLIGHT: usize = 1024;
+
+/// Backoff applied between reconnect attempts. Kept short — the
+/// Python side is on the same Pod and "down" usually means "still
+/// finishing startup" or "just restarted".
+const RECONNECT_BACKOFF: Duration = Duration::from_millis(100);
+
+/// IPC errors visible at the `MuxClient::call` boundary. Mirrors the
+/// shape of [`crate::ipc_client::IpcError`] for the subset that's
+/// observable through the multiplexed transport — the typed
+/// deserialization, version check, and `ok=false` mapping happen in
+/// the wrapping `IpcClient`.
+#[derive(Debug, thiserror::Error)]
+pub enum MuxError {
+ #[error("io: {0}")]
+ Io(std::io::Error),
+ #[error("frame too large: {0} > {MAX_FRAME_BYTES}")]
+ FrameTooLarge(u32),
+ #[error("connection lost while waiting for response")]
+ ConnectionLost,
+ #[error("multiplexer shutting down")]
+ Shutdown,
+}
+
+/// Minimal envelope view — just the field needed to demux responses
+/// back to their callers. We deliberately keep this tiny and
+/// `#[serde(default)]` everything we don't read so a malformed frame
+/// doesn't kill the reader task.
+#[derive(Deserialize)]
+struct EnvelopeHead {
+ #[serde(default)]
+ request_id: String,
+}
+
+/// One pending response, registered before the request frame goes on
+/// the wire and consumed exactly once by either the reader (success
+/// path) or the actor's reconnect handler (drain path).
+type Pending = oneshot::Sender<Result<Vec<u8>, MuxError>>;
+
+/// Map of in-flight requests indexed by `request_id`.
+type Inflight = Arc<StdMutex<HashMap<String, Pending>>>;
+
+/// Command sent from `MuxClient::call` to the writer task.
+struct Command {
+ request_id: String,
+ payload: Vec<u8>,
+ respond: Pending,
+}
+
+/// RAII guard that decrements `ipc_mux_inflight` on drop. Survives
+/// every early-return / cancellation path in `MuxClient::call_raw`,
+/// so the gauge is always balanced (no need for manual `dec` after
+/// every `?`).
+struct InflightGuard {
+ gauge: prometheus::IntGauge,
+}
+
+impl Drop for InflightGuard {
+ fn drop(&mut self) {
+ self.gauge.dec();
+ }
+}
+
+/// Caller-facing handle. Cheap to clone (just a few `Arc`s); intended
+/// to be wrapped by [`crate::ipc_client::IpcClient`]. The actor task
+/// owns the I/O and reconnect logic. The handle owns the command
+/// sender plus an optional `MetricsRegistry` clone so `call_raw` can
+/// inc/dec `ipc_mux_inflight` without crossing the channel.
+pub struct MuxClient {
+ cmd_tx: mpsc::Sender<Command>,
+ next_id: AtomicU64,
+ metrics: Option<Arc<MetricsRegistry>>,
+}
+
+impl MuxClient {
+ /// Spawn a multiplexer pointed at `socket_path`. The actor task
+ /// owns the connection; this handle owns only the command sender.
+ pub fn spawn(socket_path: impl Into<PathBuf>) -> Self {
+ Self::spawn_with_metrics(socket_path, None)
+ }
+
+ pub fn spawn_with_metrics(
+ socket_path: impl Into<PathBuf>,
+ metrics: Option<Arc<MetricsRegistry>>,
+ ) -> Self {
+ let socket_path = socket_path.into();
+ let (cmd_tx, cmd_rx) = mpsc::channel::<Command>(MAX_INFLIGHT);
+ let actor_metrics = metrics.clone();
+ tokio::spawn(async move {
+ mux_actor(socket_path, cmd_rx, actor_metrics).await;
+ });
+ Self {
+ cmd_tx,
+ next_id: AtomicU64::new(1),
+ metrics,
+ }
+ }
+
+ /// Generate a unique request id. The `mw-` prefix lets log
+ /// scanners distinguish multiplexer ids from the pool transport's
+ /// `w-` ids.
+ pub fn next_request_id(&self) -> String {
+ format!("mw-{}", self.next_id.fetch_add(1, Ordering::Relaxed))
+ }
+
+ /// Send `payload` (a fully-serialized [`crate::ipc_types::RequestEnvelope`])
+ /// and await the response frame as raw bytes. The caller is
+ /// responsible for typed deserialization on the way out.
+ ///
+ /// Three failure modes:
+ /// * channel send fails → mux actor exited (shutdown).
+ /// * `oneshot::Receiver` resolves with `Err` → I/O error or
+ /// reconnect drained this request.
+ /// * `oneshot::Receiver` resolves with `Ok(bytes)` → caller decodes.
+ pub async fn call_raw(
+ &self,
+ request_id: String,
+ payload: Vec<u8>,
+ ) -> Result<Vec<u8>, MuxError> {
+ // Increment the inflight gauge for the duration of this call.
+ // RAII drop guard protects the gauge against any early return,
+ // including a cancelled future or an `Err` from `cmd_tx.send`.
+ let _inflight = self.metrics.as_ref().map(|m| {
+ m.ipc_mux_inflight.inc();
+ InflightGuard {
+ gauge: m.ipc_mux_inflight.clone(),
+ }
+ });
+ // Acquire-wait observation point. There is no cap today, so
+ // the histogram only records the trivial setup time (well
+ // below the smallest bucket). Once the
+ // `SIE_IPC_MUX_MAX_INFLIGHT_PER_POD` semaphore lands, the
+ // permit acquisition will be wrapped here and the histogram
+ // becomes the primary signal for tuning the cap.
+ let acquire_started = std::time::Instant::now();
+ if let Some(m) = self.metrics.as_ref() {
+ m.ipc_mux_acquire_wait_seconds
+ .observe(acquire_started.elapsed().as_secs_f64());
+ }
+ let (respond, wait) = oneshot::channel();
+ let cmd = Command {
+ request_id,
+ payload,
+ respond,
+ };
+ if self.cmd_tx.send(cmd).await.is_err() {
+ return Err(MuxError::Shutdown);
+ }
+ match wait.await {
+ Ok(r) => r,
+ // Sender dropped without sending — actor torn down with
+ // this request still pending. Treat as connection lost.
+ Err(_) => Err(MuxError::ConnectionLost),
+ }
+ }
+
+ /// Approximate pool-size analog for parity with the slot pool's
+ /// metric: the multiplexer can drive up to `MAX_INFLIGHT`
+ /// in-flight RPCs from a single connection.
+ pub fn capacity(&self) -> usize {
+ MAX_INFLIGHT
+ }
+}
+
+/// Long-lived actor task. Holds the connection, spawns reader/writer,
+/// reconnects forever (until the command channel closes).
+async fn mux_actor(
+ socket_path: PathBuf,
+ mut cmd_rx: mpsc::Receiver<Command>,
+ metrics: Option<Arc<MetricsRegistry>>,
+) {
+ let inflight: Inflight = Arc::new(StdMutex::new(HashMap::new()));
+
+ loop {
+ // (Re)connect.
+ let stream = match UnixStream::connect(&socket_path).await {
+ Ok(s) => {
+ info!(
+ socket = %socket_path.display(),
+ "mux: connected to ipc_server"
+ );
+ if let Some(m) = &metrics {
+ m.ipc_connect_total.with_label_values(&["ok"]).inc();
+ }
+ s
+ }
+ Err(e) => {
+ warn!(
+ socket = %socket_path.display(),
+ error = %ErrChain(&e),
+ "mux: connect failed — backing off"
+ );
+ if let Some(m) = &metrics {
+ m.ipc_connect_total.with_label_values(&["error"]).inc();
+ }
+ tokio::time::sleep(RECONNECT_BACKOFF).await;
+ continue;
+ }
+ };
+
+ let (read_half, write_half) = stream.into_split();
+ let reader_inflight = Arc::clone(&inflight);
+ let mut reader_task = tokio::spawn(reader_loop(read_half, reader_inflight));
+
+ let writer_inflight = Arc::clone(&inflight);
+ // Writer borrows cmd_rx exclusively for this connection's
+ // lifetime; on disconnect we get it back to drive the next.
+ //
+ // We `select!` on writer-finishes vs reader-exits so a peer-
+ // initiated close detected by the reader (`read_exact` →
+ // EOF) immediately tears down the writer + drains inflight,
+ // even if no caller has a request in flight to drive the
+ // writer's I/O. Without this, a quiet-window disconnect
+ // would park the writer on `cmd_rx.recv()` and any caller
+ // waiting on a previously-sent request would hang until its
+ // own `request_timeout` (60s) fires.
+ let writer_fut = writer_loop(write_half, &mut cmd_rx, writer_inflight);
+ tokio::pin!(writer_fut);
+ let writer_outcome = tokio::select! {
+ o = &mut writer_fut => o,
+ _ = &mut reader_task => {
+ // Reader exited (EOF / IO / oversized frame). The
+ // connection is dead — abandon the writer (its
+ // pinned future is dropped on the way out of this
+ // select), drain, reconnect.
+ debug!("mux: reader exited before writer — connection lost");
+ WriterOutcome::IoError
+ }
+ };
+
+ // Stop the reader (no-op if it already exited on EOF / error).
+ reader_task.abort();
+ let _ = reader_task.await;
+
+ // Drain all still-pending requests with ConnectionLost so
+ // callers don't hang forever. The actor is the single owner
+ // of the inflight map at this point — the reader task is
+ // gone and the writer returned.
+ let drained: Vec<(String, Pending)> = {
+ let mut guard = inflight
+ .lock()
+ .expect("mux: inflight mutex poisoned during drain");
+ guard.drain().collect()
+ };
+ let drained_count = drained.len();
+ for (rid, tx) in drained {
+ debug!(request_id = %rid, "mux: draining inflight on reconnect");
+ let _ = tx.send(Err(MuxError::ConnectionLost));
+ }
+ if let Some(m) = &metrics {
+ m.ipc_reconnect_total.inc();
+ }
+ if drained_count > 0 {
+ warn!(
+ drained_count,
+ "mux: connection lost — drained inflight, will reconnect"
+ );
+ }
+
+ // Channel closed → no more callers, exit cleanly. Otherwise
+ // loop back and try to reconnect.
+ if let WriterOutcome::ChannelClosed = writer_outcome {
+ info!("mux: command channel closed — actor exiting");
+ return;
+ }
+ tokio::time::sleep(RECONNECT_BACKOFF).await;
+ }
+}
+
+/// Reason the writer loop returned.
+enum WriterOutcome {
+ /// Caller side dropped its [`MuxClient`] — no more commands will
+ /// arrive. Actor should exit.
+ ChannelClosed,
+ /// Outbound I/O error. Actor should reconnect.
+ IoError,
+}
+
+async fn writer_loop(
+ mut write_half: tokio::net::unix::OwnedWriteHalf,
+ cmd_rx: &mut mpsc::Receiver<Command>,
+ inflight: Inflight,
+) -> WriterOutcome {
+ while let Some(cmd) = cmd_rx.recv().await {
+ let Command {
+ request_id,
+ payload,
+ respond,
+ } = cmd;
+
+ // Register the responder BEFORE writing the frame: if the
+ // reader gets the response back faster than this thread can
+ // schedule (test scenarios with in-process echo do hit this),
+ // the lookup must already succeed.
+ if let Ok(mut guard) = inflight.lock() {
+ guard.insert(request_id.clone(), respond);
+ } else {
+ // Mutex poisoned — surface to caller and bail. A poisoned
+ // mutex means a previous panic in this actor; further I/O
+ // would just propagate the corruption.
+ return WriterOutcome::IoError;
+ }
+
+ // Length prefix is u32 big-endian — matches the pool transport
+ // and `ipc_server.py::_LEN_STRUCT`.
+ let len = match u32::try_from(payload.len()) {
+ Ok(l) if (l as usize) <= MAX_FRAME_BYTES => l,
+ _ => {
+ let too_big = payload.len() as u32;
+ let tx = inflight
+ .lock()
+ .expect("mux: inflight mutex poisoned")
+ .remove(&request_id);
+ if let Some(tx) = tx {
+ let _ = tx.send(Err(MuxError::FrameTooLarge(too_big)));
+ }
+ continue;
+ }
+ };
+ if let Err(e) = write_half.write_all(&len.to_be_bytes()).await {
+ // Pull the responder back out and notify before tearing
+ // down. If we can't grab the lock the response is
+ // effectively lost; ConnectionLost will fire on the
+ // actor's drain path next.
+ if let Ok(mut guard) = inflight.lock() {
+ if let Some(tx) = guard.remove(&request_id) {
+ let _ = tx.send(Err(MuxError::Io(e)));
+ }
+ }
+ return WriterOutcome::IoError;
+ }
+ if let Err(e) = write_half.write_all(&payload).await {
+ if let Ok(mut guard) = inflight.lock() {
+ if let Some(tx) = guard.remove(&request_id) {
+ let _ = tx.send(Err(MuxError::Io(e)));
+ }
+ }
+ return WriterOutcome::IoError;
+ }
+ if let Err(e) = write_half.flush().await {
+ if let Ok(mut guard) = inflight.lock() {
+ if let Some(tx) = guard.remove(&request_id) {
+ let _ = tx.send(Err(MuxError::Io(e)));
+ }
+ }
+ return WriterOutcome::IoError;
+ }
+ }
+
+ WriterOutcome::ChannelClosed
+}
+
+async fn reader_loop(mut read_half: tokio::net::unix::OwnedReadHalf, inflight: Inflight) {
+ loop {
+ let mut len_buf = [0u8; 4];
+ if let Err(e) = read_half.read_exact(&mut len_buf).await {
+ debug!(error = %ErrChain(&e), "mux reader: read of length prefix failed (likely EOF)");
+ return;
+ }
+ let len = u32::from_be_bytes(len_buf);
+ if len as usize > MAX_FRAME_BYTES {
+ warn!(
+ len,
+ max = MAX_FRAME_BYTES,
+ "mux reader: oversized frame; dropping connection"
+ );
+ return;
+ }
+ let mut frame = vec![0u8; len as usize];
+ if let Err(e) = read_half.read_exact(&mut frame).await {
+ debug!(error = %ErrChain(&e), "mux reader: read of body failed");
+ return;
+ }
+ // Cheap header decode just to extract `request_id`. Body
+ // payload stays on the wire-bytes path; the wrapping client
+ // re-deserializes the full envelope into the typed response.
+ let head: EnvelopeHead = match rmp_serde::from_slice(&frame) {
+ Ok(h) => h,
+ Err(e) => {
+ warn!(error = %ErrChain(&e), "mux reader: malformed envelope; dropping frame");
+ continue;
+ }
+ };
+ if head.request_id.is_empty() {
+ warn!("mux reader: response envelope missing request_id; dropping frame");
+ continue;
+ }
+ let pending = match inflight.lock() {
+ Ok(mut g) => g.remove(&head.request_id),
+ Err(_) => return, // mutex poisoned — bail and let the actor reconnect
+ };
+ match pending {
+ Some(tx) => {
+ // `send` returns Err if the caller's oneshot::Receiver
+ // was dropped (caller's future cancelled). That's a
+ // no-op — nothing to clean up.
+ let _ = tx.send(Ok(frame));
+ }
+ None => {
+ warn!(
+ request_id = %head.request_id,
+ "mux reader: response with no inflight handler — late delivery after drain?"
+ );
+ }
+ }
+ }
+}
+
+/// Ergonomic helper: read the on/off flag for the multiplexed
+/// transport. Centralised so callers don't sprinkle `std::env::var`
+/// across the codebase.
+pub fn mux_enabled() -> bool {
+ matches!(
+ std::env::var("SIE_IPC_MUX").ok().as_deref(),
+ Some("1") | Some("true") | Some("TRUE") | Some("on") | Some("ON")
+ )
+}
+
+impl From<std::io::Error> for MuxError {
+ fn from(e: std::io::Error) -> Self {
+ MuxError::Io(e)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde::Serialize;
+ use std::sync::atomic::AtomicUsize;
+ use std::time::Duration;
+ use tokio::net::UnixListener;
+
+ fn short_sock_path() -> PathBuf {
+ let base = std::env::var("TMPDIR").unwrap_or_else(|_| "/tmp".to_string());
+ let base = if base.len() > 20 {
+ "/tmp".to_string()
+ } else {
+ base
+ };
+ PathBuf::from(base).join(format!("sie-mux-{}.sock", uuid::Uuid::new_v4().simple()))
+ }
+
+ /// Test echo server that **does** support multiplexed pipelining:
+ /// each frame is processed in its own task, so out-of-order
+ /// responses are guaranteed when the handler is async.
+ async fn spawn_mux_echo<F, Fut>(path: PathBuf, handler: F) -> tokio::task::JoinHandle<()>
+ where
+ F: Fn(Vec<u8>) -> Fut + Send + Sync + 'static,
+ Fut: std::future::Future<Output = Vec<u8>> + Send + 'static,
+ {
+ let _ = tokio::fs::remove_file(&path).await;
+ let listener = UnixListener::bind(&path).unwrap();
+ let handler = Arc::new(handler);
+ tokio::spawn(async move {
+ loop {
+ let (sock, _) = match listener.accept().await {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ let (mut read_half, write_half) = sock.into_split();
+ let write_half = Arc::new(tokio::sync::Mutex::new(write_half));
+ let handler = Arc::clone(&handler);
+ tokio::spawn(async move {
+ loop {
+ let mut len_buf = [0u8; 4];
+ if read_half.read_exact(&mut len_buf).await.is_err() {
+ return;
+ }
+ let n = u32::from_be_bytes(len_buf) as usize;
+ let mut buf = vec![0u8; n];
+ if read_half.read_exact(&mut buf).await.is_err() {
+ return;
+ }
+ let h = Arc::clone(&handler);
+ let w = Arc::clone(&write_half);
+ tokio::spawn(async move {
+ let resp = (h)(buf).await;
+ let mut guard = w.lock().await;
+ let _ = guard.write_all(&(resp.len() as u32).to_be_bytes()).await;
+ let _ = guard.write_all(&resp).await;
+ let _ = guard.flush().await;
+ });
+ }
+ });
+ }
+ })
+ }
+
+ #[derive(Serialize)]
+ struct StubEnv<'a> {
+ version: u32,
+ method: &'a str,
+ request_id: String,
+ body: serde_json::Value,
+ }
+
+ fn build_request(method: &str, request_id: String) -> Vec<u8> {
+ let env = StubEnv {
+ version: 1,
+ method,
+ request_id,
+ body: serde_json::Value::Null,
+ };
+ rmp_serde::to_vec_named(&env).unwrap()
+ }
+
+ fn build_response(request_id: &str, payload: serde_json::Value) -> Vec<u8> {
+ let resp = serde_json::json!({
+ "version": 1,
+ "request_id": request_id,
+ "ok": true,
+ "body": payload,
+ "error": serde_json::Value::Null,
+ });
+ rmp_serde::to_vec_named(&resp).unwrap()
+ }
+
+ /// In-order single RPC roundtrip — sanity check that the actor
+ /// wires the request id back to the right responder.
+ #[tokio::test]
+ async fn single_call_roundtrips() {
+ let path = short_sock_path();
+ let _server = spawn_mux_echo(path.clone(), |req_bytes| async move {
+ let head: EnvelopeHead = rmp_serde::from_slice(&req_bytes).unwrap();
+ build_response(&head.request_id, serde_json::json!({"ok": true}))
+ })
+ .await;
+
+ let client = MuxClient::spawn(path);
+ let rid = client.next_request_id();
+ let payload = build_request("Ping", rid.clone());
+ let resp = client
+ .call_raw(rid, payload)
+ .await
+ .expect("RPC should succeed");
+ let head: EnvelopeHead = rmp_serde::from_slice(&resp).unwrap();
+ // Echo bounced the same id back; the multiplexer routed it
+ // to our specific waiter instead of any other.
+ assert!(!head.request_id.is_empty());
+ }
+
+ /// Out-of-order responses on the same connection. The slow
+ /// request queues, the fast one resolves first; both must reach
+ /// the right caller. This is the property that the slot pool
+ /// transport can't deliver without N≥2 connections.
+ #[tokio::test]
+ async fn parallel_calls_demux_correctly() {
+ let path = short_sock_path();
+ let counter = Arc::new(AtomicUsize::new(0));
+ let counter_h = Arc::clone(&counter);
+ let _server = spawn_mux_echo(path.clone(), move |req_bytes| {
+ let counter = Arc::clone(&counter_h);
+ async move {
+ let head: EnvelopeHead = rmp_serde::from_slice(&req_bytes).unwrap();
+ let n = counter.fetch_add(1, Ordering::Relaxed);
+ // First request stalls 80 ms, every following one
+ // resolves immediately. Without multiplexing the second
+ // would be queued behind the first.
+ if n == 0 {
+ tokio::time::sleep(Duration::from_millis(80)).await;
+ }
+ build_response(&head.request_id, serde_json::json!({"n": n}))
+ }
+ })
+ .await;
+
+ let client = Arc::new(MuxClient::spawn(path));
+ let started = std::time::Instant::now();
+
+ let c1 = Arc::clone(&client);
+ let h_slow = tokio::spawn(async move {
+ let rid = c1.next_request_id();
+ let payload = build_request("Slow", rid.clone());
+ c1.call_raw(rid, payload).await
+ });
+ // Tiny stagger so the slow request enters the actor first.
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ let c2 = Arc::clone(&client);
+ let h_fast = tokio::spawn(async move {
+ let rid = c2.next_request_id();
+ let payload = build_request("Fast", rid.clone());
+ c2.call_raw(rid, payload).await
+ });
+
+ let fast = h_fast.await.unwrap().expect("fast RPC succeeds");
+ let elapsed_fast = started.elapsed();
+ // Fast call must come back well before the 80 ms slow window
+ // would have expired if we were serialized.
+ assert!(
+ elapsed_fast < Duration::from_millis(70),
+ "fast call took {elapsed_fast:?}; multiplexing apparently stalled behind slow call"
+ );
+ let _slow = h_slow.await.unwrap().expect("slow RPC succeeds");
+
+ // Sanity: both responses were valid envelopes with non-empty
+ // request_ids (i.e. demux worked, neither went to the wrong
+ // caller).
+ let head: EnvelopeHead = rmp_serde::from_slice(&fast).unwrap();
+ assert!(!head.request_id.is_empty());
+ }
+
+ /// Regression: a peer that closes the connection while a request
+ /// is in flight must surface `ConnectionLost` to the caller
+ /// promptly — *not* hang until the caller's own request timeout.
+ ///
+ /// Pre-fix, the actor's writer task awaited `cmd_rx.recv()` with
+ /// no awareness of the reader having exited; if the reader saw
+ /// EOF and there was no inbound traffic to drive the writer
+ /// into a failing `write_all`, the inflight `Pending` for the
+ /// already-sent request was never drained.
+ ///
+ /// Post-fix, the actor `select!`s on writer-finishes vs reader-
+ /// exits, so a peer close is detected immediately and the actor
+ /// drains inflight before reconnecting. We bound the wait at
+ /// 500 ms — pre-fix this would block until the IpcClient's
+ /// 60 s timeout (or forever in this test, where there is no
+ /// outer timeout).
+ #[tokio::test]
+ async fn peer_close_drains_inflight_promptly() {
+ use tokio::io::AsyncReadExt;
+
+ let path = short_sock_path();
+ let _ = tokio::fs::remove_file(&path).await;
+ let listener = UnixListener::bind(&path).unwrap();
+
+ // Custom server: read one length-prefix + body, then drop
+ // the socket. No response is ever written, so the client
+ // sits in inflight; only the actor's reader-exit detection
+ // can rescue it.
+ tokio::spawn(async move {
+ if let Ok((mut sock, _)) = listener.accept().await {
+ let mut len_buf = [0u8; 4];
+ let _ = sock.read_exact(&mut len_buf).await;
+ let n = u32::from_be_bytes(len_buf) as usize;
+ let mut body = vec![0u8; n];
+ let _ = sock.read_exact(&mut body).await;
+ // Drop sock → peer close.
+ }
+ });
+
+ let client = MuxClient::spawn(path);
+ let rid = client.next_request_id();
+ let payload = build_request("Doomed", rid.clone());
+
+ // Bounded wait. With the bug: this would never resolve (the
+ // mux actor would park on cmd_rx waiting for the next
+ // command, while the inflight request hangs forever).
+ let r = tokio::time::timeout(Duration::from_millis(500), client.call_raw(rid, payload))
+ .await
+ .expect("actor must drain inflight on peer close within 500ms");
+
+ match r {
+ Err(MuxError::ConnectionLost) | Err(MuxError::Io(_)) => {} // expected
+ other => panic!("expected ConnectionLost / Io, got {:?}", other),
+ }
+ }
+
+ /// A malformed (zero-length) frame on the wire must NOT kill the
+ /// reader — we log + drop and keep going. The first request
+ /// stays pending forever (caller's responsibility to apply a
+ /// timeout, which `IpcClient::call` does), but subsequent calls
+ /// on the same connection still succeed.
+ ///
+ /// The connection-loss + drain path itself is not exercised here
+ /// because that requires hooking the actor's reconnect; covered
+ /// indirectly by the `IpcClient` integration path which retries
+ /// once on transport errors.
+ #[tokio::test]
+ async fn malformed_frame_does_not_kill_connection() {
+ let path = short_sock_path();
+ let arrived = Arc::new(AtomicUsize::new(0));
+ let arrived_h = Arc::clone(&arrived);
+ // Only the first connection's first frame triggers the
+ // server to abort. The retry connection answers normally.
+ let _server = spawn_mux_echo(path.clone(), move |req_bytes| {
+ let arrived = Arc::clone(&arrived_h);
+ async move {
+ let head: EnvelopeHead = rmp_serde::from_slice(&req_bytes).unwrap();
+ let n = arrived.fetch_add(1, Ordering::Relaxed);
+ if n == 0 {
+ // Force "no response": empty bytes. The handler
+ // shape forces the reply to be a complete frame,
+ // so we instead return a length-0 frame; the
+ // mux reader will see a malformed envelope and
+ // drop it (does NOT close the connection in
+ // production, but the inflight remains pending
+ // forever — exercises the drain via shutdown).
+ Vec::new()
+ } else {
+ build_response(&head.request_id, serde_json::json!({"n": n}))
+ }
+ }
+ })
+ .await;
+
+ let client = MuxClient::spawn(path.clone());
+
+ // First call: server writes a length-0 frame, mux reader logs
+ // "missing request_id", inflight stays pending. We bound the
+ // wait so the test doesn't hang if anything regressed.
+ let rid1 = client.next_request_id();
+ let p1 = build_request("First", rid1.clone());
+ let r1 = tokio::time::timeout(Duration::from_millis(200), client.call_raw(rid1, p1)).await;
+ assert!(
+ r1.is_err(),
+ "first call should hang because server replied with empty frame"
+ );
+
+ // Second call must still go through on the same connection —
+ // the reader keeps reading frames after a malformed one (we
+ // don't drop the connection on a single bad frame).
+ let rid2 = client.next_request_id();
+ let p2 = build_request("Second", rid2.clone());
+ let r2 = client.call_raw(rid2, p2).await.expect("second call ok");
+ let head: EnvelopeHead = rmp_serde::from_slice(&r2).unwrap();
+ assert!(!head.request_id.is_empty());
+ }
+
+ /// `ipc_mux_inflight` must rise during concurrent calls and fall
+ /// back to zero when they all complete — RAII guard correctness
+ /// across the success path. A bug here would surface in
+ /// production as a monotonically-growing gauge that never
+ /// returns to zero, which would hide a leak in the cap (when
+ /// added) by always making it look saturated.
+ #[tokio::test]
+ async fn inflight_gauge_is_balanced() {
+ let path = short_sock_path();
+ // Server holds responses for 50 ms before answering, giving
+ // the test a window to observe the gauge above zero.
+ let _server = spawn_mux_echo(path.clone(), |req_bytes| async move {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ let head: EnvelopeHead = rmp_serde::from_slice(&req_bytes).unwrap();
+ build_response(&head.request_id, serde_json::json!({"ok": true}))
+ })
+ .await;
+
+ let metrics = Arc::new(MetricsRegistry::new().unwrap());
+ let client = MuxClient::spawn_with_metrics(path.clone(), Some(Arc::clone(&metrics)));
+
+ // Wait for the connection to come up so the first call's send
+ // doesn't race the connect.
+ tokio::time::sleep(Duration::from_millis(20)).await;
+
+ // Fire 8 calls concurrently via JoinSet so we don't pull in
+ // an extra crate just for the test.
+ let client = Arc::new(client);
+ let mut set = tokio::task::JoinSet::new();
+ for _ in 0..8u32 {
+ let c = Arc::clone(&client);
+ set.spawn(async move {
+ let rid = c.next_request_id();
+ let payload = build_request("Concurrent", rid.clone());
+ c.call_raw(rid, payload).await.unwrap();
+ });
+ }
+
+ // Sample mid-flight — must be >0 while server is sleeping.
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ let mid = metrics.ipc_mux_inflight.get();
+ assert!(
+ mid > 0,
+ "ipc_mux_inflight should be positive during concurrent calls, got {mid}"
+ );
+
+ while let Some(res) = set.join_next().await {
+ res.unwrap();
+ }
+
+ // After all calls complete, the gauge must return to zero —
+ // any leak here is the InflightGuard misbehaving on a return
+ // path (early err, cancellation, etc.).
+ let final_val = metrics.ipc_mux_inflight.get();
+ assert_eq!(final_val, 0, "gauge must rebalance to 0 after all calls");
+ }
+}
diff --git a/packages/sie_server_sidecar/src/ipc_types.rs b/packages/sie_server_sidecar/src/ipc_types.rs
new file mode 100644
index 000000000..65f20889d
--- /dev/null
+++ b/packages/sie_server_sidecar/src/ipc_types.rs
@@ -0,0 +1,12 @@
+//! IPC wire types — re-exported from [`crate::protocol::ipc_types`] so existing
+//! sidecar call sites can keep using `crate::ipc_types`.
+//!
+//! The Python mirror lives in `sie_server/src/sie_server/ipc_types.py`.
+//! CI runs a two-way parity check between the two.
+//!
+//! Wire format: `[4-byte BE length][msgpack body]`, where `body` is a
+//! msgpack **map** encoding `RequestEnvelope` / `ResponseEnvelope`.
+//! `rmp_serde::to_vec_named` + `serde(default)` for forward-compat
+//! field absorption.
+
+pub use crate::protocol::ipc_types::*;
diff --git a/packages/sie_server_sidecar/src/latency.rs b/packages/sie_server_sidecar/src/latency.rs
new file mode 100644
index 000000000..438493dde
--- /dev/null
+++ b/packages/sie_server_sidecar/src/latency.rs
@@ -0,0 +1,302 @@
+//! Adaptive batching: a rolling latency tracker and a fetch-timeout
+//! controller for the NATS pull loop.
+//!
+//! The pull loop starts at `min` expiry. On empty/error fetches it
+//! multiplicatively backs off by `backoff_growth`, capped at `max`. On
+//! non-empty fetches it nudges the expiry toward `target_p50_ms`:
+//!
+//! ```text
+//! headroom_ms = target_p50_ms - observed_p50
+//! new = current + headroom_ms * gain / 1000
+//! clamp(new, min, max)
+//! ```
+//!
+//! - headroom > 0 → under SLO → grow expiry (bigger batches, more throughput)
+//! - headroom < 0 → over SLO → shrink expiry (faster pickup, lower latency)
+//! - too few samples → reset to `min`.
+//!
+//! The tracker is fed `queue_ms + inference_ms + postprocess_ms` per
+//! successfully published result.
+
+use std::collections::VecDeque;
+use std::time::Duration;
+
+/// Rolling latency tracker with a fixed-size window. `min_samples`
+/// gates percentile queries so a cold start doesn't bias the controller.
+#[derive(Debug, Clone)]
+pub struct LatencyTracker {
+ window_size: usize,
+ min_samples: usize,
+ samples: VecDeque<f64>,
+}
+
+impl LatencyTracker {
+ pub fn new(window_size: usize, min_samples: usize) -> Self {
+ Self {
+ window_size,
+ min_samples,
+ samples: VecDeque::with_capacity(window_size),
+ }
+ }
+
+ pub fn record(&mut self, total_ms: f64) {
+ if self.samples.len() == self.window_size {
+ self.samples.pop_front();
+ }
+ self.samples.push_back(total_ms);
+ }
+
+ /// Nearest-rank percentile over the current window, or `None` if
+ /// fewer than `min_samples` are buffered. Index is integer-truncated.
+ pub fn percentile(&self, p: f64) -> Option<f64> {
+ let n = self.samples.len();
+ if n < self.min_samples {
+ return None;
+ }
+ let mut sorted: Vec<f64> = self.samples.iter().copied().collect();
+ sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
+ let idx = ((p / 100.0) * ((n - 1) as f64)) as usize;
+ sorted.get(idx).copied()
+ }
+
+ pub fn p50(&self) -> Option<f64> {
+ self.percentile(50.0)
+ }
+
+ pub fn sample_count(&self) -> usize {
+ self.samples.len()
+ }
+
+ /// Clear the sample window. Used by the adaptive scheduler's
+ /// `reset()` path (see `crate::scheduler::AdaptiveBatchController`)
+ /// when the auto-calibration state is being rebuilt from scratch
+ /// — stale inference-p50 samples would otherwise bias the next
+ /// calibration round.
+ pub fn reset(&mut self) {
+ self.samples.clear();
+ }
+
+ /// p90 helper mirroring Python's `LatencyTracker.p90()`. Kept as
+ /// a convenience for scheduler dashboards so we don't have to
+ /// remember the 90.0 magic number everywhere.
+ pub fn p90(&self) -> Option<f64> {
+ self.percentile(90.0)
+ }
+
+ /// p99 helper mirroring Python's `LatencyTracker.p99()`.
+ pub fn p99(&self) -> Option<f64> {
+ self.percentile(99.0)
+ }
+}
+
+/// Adaptive NATS-fetch expiry controller: multiplicative backoff on
+/// empty batches, latency-driven nudging on loaded ones.
+#[derive(Debug, Clone)]
+pub struct FetchExpiryController {
+ pub min: Duration,
+ pub max: Duration,
+ pub target_p50_ms: f64,
+ pub gain: f64,
+ pub backoff_growth: f64,
+}
+
+impl FetchExpiryController {
+ /// Defaults: 2ms → 15ms, `target_p50_ms=50`, `gain=0.2`, backoff ×2.
+ ///
+ /// Since the pull loop switched to a long-lived stream,
+ /// `min`/`max` now bound the **client-side batch-coalesce
+ /// quantum**, not the server-side pull expiry. The semantics for
+ /// operators are the same (bigger number = bigger batches / more
+ /// throughput, smaller number = lower per-request latency), only
+ /// the mechanism moved client-side.
+ ///
+ /// ## Default rationale
+ ///
+ /// The 2/15/50 defaults keep client-side coalescing bounded so the
+ /// sidecar does not build oversized fetch batches before the adapter
+ /// batcher can apply backpressure. Retune with a fresh validation
+ /// baseline, not by restoring Python parity by inspection.
+ ///
+ /// Env knobs (all override the defaults above):
+ ///
+ /// * `SIE_ADAPTIVE_MIN_QUANTUM_MS` (default 2) — floor in ms.
+ /// * `SIE_ADAPTIVE_MAX_QUANTUM_MS` (default 15) — ceiling in ms.
+ /// * `SIE_ADAPTIVE_TARGET_P50_MS` (default 50) — target queue-path
+ /// p50 the controller nudges toward.
+ ///
+ /// **Tracker input is configurable** via
+ /// `SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS` (default off): with the
+ /// flag set the per-record sample becomes
+ /// `queue_ms + inference + postprocess` (whole-path feedback)
+ /// instead of `inference + postprocess` only. See
+ /// `crate::pull_quantum_includes_queue_ms` for the
+ /// divergence rationale.
+ pub fn from_env_or_default() -> Self {
+ let min_ms = std::env::var("SIE_ADAPTIVE_MIN_QUANTUM_MS")
+ .ok()
+ .and_then(|v| v.parse::<u64>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or(2);
+ let max_ms = std::env::var("SIE_ADAPTIVE_MAX_QUANTUM_MS")
+ .ok()
+ .and_then(|v| v.parse::<u64>().ok())
+ .filter(|&n| n >= min_ms)
+ .unwrap_or_else(|| std::cmp::max(15, min_ms));
+ let target_ms = std::env::var("SIE_ADAPTIVE_TARGET_P50_MS")
+ .ok()
+ .and_then(|v| v.parse::<f64>().ok())
+ .unwrap_or(50.0);
+ Self {
+ min: Duration::from_millis(min_ms),
+ max: Duration::from_millis(max_ms),
+ target_p50_ms: target_ms,
+ gain: 0.2,
+ backoff_growth: 2.0,
+ }
+ }
+
+ /// Empty/error path: multiplicatively back off, clamped to `max`.
+ pub fn backoff(&self, current: Duration) -> Duration {
+ let grown = current.mul_f64(self.backoff_growth);
+ clamp_dur(grown, self.min, self.max)
+ }
+
+ /// Non-empty path: nudge toward `target_p50_ms`. Returns `min` when
+ /// the tracker hasn't warmed up yet.
+ pub fn adjust(&self, current: Duration, tracker: &LatencyTracker) -> Duration {
+ let Some(observed) = tracker.p50() else {
+ return self.min;
+ };
+ let headroom_ms = self.target_p50_ms - observed;
+ let adjustment_s = headroom_ms * self.gain / 1000.0;
+ let adjustment = Duration::from_secs_f64(adjustment_s.abs());
+ let new = if adjustment_s >= 0.0 {
+ current.saturating_add(adjustment)
+ } else {
+ current.saturating_sub(adjustment)
+ };
+ clamp_dur(new, self.min, self.max)
+ }
+}
+
+fn clamp_dur(d: Duration, lo: Duration, hi: Duration) -> Duration {
+ if d < lo {
+ lo
+ } else if d > hi {
+ hi
+ } else {
+ d
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn tracker_returns_none_below_min_samples() {
+ let mut t = LatencyTracker::new(200, 10);
+ for i in 0..9 {
+ t.record(i as f64);
+ }
+ assert_eq!(t.p50(), None);
+ }
+
+ #[test]
+ fn tracker_computes_p50_after_min_samples() {
+ let mut t = LatencyTracker::new(200, 10);
+ for i in 1..=10 {
+ t.record(i as f64);
+ }
+ // n=10 → idx = int(0.5 * 9) = 4 → sorted[4] = 5.0.
+ assert_eq!(t.p50(), Some(5.0));
+ }
+
+ #[test]
+ fn tracker_window_drops_oldest() {
+ let mut t = LatencyTracker::new(5, 3);
+ for i in 1..=10 {
+ t.record(i as f64);
+ }
+ assert_eq!(t.sample_count(), 5);
+ // window=[6..10], p50 idx=int(0.5*4)=2 → sorted[2]=8.
+ assert_eq!(t.p50(), Some(8.0));
+ }
+
+ #[test]
+ fn backoff_doubles_and_caps() {
+ let c = FetchExpiryController::from_env_or_default();
+ // With the worker defaults (2/15/50), backoff doubles 2 → 4 → 8
+ // and then clamps at max=15.
+ assert_eq!(
+ c.backoff(Duration::from_millis(2)),
+ Duration::from_millis(4)
+ );
+ assert_eq!(
+ c.backoff(Duration::from_millis(4)),
+ Duration::from_millis(8)
+ );
+ assert_eq!(
+ c.backoff(Duration::from_millis(8)),
+ Duration::from_millis(15)
+ );
+ }
+
+ #[test]
+ fn adjust_returns_min_when_not_enough_samples() {
+ let c = FetchExpiryController::from_env_or_default();
+ let t = LatencyTracker::new(200, 10);
+ assert_eq!(c.adjust(Duration::from_millis(20), &t), c.min);
+ }
+
+ #[test]
+ fn adjust_grows_timeout_when_below_target() {
+ // Worker defaults: target=50, gain=0.2. p50=10, target=50
+ // gives headroom=40 → +40*0.2/1000=+8ms → 5+8=13ms.
+ let c = FetchExpiryController::from_env_or_default();
+ let mut t = LatencyTracker::new(200, 10);
+ for _ in 0..20 {
+ t.record(10.0);
+ }
+ assert_eq!(
+ c.adjust(Duration::from_millis(5), &t),
+ Duration::from_millis(13)
+ );
+ }
+
+ #[test]
+ fn adjust_shrinks_timeout_when_over_target() {
+ // Worker defaults: target=50. p50=100, target=50 gives
+ // headroom=-50 → -10ms → 15-10=5ms.
+ let c = FetchExpiryController::from_env_or_default();
+ let mut t = LatencyTracker::new(200, 10);
+ for _ in 0..20 {
+ t.record(100.0);
+ }
+ assert_eq!(
+ c.adjust(Duration::from_millis(15), &t),
+ Duration::from_millis(5)
+ );
+ }
+
+ #[test]
+ fn adjust_clamps_to_min_on_aggressive_shrink() {
+ let c = FetchExpiryController::from_env_or_default();
+ let mut t = LatencyTracker::new(200, 10);
+ for _ in 0..20 {
+ t.record(10_000.0); // way over target
+ }
+ let out = c.adjust(Duration::from_millis(20), &t);
+ assert_eq!(out, c.min);
+ }
+
+ #[test]
+ fn defaults_match_queue_mode_scheduler_values() {
+ // Lock the queue-mode defaults that bound coalescing without
+ // forcing the pull loop to its minimum under normal load.
+ let c = FetchExpiryController::from_env_or_default();
+ assert_eq!(c.min, Duration::from_millis(2));
+ assert_eq!(c.max, Duration::from_millis(15));
+ assert_eq!(c.target_p50_ms, 50.0);
+ }
+}
diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rs
new file mode 100644
index 000000000..05daf35d0
--- /dev/null
+++ b/packages/sie_server_sidecar/src/lib.rs
@@ -0,0 +1,1497 @@
+//! Library root for the `sie-server-sidecar` binary.
+//!
+//! Sidecar-only build artifacts use the `sie-server-sidecar` name, while the
+//! Kubernetes container remains `worker-sidecar` because it runs in worker Pods.
+//! See
+//! `packages/sie_server_sidecar/docs/architecture-guide.md` for the current
+//! runtime contract.
+
+pub mod backend;
+pub mod config;
+pub mod config_reconciler;
+pub mod config_subscriber;
+pub mod dispatcher;
+pub mod health_publisher;
+pub mod ipc_client;
+pub mod ipc_mux;
+pub mod ipc_types;
+pub mod latency;
+pub mod log_util;
+pub mod metrics;
+pub mod nats_consumer;
+pub mod output;
+pub mod payload_store;
+pub mod pool_admission;
+pub mod prep;
+pub mod protocol;
+pub mod publisher;
+pub mod readiness;
+pub mod scheduler;
+pub mod shutdown;
+pub mod subject;
+pub mod tokenize;
+pub mod work_types;
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use anyhow::Context;
+use futures_util::StreamExt;
+use tokio::sync::{Mutex, Notify, Semaphore};
+use tokio::task::JoinHandle;
+use tokio::time::{interval, sleep, timeout};
+use tracing::{debug, info, warn};
+
+use crate::backend::{BackendRouter, PythonIpcBackend, SharedBackend};
+use crate::config::WorkerConfig;
+use crate::config_subscriber::ConfigApplyState;
+use crate::dispatcher::Dispatcher;
+use crate::ipc_client::IpcClient;
+use crate::latency::{FetchExpiryController, LatencyTracker};
+use crate::log_util::ErrChain;
+use crate::metrics::MetricsRegistry;
+use crate::nats_consumer::{
+ connect, ensure_stream_and_consumer, ensure_worker_stream_and_consumer,
+ reconcile_stream_and_consumer, reconcile_worker_stream_and_consumer, NatsConsumer,
+};
+use crate::payload_store::{create_payload_store, MeteredPayloadStore};
+use crate::pool_admission::PoolAdmissionGate;
+use crate::publisher::WorkPublisher;
+use crate::readiness::Readiness;
+use crate::shutdown::Shutdown;
+use crate::tokenize::TokenizerRegistry;
+
+/// How many messages to request per NATS pull-stream refill. Matches
+/// Python's historical `_DEFAULT_BATCH_BUDGET` (64) so Rust and Python
+/// workers have the same per-fetch capacity.
+///
+/// Reads `SIE_NATS_FETCH_BUDGET` (the operator-facing env var wired by
+/// the helm chart — see
+/// `deploy/helm/sie-cluster/templates/worker-statefulset.yaml`), then
+/// falls back to 64.
+pub(crate) fn fetch_batch_size() -> usize {
+ std::env::var("SIE_NATS_FETCH_BUDGET")
+ .ok()
+ .and_then(|s| s.parse::<usize>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or(64)
+}
+
+/// Server-side pull-request expiry. When async-nats opens a pull
+/// subscription it asks the server to send up to `fetch_batch_size()`
+/// messages or wait this long before replying with a `408 TIMEOUT`. The
+/// stream auto-issues the next pull; this is not the dispatcher batch
+/// size nor the client-side coalesce quantum.
+///
+/// Must stay strictly less than `ack_wait` (30 s) so a stuck stream
+/// surfaces as a heartbeat/timeout error instead of silently blocking
+/// redelivery. Override with `SIE_NATS_PULL_EXPIRES_S` (default 5).
+pub(crate) fn pull_stream_expires() -> Duration {
+ let secs = std::env::var("SIE_NATS_PULL_EXPIRES_S")
+ .ok()
+ .and_then(|s| s.parse::<u64>().ok())
+ .filter(|&n| n > 0 && n < 30)
+ .unwrap_or(5);
+ Duration::from_secs(secs)
+}
+
+const NATS_CONSUMER_RECONCILE_INTERVAL_ENV: &str = "SIE_NATS_CONSUMER_RECONCILE_INTERVAL_MS";
+const DEFAULT_NATS_CONSUMER_RECONCILE_INTERVAL_MS: u64 = 30_000;
+const MIN_NATS_CONSUMER_RECONCILE_INTERVAL_MS: u64 = 10_000;
+
+const GENERATION_CAPABILITY_RECONCILE_INTERVAL_ENV: &str =
+ "SIE_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS";
+const DEFAULT_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS: u64 = 30_000;
+const MIN_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS: u64 = 5_000;
+
+fn parse_nats_consumer_reconcile_interval_ms(raw: Option<&str>) -> Option<u64> {
+ match raw.map(str::trim) {
+ Some("0") => None,
+ Some(value) if !value.is_empty() => value
+ .parse::<u64>()
+ .ok()
+ .filter(|millis| *millis > 0)
+ .map(|millis| millis.max(MIN_NATS_CONSUMER_RECONCILE_INTERVAL_MS))
+ .or(Some(DEFAULT_NATS_CONSUMER_RECONCILE_INTERVAL_MS)),
+ _ => Some(DEFAULT_NATS_CONSUMER_RECONCILE_INTERVAL_MS),
+ }
+}
+
+fn nats_consumer_reconcile_interval() -> Option<Duration> {
+ parse_nats_consumer_reconcile_interval_ms(
+ std::env::var(NATS_CONSUMER_RECONCILE_INTERVAL_ENV)
+ .ok()
+ .as_deref(),
+ )
+ .map(Duration::from_millis)
+}
+
+fn parse_generation_capability_reconcile_interval_ms(raw: Option<&str>) -> Option<u64> {
+ match raw.map(str::trim) {
+ Some("0") => None,
+ Some(value) if !value.is_empty() => value
+ .parse::<u64>()
+ .ok()
+ .filter(|millis| *millis > 0)
+ .map(|millis| millis.max(MIN_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS))
+ .or(Some(DEFAULT_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS)),
+ _ => Some(DEFAULT_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS),
+ }
+}
+
+fn generation_capability_reconcile_interval() -> Option<Duration> {
+ parse_generation_capability_reconcile_interval_ms(
+ std::env::var(GENERATION_CAPABILITY_RECONCILE_INTERVAL_ENV)
+ .ok()
+ .as_deref(),
+ )
+ .map(Duration::from_millis)
+}
+
+/// Drain deadline sent to the Python IPC on shutdown.
+const DRAIN_DEADLINE_MS: u64 = 15_000;
+
+/// Whether the pull-loop quantum's [`LatencyTracker`] should observe
+/// the upstream `queue_ms` (gateway-publish → NATS-pull) on top of
+/// `inference_ms + postprocess_ms`.
+///
+/// **Default `false`** — excludes `queue_ms` from the controller's
+/// input. Rationale (see `dispatcher.rs::publish_outcome_for_item`):
+/// under saturation `queue_ms` rises into seconds, which would drive
+/// the controller's `headroom_ms = target − observed` deeply negative
+/// and collapse the quantum to its floor, even though the pull-loop
+/// itself is not the bottleneck.
+///
+/// **Set to `true`** to recover parity with the former Python queue-loop
+/// tracker, where `total_ms = queue_times[idx] + inference_ms +
+/// postprocess_ms`. With the tighter local defaults
+/// (`MIN_QUANTUM_MS=2`, `MAX_QUANTUM_MS=15`, `TARGET_P50_MS=50`)
+/// the asymmetry has narrowed substantially, but the flag remains as
+/// an explicit compatibility knob.
+/// Tracked as a known parity divergence in `docs/architecture-guide.md`.
+///
+/// Cached after first call: read once per process, atomic check
+/// thereafter — keeps the per-outcome `record` path branch-free
+/// in the hot loop without paying for `std::env::var()` each time.
+pub(crate) fn pull_quantum_includes_queue_ms() -> bool {
+ static CACHED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *CACHED.get_or_init(|| {
+ std::env::var("SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS")
+ .ok()
+ .map(|v| {
+ let trimmed = v.trim();
+ matches!(
+ trimmed.to_ascii_lowercase().as_str(),
+ "1" | "true" | "yes" | "on"
+ )
+ })
+ .unwrap_or(false)
+ })
+}
+
+/// Whether the scheduler should step the adaptive controller exactly
+/// once per wave (Primary only) or once per batch (Primary + every
+/// Drain).
+///
+/// Defaults to **true** — per-wave stepping. Set
+/// `SIE_RUST_WAVE_CADENCE=off` (also accepted: `0`,
+/// `false`, `no`, `disabled`) to fall back to per-batch stepping.
+///
+/// **Why a toggle.** Per-wave stepping matches Python `_process_loop`'s
+/// cadence and stops the PI loop from biasing toward the smaller
+/// drain-batch sizes. Per-batch stepping is useful only as an explicit
+/// latency/throughput tradeoff knob.
+///
+/// The cost: per-wave stepping can leave the wait knob at a value that
+/// produces larger batches than the old Python-only path. Operators who
+/// care more about light-load p50 than saturated p99 can flip this off
+/// to recover smaller batch density.
+///
+/// **No effect at `SIE_RUST_PIPELINE_DEPTH=1`** — strict serial
+/// dispatch never produces drains, so every batch is already
+/// Primary regardless of the toggle.
+///
+/// Cached after first call (`OnceLock`): same hot-path treatment as
+/// `pull_quantum_includes_queue_ms` — the per-batch gate must stay
+/// branch-free without paying for `std::env::var()` each call.
+pub(crate) fn wave_cadence_enabled() -> bool {
+ static CACHED: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+ *CACHED.get_or_init(|| {
+ std::env::var("SIE_RUST_WAVE_CADENCE")
+ .ok()
+ .map(|v| {
+ let trimmed = v.trim();
+ !matches!(
+ trimmed.to_ascii_lowercase().as_str(),
+ "0" | "off" | "false" | "no" | "disabled"
+ )
+ })
+ .unwrap_or(true)
+ })
+}
+
+/// Whether the NATS health-heartbeat publisher should run.
+///
+/// Defaults to `true` because the sidecar pod runs without
+/// `/ws/status` (that endpoint lives on the Python container), which
+/// forces the gateway into `health_mode=nats` — and that mode is a
+/// no-op until at least
+/// one worker publishes heartbeats. Override with
+/// `SIE_HEALTH_PUBLISH_ENABLED=0` (or `false` / `no`) on legacy
+/// WS-health deployments where the gateway ignores `sie.health.>`.
+pub(crate) fn health_publish_enabled() -> bool {
+ let raw = match std::env::var("SIE_HEALTH_PUBLISH_ENABLED") {
+ Ok(v) => v,
+ Err(_) => return true,
+ };
+ !matches!(
+ raw.trim().to_ascii_lowercase().as_str(),
+ "0" | "false" | "no" | "off" | ""
+ )
+}
+
+/// Max number of `handle_batch` tasks the pull loop may have in flight at
+/// once. Each in-flight task holds a full NATS fetch in memory and a
+/// model-group IPC request against Python, so this bounds both memory and
+/// the effective Rust→Python pipeline depth. Reads
+/// `SIE_PULL_LOOP_INFLIGHT`, falling back to
+/// [`dispatcher::default_max_concurrent_batches`] (4) so operators get one
+/// knob that matches both the per-model-group semaphore and the IPC pool
+/// by default.
+///
+/// Must be ≥ 1; values < 1 are clamped to 1 to avoid a never-dispatching
+/// pull loop.
+pub(crate) fn pull_loop_inflight() -> usize {
+ std::env::var("SIE_PULL_LOOP_INFLIGHT")
+ .ok()
+ .and_then(|s| s.parse::<usize>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or_else(crate::dispatcher::default_max_concurrent_batches)
+ .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
+/// hundred ms) but still < `DRAIN_DEADLINE_MS` so the drain RPC has its
+/// own headroom.
+const PULL_LOOP_TASK_JOIN_DEADLINE_MS: u64 = 10_000;
+
+/// Top-level entrypoint: wire everything together and run until shutdown.
+#[allow(clippy::vec_init_then_push)]
+pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {
+ let shutdown = Arc::new(Shutdown::new());
+ shutdown::install_signal_handlers(shutdown.clone());
+
+ // Shared sidecar readiness state for `/readyz` and NATS health
+ // heartbeats. The first successful IPC Ping flips the sidecar ready;
+ // shutdown flips it draining before backend drain starts.
+ 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,
+ ));
+ info!(
+ ping_interval_ms = config.ping_interval_ms,
+ ready_stale_mult = config.ready_stale_mult,
+ freshness_ms = readiness.freshness_ms(),
+ "readiness: /readyz freshness window configured"
+ );
+
+ // --- Metrics: one registry shared between the HTTP server, IPC client,
+ // 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")?);
+ let metrics_handle = metrics::spawn_metrics_server(
+ config.metrics_port,
+ Arc::clone(&metrics_registry),
+ Arc::clone(&readiness),
+ shutdown.clone(),
+ )
+ .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(60))
+ .with_metrics(Arc::clone(&metrics_registry)),
+ );
+ info!(
+ socket = %config.ipc_socket_path.display(),
+ ipc_pool_size = config.ipc_pool_size,
+ "IPC client initialized with connection pool"
+ );
+ let generation_capable = detect_generation_capable(&ipc).await;
+
+ // --- NATS
+ let (nats_client, jetstream) = connect(&config.nats_url).await.context("connect NATS")?;
+ info!(nats = %config.nats_url, "NATS connected");
+ let consumer = ensure_stream_and_consumer(&jetstream, &config)
+ .await
+ .context("ensure NATS stream/consumer")?;
+ let nats_consumer = NatsConsumer::new(consumer);
+ let nats_direct_active = Arc::new(AtomicBool::new(false));
+ let nats_consumer_reconciler_handle = spawn_nats_consumer_reconciler(
+ jetstream.clone(),
+ config.clone(),
+ shutdown.clone(),
+ Arc::clone(&nats_direct_active),
+ );
+
+ // --- Payload store (wrapped so every fetch records metrics).
+ 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),
+ ));
+
+ // --- Publisher
+ let publisher = Arc::new(WorkPublisher::new(nats_client.clone(), &config.worker_id));
+
+ // --- Adaptive fetch / latency tracker (shared across dispatcher + loop).
+ // 200-sample window, 10-sample warm-up before p50 is reported.
+ let latency_tracker = Arc::new(Mutex::new(LatencyTracker::new(200, 10)));
+ let fetch_ctrl = FetchExpiryController::from_env_or_default();
+
+ let pool_admission =
+ PoolAdmissionGate::from_worker_config(&config).context("construct pool admission gate")?;
+ let pool_admission_handle = pool_admission.as_ref().map(|gate| {
+ let gate = Arc::clone(gate);
+ let shutdown = Arc::clone(&shutdown);
+ tokio::spawn(async move {
+ gate.run(shutdown).await;
+ })
+ });
+
+ // --- Backend router
+ //
+ // The sidecar talks to whichever adapter is co-deployed over IPC;
+ // today that is the Python `sie_server` adapter. There is exactly
+ // one backend. `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)];
+
+ let router =
+ BackendRouter::from_backends_with_metrics(backends, Some(Arc::clone(&metrics_registry)));
+ info!(
+ backends = ?router.names(),
+ "backend router initialised"
+ );
+ let backend: SharedBackend = router;
+
+ // --- Rust-side tokenizer registry. Always created; tokenisers are
+ // ingested lazily on the `EnsureModelReady` handshake when the adapter
+ // declares a `tokenizer_path` in its `ModelDescriptor`.
+ //
+ // An empty registry is zero-cost: every `get(model_id)` returns
+ // `None` and the dispatcher falls through to the Python-tokenise
+ // fallback path, exactly like the old `Option::None` branch did.
+ let tokenizer_registry = TokenizerRegistry::empty();
+ debug!(
+ "rust-tokenize: registry empty at startup — tokenisers will be \
+ ingested from EnsureModelReady descriptors as adapters declare them"
+ );
+
+ // Rust-side scheduler. Always on when the worker runs:
+ // model-to-image routing is decided on the gateway from the
+ // config-model API, so every model that lands here goes through
+ // the Rust scheduler. Per-model drain loops spawn lazily on first
+ // traffic inside `Dispatcher::resolve_scheduler`; the shutdown
+ // path below awaits every handle collected along the way so
+ // final-drain windows have a chance to complete.
+ let scheduler_registry: Arc<crate::scheduler::ProductionSchedulerRegistry> =
+ Arc::new(crate::scheduler::ProductionSchedulerRegistry::new(
+ // BatchConfig pulls `SIE_BATCHER_*` overrides; the
+ // controller (constructed lazily per model in
+ // `Scheduler::builder().build()`) pulls
+ // `SIE_ADAPTIVE_BATCH_*` overrides — see the doc comments
+ // on `BatchConfig::from_env_or_default` and
+ // `AdaptiveBatchController::from_env_or_default` for the
+ // full list.
+ crate::scheduler::BatchConfig::from_env_or_default(),
+ ));
+ info!("rust-scheduler: enabled for every model (per-model drain loops spawn on first traffic)");
+
+ let config_apply_state = Arc::new(ConfigApplyState::new(config.bundle_config_hash.clone()));
+
+ let dispatcher = Arc::new(Dispatcher::new(
+ Arc::clone(&backend),
+ Arc::clone(&ipc),
+ payload_store,
+ Arc::clone(&publisher),
+ Arc::clone(&metrics_registry),
+ Arc::clone(&latency_tracker),
+ tokenizer_registry,
+ Some(Arc::clone(&scheduler_registry)),
+ Some(shutdown.clone()),
+ Some(Arc::clone(&config_apply_state)),
+ ));
+
+ let generation_direct_dispatch = Arc::new(GenerationDirectDispatch::new(
+ jetstream.clone(),
+ nats_client.clone(),
+ config.clone(),
+ Arc::clone(&dispatcher),
+ shutdown.clone(),
+ fetch_ctrl.clone(),
+ Arc::clone(&latency_tracker),
+ pool_admission.clone(),
+ Arc::clone(&ipc),
+ Arc::clone(&nats_direct_active),
+ ));
+ if generation_capable {
+ generation_direct_dispatch
+ .activate("startup")
+ .await
+ .context("activate generation direct-dispatch at startup")?;
+ } else {
+ info!("generation: no generation models in this bundle; direct-dispatch stream disabled");
+ }
+ let generation_capability_reconciler_handle = spawn_generation_capability_reconciler(
+ Arc::clone(&ipc),
+ Arc::clone(&generation_direct_dispatch),
+ shutdown.clone(),
+ );
+ let generation_notify = Some(generation_direct_dispatch.reconcile_notifier());
+
+ let config_subscriber_handle = crate::config_subscriber::spawn(
+ nats_client.clone(),
+ config.bundle.clone(),
+ Arc::clone(&ipc),
+ Arc::clone(&config_apply_state),
+ Arc::clone(&metrics_registry),
+ shutdown.clone(),
+ crate::config_subscriber::ConfigSubscriberOptions {
+ trusted_producers: config.nats_config_trusted_producers.clone(),
+ generation_reconcile: generation_notify.clone(),
+ },
+ );
+ let config_reconciler_handle = crate::config_reconciler::spawn(
+ 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(),
+ 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(&ipc),
+ Arc::clone(&config_apply_state),
+ Arc::clone(&metrics_registry),
+ shutdown.clone(),
+ generation_notify,
+ );
+
+ // --- Background: heartbeat pings into IPC so /readyz reflects liveness
+ let heartbeat_handle = spawn_heartbeat(
+ Arc::clone(&ipc),
+ Duration::from_millis(config.ping_interval_ms),
+ Arc::clone(&readiness),
+ Arc::clone(&config_apply_state),
+ shutdown.clone(),
+ );
+
+ // --- Background: NATS health-heartbeat publisher.
+ //
+ // In `health_mode=nats` the gateway's `WorkerRegistry` is built
+ // exclusively from `sie.health.>` messages — no publisher means
+ // no registered workers, which makes `resolve_queue_pool`
+ // return `None` and every inbound request `202 provisioning`.
+ //
+ // Skipped silently when `SIE_HEALTH_PUBLISH_ENABLED=false` (or
+ // any value that parses to `false`) so operators on the legacy
+ // WS-health gateway aren't forced to consume heartbeats they
+ // ignore. Default is enabled because the sidecar pod has no
+ // `/ws/status` endpoint (that endpoint lives on the Python
+ // container) and therefore forces the gateway into `health_mode=nats`.
+ let health_publisher_handle = if health_publish_enabled() {
+ let pub_cfg = crate::health_publisher::HealthPublisherConfig {
+ worker_id: config.worker_id.clone(),
+ bundle: config.bundle.clone(),
+ pool_name: config.pool.clone(),
+ machine_profile: config.machine_profile.clone(),
+ gpu_count: config.gpu_count,
+ bundle_config_hash: config_apply_state.bundle_config_hash(),
+ interval: Duration::from_millis(config.health_publish_interval_ms),
+ };
+ Some(crate::health_publisher::spawn(
+ nats_client.clone(),
+ pub_cfg,
+ Arc::clone(&readiness),
+ shutdown.clone(),
+ ))
+ } else {
+ info!("nats-health: SIE_HEALTH_PUBLISH_ENABLED=false; skipping heartbeat publisher");
+ None
+ };
+
+ // --- Main pull loop
+ run_pull_loop(
+ &nats_consumer,
+ dispatcher.clone(),
+ shutdown.clone(),
+ &fetch_ctrl,
+ Arc::clone(&latency_tracker),
+ pool_admission.clone(),
+ )
+ .await;
+ generation_direct_dispatch.abort_and_join().await;
+
+ // --- Graceful shutdown: the pull loop has exited and awaited every
+ // dispatch task it spawned (bounded by `PULL_LOOP_TASK_JOIN_DEADLINE_MS`).
+ // Anything left running after that deadline is best-effort and will
+ // be observed by the backend drain path below. Now:
+ // 1. Stop the background heartbeat task BEFORE drain so its IPC ping
+ // doesn't race the Python drain RPC.
+ // 2. Drain every registered backend (Python gets a Drain RPC;
+ // native backends wait for in-flight work + free resources).
+ // 3. Flush any buffered NATS publishes so WorkResults don't get lost.
+ // 4. Stop the metrics task.
+ info!("pull loop exited; stopping heartbeat before drain");
+ readiness.mark_draining();
+ heartbeat_handle.abort();
+ let _ = heartbeat_handle.await; // best-effort join
+
+ // Stop the NATS health publisher AFTER `mark_draining`. The
+ // publisher reads `Readiness::snapshot().is_ready()` on every
+ // tick, so the now-draining flag means whatever heartbeat it
+ // sends from here onwards already announces `ready=false`. We
+ // still abort it explicitly because shutdown raced past the
+ // tick interval; without the abort it'd run for one more cycle
+ // before observing the shutdown signal.
+ if let Some(h) = health_publisher_handle {
+ h.abort();
+ let _ = h.await;
+ }
+ if let Some(h) = nats_consumer_reconciler_handle {
+ h.abort();
+ let _ = h.await;
+ }
+ if let Some(h) = pool_admission_handle {
+ h.abort();
+ let _ = h.await;
+ }
+ if let Some(h) = generation_capability_reconciler_handle {
+ h.abort();
+ let _ = h.await;
+ }
+ config_subscriber_handle.abort();
+ let _ = config_subscriber_handle.await;
+ if let Some(h) = config_reconciler_handle {
+ h.abort();
+ let _ = h.await;
+ }
+
+ // Wait for scheduler drain loops to finish their own final drain
+ // window (bounded by SIE_SCHEDULER_DRAIN_DEADLINE_MS inside each
+ // loop; default 10 s). They exit on `shutdown.wait()` which has already fired
+ // by this point (the pull loop returned). Items still pending
+ // after the internal deadline redeliver via JetStream ack_wait.
+ //
+ // Drain handles accumulate lazily as models see their first
+ // traffic; on a worker that never received any traffic this
+ // list is empty.
+ let scheduler_drain_handles = dispatcher.take_scheduler_drain_handles().await;
+ if !scheduler_drain_handles.is_empty() {
+ let scheduler_drain_start = Instant::now();
+ let active_count = scheduler_registry.active_count().await;
+ info!(
+ drain_loop_count = scheduler_drain_handles.len(),
+ active_models = active_count,
+ "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"
+ );
+ }
+
+ let generation_handles = dispatcher.take_generation_handles().await;
+ if !generation_handles.is_empty() {
+ let generation_drain_start = Instant::now();
+ info!(
+ generation_task_count = generation_handles.len(),
+ "generation: awaiting in-flight streams before backend drain"
+ );
+ let joined = timeout(Duration::from_millis(DRAIN_DEADLINE_MS), async {
+ for h in generation_handles {
+ let _ = h.await;
+ }
+ })
+ .await;
+ if joined.is_err() {
+ warn!(
+ deadline_ms = DRAIN_DEADLINE_MS,
+ "generation streams did not settle before drain deadline"
+ );
+ }
+ info!(
+ elapsed_ms = generation_drain_start.elapsed().as_millis() as u64,
+ "generation: in-flight stream wait complete"
+ );
+ }
+
+ info!("draining backends");
+ let drain_start = std::time::Instant::now();
+ backend.drain(DRAIN_DEADLINE_MS).await;
+ let drain_elapsed = drain_start.elapsed();
+ let drain_result = if drain_elapsed.as_millis() as u64 > DRAIN_DEADLINE_MS {
+ metrics_registry
+ .shutdown_drain_deadline_exceeded_total
+ .inc();
+ "deadline_exceeded"
+ } else {
+ "ok"
+ };
+ metrics_registry
+ .shutdown_drain_seconds
+ .with_label_values(&[drain_result])
+ .observe(drain_elapsed.as_secs_f64());
+ info!(
+ drain_seconds = drain_elapsed.as_secs_f64(),
+ drain_result, "backends drained"
+ );
+
+ // Flush NATS publishes. async-nats buffers writes in a background
+ // task; without a flush we can lose results in flight when the
+ // client drops.
+ if let Err(e) = nats_client.flush().await {
+ warn!(error = %e, "NATS flush on shutdown failed");
+ } else {
+ debug!("NATS client flushed");
+ }
+
+ metrics_handle.abort();
+ info!("sie-server-sidecar shutdown complete");
+ Ok(())
+}
+
+#[derive(Default)]
+struct GenerationDirectHandles {
+ pull: Option<JoinHandle<()>>,
+ cancel: Option<JoinHandle<()>>,
+}
+
+/// Owns the worker-specific generation stream and cancel subscription.
+///
+/// Startup detection keeps encode-only workers on the single pool consumer.
+/// Live config apply can add a generation model later, so this controller can
+/// activate the direct-dispatch path exactly once after WorkerCapabilities
+/// reports generation support.
+struct GenerationDirectDispatch {
+ jetstream: async_nats::jetstream::Context,
+ nats_client: async_nats::Client,
+ config: WorkerConfig,
+ dispatcher: Arc<Dispatcher>,
+ shutdown: Arc<Shutdown>,
+ fetch_ctrl: FetchExpiryController,
+ latency_tracker: Arc<Mutex<LatencyTracker>>,
+ pool_admission: Option<Arc<PoolAdmissionGate>>,
+ ipc: Arc<IpcClient>,
+ active: Arc<AtomicBool>,
+ reconcile_notify: Arc<Notify>,
+ handles: Mutex<GenerationDirectHandles>,
+}
+
+impl GenerationDirectDispatch {
+ #[allow(clippy::too_many_arguments)]
+ fn new(
+ jetstream: async_nats::jetstream::Context,
+ nats_client: async_nats::Client,
+ config: WorkerConfig,
+ dispatcher: Arc<Dispatcher>,
+ shutdown: Arc<Shutdown>,
+ fetch_ctrl: FetchExpiryController,
+ latency_tracker: Arc<Mutex<LatencyTracker>>,
+ pool_admission: Option<Arc<PoolAdmissionGate>>,
+ ipc: Arc<IpcClient>,
+ active: Arc<AtomicBool>,
+ ) -> Self {
+ Self {
+ jetstream,
+ nats_client,
+ config,
+ dispatcher,
+ shutdown,
+ fetch_ctrl,
+ latency_tracker,
+ pool_admission,
+ ipc,
+ active,
+ reconcile_notify: Arc::new(Notify::new()),
+ handles: Mutex::new(GenerationDirectHandles::default()),
+ }
+ }
+
+ fn is_active(&self) -> bool {
+ self.active.load(Ordering::Acquire)
+ }
+
+ fn reconcile_notifier(&self) -> Arc<Notify> {
+ Arc::clone(&self.reconcile_notify)
+ }
+
+ async fn activate(&self, reason: &str) -> anyhow::Result<bool> {
+ if self
+ .active
+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
+ .is_err()
+ {
+ return Ok(false);
+ }
+
+ let worker_consumer = match ensure_worker_stream_and_consumer(&self.jetstream, &self.config)
+ .await
+ .context("ensure generation direct-dispatch stream/consumer")
+ {
+ Ok(consumer) => consumer,
+ Err(e) => {
+ self.active.store(false, Ordering::Release);
+ return Err(e);
+ }
+ };
+
+ let nats_worker_consumer = NatsConsumer::new(worker_consumer);
+ let direct_fetch_ctrl = self.fetch_ctrl.clone();
+ let direct_dispatcher = Arc::clone(&self.dispatcher);
+ let direct_shutdown = Arc::clone(&self.shutdown);
+ let direct_latency_tracker = Arc::clone(&self.latency_tracker);
+ let direct_pool_admission = self.pool_admission.clone();
+ let pull = tokio::spawn(async move {
+ run_pull_loop(
+ &nats_worker_consumer,
+ direct_dispatcher,
+ direct_shutdown,
+ &direct_fetch_ctrl,
+ direct_latency_tracker,
+ direct_pool_admission,
+ )
+ .await;
+ });
+ let cancel = spawn_generation_cancel_subscriber(
+ self.nats_client.clone(),
+ Arc::clone(&self.ipc),
+ Arc::clone(&self.shutdown),
+ );
+
+ let mut handles = self.handles.lock().await;
+ handles.pull = Some(pull);
+ handles.cancel = Some(cancel);
+ info!(reason, "generation: direct-dispatch activated");
+ Ok(true)
+ }
+
+ async fn abort_and_join(&self) {
+ let handles = {
+ let mut guard = self.handles.lock().await;
+ GenerationDirectHandles {
+ pull: guard.pull.take(),
+ cancel: guard.cancel.take(),
+ }
+ };
+
+ if let Some(h) = handles.pull {
+ if !h.is_finished() {
+ h.abort();
+ }
+ let _ = h.await;
+ }
+ if let Some(h) = handles.cancel {
+ h.abort();
+ let _ = h.await;
+ }
+ }
+}
+
+fn spawn_nats_consumer_reconciler(
+ jetstream: async_nats::jetstream::Context,
+ config: WorkerConfig,
+ shutdown: Arc<Shutdown>,
+ worker_direct_active: Arc<AtomicBool>,
+) -> Option<JoinHandle<()>> {
+ let every = nats_consumer_reconcile_interval()?;
+ Some(tokio::spawn(async move {
+ info!(
+ interval_ms = every.as_millis() as u64,
+ minimum_interval_ms = MIN_NATS_CONSUMER_RECONCILE_INTERVAL_MS,
+ "nats-consumer: stream/durable reconciler enabled"
+ );
+ loop {
+ tokio::select! {
+ biased;
+ _ = shutdown.wait() => return,
+ _ = sleep(every) => {}
+ }
+ match reconcile_stream_and_consumer(&jetstream, &config).await {
+ Ok(()) => {}
+ Err(e) => warn!(
+ error = %e,
+ "nats-consumer: stream/durable reconcile failed"
+ ),
+ }
+ if worker_direct_active.load(Ordering::Acquire) {
+ match reconcile_worker_stream_and_consumer(&jetstream, &config).await {
+ Ok(()) => {}
+ Err(e) => warn!(
+ error = %e,
+ "nats-consumer: generation direct-dispatch reconcile failed"
+ ),
+ }
+ }
+ }
+ }))
+}
+
+fn spawn_generation_capability_reconciler(
+ ipc: Arc<IpcClient>,
+ direct_dispatch: Arc<GenerationDirectDispatch>,
+ shutdown: Arc<Shutdown>,
+) -> Option<JoinHandle<()>> {
+ if direct_dispatch.is_active() {
+ return None;
+ }
+ let every = generation_capability_reconcile_interval()?;
+ Some(tokio::spawn(async move {
+ info!(
+ interval_ms = every.as_millis() as u64,
+ minimum_interval_ms = MIN_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS,
+ "generation: capability reconciler enabled"
+ );
+ loop {
+ tokio::select! {
+ biased;
+ _ = shutdown.wait() => return,
+ _ = direct_dispatch.reconcile_notify.notified() => {},
+ _ = sleep(every) => {},
+ }
+
+ if direct_dispatch.is_active() {
+ return;
+ }
+
+ match probe_generation_capable(&ipc).await {
+ Some(true) => match direct_dispatch.activate("capability_reconcile").await {
+ Ok(true) => return,
+ Ok(false) => return,
+ Err(e) => warn!(
+ error = %ErrChain(e.as_ref()),
+ "generation: direct-dispatch activation failed; will retry"
+ ),
+ },
+ Some(false) => {
+ debug!("generation: WorkerCapabilities still reports no generation models");
+ }
+ None => {
+ debug!("generation: WorkerCapabilities probe unavailable; will retry");
+ }
+ }
+ }
+ }))
+}
+
+async fn detect_generation_capable(ipc: &Arc<IpcClient>) -> bool {
+ let attempts = worker_capabilities_attempts();
+ let timeout_ms = worker_capabilities_timeout_ms();
+ let mut last_error = String::new();
+ for attempt in 1..=attempts {
+ match timeout(Duration::from_millis(timeout_ms), ipc.worker_capabilities()).await {
+ Ok(Ok(capabilities)) => {
+ info!(
+ has_generation_models = capabilities.has_generation_models,
+ generation_models = ?capabilities.generation_models,
+ "worker capabilities loaded from Python IPC"
+ );
+ return capabilities.has_generation_models;
+ }
+ Ok(Err(e)) => {
+ last_error = e.to_string();
+ }
+ Err(_) => {
+ last_error = format!("timeout after {timeout_ms}ms");
+ }
+ }
+ if attempt < attempts {
+ sleep(Duration::from_millis(200)).await;
+ }
+ }
+ warn!(
+ attempts,
+ timeout_ms,
+ error = %last_error,
+ "worker capabilities unavailable; enabling generation direct-dispatch conservatively"
+ );
+ true
+}
+
+async fn probe_generation_capable(ipc: &Arc<IpcClient>) -> Option<bool> {
+ let timeout_ms = worker_capabilities_timeout_ms();
+ match timeout(Duration::from_millis(timeout_ms), ipc.worker_capabilities()).await {
+ Ok(Ok(capabilities)) => {
+ info!(
+ has_generation_models = capabilities.has_generation_models,
+ generation_models = ?capabilities.generation_models,
+ "generation: WorkerCapabilities reconcile probe complete"
+ );
+ Some(capabilities.has_generation_models)
+ }
+ Ok(Err(e)) => {
+ debug!(error = %e, "generation: WorkerCapabilities reconcile probe failed");
+ None
+ }
+ Err(_) => {
+ debug!(
+ timeout_ms,
+ "generation: WorkerCapabilities reconcile probe timed out"
+ );
+ None
+ }
+ }
+}
+
+fn worker_capabilities_attempts() -> usize {
+ std::env::var("SIE_WORKER_CAPABILITIES_ATTEMPTS")
+ .ok()
+ .and_then(|s| s.parse::<usize>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or(30)
+}
+
+fn worker_capabilities_timeout_ms() -> u64 {
+ std::env::var("SIE_WORKER_CAPABILITIES_TIMEOUT_MS")
+ .ok()
+ .and_then(|s| s.parse::<u64>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or(1_000)
+}
+
+fn spawn_generation_cancel_subscriber(
+ nats_client: async_nats::Client,
+ ipc: Arc<IpcClient>,
+ shutdown: Arc<Shutdown>,
+) -> JoinHandle<()> {
+ tokio::spawn(async move {
+ let mut sub = match nats_client.subscribe("cancel.>".to_string()).await {
+ Ok(sub) => sub,
+ Err(e) => {
+ warn!(error = %e, "generation: failed to subscribe to cancel.>");
+ return;
+ }
+ };
+ info!("generation: cancel subscription started");
+ loop {
+ tokio::select! {
+ biased;
+ _ = shutdown.wait() => return,
+ maybe_msg = sub.next() => {
+ let Some(msg) = maybe_msg else {
+ warn!("generation: cancel subscription ended");
+ return;
+ };
+ let subject = msg.subject.to_string();
+ let Some(request_id) = request_id_from_cancel_subject(&subject) else {
+ debug!(subject = %subject, "generation: ignoring malformed cancel subject");
+ continue;
+ };
+ match ipc.signal_generate_cancel(request_id.clone()).await {
+ Ok(resp) => {
+ debug!(
+ request_id = %request_id,
+ matched = resp.matched,
+ "generation: cancel signal forwarded to Python"
+ );
+ }
+ Err(e) => warn!(
+ request_id = %request_id,
+ error = %e,
+ "generation: failed to forward cancel signal to Python"
+ ),
+ }
+ }
+ }
+ }
+ })
+}
+
+fn request_id_from_cancel_subject(subject: &str) -> Option<String> {
+ let mut parts = subject.splitn(3, '.');
+ match (parts.next(), parts.next(), parts.next()) {
+ (Some("cancel"), Some(_router_id), Some(request_id)) if !request_id.is_empty() => {
+ Some(request_id.to_string())
+ }
+ _ => None,
+ }
+}
+
+/// Ping the Python 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.
+fn spawn_heartbeat(
+ ipc: Arc<IpcClient>,
+ every: Duration,
+ readiness: Arc<Readiness>,
+ config_apply_state: Arc<ConfigApplyState>,
+ shutdown: Arc<Shutdown>,
+) -> tokio::task::JoinHandle<()> {
+ tokio::spawn(async move {
+ let mut tick = interval(every);
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ // Track consecutive failures so we warn on transitions
+ // (0 -> 1 "heartbeat broke", N -> 0 "heartbeat recovered")
+ // without spamming once per tick while Python is down.
+ let mut consecutive_failures: u64 = 0;
+ loop {
+ let wait = shutdown.wait();
+ tokio::select! {
+ biased;
+ _ = wait => return,
+ _ = tick.tick() => {
+ let ts = std::time::SystemTime::now()
+ .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);
+ }
+ readiness.record_ping_success();
+ if consecutive_failures > 0 {
+ info!(
+ consecutive_failures,
+ "IPC heartbeat recovered — /readyz will flip green"
+ );
+ }
+ 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"
+ );
+ }
+ }
+ }
+ }
+ }
+ }
+ })
+}
+
+/// Compute the client-side batch-coalesce quantum from the adaptive
+/// controller, given current latency observations. Bounded by
+/// `fetch_ctrl.{min,max}`. Under cold start (fewer than `min_samples`
+/// observations) returns `fetch_ctrl.min`.
+fn batch_quantum(ctrl: &FetchExpiryController, tracker: &LatencyTracker) -> Duration {
+ // Reuse the existing adaptive controller output so the operator knobs
+ // (`SIE_ADAPTIVE_{MIN,MAX}_QUANTUM_MS`, `SIE_ADAPTIVE_TARGET_P50_MS`)
+ // still apply.
+ ctrl.adjust(ctrl.min, tracker)
+}
+
+/// Open a long-lived pull stream, retrying on transient build failures
+/// until either we succeed or shutdown fires. Returns `None` on
+/// shutdown.
+async fn build_pull_stream(
+ consumer: &NatsConsumer,
+ shutdown: &Shutdown,
+ dispatcher: &Dispatcher,
+ fetch_batch: usize,
+ expires: Duration,
+ backoff: Duration,
+) -> Option<async_nats::jetstream::consumer::pull::Stream> {
+ loop {
+ match consumer.messages(fetch_batch, expires).await {
+ Ok(s) => return Some(s),
+ Err(e) => {
+ warn!(error = %e, "failed to open pull stream; retrying");
+ dispatcher.metrics.nats_fetch_errors_total.inc();
+ tokio::select! {
+ biased;
+ _ = shutdown.wait() => {
+ info!("shutdown while (re)building pull stream");
+ return None;
+ }
+ _ = sleep(backoff) => continue,
+ }
+ }
+ }
+ }
+}
+
+/// Pull messages in a loop and dispatch each batch through the Dispatcher.
+///
+/// # Why one long-lived [`async_nats::jetstream::consumer::pull::Stream`]
+///
+/// async-nats' [`pull::Stream`] issues background pull requests to the
+/// JetStream server and auto-refills credits in the background. When
+/// the stream is dropped, any messages the server has already routed
+/// but which the client hasn't consumed become `ack_pending` from the
+/// server's point of view — they sit stuck until `ack_wait` (30 s)
+/// elapses and the server redelivers them. Under concurrent load the
+/// original "create a stream, pull for N ms, drop it" pattern therefore
+/// collapsed to ~1 message per 30 s throughput with the rest 504'ing at
+/// the gateway.
+///
+/// So: keep one stream open while the worker is admitted to its pool, poll it
+/// continuously, and only rebuild on terminal (`None`) stream death or after a
+/// pool-admission pause. The stream expire inside `pull_stream_expires()`
+/// governs per-pull-request server-side lifetime (default 5 s -> a no-data
+/// `408` every 5 s when idle) and is invisible to callers — `poll_next` handles
+/// the refill.
+///
+/// # Batching
+///
+/// Each loop iteration:
+/// 1. Block on `stream.next()` for the first message of a batch.
+/// 2. Compute a short client-side **quantum** from the adaptive
+/// controller (`batch_quantum`), bounded to
+/// `SIE_ADAPTIVE_{MIN,MAX}_QUANTUM_MS`.
+/// 3. Greedily drain any already-arrived messages until `fetch_batch` or
+/// the quantum deadline, whichever first.
+/// 4. Hand the batch to the dispatcher **as a spawned task**, bounded by
+/// [`pull_loop_inflight`] so the next fetch can start immediately
+/// while Python processes the previous batch. Without this, a single
+/// pull loop serialises `fetch → IPC → GPU → NATS ACK → next fetch`,
+/// leaving the IPC pool and GPU under-fed under distributed load.
+///
+/// The quantum adds at most ~20 ms of latency to the first message of a
+/// burst. A single concurrent request always completes end-to-end in
+/// `quantum + IPC` ≈ tens of ms, independent of ack_wait.
+async fn run_pull_loop(
+ consumer: &NatsConsumer,
+ dispatcher: Arc<Dispatcher>,
+ shutdown: Arc<Shutdown>,
+ fetch_ctrl: &FetchExpiryController,
+ latency_tracker: Arc<Mutex<LatencyTracker>>,
+ pool_admission: Option<Arc<PoolAdmissionGate>>,
+) {
+ let fetch_batch = fetch_batch_size();
+ let pull_expires = pull_stream_expires();
+ let rebuild_backoff = Duration::from_millis(500);
+ let inflight_cap = pull_loop_inflight();
+ let dispatch_permits = Arc::new(Semaphore::new(inflight_cap));
+ let mut inflight_tasks: Vec<JoinHandle<()>> = Vec::new();
+
+ info!(
+ fetch_batch,
+ pull_expires_s = pull_expires.as_secs(),
+ quantum_min_ms = fetch_ctrl.min.as_millis() as u64,
+ quantum_max_ms = fetch_ctrl.max.as_millis() as u64,
+ inflight_cap,
+ "pull loop starting",
+ );
+
+ let mut stream: Option<async_nats::jetstream::consumer::pull::Stream> = None;
+
+ 'outer: loop {
+ if let Some(gate) = pool_admission.as_ref() {
+ if !gate.admitted() {
+ // Drop the long-lived pull stream while not admitted. Keeping
+ // it open would leave server-side pull credits active and let
+ // JetStream deliver messages into this client even though this
+ // worker is outside the pool assignment.
+ stream = None;
+ tokio::select! {
+ biased;
+ _ = shutdown.wait() => break 'outer,
+ _ = sleep(gate.pause_duration()) => continue 'outer,
+ }
+ }
+ }
+
+ if stream.is_none() {
+ stream = match build_pull_stream(
+ consumer,
+ &shutdown,
+ &dispatcher,
+ fetch_batch,
+ pull_expires,
+ rebuild_backoff,
+ )
+ .await
+ {
+ Some(s) => Some(s),
+ None => break 'outer,
+ };
+ }
+
+ // Step 1: block for the first message of the next batch.
+ 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(Err(e)) => {
+ // Recoverable per-poll errors (server TIMEOUT 408, missed
+ // heartbeat, etc.) surface here. The underlying Stream is
+ // still usable — async-nats will have re-armed another pull
+ // internally. Log, count, and keep going.
+ debug!(error = %e, "pull stream poll error; continuing");
+ dispatcher.metrics.nats_stream_errors_total.inc();
+ continue 'outer;
+ }
+ None => {
+ // Terminal end of stream (internal async-nats task died,
+ // connection gone, etc.). Rebuild. Any messages that had
+ // been routed to the old stream but not yet consumed are
+ // recoverable via ack_wait → redelivery; we can't do
+ // better than that without a fresh stream.
+ warn!("pull stream returned None (terminal); rebuilding");
+ dispatcher.metrics.nats_stream_errors_total.inc();
+ stream = None;
+ continue 'outer;
+ }
+ };
+
+ // Step 2: coalesce. Compute the quantum once, relative to now.
+ let started = Instant::now();
+ let mut batch = Vec::with_capacity(fetch_batch);
+ batch.push(first_msg);
+
+ let quantum = {
+ let tracker = latency_tracker.lock().await;
+ batch_quantum(fetch_ctrl, &tracker)
+ };
+ let deadline = started + quantum;
+
+ while batch.len() < fetch_batch {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ if remaining.is_zero() {
+ 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(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();
+ break;
+ }
+ None => {
+ // Terminal mid-batch. Flush what we have, then
+ // the next iteration will rebuild.
+ warn!("pull stream ended mid-batch; flushing partial batch");
+ dispatcher.metrics.nats_stream_errors_total.inc();
+ stream = None;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ // Step 3: dispatch. Acquire a dispatch permit (bounded by
+ // `inflight_cap`) and spawn `handle_batch`, so the next fetch can
+ // start immediately while Python processes this batch. Acquiring
+ // *before* spawning is important: it keeps memory bounded when
+ // Python is slower than NATS, and naturally applies backpressure
+ // up to the stream (unacked messages will stop being pulled once
+ // the server-side window fills).
+ let got = batch.len();
+ debug!(
+ batch_size = got,
+ quantum_ms = quantum.as_millis() as u64,
+ assembled_ms = started.elapsed().as_millis() as u64,
+ "batch assembled"
+ );
+
+ // Opportunistically reap finished task handles so the vec doesn't
+ // grow unboundedly across a long-running loop. Cheap: only
+ // allocates when there's actual movement and doesn't block.
+ inflight_tasks.retain(|h| !h.is_finished());
+
+ let permit = tokio::select! {
+ biased;
+ _ = shutdown.wait() => break 'outer,
+ permit = dispatch_permits.clone().acquire_owned() => match permit {
+ Ok(p) => p,
+ Err(_) => {
+ warn!("pull-loop dispatch semaphore closed — exiting loop");
+ break 'outer;
+ }
+ },
+ };
+
+ let dispatcher_clone = Arc::clone(&dispatcher);
+ let handle = tokio::spawn(async move {
+ dispatcher_clone.handle_batch(batch).await;
+ drop(permit);
+ });
+ inflight_tasks.push(handle);
+ }
+
+ // Wait for any spawned dispatch tasks to finish so callers can rely
+ // on the pull-loop exit being a quiescence point (no still-running
+ // IPC / NATS ACK work). We keep the deadline generous but bounded so
+ // a pathological backend can't indefinitely stall shutdown.
+ let pending = inflight_tasks.len();
+ if pending > 0 {
+ info!(
+ pending_tasks = pending,
+ deadline_ms = PULL_LOOP_TASK_JOIN_DEADLINE_MS,
+ "pull loop exited; waiting for in-flight dispatch tasks"
+ );
+ let join_deadline = Duration::from_millis(PULL_LOOP_TASK_JOIN_DEADLINE_MS);
+ let joined = timeout(join_deadline, async {
+ for h in inflight_tasks.drain(..) {
+ let _ = h.await;
+ }
+ })
+ .await;
+ if joined.is_err() {
+ warn!(
+ deadline_ms = PULL_LOOP_TASK_JOIN_DEADLINE_MS,
+ "in-flight dispatch tasks did not finish before join deadline — proceeding to drain"
+ );
+ }
+ }
+ info!("pull loop exiting");
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn pull_loop_inflight_defaults_are_positive() {
+ // Env-free default should be at least 1 and match the dispatcher
+ // concurrency default when `SIE_PULL_LOOP_INFLIGHT` is unset. We
+ // don't mutate env here to avoid polluting other tests in the
+ // same process.
+ assert!(pull_loop_inflight() >= 1);
+ assert_eq!(
+ pull_loop_inflight(),
+ crate::dispatcher::default_max_concurrent_batches().max(1)
+ );
+ }
+
+ #[test]
+ fn nats_consumer_reconcile_interval_defaults_and_disables() {
+ assert_eq!(
+ parse_nats_consumer_reconcile_interval_ms(None),
+ Some(DEFAULT_NATS_CONSUMER_RECONCILE_INTERVAL_MS)
+ );
+ assert_eq!(
+ parse_nats_consumer_reconcile_interval_ms(Some("")),
+ Some(DEFAULT_NATS_CONSUMER_RECONCILE_INTERVAL_MS)
+ );
+ assert_eq!(parse_nats_consumer_reconcile_interval_ms(Some("0")), None);
+ }
+
+ #[test]
+ fn nats_consumer_reconcile_interval_clamps_to_slow_floor() {
+ assert_eq!(
+ parse_nats_consumer_reconcile_interval_ms(Some("1")),
+ Some(MIN_NATS_CONSUMER_RECONCILE_INTERVAL_MS)
+ );
+ assert_eq!(
+ parse_nats_consumer_reconcile_interval_ms(Some("10000")),
+ Some(MIN_NATS_CONSUMER_RECONCILE_INTERVAL_MS)
+ );
+ assert_eq!(
+ parse_nats_consumer_reconcile_interval_ms(Some("30000")),
+ Some(DEFAULT_NATS_CONSUMER_RECONCILE_INTERVAL_MS)
+ );
+ assert_eq!(
+ parse_nats_consumer_reconcile_interval_ms(Some("bad")),
+ Some(DEFAULT_NATS_CONSUMER_RECONCILE_INTERVAL_MS)
+ );
+ }
+
+ #[test]
+ fn wave_cadence_enabled_default_is_true() {
+ // Per-wave stepping is the default tail-latency posture.
+ // Operators flip off via `SIE_RUST_WAVE_CADENCE=off` for the
+ // inverse trade (smaller batches, lower p50, looser p99). We
+ // don't mutate env here to avoid contaminating sibling tests
+ // via the function's `OnceLock` cache.
+ if std::env::var("SIE_RUST_WAVE_CADENCE").is_err() {
+ assert!(
+ wave_cadence_enabled(),
+ "wave-cadence must default ON; see lib.rs docstring for the p99 rationale"
+ );
+ }
+ }
+
+ #[test]
+ fn pull_quantum_includes_queue_ms_default_is_false() {
+ // Env-free default must exclude `queue_ms` from the
+ // FetchExpiryController input.
+ // Operators opt in via `SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS=1`.
+ // We don't mutate env here to avoid cross-test flakiness; the
+ // function's `OnceLock` cache makes any toggle in a sibling
+ // test a permanent contamination across the process.
+ if std::env::var("SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS").is_err() {
+ assert!(
+ !pull_quantum_includes_queue_ms(),
+ "queue_ms must be excluded by default — see Dispatcher docstring"
+ );
+ }
+ }
+
+ #[test]
+ fn cancel_subject_parser_extracts_request_id() {
+ assert_eq!(
+ request_id_from_cancel_subject("cancel.gateway-1.018f9b0c-req"),
+ Some("018f9b0c-req".to_string())
+ );
+ assert_eq!(
+ request_id_from_cancel_subject("cancel.gateway-1.req.with.dots"),
+ Some("req.with.dots".to_string())
+ );
+ assert_eq!(request_id_from_cancel_subject("cancel.gateway-1"), None);
+ assert_eq!(request_id_from_cancel_subject("other.gateway-1.req"), None);
+ }
+}
diff --git a/packages/sie_server_sidecar/src/log_util.rs b/packages/sie_server_sidecar/src/log_util.rs
new file mode 100644
index 000000000..fc563e3b3
--- /dev/null
+++ b/packages/sie_server_sidecar/src/log_util.rs
@@ -0,0 +1,82 @@
+//! Small helpers for structured logging.
+//!
+//! [`ErrChain`] renders an error together with its full `#[source]`
+//! chain, so `warn!(error = %ErrChain(&e), ...)` shows everything from
+//! the outermost user-facing message down to the root cause in one
+//! structured field. Without this, the default `Display` for
+//! `thiserror`-derived errors only shows the outermost layer — you lose
+//! "caused by: connection refused" etc., which is exactly what you
+//! need when diagnosing a problem from prod logs.
+
+use std::error::Error;
+use std::fmt;
+
+/// Wrap an error so its `Display` walks the `#[source]` chain.
+///
+/// Each layer is joined with ` -> ` so the final rendering still fits
+/// on a single log line (Loki / Cloud Logging both dislike newlines
+/// inside structured fields). Example:
+///
+/// ```text
+/// ipc call failed -> io error -> connection refused
+/// ```
+pub struct ErrChain<'a>(pub &'a dyn Error);
+
+impl fmt::Display for ErrChain<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.0)?;
+ let mut source = self.0.source();
+ while let Some(cause) = source {
+ write!(f, " -> {cause}")?;
+ source = cause.source();
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use thiserror::Error;
+
+ #[derive(Debug, Error)]
+ enum Inner {
+ #[error("inner boom")]
+ Boom,
+ }
+
+ #[derive(Debug, Error)]
+ enum Outer {
+ #[error("outer wrap")]
+ Wrap(#[source] Inner),
+ }
+
+ #[test]
+ fn renders_full_chain() {
+ let e = Outer::Wrap(Inner::Boom);
+ let chain: &dyn Error = &e;
+ let rendered = format!("{}", ErrChain(chain));
+ assert_eq!(rendered, "outer wrap -> inner boom");
+ }
+
+ #[test]
+ fn single_layer_renders_display_verbatim() {
+ let e = Inner::Boom;
+ let chain: &dyn Error = &e;
+ assert_eq!(format!("{}", ErrChain(chain)), "inner boom");
+ }
+
+ #[test]
+ fn deeper_chain_joined_with_arrow() {
+ // Chain of three layers via std::io::Error wrapping.
+ #[derive(Debug, Error)]
+ enum Wrap {
+ #[error("wrap")]
+ Io(#[source] std::io::Error),
+ }
+ let io = std::io::Error::new(std::io::ErrorKind::BrokenPipe, "kernel said pipe");
+ let outer = Wrap::Io(io);
+ let chain: &dyn Error = &outer;
+ assert_eq!(format!("{}", ErrChain(chain)), "wrap -> kernel said pipe");
+ }
+}
diff --git a/packages/sie_server_sidecar/src/main.rs b/packages/sie_server_sidecar/src/main.rs
new file mode 100644
index 000000000..1387873ee
--- /dev/null
+++ b/packages/sie_server_sidecar/src/main.rs
@@ -0,0 +1,230 @@
+//! sie-server-sidecar — sidecar driving the NATS queue for a sie-server pod.
+//!
+//! See `docs/architecture-guide.md` for the design. This binary is the
+//! entrypoint; the library modules live in `lib.rs`.
+
+use anyhow::Context;
+use clap::Parser;
+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;
+
+#[derive(Parser, Debug)]
+#[command(author, version, about = "SIE server sidecar", long_about = None)]
+struct Cli {
+ #[arg(long, env = "SIE_NATS_URL")]
+ nats_url: String,
+
+ #[arg(long, env = "SIE_POOL", default_value = "_default")]
+ pool: String,
+
+ #[arg(long, env = "SIE_BUNDLE", default_value = "default")]
+ bundle: String,
+
+ #[arg(long, env = "SIE_IPC_SOCKET_PATH", default_value = "/tmp/sie-ipc.sock")]
+ ipc_socket_path: String,
+
+ /// Number of concurrent IPC connections to the Python 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
+ /// concurrency cap.
+ #[arg(long, env = "SIE_IPC_POOL_SIZE")]
+ ipc_pool_size: Option<usize>,
+
+ #[arg(long, env = "SIE_PAYLOAD_STORE_URL")]
+ payload_store_url: Option<String>,
+
+ /// Gateway URL used by the worker-side pool admission gate.
+ #[arg(long, env = "SIE_GATEWAY_URL")]
+ gateway_url: Option<String>,
+
+ /// Bearer token for gateway pool-status reads.
+ #[arg(long, env = "SIE_GATEWAY_API_KEY")]
+ gateway_api_key: Option<String>,
+
+ /// Enable/disable the worker-side pool admission gate.
+ #[arg(long, env = "SIE_POOL_ADMISSION_ENABLED")]
+ pool_admission_enabled: Option<String>,
+
+ /// Pool admission check cadence, in seconds.
+ #[arg(
+ long,
+ env = "SIE_POOL_ADMISSION_CHECK_INTERVAL_S",
+ default_value = "5.0"
+ )]
+ pool_admission_check_interval_s: f64,
+
+ /// Sleep duration while the worker is not admitted, in seconds.
+ #[arg(long, env = "SIE_POOL_ADMISSION_PAUSE_S", default_value = "1.0")]
+ pool_admission_pause_s: f64,
+
+ /// How long to reuse the last successful admission decision after a
+ /// transient gateway/status error, in seconds.
+ #[arg(long, env = "SIE_POOL_ADMISSION_STALE_AFTER_S", default_value = "30.0")]
+ pool_admission_stale_after_s: f64,
+
+ #[arg(long, env = "SIE_WORKER_METRICS_PORT", default_value = "9095")]
+ metrics_port: u16,
+
+ #[arg(long, env = "SIE_WORKER_ID")]
+ worker_id: Option<String>,
+
+ #[arg(long, env = "SIE_WORKER_PING_INTERVAL_MS", default_value = "2000")]
+ ping_interval_ms: u64,
+
+ /// Multiplier applied to `--ping-interval-ms` to derive the
+ /// staleness threshold for `/readyz`. Default `3`, matching the
+ /// sidecar readiness contract. `0` is treated
+ /// as the default (see `WorkerConfig::ready_stale_mult`).
+ #[arg(long, env = "SIE_WORKER_READYZ_STALE_MULT", default_value = "3")]
+ ready_stale_mult: u32,
+
+ /// Machine-profile label echoed in NATS health heartbeats.
+ /// Used by the gateway when a request carries
+ /// `X-SIE-MACHINE-PROFILE`; empty disables that filter.
+ /// Defaults to the pool name (the historical convention where
+ /// pool == GPU type, e.g. `l4`).
+ #[arg(long, env = "SIE_MACHINE_PROFILE")]
+ machine_profile: Option<String>,
+
+ /// GPU count surfaced in heartbeats. Informational; the
+ /// gateway coerces 0 to 1. Defaults to 1.
+ #[arg(long, env = "SIE_GPU_COUNT", default_value = "1")]
+ gpu_count: i32,
+
+ /// Optional bundle-config hash echoed in heartbeats. Empty
+ /// when the operator hasn't pinned a value.
+ #[arg(long, env = "SIE_BUNDLE_CONFIG_HASH", default_value = "")]
+ bundle_config_hash: String,
+
+ /// Optional sie-config base URL. When set, the sidecar polls
+ /// /v1/configs/epoch and reconciles missed config deltas from
+ /// /v1/configs/export.
+ #[arg(long, env = "SIE_CONFIG_SERVICE_URL")]
+ config_service_url: Option<String>,
+
+ /// Bearer token for sie-config export reads. Defaults from the shared
+ /// SIE_ADMIN_TOKEN secret in Helm when config auth is enabled.
+ #[arg(long, env = "SIE_ADMIN_TOKEN")]
+ config_service_token: Option<String>,
+
+ /// Worker-side config epoch poll interval in milliseconds.
+ #[arg(
+ long,
+ env = "SIE_WORKER_CONFIG_POLL_INTERVAL_MS",
+ default_value = "30000"
+ )]
+ config_poll_interval_ms: u64,
+
+ /// Slow full-export reconcile interval in milliseconds. Set to 0 to
+ /// disable after the startup export. Kept separate from the epoch poll
+ /// so no-config-store deployments can still recover missed live deltas.
+ #[arg(
+ long,
+ env = "SIE_WORKER_CONFIG_FULL_EXPORT_INTERVAL_MS",
+ default_value = "300000"
+ )]
+ config_full_export_interval_ms: u64,
+
+ /// Heartbeat interval (ms) for the NATS health publisher.
+ /// Default 5_000 ms; must stay << gateway
+ /// `heartbeat_timeout` (30 s) so the staleness check has
+ /// margin.
+ #[arg(long, env = "SIE_HEALTH_PUBLISH_INTERVAL_MS", default_value = "5000")]
+ health_publish_interval_ms: u64,
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ init_tracing();
+
+ let cli = Cli::parse();
+ let pool = cli.pool;
+ // Default machine_profile to the pool name: in practice every
+ // existing helm pool we operate (`l4`, `a100`, `h100`) is named
+ // after its GPU SKU, and the gateway compares the field
+ // case-insensitively. Operators with a non-conventional pool
+ // (`mixed-spot-1`) can override via `SIE_MACHINE_PROFILE`.
+ let machine_profile = cli.machine_profile.unwrap_or_else(|| pool.clone());
+ let config = WorkerConfig {
+ nats_url: cli.nats_url,
+ pool,
+ bundle: cli.bundle,
+ ipc_socket_path: cli.ipc_socket_path.into(),
+ ipc_pool_size: cli
+ .ipc_pool_size
+ .filter(|&n| n > 0)
+ .unwrap_or_else(default_max_concurrent_batches),
+ payload_store_url: cli.payload_store_url,
+ gateway_url: cli.gateway_url.filter(|url| !url.trim().is_empty()),
+ gateway_api_key: cli.gateway_api_key.filter(|token| !token.trim().is_empty()),
+ pool_admission_enabled: env_bool_value(cli.pool_admission_enabled.as_deref(), true),
+ pool_admission_check_interval_ms: seconds_to_millis(
+ cli.pool_admission_check_interval_s,
+ 1_000,
+ ),
+ pool_admission_pause_ms: seconds_to_millis(cli.pool_admission_pause_s, 100),
+ pool_admission_stale_after_ms: seconds_to_millis(cli.pool_admission_stale_after_s, 0),
+ metrics_port: cli.metrics_port,
+ worker_id: cli.worker_id.unwrap_or_else(|| {
+ std::env::var("HOSTNAME").unwrap_or_else(|_| format!("worker-{}", uuid::Uuid::new_v4()))
+ }),
+ ping_interval_ms: cli.ping_interval_ms,
+ ready_stale_mult: cli.ready_stale_mult,
+ machine_profile,
+ gpu_count: cli.gpu_count,
+ bundle_config_hash: cli.bundle_config_hash,
+ config_service_url: cli.config_service_url.filter(|url| !url.trim().is_empty()),
+ config_service_token: cli
+ .config_service_token
+ .filter(|token| !token.trim().is_empty()),
+ config_poll_interval_ms: cli.config_poll_interval_ms.max(1_000),
+ config_full_export_interval_ms: cli.config_full_export_interval_ms,
+ nats_config_trusted_producers: trusted_producers_from_env(),
+ health_publish_interval_ms: cli.health_publish_interval_ms,
+ };
+
+ info!(
+ pool = %config.pool,
+ bundle = %config.bundle,
+ ipc = %config.ipc_socket_path.display(),
+ ipc_pool_size = config.ipc_pool_size,
+ worker_id = %config.worker_id,
+ "sie-server-sidecar starting"
+ );
+
+ if let Err(e) = run(config).await.context("server sidecar run loop") {
+ error!(error = ?e, "sie-server-sidecar exited with error");
+ std::process::exit(1);
+ }
+
+ Ok(())
+}
+
+fn init_tracing() {
+ use tracing_subscriber::{fmt, EnvFilter};
+ let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
+ fmt().with_env_filter(filter).json().init();
+}
+
+fn env_bool_value(raw: Option<&str>, default: bool) -> bool {
+ let Some(raw) = raw else {
+ return default;
+ };
+ let trimmed = raw.trim().to_ascii_lowercase();
+ if trimmed.is_empty() {
+ return default;
+ }
+ !matches!(trimmed.as_str(), "0" | "false" | "no" | "off")
+}
+
+fn seconds_to_millis(seconds: f64, min_ms: u64) -> u64 {
+ if !seconds.is_finite() || seconds <= 0.0 {
+ return min_ms;
+ }
+ ((seconds * 1_000.0).round() as u64).max(min_ms)
+}
diff --git a/packages/sie_server_sidecar/src/metrics.rs b/packages/sie_server_sidecar/src/metrics.rs
new file mode 100644
index 000000000..ab90583f9
--- /dev/null
+++ b/packages/sie_server_sidecar/src/metrics.rs
@@ -0,0 +1,861 @@
+//! Prometheus metrics + HTTP /metrics + /healthz server.
+//!
+//! Port defaults to 9095. The dispatcher and scheduler register the
+//! counters/histograms used by the worker hot path.
+
+use std::convert::Infallible;
+use std::net::SocketAddr;
+use std::sync::Arc;
+
+use http_body_util::Full;
+use hyper::body::Bytes;
+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,
+};
+use tokio::net::TcpListener;
+use tokio::task::JoinHandle;
+use tracing::{error, info, warn};
+
+use crate::readiness::Readiness;
+use crate::shutdown::Shutdown;
+
+/// Histogram buckets for items-fetched-per-pull-cycle.
+const ITEMS_FETCHED_BUCKETS: &[f64] = &[1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0];
+
+/// Histogram buckets for batch-process-seconds.
+const BATCH_PROCESS_BUCKETS: &[f64] = &[
+ 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
+];
+
+/// Finer buckets for sub-millisecond IPC RPCs (UDS to local Python).
+const IPC_REQUEST_BUCKETS: &[f64] = &[
+ 0.0001, 0.00025, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5,
+ 5.0, 10.0, 30.0,
+];
+
+/// Buckets for payload bytes (request/response frames).
+const BYTES_BUCKETS: &[f64] = &[
+ 256.0,
+ 1024.0,
+ 4096.0,
+ 16_384.0,
+ 65_536.0,
+ 262_144.0,
+ 1_048_576.0,
+ 4_194_304.0,
+ 16_777_216.0,
+ 67_108_864.0,
+];
+
+/// Buckets for drain-duration-seconds (graceful shutdown timing).
+const DRAIN_DURATION_BUCKETS: &[f64] = &[
+ 0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 15.0, 30.0, 60.0,
+];
+
+/// Buckets for NATS JetStream redelivery counts (capped at 10).
+const DELIVER_COUNT_BUCKETS: &[f64] = &[1.0, 2.0, 3.0, 5.0, 10.0];
+
+/// Prometheus metrics shared by the worker.
+///
+/// The `sie_worker_*` surface is internal/Rust-only; the `sie_pull_loop_*`
+/// surface preserves the metric names used by existing Grafana dashboards
+/// originally wired to the Python pull loop.
+///
+/// ## Label cardinality
+///
+/// Metric labels that carry a `model` dimension use the full model_id
+/// by default. For deployments that worry about cardinality (very
+/// wide model fleets, untrusted model_ids, multi-tenant clusters),
+/// set `SIE_METRIC_MODEL_ALLOWLIST` to the active/materialized
+/// model ids; anything outside that set will be re-labeled `"other"`.
+/// This is applied via [`MetricsRegistry::model_label`] — use it
+/// everywhere a `model` label value is constructed.
+pub struct MetricsRegistry {
+ pub registry: Registry,
+ pub messages_received_total: IntCounter,
+ pub messages_acked_total: IntCounter,
+ pub messages_naked_total: IntCounter,
+ pub ipc_requests_total: IntCounter,
+ pub ipc_failures_total: IntCounter,
+ pub inflight_batches: IntGauge,
+
+ pub pull_items_fetched: HistogramVec,
+ pub pull_batch_process_seconds: HistogramVec,
+ pub pull_nak_unloaded_total: IntCounterVec,
+ pub pull_model_loads_total: IntCounterVec,
+
+ // Per-backend visibility. These measure what actually landed in
+ // each backend after routing, so operators can compare native and
+ // Python batch rates, outcome counts, and backend latency.
+ pub backend_process_seconds: HistogramVec,
+ pub backend_batch_items: HistogramVec,
+ pub backend_process_errors_total: IntCounterVec,
+ pub backend_ensure_ready_seconds: HistogramVec,
+ pub backend_item_outcomes_total: IntCounterVec,
+
+ /// Backend timing breakdown for successful backend round-trips.
+ /// Observations are populated from per-item `inference_ms` /
+ /// `tokenization_ms` / `postprocessing_ms` fields on each
+ /// `ItemOutcome`.
+ ///
+ /// Python 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
+ /// within the same backend/model and use rate(sum)/rate(count)
+ /// when an aggregate mean is required.
+ ///
+ /// Labels are bounded: `phase` is a 3-value enum, `operation`
+ /// is restricted to encode/score/extract at the observe site,
+ /// and `model` goes through `model_label()` which honours
+ /// `SIE_METRIC_MODEL_ALLOWLIST`.
+ pub backend_phase_seconds: HistogramVec,
+
+ // IPC client visibility (per-method).
+ pub ipc_request_seconds: HistogramVec,
+ pub ipc_request_bytes: HistogramVec,
+ pub ipc_response_bytes: HistogramVec,
+ pub ipc_connect_total: IntCounterVec,
+ pub ipc_reconnect_total: IntCounter,
+
+ // IPC connection pool visibility. `ipc_pool_size` is a constant
+ // reflecting the configured pool capacity; `ipc_pool_inflight` is
+ // the live count of checked-out slots (≈ concurrent in-flight RPCs);
+ // `ipc_pool_acquire_wait_seconds` measures how long a caller waited
+ // for a free slot — a non-zero p50 is the signal that the pool is
+ // saturated and should be grown.
+ pub ipc_pool_size: IntGauge,
+ pub ipc_pool_inflight: IntGauge,
+ pub ipc_pool_acquire_wait_seconds: Histogram,
+
+ // IPC multiplexer (`SIE_IPC_MUX=1`) visibility. Both metrics are
+ // registered unconditionally so dashboards can compare the slot-pool
+ // path to the mux path side-by-side; they stay at zero on the
+ // slot-pool path. `ipc_mux_inflight` is a gauge of in-flight RPCs
+ // through the multiplexer; without an explicit cap (the eventual
+ // SIE_IPC_MUX_MAX_INFLIGHT_PER_POD knob) it tracks the raw concurrency
+ // dispatched onto the single UDS connection.
+ // `ipc_mux_acquire_wait_seconds` is the wall time spent waiting for
+ // a per-pod inflight permit — the histogram is wired through
+ // `MuxClient::call_raw` so it lights up the moment the cap is added,
+ // no rebuild required.
+ pub ipc_mux_inflight: IntGauge,
+ pub ipc_mux_acquire_wait_seconds: Histogram,
+
+ // Payload store visibility.
+ pub payload_fetch_total: IntCounter,
+ pub payload_fetch_errors_total: IntCounterVec,
+ pub payload_fetch_seconds: HistogramVec,
+ pub payload_bytes: HistogramVec,
+
+ // JetStream ACK/NAK outcome accounting.
+ pub jetstream_ack_failures_total: IntCounter,
+ pub jetstream_nak_failures_total: IntCounter,
+ pub nats_fetch_errors_total: IntCounter,
+ pub nats_stream_errors_total: IntCounter,
+ pub nats_redelivery_total: IntCounter,
+ pub nats_deliver_count: HistogramVec,
+
+ // Live worker config apply.
+ pub config_deltas_total: IntCounterVec,
+ pub config_epoch: IntGauge,
+
+ // Shutdown / drain timing.
+ pub shutdown_drain_seconds: HistogramVec,
+ pub shutdown_drain_deadline_exceeded_total: IntCounter,
+
+ // Router fall-through events (A said supports, returned UnsupportedModel,
+ // router moved on to B).
+ pub router_fallthrough_total: IntCounterVec,
+
+ /// Scheduler-family metrics. Registered at startup but populated
+ /// only once the Rust scheduler is actually
+ /// draining traffic — keeps `/metrics` shape stable across
+ /// partially-wired / fully-wired deployments.
+ pub scheduler: crate::scheduler::SchedulerMetrics,
+
+ /// Optional active/materialized model ids for bounding cardinality.
+ /// None => unrestricted (matches Python's behaviour).
+ materialized_model_ids: Option<std::collections::HashSet<String>>,
+}
+
+impl MetricsRegistry {
+ pub fn new() -> anyhow::Result<Self> {
+ let registry = Registry::new();
+
+ let messages_received_total =
+ IntCounter::new("sie_worker_messages_received_total", "NATS msgs pulled")?;
+ let messages_acked_total =
+ IntCounter::new("sie_worker_messages_acked_total", "NATS msgs ACKed")?;
+ let messages_naked_total =
+ IntCounter::new("sie_worker_messages_naked_total", "NATS msgs NAKed")?;
+ let ipc_requests_total = IntCounter::new("sie_worker_ipc_requests_total", "IPC RPCs sent")?;
+ let ipc_failures_total = IntCounter::new(
+ "sie_worker_ipc_failures_total",
+ "IPC RPCs that returned ok=false or failed",
+ )?;
+ let inflight_batches = IntGauge::new(
+ "sie_worker_inflight_batches",
+ "Number of batches currently in flight through IPC",
+ )?;
+
+ let pull_items_fetched = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_pull_loop_items_fetched",
+ "Number of items fetched per pull cycle",
+ )
+ .buckets(ITEMS_FETCHED_BUCKETS.to_vec()),
+ &["model"],
+ )?;
+ let pull_batch_process_seconds = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_pull_loop_batch_process_seconds",
+ "Time to process a pulled batch (seconds)",
+ )
+ .buckets(BATCH_PROCESS_BUCKETS.to_vec()),
+ &["model", "operation"],
+ )?;
+ let pull_nak_unloaded_total = IntCounterVec::new(
+ Opts::new(
+ "sie_pull_loop_nak_unloaded_total",
+ "Work items NAKed because the target model is not loaded",
+ ),
+ &["model"],
+ )?;
+ let pull_model_loads_total = IntCounterVec::new(
+ Opts::new(
+ "sie_pull_loop_model_loads_total",
+ "Background model loads triggered by demand",
+ ),
+ &["model"],
+ )?;
+
+ let backend_process_seconds = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_backend_process_seconds",
+ "End-to-end wall time for a single batch in a backend (seconds)",
+ )
+ .buckets(BATCH_PROCESS_BUCKETS.to_vec()),
+ &["backend", "operation", "model", "result"],
+ )?;
+ let backend_batch_items = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_backend_batch_items",
+ "Number of items in a batch handed to a backend",
+ )
+ .buckets(ITEMS_FETCHED_BUCKETS.to_vec()),
+ &["backend", "operation"],
+ )?;
+ let backend_process_errors_total = IntCounterVec::new(
+ Opts::new(
+ "sie_worker_backend_process_errors_total",
+ "Batch-level errors returned by a backend (broken out by kind)",
+ ),
+ &["backend", "operation", "error_kind"],
+ )?;
+ let backend_ensure_ready_seconds = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_backend_ensure_ready_seconds",
+ "Wall time for ensure_model_ready calls (seconds)",
+ )
+ .buckets(BATCH_PROCESS_BUCKETS.to_vec()),
+ &["backend", "model", "result"],
+ )?;
+ let backend_item_outcomes_total = IntCounterVec::new(
+ Opts::new(
+ "sie_worker_backend_item_outcomes_total",
+ "Per-item dispositions returned by a backend (publish, error, ack-to-drop, ...)",
+ ),
+ &["backend", "operation", "disposition"],
+ )?;
+
+ let backend_phase_seconds = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_backend_phase_seconds",
+ "Per-item wall time for each backend phase (tokenize, inference, postprocess), in seconds. Populated from ItemOutcome timings on the success path.",
+ )
+ .buckets(BATCH_PROCESS_BUCKETS.to_vec()),
+ &["operation", "model", "phase"],
+ )?;
+
+ let ipc_request_seconds = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_ipc_request_seconds",
+ "Wall time of a single IPC RPC, by method and outcome",
+ )
+ .buckets(IPC_REQUEST_BUCKETS.to_vec()),
+ &["method", "result"],
+ )?;
+ let ipc_request_bytes = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_ipc_request_bytes",
+ "Bytes in outgoing IPC request frames",
+ )
+ .buckets(BYTES_BUCKETS.to_vec()),
+ &["method"],
+ )?;
+ let ipc_response_bytes = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_ipc_response_bytes",
+ "Bytes in incoming IPC response frames",
+ )
+ .buckets(BYTES_BUCKETS.to_vec()),
+ &["method"],
+ )?;
+ let ipc_connect_total = IntCounterVec::new(
+ Opts::new(
+ "sie_worker_ipc_connect_total",
+ "IPC socket connect attempts, by outcome",
+ ),
+ &["result"],
+ )?;
+ let ipc_reconnect_total = IntCounter::new(
+ "sie_worker_ipc_reconnect_total",
+ "IPC connection resets that triggered a reconnect",
+ )?;
+
+ let ipc_pool_size = IntGauge::new(
+ "sie_worker_ipc_pool_size",
+ "Configured IPC connection pool capacity (constant after startup)",
+ )?;
+ let ipc_pool_inflight = IntGauge::new(
+ "sie_worker_ipc_pool_inflight",
+ "IPC connections currently checked out of the pool (concurrent in-flight RPCs)",
+ )?;
+ let ipc_pool_acquire_wait_seconds = Histogram::with_opts(
+ HistogramOpts::new(
+ "sie_worker_ipc_pool_acquire_wait_seconds",
+ "Wall time a caller waited for a free IPC pool slot; non-zero p50 indicates \
+ the pool is saturated and should be enlarged via SIE_IPC_POOL_SIZE",
+ )
+ .buckets(IPC_REQUEST_BUCKETS.to_vec()),
+ )?;
+
+ let ipc_mux_inflight = IntGauge::new(
+ "sie_worker_ipc_mux_inflight",
+ "RPCs currently in flight on the IPC multiplexer (SIE_IPC_MUX=1). Stays at 0 \
+ when the slot-pool transport is in use.",
+ )?;
+ let ipc_mux_acquire_wait_seconds = Histogram::with_opts(
+ HistogramOpts::new(
+ "sie_worker_ipc_mux_acquire_wait_seconds",
+ "Wall time a caller waited for a multiplexer inflight permit \
+ (SIE_IPC_MUX_MAX_INFLIGHT_PER_POD). Non-zero p50 means the cap is shaping \
+ dispatch to Python; flat zero means no cap is in effect.",
+ )
+ .buckets(IPC_REQUEST_BUCKETS.to_vec()),
+ )?;
+
+ let payload_fetch_total = IntCounter::new(
+ "sie_worker_payload_fetch_total",
+ "Payload store fetches (payload_ref inline resolution)",
+ )?;
+ let payload_fetch_errors_total = IntCounterVec::new(
+ Opts::new(
+ "sie_worker_payload_fetch_errors_total",
+ "Payload store fetch failures, by reason",
+ ),
+ &["reason"],
+ )?;
+ let payload_fetch_seconds = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_payload_fetch_seconds",
+ "Payload store fetch wall time (seconds)",
+ )
+ .buckets(IPC_REQUEST_BUCKETS.to_vec()),
+ &["result"],
+ )?;
+ let payload_bytes = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_payload_bytes",
+ "Payload store fetch payload size (bytes)",
+ )
+ .buckets(BYTES_BUCKETS.to_vec()),
+ &["result"],
+ )?;
+
+ let jetstream_ack_failures_total = IntCounter::new(
+ "sie_worker_jetstream_ack_failures_total",
+ "JetStream ACK RPCs that failed at the broker",
+ )?;
+ let jetstream_nak_failures_total = IntCounter::new(
+ "sie_worker_jetstream_nak_failures_total",
+ "JetStream NAK RPCs that failed at the broker",
+ )?;
+ let nats_fetch_errors_total = IntCounter::new(
+ "sie_worker_nats_fetch_errors_total",
+ "Failures to build a JetStream pull/fetch stream",
+ )?;
+ let nats_stream_errors_total = IntCounter::new(
+ "sie_worker_nats_stream_errors_total",
+ "Errors reading messages from an active JetStream pull stream",
+ )?;
+ let nats_redelivery_total = IntCounter::new(
+ "sie_worker_nats_redelivery_total",
+ "Messages observed with deliver_count > 1 (JetStream redeliveries)",
+ )?;
+ let nats_deliver_count = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_nats_deliver_count",
+ "JetStream delivery count observed per message (1 = first delivery)",
+ )
+ .buckets(DELIVER_COUNT_BUCKETS.to_vec()),
+ &["operation"],
+ )?;
+ let config_deltas_total = IntCounterVec::new(
+ Opts::new(
+ "sie_worker_config_deltas_total",
+ "Bundle-scoped worker config notifications by kind and result",
+ ),
+ &["kind", "result"],
+ )?;
+ let config_epoch = IntGauge::new(
+ "sie_worker_config_epoch",
+ "Highest bundle-scoped config epoch successfully applied by this worker",
+ )?;
+
+ let shutdown_drain_seconds = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_shutdown_drain_seconds",
+ "Graceful shutdown drain wall time (seconds)",
+ )
+ .buckets(DRAIN_DURATION_BUCKETS.to_vec()),
+ &["result"],
+ )?;
+ let shutdown_drain_deadline_exceeded_total = IntCounter::new(
+ "sie_worker_shutdown_drain_deadline_exceeded_total",
+ "Shutdown drains that hit the configured deadline",
+ )?;
+
+ let router_fallthrough_total = IntCounterVec::new(
+ Opts::new(
+ "sie_worker_router_fallthrough_total",
+ "Router fell through from one backend to the next because the first returned UnsupportedModel",
+ ),
+ &["from_backend", "to_backend", "operation"],
+ )?;
+
+ registry.register(Box::new(messages_received_total.clone()))?;
+ registry.register(Box::new(messages_acked_total.clone()))?;
+ registry.register(Box::new(messages_naked_total.clone()))?;
+ registry.register(Box::new(ipc_requests_total.clone()))?;
+ registry.register(Box::new(ipc_failures_total.clone()))?;
+ registry.register(Box::new(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()))?;
+ registry.register(Box::new(pull_model_loads_total.clone()))?;
+ registry.register(Box::new(backend_process_seconds.clone()))?;
+ registry.register(Box::new(backend_batch_items.clone()))?;
+ registry.register(Box::new(backend_process_errors_total.clone()))?;
+ registry.register(Box::new(backend_ensure_ready_seconds.clone()))?;
+ registry.register(Box::new(backend_item_outcomes_total.clone()))?;
+ registry.register(Box::new(backend_phase_seconds.clone()))?;
+ registry.register(Box::new(ipc_request_seconds.clone()))?;
+ registry.register(Box::new(ipc_request_bytes.clone()))?;
+ registry.register(Box::new(ipc_response_bytes.clone()))?;
+ registry.register(Box::new(ipc_connect_total.clone()))?;
+ registry.register(Box::new(ipc_reconnect_total.clone()))?;
+ registry.register(Box::new(ipc_pool_size.clone()))?;
+ registry.register(Box::new(ipc_pool_inflight.clone()))?;
+ registry.register(Box::new(ipc_pool_acquire_wait_seconds.clone()))?;
+ registry.register(Box::new(ipc_mux_inflight.clone()))?;
+ registry.register(Box::new(ipc_mux_acquire_wait_seconds.clone()))?;
+ registry.register(Box::new(payload_fetch_total.clone()))?;
+ registry.register(Box::new(payload_fetch_errors_total.clone()))?;
+ registry.register(Box::new(payload_fetch_seconds.clone()))?;
+ registry.register(Box::new(payload_bytes.clone()))?;
+ registry.register(Box::new(jetstream_ack_failures_total.clone()))?;
+ registry.register(Box::new(jetstream_nak_failures_total.clone()))?;
+ registry.register(Box::new(nats_fetch_errors_total.clone()))?;
+ registry.register(Box::new(nats_stream_errors_total.clone()))?;
+ registry.register(Box::new(nats_redelivery_total.clone()))?;
+ registry.register(Box::new(nats_deliver_count.clone()))?;
+ registry.register(Box::new(config_deltas_total.clone()))?;
+ registry.register(Box::new(config_epoch.clone()))?;
+ registry.register(Box::new(shutdown_drain_seconds.clone()))?;
+ registry.register(Box::new(shutdown_drain_deadline_exceeded_total.clone()))?;
+ registry.register(Box::new(router_fallthrough_total.clone()))?;
+
+ // Register the scheduler metric family. Keeps the Scheduler
+ // module self-contained — this file doesn't need to know
+ // about the internal layout or buckets, it just offers the
+ // registry handle.
+ let scheduler = crate::scheduler::SchedulerMetrics::register(&registry)?;
+
+ let materialized_model_ids = std::env::var("SIE_METRIC_MODEL_ALLOWLIST")
+ .ok()
+ .map(|raw| {
+ raw.split(',')
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+ .collect::<std::collections::HashSet<_>>()
+ })
+ .filter(|set| !set.is_empty());
+
+ Ok(Self {
+ registry,
+ messages_received_total,
+ messages_acked_total,
+ messages_naked_total,
+ ipc_requests_total,
+ ipc_failures_total,
+ inflight_batches,
+ pull_items_fetched,
+ pull_batch_process_seconds,
+ pull_nak_unloaded_total,
+ pull_model_loads_total,
+ backend_process_seconds,
+ backend_batch_items,
+ backend_process_errors_total,
+ backend_ensure_ready_seconds,
+ backend_item_outcomes_total,
+ backend_phase_seconds,
+ ipc_request_seconds,
+ ipc_request_bytes,
+ ipc_response_bytes,
+ ipc_connect_total,
+ ipc_reconnect_total,
+ ipc_pool_size,
+ ipc_pool_inflight,
+ ipc_pool_acquire_wait_seconds,
+ ipc_mux_inflight,
+ ipc_mux_acquire_wait_seconds,
+ payload_fetch_total,
+ payload_fetch_errors_total,
+ payload_fetch_seconds,
+ payload_bytes,
+ jetstream_ack_failures_total,
+ jetstream_nak_failures_total,
+ nats_fetch_errors_total,
+ nats_stream_errors_total,
+ nats_redelivery_total,
+ nats_deliver_count,
+ config_deltas_total,
+ config_epoch,
+ shutdown_drain_seconds,
+ shutdown_drain_deadline_exceeded_total,
+ router_fallthrough_total,
+ scheduler,
+ materialized_model_ids,
+ })
+ }
+
+ /// Resolve a raw model id into the value that should be used as
+ /// a `model` Prometheus label. Honors `SIE_METRIC_MODEL_ALLOWLIST`;
+ /// models outside the active/materialized set get bucketed as
+ /// `"other"` to bound cardinality. If no set is configured we pass
+ /// the id through unchanged.
+ pub fn model_label<'a>(&self, model_id: &'a str) -> std::borrow::Cow<'a, str> {
+ match &self.materialized_model_ids {
+ Some(set) if !set.contains(model_id) => std::borrow::Cow::Borrowed("other"),
+ _ => std::borrow::Cow::Borrowed(model_id),
+ }
+ }
+
+ /// Test-only constructor that bypasses env parsing so unit tests
+ /// can exercise [`model_label`] without racing on
+ /// `SIE_METRIC_MODEL_ALLOWLIST`. Pass `None` for "no configured set"
+ /// (passthrough behaviour) or `Some(set)` to enable bucketing.
+ #[cfg(test)]
+ fn with_materialized_models_for_tests(
+ materialized_model_ids: Option<std::collections::HashSet<String>>,
+ ) -> anyhow::Result<Self> {
+ let mut reg = Self::new()?;
+ // Even an explicit empty set means "no configured set" — matches
+ // the `filter(|set| !set.is_empty())` rule in `new()`.
+ reg.materialized_model_ids = materialized_model_ids.filter(|s| !s.is_empty());
+ Ok(reg)
+ }
+}
+
+/// Serve the sidecar's HTTP probe + observability surface.
+///
+/// The caller provides the `MetricsRegistry` so counters updated by the
+/// dispatcher and friends are exposed here.
+/// * `GET /metrics` — Prometheus text (counters/histograms wired by
+/// the dispatcher and friends).
+/// * `GET /healthz` — **liveness**. Always 200 unless the process is
+/// wedged hard enough that the tokio runtime stops servicing this
+/// handler. Operators (and K8s `livenessProbe`) point here.
+/// * `GET /readyz` — **readiness**. 200 iff the IPC handshake has
+/// succeeded AND the most recent heartbeat-echo arrived within
+/// the configured freshness window AND we are not draining. See
+/// [`crate::readiness`] for the precise contract.
+///
+/// The Helm chart can point the K8s `readinessProbe` here during the
+/// dual-probe transition instead of at Python `/readyz` on port 8080.
+/// See `docs/architecture-guide.md` for the readiness contract.
+pub fn spawn_metrics_server(
+ port: u16,
+ metrics: Arc<MetricsRegistry>,
+ readiness: Arc<Readiness>,
+ shutdown: Arc<Shutdown>,
+) -> anyhow::Result<JoinHandle<()>> {
+ let registry = Arc::clone(&metrics);
+
+ let handle = tokio::spawn(async move {
+ let addr: SocketAddr = ([0, 0, 0, 0], port).into();
+ let listener = match TcpListener::bind(addr).await {
+ Ok(l) => l,
+ Err(e) => {
+ error!(error = %e, addr = %addr, "metrics server: bind failed");
+ return;
+ }
+ };
+ info!(addr = %addr, "metrics server listening");
+
+ loop {
+ let accept = listener.accept();
+ let shutdown_wait = shutdown.wait();
+ tokio::select! {
+ biased;
+ _ = shutdown_wait => {
+ info!("metrics server stopping (shutdown)");
+ return;
+ }
+ res = accept => {
+ match res {
+ Ok((stream, _peer)) => {
+ let reg = Arc::clone(&registry);
+ let ready = Arc::clone(&readiness);
+ let io = TokioIo::new(stream);
+ tokio::spawn(async move {
+ let svc = service_fn(move |req| {
+ handle_request(req, Arc::clone(&reg), Arc::clone(&ready))
+ });
+ if let Err(e) = hyper::server::conn::http1::Builder::new()
+ .serve_connection(io, svc)
+ .await
+ {
+ warn!(error = %e, "metrics connection failed");
+ }
+ });
+ }
+ Err(e) => {
+ warn!(error = %e, "metrics accept failed");
+ }
+ }
+ }
+ }
+ }
+ });
+
+ Ok(handle)
+}
+
+async fn handle_request(
+ req: Request<hyper::body::Incoming>,
+ metrics: Arc<MetricsRegistry>,
+ readiness: Arc<Readiness>,
+) -> Result<Response<Full<Bytes>>, Infallible> {
+ match (req.method(), req.uri().path()) {
+ (&Method::GET, "/metrics") => {
+ let encoder = TextEncoder::new();
+ let mut buf = Vec::new();
+ if let Err(e) = encoder.encode(&metrics.registry.gather(), &mut buf) {
+ warn!(error = %e, "metrics encode failed");
+ }
+ let resp = Response::builder()
+ .status(StatusCode::OK)
+ .header("Content-Type", encoder.format_type())
+ .body(Full::new(Bytes::from(buf)))
+ .unwrap();
+ Ok(resp)
+ }
+ (&Method::GET, "/healthz") => Ok(Response::builder()
+ .status(StatusCode::OK)
+ .body(Full::new(Bytes::from_static(b"ok")))
+ .unwrap()),
+ (&Method::GET, "/readyz") => Ok(readyz_response(&readiness)),
+ _ => Ok(Response::builder()
+ .status(StatusCode::NOT_FOUND)
+ .body(Full::new(Bytes::from_static(b"not found")))
+ .unwrap()),
+ }
+}
+
+fn readyz_status_and_body(readiness: &Readiness) -> (StatusCode, String) {
+ let snap = readiness.snapshot();
+ if snap.is_ready() {
+ (StatusCode::OK, "ok".to_owned())
+ } else {
+ (
+ StatusCode::SERVICE_UNAVAILABLE,
+ format!("not ready: {}", snap.reason()),
+ )
+ }
+}
+
+fn readyz_response(readiness: &Readiness) -> Response<Full<Bytes>> {
+ let (status, body) = readyz_status_and_body(readiness);
+ Response::builder()
+ .status(status)
+ .header("Content-Type", "text/plain; charset=utf-8")
+ .body(Full::new(Bytes::from(body)))
+ .unwrap()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn registry_constructs_cleanly() {
+ let m = MetricsRegistry::new().unwrap();
+ m.messages_received_total.inc();
+ m.messages_acked_total.inc_by(5);
+ m.inflight_batches.set(3);
+ assert_eq!(m.messages_received_total.get(), 1);
+ assert_eq!(m.messages_acked_total.get(), 5);
+ assert_eq!(m.inflight_batches.get(), 3);
+
+ m.pull_items_fetched.with_label_values(&["m1"]).observe(4.0);
+ m.pull_batch_process_seconds
+ .with_label_values(&["m1", "encode"])
+ .observe(0.123);
+ m.pull_nak_unloaded_total
+ .with_label_values(&["m1"])
+ .inc_by(3);
+ m.pull_model_loads_total.with_label_values(&["m1"]).inc();
+
+ let families = m.registry.gather();
+ let names: Vec<&str> = families.iter().map(|f| f.get_name()).collect();
+ for expected in [
+ "sie_worker_messages_received_total",
+ "sie_pull_loop_items_fetched",
+ "sie_pull_loop_batch_process_seconds",
+ "sie_pull_loop_nak_unloaded_total",
+ "sie_pull_loop_model_loads_total",
+ ] {
+ assert!(names.contains(&expected), "missing metric {expected}");
+ }
+ }
+
+ #[test]
+ fn model_label_is_passthrough_when_materialized_set_is_absent() {
+ // Default install (no SIE_METRIC_MODEL_ALLOWLIST set) keeps
+ // existing dashboards unchanged: every unique model_id shows
+ // up as its own Prometheus label. No bucketing.
+ let m = MetricsRegistry::with_materialized_models_for_tests(None).unwrap();
+ assert_eq!(m.model_label("any/model"), "any/model");
+ assert_eq!(m.model_label(""), "");
+ }
+
+ #[test]
+ fn model_label_passes_through_materialized_ids() {
+ let set: std::collections::HashSet<String> =
+ ["bge-m3", "sentence-transformers/all-MiniLM-L6-v2"]
+ .iter()
+ .map(|s| s.to_string())
+ .collect();
+ let m = MetricsRegistry::with_materialized_models_for_tests(Some(set)).unwrap();
+ assert_eq!(m.model_label("bge-m3"), "bge-m3");
+ assert_eq!(
+ m.model_label("sentence-transformers/all-MiniLM-L6-v2"),
+ "sentence-transformers/all-MiniLM-L6-v2"
+ );
+ }
+
+ #[test]
+ fn model_label_buckets_unknown_ids_as_other() {
+ // Misbehaving or unexpected model_ids must not explode
+ // Prometheus cardinality. Anything not in the active set
+ // collapses to the sentinel `"other"` bucket, regardless of
+ // content (unicode, path separators, length, empty string).
+ let set: std::collections::HashSet<String> = ["bge-m3".to_string()].into_iter().collect();
+ let m = MetricsRegistry::with_materialized_models_for_tests(Some(set)).unwrap();
+ for rogue in [
+ "random/model",
+ "",
+ "🦀🦀🦀",
+ &"x".repeat(4096),
+ "weird chars & '\" with spaces",
+ ] {
+ assert_eq!(
+ m.model_label(rogue),
+ "other",
+ "expected bucket for {rogue:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn empty_materialized_set_is_equivalent_to_no_configured_set() {
+ // Matches the env-parse rule in `new()` that treats an empty
+ // `SIE_METRIC_MODEL_ALLOWLIST=""` as absent — otherwise
+ // operators could accidentally collapse every label to
+ // `"other"` by clearing the env var.
+ let empty: std::collections::HashSet<String> = std::collections::HashSet::new();
+ let m = MetricsRegistry::with_materialized_models_for_tests(Some(empty)).unwrap();
+ assert_eq!(m.model_label("whatever"), "whatever");
+ }
+
+ /// Guardrail that `backend_phase_seconds` is wired up: name +
+ /// labels match what dispatcher.rs observes into, the histogram
+ /// is registered in the shared Prometheus registry, and sample
+ /// observations make it through `gather()`. Without this test a
+ /// typo in either the declaration or the `with_label_values()`
+ /// call would silently produce a Prometheus error counter
+ /// ("inconsistent label cardinality") at runtime — the kind of
+ /// thing you only notice when the dashboard stays flat under
+ /// load.
+ #[test]
+ fn backend_phase_seconds_is_registered_and_observable() {
+ let m = MetricsRegistry::new().unwrap();
+
+ // Exercise the same three phases the dispatcher emits, with a
+ // couple of distinct (operation, model) combinations so we
+ // prove the label set survives round-tripping.
+ for (op, model, phase, ms) in [
+ ("encode", "BAAI/bge-m3", "tokenize", 1.2_f64),
+ ("encode", "BAAI/bge-m3", "inference", 42.7),
+ ("encode", "BAAI/bge-m3", "postprocess", 0.3),
+ ("score", "cross-encoder/ms-marco", "inference", 88.1),
+ ] {
+ m.backend_phase_seconds
+ .with_label_values(&[op, model, phase])
+ .observe(ms / 1_000.0);
+ }
+
+ let families = m.registry.gather();
+ let fam = families
+ .iter()
+ .find(|f| f.get_name() == "sie_worker_backend_phase_seconds")
+ .expect("backend_phase_seconds not registered in shared registry");
+
+ // Expect exactly four time-series (one per distinct label
+ // tuple), each with a single observation.
+ assert_eq!(
+ fam.get_metric().len(),
+ 4,
+ "expected 4 label-tuples, got {}",
+ fam.get_metric().len()
+ );
+ for metric in fam.get_metric() {
+ assert_eq!(
+ metric.get_histogram().get_sample_count(),
+ 1,
+ "expected 1 sample per tuple, got {}",
+ metric.get_histogram().get_sample_count()
+ );
+ let labels: std::collections::HashMap<&str, &str> = metric
+ .get_label()
+ .iter()
+ .map(|lp| (lp.get_name(), lp.get_value()))
+ .collect();
+ assert!(labels.contains_key("operation"));
+ assert!(labels.contains_key("model"));
+ assert!(labels.contains_key("phase"));
+ assert!(
+ matches!(labels["phase"], "tokenize" | "inference" | "postprocess"),
+ "unexpected phase label: {:?}",
+ labels["phase"]
+ );
+ }
+ }
+}
diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rs
new file mode 100644
index 000000000..23d5719da
--- /dev/null
+++ b/packages/sie_server_sidecar/src/nats_consumer.rs
@@ -0,0 +1,795 @@
+//! NATS JetStream pull consumer.
+//!
+//! This module owns the pool-level stream and durable pull consumer
+//! matching the Python naming contract (see
+//! `config::WorkerConfig::{stream_name,consumer_name,subject_filter}`),
+//! then exposes a long-lived pull stream for the dispatcher. ACK/NAK,
+//! batching, and adaptive fetch timing live above this layer.
+
+use std::time::Duration;
+
+use async_nats::jetstream::consumer::pull::{Config as ConsumerConfig, Stream as PullStream};
+use async_nats::jetstream::consumer::{AckPolicy, PullConsumer};
+use async_nats::jetstream::stream::{
+ Config as StreamConfig, DiscardPolicy, RetentionPolicy, StorageType, Stream as JsStream,
+};
+use async_nats::jetstream::Context as JsContext;
+use futures_util::TryStreamExt;
+use thiserror::Error;
+use tracing::{debug, info, warn};
+
+use crate::config::WorkerConfig;
+use crate::subject::subjects_overlap;
+
+/// Default consumer parameters. Must match the gateway's stream creator
+/// and any other worker in the pool — when multiple creators share a
+/// durable consumer by name, the first to create it wins, and subsequent
+/// callers silently inherit whatever was there.
+const ACK_WAIT_SECS: u64 = 30;
+const GENERATION_ACK_WAIT_SECS: u64 = 300;
+const DEFAULT_MAX_DELIVER: i64 = 20;
+const DEFAULT_MAX_ACK_PENDING: i64 = 1000;
+const DEFAULT_STREAM_MAX_AGE_SECS: u64 = ACK_WAIT_SECS * (DEFAULT_MAX_DELIVER as u64);
+const STREAM_MAX_MSGS: i64 = 100_000;
+
+/// Env-overridable `max_deliver`. Mirrors Python's `SIE_MAX_DELIVER`
+/// (default 20). With the default 30s ACK wait, this gives a 600s retry
+/// envelope before a message hits the DLQ.
+fn max_deliver() -> i64 {
+ std::env::var("SIE_MAX_DELIVER")
+ .ok()
+ .and_then(|s| s.parse::<i64>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or(DEFAULT_MAX_DELIVER)
+}
+
+/// Env-overridable stream `max_age`. Mirrors Python's
+/// `SIE_STREAM_MAX_AGE_S` (default 600). Should be >=
+/// `max_deliver * ack_wait` so messages don't expire mid-retry.
+fn stream_max_age_secs() -> u64 {
+ std::env::var("SIE_STREAM_MAX_AGE_S")
+ .ok()
+ .and_then(|s| s.parse::<u64>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or(DEFAULT_STREAM_MAX_AGE_SECS)
+}
+
+/// Env-overridable `max_ack_pending`. Python hardcodes 1000 for now but
+/// exposing the knob keeps the option open without a code change.
+fn max_ack_pending() -> i64 {
+ std::env::var("SIE_MAX_ACK_PENDING")
+ .ok()
+ .and_then(|s| s.parse::<i64>().ok())
+ .filter(|&n| n > 0)
+ .unwrap_or(DEFAULT_MAX_ACK_PENDING)
+}
+
+fn generation_stream_max_age_secs() -> u64 {
+ stream_max_age_secs().max(GENERATION_ACK_WAIT_SECS * max_deliver() as u64)
+}
+
+/// Opt-in: when `SIE_NATS_CONSERVATIVE_CLEANUP=1`, the stale-durable
+/// sweep only deletes consumers that have **zero** pull waiters
+/// (`num_waiting == 0`) and **zero** in-flight acks
+/// (`num_ack_pending == 0`). Default behaviour (env unset / `0`)
+/// keeps the historical aggressive delete because today's topology is
+/// one bundle per pool — flipping bundles on a pool must clobber the
+/// old durable for the new worker to bind.
+///
+/// Flip this on if you ever introduce a topology where two bundles
+/// legitimately share a pool stream with overlapping filters; we
+/// then refuse to delete a healthy peer consumer and let the
+/// authoritative `get_or_create_consumer` error surface so the
+/// operator can resolve the conflict explicitly.
+fn conservative_cleanup() -> bool {
+ std::env::var("SIE_NATS_CONSERVATIVE_CLEANUP")
+ .ok()
+ .filter(|v| v == "1" || v.eq_ignore_ascii_case("true"))
+ .is_some()
+}
+
+#[derive(Debug, Error)]
+pub enum NatsSetupError {
+ #[error("ensure stream {name}: {source}")]
+ EnsureStream {
+ name: String,
+ #[source]
+ source: async_nats::Error,
+ },
+ #[error("ensure consumer {name}: {source}")]
+ EnsureConsumer {
+ name: String,
+ #[source]
+ source: async_nats::Error,
+ },
+ #[error("connect NATS: {source}")]
+ Connect {
+ #[source]
+ source: async_nats::ConnectError,
+ },
+}
+
+/// Connect to NATS and return a JetStream context.
+pub async fn connect(nats_url: &str) -> Result<(async_nats::Client, JsContext), NatsSetupError> {
+ let client = async_nats::connect(nats_url)
+ .await
+ .map_err(|source| NatsSetupError::Connect { source })?;
+ let js = async_nats::jetstream::new(client.clone());
+ Ok((client, js))
+}
+
+/// Predicate used by [`cleanup_overlapping_consumers`]. Returns true
+/// iff any of the consumer's configured filter(s) overlaps the
+/// worker's intended `desired_subject` per NATS wildcard semantics.
+///
+/// Split out from `Info` so it can be unit-tested without constructing
+/// the (large, time-stamped) `Info` value.
+fn any_filter_overlaps(
+ primary_filter: &str,
+ multi_filters: &[String],
+ desired_subject: &str,
+) -> bool {
+ if !primary_filter.is_empty() && subjects_overlap(primary_filter, desired_subject) {
+ return true;
+ }
+ multi_filters
+ .iter()
+ .any(|s| subjects_overlap(s, desired_subject))
+}
+
+fn is_legacy_per_model_work_stream(stream_name: &str) -> bool {
+ stream_name.starts_with("WORK_") && !stream_name.starts_with("WORK_POOL_")
+}
+
+fn legacy_stream_overlaps_pool(
+ stream_name: &str,
+ subjects: &[String],
+ desired_stream_name: &str,
+ desired_subject: &str,
+) -> bool {
+ stream_name != desired_stream_name
+ && is_legacy_per_model_work_stream(stream_name)
+ && subjects
+ .iter()
+ .any(|subject| subjects_overlap(subject, desired_subject))
+}
+
+fn legacy_stream_is_safe_to_delete(
+ stream_name: &str,
+ subjects: &[String],
+ desired_stream_name: &str,
+ desired_subject: &str,
+ message_count: u64,
+) -> bool {
+ message_count == 0
+ && legacy_stream_overlaps_pool(stream_name, subjects, desired_stream_name, desired_subject)
+}
+
+/// Best-effort: delete empty old per-model `WORK_<model>` streams whose
+/// subjects overlap the pool stream we are about to create.
+///
+/// Older Python adapter processes created one WorkQueue stream per model. The Rust
+/// sidecar creates one pool stream (`WORK_POOL_<pool>`) for
+/// `sie.work.*.<pool>`. NATS forbids overlapping WorkQueue streams, so a
+/// leftover per-model stream can prevent the new pool stream from being
+/// created. We only delete empty streams that match the old naming convention
+/// and overlap this pool's subject filter; non-empty streams must be drained
+/// or migrated explicitly so startup never drops queued work.
+async fn cleanup_legacy_per_model_streams(
+ js: &JsContext,
+ desired_stream_name: &str,
+ desired_subject: &str,
+) {
+ let mut listing = js.streams();
+ let mut stale = Vec::new();
+
+ loop {
+ match listing.try_next().await {
+ Ok(Some(info)) => {
+ if legacy_stream_overlaps_pool(
+ &info.config.name,
+ &info.config.subjects,
+ desired_stream_name,
+ desired_subject,
+ ) {
+ if legacy_stream_is_safe_to_delete(
+ &info.config.name,
+ &info.config.subjects,
+ desired_stream_name,
+ desired_subject,
+ info.state.messages,
+ ) {
+ stale.push((info.config.name, info.config.subjects));
+ } else {
+ warn!(
+ stale_stream = %info.config.name,
+ desired_stream = %desired_stream_name,
+ desired_subject,
+ messages = info.state.messages,
+ subjects = ?info.config.subjects,
+ "legacy per-model stream overlaps the pool stream but still has \
+ queued messages; drain or migrate it before starting this sidecar"
+ );
+ }
+ }
+ }
+ Ok(None) => break,
+ Err(e) => {
+ warn!(
+ error = %e,
+ desired_stream = %desired_stream_name,
+ desired_subject,
+ "listing streams failed during legacy per-model stream cleanup; \
+ proceeding to pool stream creation"
+ );
+ return;
+ }
+ }
+ }
+
+ let mut deleted = 0usize;
+ for (stream_name, subjects) in stale {
+ warn!(
+ stale_stream = %stream_name,
+ desired_stream = %desired_stream_name,
+ desired_subject,
+ subjects = ?subjects,
+ "deleting legacy per-model stream that overlaps the pool stream"
+ );
+ match js.delete_stream(&stream_name).await {
+ Ok(_) => deleted += 1,
+ Err(e) => warn!(
+ stale_stream = %stream_name,
+ error = %e,
+ "failed to delete legacy per-model stream; pool stream creation may fail"
+ ),
+ }
+ }
+
+ if deleted > 0 {
+ info!(
+ desired_stream = %desired_stream_name,
+ desired_subject,
+ deleted,
+ "deleted legacy per-model streams before pool stream creation"
+ );
+ }
+}
+
+/// Best-effort: remove any durable consumer on `stream` whose name is
+/// not `desired_name` but whose filter subject(s) overlap
+/// `desired_subject`. NATS WorkQueue forbids overlapping filters across
+/// consumers on the same stream — without this, the worker can't bind
+/// after a bundle/engine flip on a shared pool.
+///
+/// Failures (list errors, individual deletes) are logged but never
+/// returned: we'd rather let `get_or_create_consumer` produce the
+/// authoritative error a moment later than block startup on a transient
+/// listing hiccup. In practice the only scenarios where listing fails
+/// are also scenarios where the consumer create will fail loudly.
+async fn cleanup_overlapping_consumers(
+ stream: &JsStream,
+ desired_name: &str,
+ desired_subject: &str,
+) {
+ let conservative = conservative_cleanup();
+ let mut listing = stream.consumers();
+ let mut stale: Vec<(String, i64, i64)> = Vec::new();
+ loop {
+ match listing.try_next().await {
+ Ok(Some(info)) => {
+ if info.name == desired_name {
+ continue;
+ }
+ if any_filter_overlaps(
+ &info.config.filter_subject,
+ &info.config.filter_subjects,
+ desired_subject,
+ ) {
+ stale.push((
+ info.name,
+ info.num_waiting as i64,
+ info.num_ack_pending as i64,
+ ));
+ }
+ }
+ Ok(None) => break,
+ Err(e) => {
+ warn!(
+ error = %e,
+ desired_subject,
+ "listing consumers failed during stale-durable sweep; \
+ proceeding to consumer-create which will surface the \
+ authoritative error if a true overlap remains"
+ );
+ return;
+ }
+ }
+ }
+
+ for (name, num_waiting, num_ack_pending) in stale {
+ if conservative && (num_waiting > 0 || num_ack_pending > 0) {
+ warn!(
+ stream = %stream.cached_info().config.name,
+ stale_consumer = %name,
+ desired_consumer = %desired_name,
+ desired_subject,
+ num_waiting,
+ num_ack_pending,
+ "skipping stale-durable delete: peer consumer looks active and \
+ SIE_NATS_CONSERVATIVE_CLEANUP=1; consumer-create will surface \
+ the overlap error and the operator must resolve it manually"
+ );
+ continue;
+ }
+ warn!(
+ stream = %stream.cached_info().config.name,
+ stale_consumer = %name,
+ desired_consumer = %desired_name,
+ desired_subject,
+ num_waiting,
+ num_ack_pending,
+ conservative,
+ "deleting stale durable that overlaps this worker's filter \
+ (left over from a prior bundle/engine deploy on this pool)"
+ );
+ if let Err(e) = stream.delete_consumer(&name).await {
+ warn!(
+ stale_consumer = %name,
+ error = %e,
+ "failed to delete stale durable; consumer-create will likely fail next"
+ );
+ }
+ }
+}
+
+/// Ensure the pool stream and the durable pull consumer exist. Called once
+/// per worker startup; safe to call again for slow stream/durable reconcile.
+pub async fn ensure_stream_and_consumer(
+ js: &JsContext,
+ config: &WorkerConfig,
+) -> Result<PullConsumer, NatsSetupError> {
+ ensure_stream_and_consumer_inner(js, config, true).await
+}
+
+/// Re-ensure the pool stream and durable consumer without rebuilding the
+/// active pull stream. This is intentionally a slow control-plane repair path:
+/// the hot fetch loop still owns pull-stream recovery on terminal stream errors.
+pub async fn reconcile_stream_and_consumer(
+ js: &JsContext,
+ config: &WorkerConfig,
+) -> Result<(), NatsSetupError> {
+ ensure_stream_and_consumer_inner(js, config, false)
+ .await
+ .map(|_| ())
+}
+
+/// Ensure the worker-specific stream used by generation direct-dispatch.
+///
+/// The gateway publishes direct generation work to
+/// `sie.work.{model}.{pool}.{worker_id}`. That subject intentionally does
+/// not match the pool stream (`sie.work.*.{pool}`), so the sidecar must
+/// bind this second stream for generation to avoid relying solely on
+/// first-chunk fallback republish to the pool.
+pub async fn ensure_worker_stream_and_consumer(
+ js: &JsContext,
+ config: &WorkerConfig,
+) -> Result<PullConsumer, NatsSetupError> {
+ let stream_name = config.worker_stream_name();
+ let subject = config.worker_subject_filter();
+ let consumer_name = config.worker_consumer_name();
+
+ let stream_cfg = StreamConfig {
+ name: stream_name.clone(),
+ subjects: vec![subject.clone()],
+ retention: RetentionPolicy::WorkQueue,
+ storage: StorageType::Memory,
+ max_age: Duration::from_secs(generation_stream_max_age_secs()),
+ max_messages: STREAM_MAX_MSGS,
+ num_replicas: 1,
+ discard: DiscardPolicy::New,
+ ..Default::default()
+ };
+
+ let desired_ack_wait = Duration::from_secs(GENERATION_ACK_WAIT_SECS);
+ let desired_max_deliver = max_deliver();
+ let desired_max_ack_pending = max_ack_pending();
+ let stream =
+ js.get_or_create_stream(stream_cfg)
+ .await
+ .map_err(|e| NatsSetupError::EnsureStream {
+ name: stream_name.clone(),
+ source: e.into(),
+ })?;
+
+ cleanup_overlapping_consumers(&stream, &consumer_name, &subject).await;
+
+ let consumer_cfg = ConsumerConfig {
+ durable_name: Some(consumer_name.clone()),
+ filter_subject: subject.clone(),
+ ack_policy: AckPolicy::Explicit,
+ ack_wait: desired_ack_wait,
+ max_deliver: desired_max_deliver,
+ max_ack_pending: desired_max_ack_pending,
+ ..Default::default()
+ };
+ let consumer: PullConsumer = stream
+ .get_or_create_consumer(&consumer_name, consumer_cfg)
+ .await
+ .map_err(|e| NatsSetupError::EnsureConsumer {
+ name: consumer_name.clone(),
+ source: e.into(),
+ })?;
+ info!(
+ stream = %stream_name,
+ consumer = %consumer_name,
+ subject = %subject,
+ ack_wait_s = GENERATION_ACK_WAIT_SECS,
+ "ensured generation direct-dispatch stream and pull consumer"
+ );
+ Ok(consumer)
+}
+
+pub async fn reconcile_worker_stream_and_consumer(
+ js: &JsContext,
+ config: &WorkerConfig,
+) -> Result<(), NatsSetupError> {
+ ensure_worker_stream_and_consumer(js, config)
+ .await
+ .map(|_| ())
+}
+
+async fn ensure_stream_and_consumer_inner(
+ js: &JsContext,
+ config: &WorkerConfig,
+ log_success_at_info: bool,
+) -> Result<PullConsumer, NatsSetupError> {
+ let stream_name = config.stream_name();
+ let subject = config.subject_filter();
+ let consumer_name = config.consumer_name();
+
+ let stream_cfg = StreamConfig {
+ name: stream_name.clone(),
+ subjects: vec![subject.clone()],
+ retention: RetentionPolicy::WorkQueue,
+ storage: StorageType::Memory,
+ max_age: Duration::from_secs(stream_max_age_secs()),
+ max_messages: STREAM_MAX_MSGS,
+ num_replicas: 1,
+ discard: DiscardPolicy::New,
+ ..Default::default()
+ };
+
+ let desired_max_age = stream_cfg.max_age;
+ let desired_max_deliver = max_deliver();
+ let desired_max_ack_pending = max_ack_pending();
+ let desired_ack_wait = Duration::from_secs(ACK_WAIT_SECS);
+
+ cleanup_legacy_per_model_streams(js, &stream_name, &subject).await;
+
+ let stream =
+ js.get_or_create_stream(stream_cfg)
+ .await
+ .map_err(|e| NatsSetupError::EnsureStream {
+ name: stream_name.clone(),
+ source: e.into(),
+ })?;
+
+ // `get_or_create_stream` is a no-op against an EXISTING stream with a
+ // different config (the first writer's config wins). If the gateway
+ // and the worker disagree on `max_age`, retries may be purged before
+ // `max_deliver` is reached — silent data loss. Warn so ops can tell.
+ let observed_max_age = stream.cached_info().config.max_age;
+ if observed_max_age != desired_max_age {
+ warn!(
+ stream = %stream_name,
+ observed_max_age_s = observed_max_age.as_secs(),
+ desired_max_age_s = desired_max_age.as_secs(),
+ "stream max_age drift: existing stream config disagrees with this worker's intent; \
+ whoever created the stream first wins. This can cause retries to expire before \
+ max_deliver is reached. Align SIE_STREAM_MAX_AGE_S across gateway + workers."
+ );
+ }
+
+ // Self-heal stale durables left behind by a prior bundle deploy on
+ // this pool. Without this, NATS rejects our consumer create with
+ // `consumer filter subject overlaps with X` and the worker
+ // CrashLoops until an operator runs `nats consumer rm` by hand.
+ // Concretely: a previous deploy may leave `<old-bundle>_l4`
+ // filtering on `sie.work.*.l4` while the new `<new-bundle>_l4`
+ // wants the same filter.
+ cleanup_overlapping_consumers(&stream, &consumer_name, &subject).await;
+
+ let consumer_cfg = ConsumerConfig {
+ durable_name: Some(consumer_name.clone()),
+ filter_subject: subject.clone(),
+ ack_policy: AckPolicy::Explicit,
+ ack_wait: desired_ack_wait,
+ max_deliver: desired_max_deliver,
+ max_ack_pending: desired_max_ack_pending,
+ ..Default::default()
+ };
+
+ let mut consumer: PullConsumer = stream
+ .get_or_create_consumer(&consumer_name, consumer_cfg)
+ .await
+ .map_err(|e| NatsSetupError::EnsureConsumer {
+ name: consumer_name.clone(),
+ source: e.into(),
+ })?;
+
+ // Same drift warning for the durable consumer. `get_or_create_consumer`
+ // inherits the existing durable's config; new tuning here is silently
+ // dropped until someone deletes the consumer.
+ if let Ok(info) = consumer.info().await {
+ if info.config.max_deliver != desired_max_deliver
+ || info.config.ack_wait != desired_ack_wait
+ || info.config.max_ack_pending != desired_max_ack_pending
+ {
+ warn!(
+ consumer = %consumer_name,
+ observed_max_deliver = info.config.max_deliver,
+ desired_max_deliver,
+ observed_ack_wait_s = info.config.ack_wait.as_secs(),
+ desired_ack_wait_s = desired_ack_wait.as_secs(),
+ observed_max_ack_pending = info.config.max_ack_pending,
+ desired_max_ack_pending,
+ "durable consumer config drift: existing durable does not match this worker's \
+ intended tuning. Delete the consumer or update the owning provisioner."
+ );
+ }
+ }
+
+ if log_success_at_info {
+ info!(
+ stream = %stream_name,
+ consumer = %consumer_name,
+ subject = %subject,
+ "ensured NATS stream and pull consumer"
+ );
+ } else {
+ debug!(
+ stream = %stream_name,
+ consumer = %consumer_name,
+ subject = %subject,
+ "reconciled NATS stream and pull consumer"
+ );
+ }
+ Ok(consumer)
+}
+
+/// Lightweight wrapper around a pull consumer stream.
+pub struct NatsConsumer {
+ consumer: PullConsumer,
+}
+
+impl NatsConsumer {
+ pub fn new(consumer: PullConsumer) -> Self {
+ Self { consumer }
+ }
+
+ /// Begin a message stream with the given per-fetch batch size and
+ /// expiry. Callers drive it via `futures_util::StreamExt::next` in the
+ /// dispatcher loop.
+ ///
+ /// **Important:** the returned [`PullStream`] is designed to be held
+ /// open for the process lifetime. Dropping & recreating it per tick
+ /// is pathological — any messages the server has already routed to a
+ /// not-yet-drained stream become `ack_pending` until `ack_wait`
+ /// elapses (30 s by default), producing a catastrophic throughput
+ /// collapse. Callers therefore construct one stream at startup and poll it
+ /// with `.next().await` for as long as the worker runs.
+ pub async fn messages(
+ &self,
+ batch: usize,
+ expires: Duration,
+ ) -> Result<PullStream, async_nats::Error> {
+ let stream = self
+ .consumer
+ .stream()
+ .max_messages_per_batch(batch)
+ .expires(expires)
+ .messages()
+ .await?;
+ Ok(stream)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::config::WorkerConfig;
+ use std::path::PathBuf;
+
+ #[test]
+ fn consumer_config_matches_shared_defaults() {
+ // Shared defaults (env-overridable where documented) across all
+ // consumer creators in the pool:
+ // ack_wait = 30s
+ // max_deliver = 20 (env SIE_MAX_DELIVER)
+ // max_ack_pending = 1000 (env SIE_MAX_ACK_PENDING)
+ // stream max_age = 600s (env SIE_STREAM_MAX_AGE_S)
+ // stream max_msgs = 100_000
+ assert_eq!(ACK_WAIT_SECS, 30);
+ assert_eq!(DEFAULT_MAX_DELIVER, 20);
+ assert_eq!(DEFAULT_MAX_ACK_PENDING, 1000);
+ assert_eq!(DEFAULT_STREAM_MAX_AGE_SECS, 600);
+ assert_eq!(STREAM_MAX_MSGS, 100_000);
+ }
+
+ #[test]
+ fn env_free_accessors_match_defaults() {
+ // Env-free calls must return the hardcoded defaults. We do not
+ // touch the environment (would be racy with other tests) — this
+ // just guards against accidental typos in the env-var key.
+ // If a developer happens to set these env vars locally, the
+ // assertion may legitimately differ; skip-gate on that case.
+ if std::env::var("SIE_MAX_DELIVER").is_err() {
+ assert_eq!(max_deliver(), DEFAULT_MAX_DELIVER);
+ }
+ if std::env::var("SIE_STREAM_MAX_AGE_S").is_err() {
+ assert_eq!(stream_max_age_secs(), DEFAULT_STREAM_MAX_AGE_SECS);
+ }
+ if std::env::var("SIE_MAX_ACK_PENDING").is_err() {
+ assert_eq!(max_ack_pending(), DEFAULT_MAX_ACK_PENDING);
+ }
+ }
+
+ #[test]
+ fn config_produces_expected_names() {
+ let cfg = WorkerConfig {
+ nats_url: String::new(),
+ pool: "default".into(),
+ bundle: "b".into(),
+ ipc_socket_path: PathBuf::from("/tmp/s.sock"),
+ ipc_pool_size: 1,
+ payload_store_url: None,
+ gateway_url: None,
+ gateway_api_key: None,
+ pool_admission_enabled: true,
+ pool_admission_check_interval_ms: 5_000,
+ pool_admission_pause_ms: 1_000,
+ pool_admission_stale_after_ms: 30_000,
+ metrics_port: 9095,
+ worker_id: "w".into(),
+ ping_interval_ms: 2000,
+ ready_stale_mult: 3,
+ machine_profile: "default".into(),
+ gpu_count: 1,
+ bundle_config_hash: String::new(),
+ config_service_url: None,
+ config_service_token: None,
+ config_poll_interval_ms: 30_000,
+ config_full_export_interval_ms: 300_000,
+ nats_config_trusted_producers: vec!["sie-config".into()],
+ health_publish_interval_ms: 5_000,
+ };
+ assert_eq!(cfg.stream_name(), "WORK_POOL_default");
+ assert_eq!(cfg.consumer_name(), "b_default");
+ assert_eq!(cfg.subject_filter(), "sie.work.*.default");
+ }
+
+ // Connect/ensure tests need a live NATS and are covered by integration
+ // smoke tests. Here we just ensure the code compiles and the surface is usable.
+ #[allow(dead_code)]
+ fn _compile_check(_js: &JsContext, _cfg: &WorkerConfig) {}
+
+ // ----- legacy per-model stream cleanup predicate --------------------------
+
+ #[test]
+ fn legacy_stream_cleanup_targets_overlapping_per_model_streams() {
+ let subjects = vec!["sie.work.BAAI__bge-m3.l4".to_string()];
+ assert!(legacy_stream_overlaps_pool(
+ "WORK_BAAI__bge-m3",
+ &subjects,
+ "WORK_POOL_l4",
+ "sie.work.*.l4"
+ ));
+ assert!(legacy_stream_is_safe_to_delete(
+ "WORK_BAAI__bge-m3",
+ &subjects,
+ "WORK_POOL_l4",
+ "sie.work.*.l4",
+ 0
+ ));
+ }
+
+ #[test]
+ fn legacy_stream_cleanup_does_not_auto_delete_non_empty_streams() {
+ let subjects = vec!["sie.work.BAAI__bge-m3.l4".to_string()];
+ assert!(!legacy_stream_is_safe_to_delete(
+ "WORK_BAAI__bge-m3",
+ &subjects,
+ "WORK_POOL_l4",
+ "sie.work.*.l4",
+ 1
+ ));
+ }
+
+ #[test]
+ fn legacy_stream_cleanup_ignores_pool_streams() {
+ let subjects = vec!["sie.work.*.l4".to_string()];
+ assert!(!legacy_stream_overlaps_pool(
+ "WORK_POOL_l4",
+ &subjects,
+ "WORK_POOL_l4",
+ "sie.work.*.l4"
+ ));
+ assert!(!legacy_stream_overlaps_pool(
+ "WORK_POOL_other",
+ &subjects,
+ "WORK_POOL_l4",
+ "sie.work.*.l4"
+ ));
+ }
+
+ #[test]
+ fn legacy_stream_cleanup_ignores_non_overlapping_work_streams() {
+ let subjects = vec!["sie.work.BAAI__bge-m3.h100".to_string()];
+ assert!(!legacy_stream_overlaps_pool(
+ "WORK_BAAI__bge-m3",
+ &subjects,
+ "WORK_POOL_l4",
+ "sie.work.*.l4"
+ ));
+ }
+
+ #[test]
+ fn legacy_stream_cleanup_ignores_unrelated_stream_names() {
+ let subjects = vec!["sie.work.BAAI__bge-m3.l4".to_string()];
+ assert!(!legacy_stream_overlaps_pool(
+ "ORDERS",
+ &subjects,
+ "WORK_POOL_l4",
+ "sie.work.*.l4"
+ ));
+ }
+
+ // ----- stale-durable predicate -------------------------------------------
+
+ #[test]
+ fn any_filter_overlaps_detects_bundle_flip_collision() {
+ // Real-world case: previous deploy left a `<stale-bundle>_l4`
+ // consumer with filter `sie.work.*.l4`; new deploy wants
+ // `default_l4` with the same filter. The cleanup pass must
+ // mark the old one as overlapping.
+ let stale_filter = "sie.work.*.l4";
+ let desired = "sie.work.*.l4";
+ assert!(any_filter_overlaps(stale_filter, &[], desired));
+ }
+
+ #[test]
+ fn any_filter_overlaps_ignores_other_pools() {
+ // A `default_h100` consumer on a shared NATS account must not
+ // be deleted just because we're deploying `default_l4`.
+ assert!(!any_filter_overlaps(
+ "sie.work.*.h100",
+ &[],
+ "sie.work.*.l4"
+ ));
+ }
+
+ #[test]
+ fn any_filter_overlaps_handles_filter_subjects_list() {
+ // Newer NATS consumers can use the multi-filter
+ // `filter_subjects` list (with `filter_subject` blank).
+ let multi = vec!["sie.work.foo.h100".to_string(), "sie.work.*.l4".to_string()];
+ assert!(any_filter_overlaps("", &multi, "sie.work.*.l4"));
+
+ let multi_disjoint = vec![
+ "sie.work.foo.h100".to_string(),
+ "sie.work.*.eval-l4".to_string(),
+ ];
+ assert!(!any_filter_overlaps("", &multi_disjoint, "sie.work.*.l4"));
+ }
+
+ #[test]
+ fn any_filter_overlaps_treats_empty_primary_as_unset() {
+ // Empty `filter_subject` with empty `filter_subjects` means
+ // a consumer with no filter — JetStream actually rejects
+ // creating that on a WorkQueue stream, so it shouldn't
+ // appear, but if it ever does we don't want to spuriously
+ // delete it.
+ assert!(!any_filter_overlaps("", &[], "sie.work.*.l4"));
+ }
+}
diff --git a/packages/sie_server_sidecar/src/output/mod.rs b/packages/sie_server_sidecar/src/output/mod.rs
new file mode 100644
index 000000000..bfc3c5f3d
--- /dev/null
+++ b/packages/sie_server_sidecar/src/output/mod.rs
@@ -0,0 +1,632 @@
+//! Rust-side output shaping and result framing.
+//!
+//! Instead of Python building the full
+//! `msgpack(WorkResult.result_msgpack)` envelope, the Python adapter
+//! can emit a typed [`crate::ipc_types::RawOutput`] and let Rust
+//! assemble the final on-wire bytes here.
+//!
+//! # Why this lives at top-level
+//!
+//! The canonical msgpack-numpy sentinel writer lives in
+//! [`crate::prep::numpy_sentinel`]. This top-level module keeps the
+//! dispatcher/publisher-facing output-shaping API.
+//!
+//! # Backend-agnostic
+//!
+//! The shapers below only touch host-side `Vec<f32>` / `Vec<String>`
+//! data. They are identical whether the values come from a Python
+//! adapter (copied off-device inside Python) or a future native
+//! adapter (e.g. `tch-rs`'s `.to_kind(Kind::Float).to(Device::Cpu).data()`).
+//! Moving output shaping into Rust lands the same wire-format
+//! guarantee for every backend.
+//!
+//! # Non-destructive contract
+//!
+//! * Supported: `dense`, `sparse`, and `multivector` encode outputs,
+//! plus `score` rerank outputs.
+//! * Deferred: `json` extract payloads, MUVERA post-processing, and
+//! quantization to dtypes other than float32.
+//! * When Python emits the legacy `result_msgpack` or when the Rust
+//! build is missing a shaper for a given [`crate::ipc_types::RawOutput`] variant,
+//! the publisher passes through the Python bytes unchanged.
+//!
+//! See `packages/sie_server_sidecar/docs/architecture-guide.md`
+//! for the full design and
+//! `packages/sie_server/src/sie_server/queue_executor.py::_wrap_encode_output`
+//! for the Python reference wire shape this matches byte-for-byte.
+
+pub mod numpy_sentinel;
+
+use rmp::encode::{write_array_len, write_f64, write_map_len, write_nil, write_str, write_uint};
+
+pub use numpy_sentinel::{
+ write_f32_matrix_2d, write_f32_vector, write_i32_vector, write_numpy_sentinel, SentinelError,
+ DTYPE_F32, DTYPE_I32,
+};
+
+/// Errors raised while shaping a `RawOutput` into final msgpack
+/// bytes. Always recoverable: the publisher turns these into an
+/// error `WorkResult` so one bad shaper can't drop the work item.
+#[derive(Debug, thiserror::Error)]
+pub enum ShapeError {
+ #[error("dense output: expected values.len() == dim ({expected}), got {actual}")]
+ DenseDimMismatch { expected: usize, actual: usize },
+
+ #[error("score output: scores.len() ({scores}) != item_ids.len() ({items})")]
+ ScoreLenMismatch { scores: usize, items: usize },
+
+ #[error("sparse output: indices.len() ({indices}) != values.len() ({values})")]
+ SparseLenMismatch { indices: usize, values: usize },
+
+ #[error("multivector output: values.len() ({values}) != rows ({rows}) * cols ({cols})")]
+ MultivectorShapeMismatch {
+ values: usize,
+ rows: usize,
+ cols: usize,
+ },
+
+ #[error("msgpack write: {0}")]
+ MsgpackWrite(String),
+
+ #[error("sentinel write: {0}")]
+ Sentinel(#[from] SentinelError),
+}
+
+fn wrap_err<E: std::fmt::Display>(e: E) -> ShapeError {
+ ShapeError::MsgpackWrite(e.to_string())
+}
+
+/// L2-normalize a flat f32 vector in place.
+///
+/// Matches the Python adapter's `x / np.linalg.norm(x)` with the
+/// same zero-norm guard (`norms = where(norms > 0, norms, 1.0)`).
+/// Used when the Python side sets `DenseOutput.normalize = true` to
+/// delegate the normalization step to Rust.
+///
+/// Stays numerically close to numpy: we sum `f64` partial squares
+/// so a 1024-dim vector doesn't accumulate drift vs numpy's
+/// per-row reduction (which also upcasts implicitly under BLAS).
+pub fn l2_normalize_in_place(values: &mut [f32]) {
+ if values.is_empty() {
+ return;
+ }
+ let sq: f64 = values.iter().map(|v| f64::from(*v) * f64::from(*v)).sum();
+ let norm = sq.sqrt();
+ if norm <= 0.0 {
+ return;
+ }
+ let norm = norm as f32;
+ for v in values.iter_mut() {
+ *v /= norm;
+ }
+}
+
+/// Build the per-item `result_msgpack` bytes for a dense-only
+/// encoder outcome, mirroring
+/// [`_wrap_encode_output`][py-wrap] verbatim:
+///
+/// ```text
+/// {
+/// "dense": {
+/// "dims": <dim>,
+/// "dtype": "float32",
+/// "values": <numpy_sentinel for [dim] f32>,
+/// },
+/// }
+/// ```
+///
+/// Top-level keys are msgpack **str** (Python source-string keys),
+/// matching what the SDK's `msgpack_numpy.patch()` decoder expects.
+/// `values` uses the [`numpy_sentinel`] map form, identical byte
+/// layout to
+/// `msgpack.packb(np.array(values, dtype=np.float32))` after
+/// `msgpack_numpy.patch()`.
+///
+/// [py-wrap]: ../../../../../../sie_server/src/sie_server/queue_executor.py
+///
+/// This wrapper delegates the actual msgpack writing to
+/// [`crate::prep::outcome::build_dense_payload`], the canonical Rust
+/// dense framer. It retains the sidecar's
+/// stricter [`ShapeError::DenseDimMismatch`] runtime check (callers in
+/// [`crate::publisher`] depend on that taxonomy) while letting the
+/// `prep` module own the actual byte layout. Both paths still pass
+/// the golden byte-for-byte tests in this module AND in
+/// `prep::outcome::tests::build_dense_payload_matches_python_wire_format`.
+pub fn build_dense_payload(values: &[f32], dim: usize) -> Result<Vec<u8>, ShapeError> {
+ if values.len() != dim {
+ return Err(ShapeError::DenseDimMismatch {
+ expected: dim,
+ actual: values.len(),
+ });
+ }
+ crate::prep::outcome::build_dense_payload(values, dim)
+ .map_err(|e| ShapeError::MsgpackWrite(e.to_string()))
+}
+
+/// Build the per-item `result_msgpack` bytes for a score (rerank)
+/// outcome, mirroring
+/// [`_process_single_score`][py-score] verbatim:
+///
+/// ```text
+/// [
+/// {"item_id": "<id>", "score": <f64>, "rank": <uint>},
+/// ... // sorted by score desc
+/// ]
+/// ```
+///
+/// Matches the Python output byte-for-byte:
+///
+/// * top-level msgpack array
+/// * each entry is a 3-key map, keys as msgpack `str` (`fixstr` for
+/// `"item_id"` / `"score"` / `"rank"`)
+/// * `score` packed as msgpack `float64` (`0xcb` + BE 8 bytes), same
+/// as Python's `msgpack.packb(float)`
+/// * `rank` packed as the shortest msgpack uint (fixint for the
+/// usual small N), matching Python's rank integers
+///
+/// Ordering is by `scores[i]` descending, stable for ties (preserves
+/// the caller's natural order), matching `scored.sort(key=..., reverse=True)`
+/// in Python. (Python's `list.sort` is stable — Rust's
+/// `sort_by` is not stable but `sort_by_cached_key` / `sort_by`
+/// with a secondary key would be heavier; a stable sort is used
+/// here via [`slice::sort_by`]'s stable alias
+/// [`<[T]>::sort_by`].)
+///
+/// [py-score]: ../../../../../../sie_server/src/sie_server/queue_executor.py
+pub fn build_score_payload(scores: &[f32], item_ids: &[String]) -> Result<Vec<u8>, ShapeError> {
+ if scores.len() != item_ids.len() {
+ return Err(ShapeError::ScoreLenMismatch {
+ scores: scores.len(),
+ items: item_ids.len(),
+ });
+ }
+ // Stable sort by score descending. Python's `list.sort` is
+ // stable; `<[T]>::sort_by` in stdlib is stable as well
+ // (documented guarantee), so equal-scored items preserve their
+ // input order across languages.
+ let mut ordered: Vec<(usize, f32)> = scores.iter().copied().enumerate().collect();
+ ordered.sort_by(|a, b| {
+ // Reverse: descending.
+ // `partial_cmp` handles NaN by returning None; treat as
+ // Equal so we never panic — Python does the same under
+ // `reverse=True` (NaN comparisons yield False and numpy
+ // scores are never NaN in practice).
+ b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal)
+ });
+
+ let mut buf = Vec::with_capacity(4 + ordered.len() * 48);
+ write_array_len(&mut buf, ordered.len() as u32).map_err(wrap_err)?;
+ for (rank, (orig_idx, score)) in ordered.iter().enumerate() {
+ write_map_len(&mut buf, 3).map_err(wrap_err)?;
+ write_str(&mut buf, "item_id").map_err(wrap_err)?;
+ write_str(&mut buf, &item_ids[*orig_idx]).map_err(wrap_err)?;
+ write_str(&mut buf, "score").map_err(wrap_err)?;
+ // Python packs `float(score)` as f64 (msgpack `0xcb` + 8 BE
+ // bytes). `rmp::write_f64` emits the same encoding.
+ write_f64(&mut buf, f64::from(*score)).map_err(wrap_err)?;
+ write_str(&mut buf, "rank").map_err(wrap_err)?;
+ write_uint(&mut buf, rank as u64).map_err(wrap_err)?;
+ }
+
+ Ok(buf)
+}
+
+/// Build the per-item `result_msgpack` bytes for a `sparse` encode
+/// outcome, mirroring the `sparse` branch of
+/// [`_wrap_encode_output`][py-wrap] verbatim:
+///
+/// ```text
+/// {
+/// "sparse": {
+/// "dims": <u32> | nil,
+/// "dtype": "float32",
+/// "indices": <numpy_sentinel for [n] i32>,
+/// "values": <numpy_sentinel for [n] f32>,
+/// },
+/// }
+/// ```
+///
+/// Wire contract details:
+///
+/// * `dims` uses msgpack **nil** when `None` (matching Python's
+/// `{"dims": None, ...}` which `msgpack.packb` emits as `0xc0`).
+/// When present it's packed as the shortest-width uint (fixint for
+/// small vocabs, `0xcd`/`0xce` for bigger — same as Python).
+/// * `dtype` is always the literal `"float32"`. v1 does not cover
+/// `float16` (the other case Python handles) to keep the wire
+/// stable; models emitting float16 sparse still use the Python
+/// path via the safety gate in `queue_executor`.
+/// * `indices` dtype is always `"<i4"` (`int32`) because every
+/// in-tree sparse adapter emits `np.int32` token ids (see e.g.
+/// `splade_flash`, `gte_sparse_flash`, `sentence_transformer`).
+///
+/// [py-wrap]: ../../../../../../sie_server/src/sie_server/queue_executor.py
+pub fn build_sparse_payload(
+ indices: &[i32],
+ values: &[f32],
+ dims: Option<u32>,
+) -> Result<Vec<u8>, ShapeError> {
+ if indices.len() != values.len() {
+ return Err(ShapeError::SparseLenMismatch {
+ indices: indices.len(),
+ values: values.len(),
+ });
+ }
+ let mut buf = Vec::with_capacity(64 + indices.len() * 8);
+
+ write_map_len(&mut buf, 1).map_err(wrap_err)?;
+ write_str(&mut buf, "sparse").map_err(wrap_err)?;
+
+ write_map_len(&mut buf, 4).map_err(wrap_err)?;
+
+ write_str(&mut buf, "dims").map_err(wrap_err)?;
+ if let Some(d) = dims {
+ write_uint(&mut buf, u64::from(d)).map_err(wrap_err)?;
+ } else {
+ write_nil(&mut buf).map_err(wrap_err)?;
+ }
+
+ write_str(&mut buf, "dtype").map_err(wrap_err)?;
+ write_str(&mut buf, "float32").map_err(wrap_err)?;
+
+ write_str(&mut buf, "indices").map_err(wrap_err)?;
+ write_i32_vector(&mut buf, indices)?;
+
+ write_str(&mut buf, "values").map_err(wrap_err)?;
+ write_f32_vector(&mut buf, values)?;
+
+ Ok(buf)
+}
+
+/// Build the per-item `result_msgpack` bytes for a `multivector`
+/// encode outcome, mirroring the `multivector` branch of
+/// [`_wrap_encode_output`][py-wrap]:
+///
+/// ```text
+/// {
+/// "multivector": {
+/// "token_dims": <u32>,
+/// "num_tokens": <u32>,
+/// "dtype": "float32",
+/// "values": <numpy_sentinel for [num_tokens, token_dims] f32>,
+/// },
+/// }
+/// ```
+///
+/// v1 scope is `float32` only. `float16` and the bit-packed `binary`
+/// path (`shape[1] < token_dims`, `dim/8` bytes per token) both stay
+/// on the Python framing path — the safety gate in
+/// `queue_executor._maybe_multivector_raw_output` refuses to emit a
+/// `MultivectorOutput` for those dtypes.
+///
+/// `values.len() == num_tokens * token_dims` is required; the shaper
+/// returns [`ShapeError::MultivectorShapeMismatch`] otherwise and
+/// the publisher converts that into a typed error outcome rather
+/// than publishing garbage.
+///
+/// [py-wrap]: ../../../../../../sie_server/src/sie_server/queue_executor.py
+pub fn build_multivector_payload(
+ values: &[f32],
+ num_tokens: u32,
+ token_dims: u32,
+) -> Result<Vec<u8>, ShapeError> {
+ let expected = num_tokens as usize * token_dims as usize;
+ if values.len() != expected {
+ return Err(ShapeError::MultivectorShapeMismatch {
+ values: values.len(),
+ rows: num_tokens as usize,
+ cols: token_dims as usize,
+ });
+ }
+
+ let mut buf = Vec::with_capacity(64 + values.len() * 4);
+
+ write_map_len(&mut buf, 1).map_err(wrap_err)?;
+ write_str(&mut buf, "multivector").map_err(wrap_err)?;
+
+ write_map_len(&mut buf, 4).map_err(wrap_err)?;
+
+ write_str(&mut buf, "token_dims").map_err(wrap_err)?;
+ write_uint(&mut buf, u64::from(token_dims)).map_err(wrap_err)?;
+
+ write_str(&mut buf, "num_tokens").map_err(wrap_err)?;
+ write_uint(&mut buf, u64::from(num_tokens)).map_err(wrap_err)?;
+
+ write_str(&mut buf, "dtype").map_err(wrap_err)?;
+ write_str(&mut buf, "float32").map_err(wrap_err)?;
+
+ write_str(&mut buf, "values").map_err(wrap_err)?;
+ write_f32_matrix_2d(&mut buf, values, num_tokens, token_dims)?;
+
+ Ok(buf)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // ---- l2_normalize_in_place ---------------------------------
+
+ #[test]
+ fn l2_normalize_unit_vector_stays_unit() {
+ let mut v = vec![1.0_f32, 0.0, 0.0];
+ l2_normalize_in_place(&mut v);
+ assert!((v[0] - 1.0).abs() < 1e-6);
+ assert_eq!(v[1], 0.0);
+ assert_eq!(v[2], 0.0);
+ }
+
+ #[test]
+ fn l2_normalize_scales_to_unit_length() {
+ let mut v = vec![3.0_f32, 4.0];
+ l2_normalize_in_place(&mut v);
+ let norm = (v[0] * v[0] + v[1] * v[1]).sqrt();
+ assert!((norm - 1.0).abs() < 1e-6, "got norm {norm}");
+ // 3/5, 4/5
+ assert!((v[0] - 0.6).abs() < 1e-6);
+ assert!((v[1] - 0.8).abs() < 1e-6);
+ }
+
+ #[test]
+ fn l2_normalize_zero_vector_is_left_alone() {
+ // Python does `where(norms > 0, norms, 1.0)` → zero vector
+ // stays zero. Match that: no divide by zero, no NaN.
+ let mut v = vec![0.0_f32; 5];
+ l2_normalize_in_place(&mut v);
+ assert!(v.iter().all(|&x| x == 0.0));
+ }
+
+ #[test]
+ fn l2_normalize_empty_slice_is_noop() {
+ let mut v: Vec<f32> = Vec::new();
+ l2_normalize_in_place(&mut v);
+ assert!(v.is_empty());
+ }
+
+ // ---- build_dense_payload -----------------------------------
+
+ /// Golden: Python side runs
+ /// `msgpack.packb({"dense": {"dims": 3, "dtype": "float32",
+ /// "values": np.array([1,2,3], dtype=f32)}},
+ /// use_bin_type=True)`
+ /// after `msgpack_numpy.patch()`. Captured from CPython (88 bytes).
+ /// Same golden the `prep::outcome` tests use; duplicated here
+ /// so the sidecar output-shaping path is validated independently.
+ const GOLDEN_DENSE_123: &[u8] = &[
+ 0x81, 0xa5, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x83, 0xa4, 0x64, 0x69, 0x6d, 0x73, 0x03, 0xa5,
+ 0x64, 0x74, 0x79, 0x70, 0x65, 0xa7, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x33, 0x32, 0xa6, 0x76,
+ 0x61, 0x6c, 0x75, 0x65, 0x73, 0x85, 0xc4, 0x02, 0x6e, 0x64, 0xc3, 0xc4, 0x04, 0x74, 0x79,
+ 0x70, 0x65, 0xa3, 0x3c, 0x66, 0x34, 0xc4, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0xc4, 0x00, 0xc4,
+ 0x05, 0x73, 0x68, 0x61, 0x70, 0x65, 0x91, 0x03, 0xc4, 0x04, 0x64, 0x61, 0x74, 0x61, 0xc4,
+ 0x0c, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40,
+ ];
+
+ #[test]
+ fn build_dense_payload_matches_python_wire_format() {
+ let buf = build_dense_payload(&[1.0, 2.0, 3.0], 3).unwrap();
+ assert_eq!(
+ buf, GOLDEN_DENSE_123,
+ "dense payload must be byte-identical to _wrap_encode_output"
+ );
+ }
+
+ #[test]
+ fn build_dense_payload_rejects_dim_mismatch() {
+ let err = build_dense_payload(&[1.0, 2.0], 3).unwrap_err();
+ assert!(matches!(
+ err,
+ ShapeError::DenseDimMismatch {
+ expected: 3,
+ actual: 2
+ }
+ ));
+ }
+
+ // ---- build_score_payload -----------------------------------
+
+ /// Golden: Python `queue_executor._process_single_score` emits
+ /// scores via `float(score_output.scores[i])` where
+ /// `score_output.scores` is `np.float32`. That widens each
+ /// score to `f64` **without** recovering full `f64` precision —
+ /// `float(np.float32(0.9))` ≠ the Python literal `0.9`. The
+ /// golden below reflects the real production path.
+ ///
+ /// Regenerate with:
+ ///
+ /// ```sh
+ /// uv run --no-project --with msgpack --with numpy python -c "
+ /// import msgpack, numpy as np
+ /// scores = np.array([0.9, 0.5], dtype=np.float32)
+ /// ids = ['a', 'b']
+ /// scored = sorted(zip(ids, scores), key=lambda x: x[1], reverse=True)
+ /// entries = [{'item_id': i, 'score': float(s), 'rank': r}
+ /// for r, (i, s) in enumerate(scored)]
+ /// print(msgpack.packb(entries, use_bin_type=True).hex())"
+ /// ```
+ ///
+ /// Captured: 65 bytes.
+ const GOLDEN_SCORE_AB: &[u8] = &[
+ 0x92, 0x83, 0xa7, 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x69, 0x64, 0xa1, 0x61, 0xa5, 0x73, 0x63,
+ 0x6f, 0x72, 0x65, 0xcb, 0x3f, 0xec, 0xcc, 0xcc, 0xc0, 0x00, 0x00, 0x00, 0xa4, 0x72, 0x61,
+ 0x6e, 0x6b, 0x00, 0x83, 0xa7, 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x69, 0x64, 0xa1, 0x62, 0xa5,
+ 0x73, 0x63, 0x6f, 0x72, 0x65, 0xcb, 0x3f, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa4,
+ 0x72, 0x61, 0x6e, 0x6b, 0x01,
+ ];
+
+ #[test]
+ fn build_score_payload_matches_python_wire_format_sorted_desc() {
+ // Pass unsorted; the shaper must rank-sort desc like Python.
+ // scores: a=0.9, b=0.5 → already desc on input, but exercises
+ // the stable-sort path with a tied pair below.
+ let scores = vec![0.9_f32, 0.5_f32];
+ let ids = vec!["a".to_string(), "b".to_string()];
+ let buf = build_score_payload(&scores, &ids).unwrap();
+ assert_eq!(
+ buf, GOLDEN_SCORE_AB,
+ "score payload must be byte-identical to Python msgpack.packb"
+ );
+ }
+
+ #[test]
+ fn build_score_payload_reorders_and_reranks() {
+ // Feed Python the same pair in reversed order — it still
+ // emits a=rank0, b=rank1 after sorting desc.
+ let scores = vec![0.5_f32, 0.9_f32];
+ let ids = vec!["b".to_string(), "a".to_string()];
+ let buf = build_score_payload(&scores, &ids).unwrap();
+ assert_eq!(
+ buf, GOLDEN_SCORE_AB,
+ "score payload must sort desc before emission, regardless of input order"
+ );
+ }
+
+ #[test]
+ fn build_score_payload_stable_on_ties() {
+ // Python's `list.sort(key=lambda x: x[1], reverse=True)` is
+ // stable: equal-scored items keep their input order.
+ // Assert the same here. Manually pack the expected output.
+ let scores = vec![0.5_f32, 0.5_f32, 0.5_f32];
+ let ids = vec!["x".to_string(), "y".to_string(), "z".to_string()];
+ let buf = build_score_payload(&scores, &ids).unwrap();
+
+ // Reconstruct expected Python bytes in-place — stable sort
+ // means rank order is x=0, y=1, z=2.
+ let mut expected = Vec::new();
+ write_array_len(&mut expected, 3).unwrap();
+ for (rank, id) in ["x", "y", "z"].iter().enumerate() {
+ write_map_len(&mut expected, 3).unwrap();
+ write_str(&mut expected, "item_id").unwrap();
+ write_str(&mut expected, id).unwrap();
+ write_str(&mut expected, "score").unwrap();
+ write_f64(&mut expected, 0.5).unwrap();
+ write_str(&mut expected, "rank").unwrap();
+ write_uint(&mut expected, rank as u64).unwrap();
+ }
+ assert_eq!(buf, expected, "stable tie-breaking must match Python");
+ }
+
+ #[test]
+ fn build_score_payload_rejects_length_mismatch() {
+ let err = build_score_payload(&[1.0, 2.0], &["only-one".to_string()]).unwrap_err();
+ assert!(matches!(
+ err,
+ ShapeError::ScoreLenMismatch {
+ scores: 2,
+ items: 1
+ }
+ ));
+ }
+
+ #[test]
+ fn build_score_payload_empty_is_empty_array() {
+ let buf = build_score_payload(&[], &[]).unwrap();
+ // msgpack empty array is `0x90`.
+ assert_eq!(buf, vec![0x90]);
+ }
+
+ // ---- build_sparse_payload ----------------------------------
+
+ fn hex_to_bytes(hex: &str) -> Vec<u8> {
+ (0..hex.len())
+ .step_by(2)
+ .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
+ .collect()
+ }
+
+ /// Golden for `{"sparse": {"dims": None, "dtype": "float32",
+ /// "indices": np.array([3, 7, 42], i32),
+ /// "values": np.array([0.5, 1.5, 2.5], f32)}}`.
+ ///
+ /// Regenerate via (keep in lockstep with the Python tests in
+ /// `packages/sie_server/tests/test_stage1d_byte_identity.py`):
+ ///
+ /// ```sh
+ /// uv run python -c "
+ /// import msgpack, msgpack_numpy as m; m.patch()
+ /// import numpy as np
+ /// print(msgpack.packb({'sparse': {'dims': None, 'dtype': 'float32',
+ /// 'indices': np.array([3,7,42], dtype=np.int32),
+ /// 'values': np.array([0.5,1.5,2.5], dtype=np.float32)}},
+ /// use_bin_type=True).hex())"
+ /// ```
+ const GOLDEN_SPARSE_NIL_DIM_HEX: &str = "81a673706172736584a464696d73c0a56474797065a7666c6f61743332a7696e646963657385c4026e64c3c40474797065a33c6934c4046b696e64c400c40573686170659103c40464617461c40c03000000070000002a000000a676616c75657385c4026e64c3c40474797065a33c6634c4046b696e64c400c40573686170659103c40464617461c40c0000003f0000c03f00002040";
+
+ const GOLDEN_SPARSE_WITH_DIM_HEX: &str = "81a673706172736584a464696d73cd773aa56474797065a7666c6f61743332a7696e646963657385c4026e64c3c40474797065a33c6934c4046b696e64c400c40573686170659103c40464617461c40c03000000070000002a000000a676616c75657385c4026e64c3c40474797065a33c6634c4046b696e64c400c40573686170659103c40464617461c40c0000003f0000c03f00002040";
+
+ const GOLDEN_SPARSE_EMPTY_HEX: &str = "81a673706172736584a464696d73cd03e8a56474797065a7666c6f61743332a7696e646963657385c4026e64c3c40474797065a33c6934c4046b696e64c400c40573686170659100c40464617461c400a676616c75657385c4026e64c3c40474797065a33c6634c4046b696e64c400c40573686170659100c40464617461c400";
+
+ #[test]
+ fn build_sparse_payload_nil_dim_matches_python() {
+ let buf = build_sparse_payload(&[3, 7, 42], &[0.5, 1.5, 2.5], None).unwrap();
+ assert_eq!(
+ buf,
+ hex_to_bytes(GOLDEN_SPARSE_NIL_DIM_HEX),
+ "sparse (dims=None) bytes must match _wrap_encode_output output"
+ );
+ }
+
+ #[test]
+ fn build_sparse_payload_with_dim_matches_python() {
+ // 30522 -> 0xcd 0x77 0x3a (msgpack uint16)
+ let buf = build_sparse_payload(&[3, 7, 42], &[0.5, 1.5, 2.5], Some(30522)).unwrap();
+ assert_eq!(
+ buf,
+ hex_to_bytes(GOLDEN_SPARSE_WITH_DIM_HEX),
+ "sparse (dims=30522) bytes must match _wrap_encode_output output"
+ );
+ }
+
+ #[test]
+ fn build_sparse_payload_empty_matches_python() {
+ let buf = build_sparse_payload(&[], &[], Some(1000)).unwrap();
+ assert_eq!(
+ buf,
+ hex_to_bytes(GOLDEN_SPARSE_EMPTY_HEX),
+ "empty sparse must match Python: shape=[0], data=empty"
+ );
+ }
+
+ #[test]
+ fn build_sparse_payload_rejects_length_mismatch() {
+ let err = build_sparse_payload(&[1, 2], &[0.5], None).unwrap_err();
+ assert!(matches!(
+ err,
+ ShapeError::SparseLenMismatch {
+ indices: 2,
+ values: 1
+ }
+ ));
+ }
+
+ // ---- build_multivector_payload -----------------------------
+
+ /// Golden: `{"multivector": {"token_dims": 4, "num_tokens": 3,
+ /// "dtype": "float32",
+ /// "values": np.arange(12, f32).reshape(3,4)}}`.
+ const GOLDEN_MULTIVECTOR_3X4_HEX: &str = "81ab6d756c7469766563746f7284aa746f6b656e5f64696d7304aa6e756d5f746f6b656e7303a56474797065a7666c6f61743332a676616c75657385c4026e64c3c40474797065a33c6634c4046b696e64c400c4057368617065920304c40464617461c430000000000000803f0000004000004040000080400000a0400000c0400000e04000000041000010410000204100003041";
+
+ #[test]
+ fn build_multivector_payload_matches_python() {
+ let values: Vec<f32> = (0..12).map(|i| i as f32).collect();
+ let buf = build_multivector_payload(&values, 3, 4).unwrap();
+ assert_eq!(
+ buf,
+ hex_to_bytes(GOLDEN_MULTIVECTOR_3X4_HEX),
+ "multivector [3, 4] f32 bytes must match _wrap_encode_output output"
+ );
+ }
+
+ #[test]
+ fn build_multivector_payload_rejects_shape_mismatch() {
+ // 3*4 = 12, feeding 10 values is wrong.
+ let err = build_multivector_payload(&[0.0; 10], 3, 4).unwrap_err();
+ assert!(matches!(
+ err,
+ ShapeError::MultivectorShapeMismatch {
+ values: 10,
+ rows: 3,
+ cols: 4,
+ }
+ ));
+ }
+}
diff --git a/packages/sie_server_sidecar/src/output/numpy_sentinel.rs b/packages/sie_server_sidecar/src/output/numpy_sentinel.rs
new file mode 100644
index 000000000..a8c1c26e6
--- /dev/null
+++ b/packages/sie_server_sidecar/src/output/numpy_sentinel.rs
@@ -0,0 +1,210 @@
+//! Build msgpack bytes that match `msgpack_numpy`'s on-wire format.
+//!
+//! The Python queue executor serializes a successful encode outcome
+//! with `msgpack.packb(output, use_bin_type=True)` after
+//! `msgpack_numpy.patch()` has installed a `default` encoder hook.
+//! That hook rewrites any `numpy.ndarray` into a 5-key map — the
+//! so-called **numpy sentinel**:
+//!
+//! ```text
+//! {
+//! b"nd": true,
+//! b"type": "<f4", // ndarray.dtype.str
+//! b"kind": b"", // ndarray.dtype.kind for structured dtypes
+//! b"shape": [d0, d1, ...], // ndarray.shape
+//! b"data": <raw bytes>, // ndarray.tobytes() (little-endian, C-order)
+//! }
+//! ```
+//!
+//! All five keys are packed as **bin8** (not str) because
+//! `msgpack_numpy.encode` uses Python `bytes` literals. The SDK's
+//! decoder relies on this exact shape (see `_shared.py::parse_encode_results`
+//! and gateway `convert_numpy_for_json::is_numpy_sentinel`), so we have
+//! to match it byte-for-byte.
+//!
+//! Keeping this in one place also makes it trivial to unit-test the
+//! output against a golden blob captured from Python.
+
+use std::io::Write;
+
+use rmp::encode::{write_array_len, write_bin, write_bool, write_map_len, write_str, write_uint};
+
+/// Internal error type for sentinel writers. All writes go to a
+/// `Vec<u8>`, so I/O can't fail in practice — the error exists so
+/// callers can propagate without unwrapping.
+#[derive(Debug, thiserror::Error)]
+pub enum SentinelError {
+ #[error("msgpack write: {0}")]
+ MsgpackWrite(String),
+ #[error("invalid matrix shape: rows*cols ({expected}) != data.len() ({actual})")]
+ InvalidMatrixShape { expected: usize, actual: usize },
+}
+
+/// Small helper so the writers below stay readable: stringify any
+/// error we get from `rmp::encode` and wrap it as `SentinelError`.
+fn wrap_err<E: std::fmt::Display>(e: E) -> SentinelError {
+ SentinelError::MsgpackWrite(e.to_string())
+}
+
+/// msgpack-numpy dtype string for a contiguous little-endian float32
+/// array. This is `numpy.dtype("float32").str` on a little-endian
+/// host, which is what the SDK expects.
+pub const DTYPE_F32: &str = "<f4";
+
+/// msgpack-numpy dtype string for int32 little-endian, used for
+/// sparse indices.
+pub const DTYPE_I32: &str = "<i4";
+
+/// Write the 5-key numpy sentinel map into `buf`, with pre-encoded
+/// raw bytes and explicit shape. The caller supplies:
+///
+/// * `dtype_str` — the `"<f4"`, `"<i4"`, etc. code. Must match the
+/// byte layout of `data`.
+/// * `shape` — dimensions in C order (`[rows, cols]` for 2D).
+/// * `data` — raw little-endian bytes, `prod(shape) * itemsize`.
+pub fn write_numpy_sentinel(
+ buf: &mut Vec<u8>,
+ dtype_str: &str,
+ shape: &[u32],
+ data: &[u8],
+) -> Result<(), SentinelError> {
+ // 5-key map: nd, type, kind, shape, data.
+ write_map_len(buf, 5).map_err(wrap_err)?;
+
+ write_bin(buf, b"nd").map_err(wrap_err)?;
+ write_bool(buf, true).map_err(wrap_err)?;
+
+ write_bin(buf, b"type").map_err(wrap_err)?;
+ write_str(buf, dtype_str).map_err(wrap_err)?;
+
+ write_bin(buf, b"kind").map_err(wrap_err)?;
+ write_bin(buf, b"").map_err(wrap_err)?;
+
+ write_bin(buf, b"shape").map_err(wrap_err)?;
+ write_array_len(buf, shape.len() as u32).map_err(wrap_err)?;
+ for dim in shape {
+ // Shapes are always non-negative. Python packs these as the
+ // smallest positive int — msgpack-numpy does the equivalent
+ // of `msgpack.packb(int)`, which for `3` is `0x03` (fixint).
+ // `write_uint` picks the shortest encoding (fixint for
+ // values ≤127) to stay byte-identical with Python.
+ write_uint(buf, u64::from(*dim)).map_err(wrap_err)?;
+ }
+
+ write_bin(buf, b"data").map_err(wrap_err)?;
+ write_bin(buf, data).map_err(wrap_err)?;
+
+ Ok(())
+}
+
+/// Convenience: write a 1-D float32 array as a numpy sentinel.
+pub fn write_f32_vector(buf: &mut Vec<u8>, vec: &[f32]) -> Result<(), SentinelError> {
+ // Flatten f32 slice into little-endian bytes. The host is
+ // little-endian for every platform we ship on, so a bytemuck
+ // cast would be zero-copy — but we keep it explicit and portable.
+ let mut data = Vec::with_capacity(vec.len() * 4);
+ for &f in vec {
+ data.write_all(&f.to_le_bytes()).map_err(wrap_err)?;
+ }
+ write_numpy_sentinel(buf, DTYPE_F32, &[vec.len() as u32], &data)
+}
+
+/// Convenience: write a 1-D int32 array as a numpy sentinel.
+pub fn write_i32_vector(buf: &mut Vec<u8>, vec: &[i32]) -> Result<(), SentinelError> {
+ let mut data = Vec::with_capacity(vec.len() * 4);
+ for &i in vec {
+ data.write_all(&i.to_le_bytes()).map_err(wrap_err)?;
+ }
+ write_numpy_sentinel(buf, DTYPE_I32, &[vec.len() as u32], &data)
+}
+
+/// Convenience: write a 2-D float32 matrix `[rows, cols]` as a numpy
+/// sentinel. `data` must be flattened in C (row-major) order —
+/// exactly what `np.ndarray.tobytes()` emits for a contiguous array.
+///
+pub fn write_f32_matrix_2d(
+ buf: &mut Vec<u8>,
+ data: &[f32],
+ rows: u32,
+ cols: u32,
+) -> Result<(), SentinelError> {
+ let expected = (rows as usize).saturating_mul(cols as usize);
+ if data.len() != expected {
+ return Err(SentinelError::InvalidMatrixShape {
+ expected,
+ actual: data.len(),
+ });
+ }
+ let mut bytes = Vec::with_capacity(data.len() * 4);
+ for &f in data {
+ bytes.write_all(&f.to_le_bytes()).map_err(wrap_err)?;
+ }
+ write_numpy_sentinel(buf, DTYPE_F32, &[rows, cols], &bytes)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Golden: `msgpack.packb(np.array([1.0, 2.0, 3.0], dtype=np.float32))`
+ /// after `msgpack_numpy.patch()`. Captured from CPython
+ /// (see docs: 53 bytes).
+ const GOLDEN_F32_123: &[u8] = &[
+ 0x85, 0xc4, 0x02, 0x6e, 0x64, 0xc3, 0xc4, 0x04, 0x74, 0x79, 0x70, 0x65, 0xa3, 0x3c, 0x66,
+ 0x34, 0xc4, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0xc4, 0x00, 0xc4, 0x05, 0x73, 0x68, 0x61, 0x70,
+ 0x65, 0x91, 0x03, 0xc4, 0x04, 0x64, 0x61, 0x74, 0x61, 0xc4, 0x0c, 0x00, 0x00, 0x80, 0x3f,
+ 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40,
+ ];
+
+ /// Golden: `msgpack.packb(np.array([5, 17, 99], dtype=np.int32))`.
+ const GOLDEN_I32: &[u8] = &[
+ 0x85, 0xc4, 0x02, 0x6e, 0x64, 0xc3, 0xc4, 0x04, 0x74, 0x79, 0x70, 0x65, 0xa3, 0x3c, 0x69,
+ 0x34, 0xc4, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0xc4, 0x00, 0xc4, 0x05, 0x73, 0x68, 0x61, 0x70,
+ 0x65, 0x91, 0x03, 0xc4, 0x04, 0x64, 0x61, 0x74, 0x61, 0xc4, 0x0c, 0x05, 0x00, 0x00, 0x00,
+ 0x11, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00,
+ ];
+
+ #[test]
+ fn f32_vector_matches_python_golden() {
+ let mut buf = Vec::new();
+ write_f32_vector(&mut buf, &[1.0, 2.0, 3.0]).unwrap();
+ assert_eq!(
+ buf, GOLDEN_F32_123,
+ "f32 vector sentinel doesn't match msgpack-numpy wire format"
+ );
+ }
+
+ #[test]
+ fn i32_vector_matches_python_golden() {
+ let mut buf = Vec::new();
+ write_i32_vector(&mut buf, &[5, 17, 99]).unwrap();
+ assert_eq!(
+ buf, GOLDEN_I32,
+ "i32 vector sentinel doesn't match msgpack-numpy wire format"
+ );
+ }
+
+ #[test]
+ fn empty_f32_vector_roundtrips() {
+ let mut buf = Vec::new();
+ write_f32_vector(&mut buf, &[]).unwrap();
+ // An empty vector should still be a 5-key map, shape [0], data zero bytes.
+ assert_eq!(&buf[0..1], &[0x85], "should be map-of-5");
+ // The last 3 bytes: c4 00 (empty bin data)
+ assert_eq!(&buf[buf.len() - 2..], &[0xc4, 0x00]);
+ }
+
+ #[test]
+ fn f32_matrix_rejects_shape_mismatch() {
+ let mut buf = Vec::new();
+ let err = write_f32_matrix_2d(&mut buf, &[1.0, 2.0, 3.0], 2, 2).unwrap_err();
+ assert!(matches!(
+ err,
+ SentinelError::InvalidMatrixShape {
+ expected: 4,
+ actual: 3
+ }
+ ));
+ assert!(buf.is_empty());
+ }
+}
diff --git a/packages/sie_server_sidecar/src/payload_store.rs b/packages/sie_server_sidecar/src/payload_store.rs
new file mode 100644
index 000000000..d1f8a958d
--- /dev/null
+++ b/packages/sie_server_sidecar/src/payload_store.rs
@@ -0,0 +1,585 @@
+//! Payload store — read-only side.
+//!
+//! Workers consume payload_refs written by the gateway
+//! (`packages/sie_gateway/src/queue/payload_store.rs`). Only `get` is needed
+//! on this side; the gateway writes/deletes.
+//!
+//! The ref format is:
+//! - local: filesystem path under the worker's configured `base_dir`
+//! (absolute paths are only accepted when they canonicalize inside
+//! `base_dir`; relative paths are resolved against it). When no
+//! `base_dir` is configured the reader is disabled for safety.
+//! - cloud: `s3://…` / `gs://…` URL (handled when the `cloud-storage`
+//! feature is enabled)
+//!
+//! Security: we canonicalize the resolved path and reject anything that
+//! escapes `base_dir`. Without this, a compromised gateway could send a
+//! `payload_ref` like `/etc/passwd` or `../../secrets/key.bin` and read
+//! arbitrary files the worker process has access to.
+
+use std::path::{Path, PathBuf};
+
+use async_trait::async_trait;
+use thiserror::Error;
+use tracing::debug;
+
+#[derive(Debug, Error)]
+pub enum PayloadError {
+ #[error("io: {0}")]
+ Io(#[from] std::io::Error),
+ #[error("invalid payload ref: {0}")]
+ InvalidRef(String),
+ #[error("unsupported payload scheme: {0}")]
+ Unsupported(String),
+ #[error("object store: {0}")]
+ ObjectStore(String),
+}
+
+#[async_trait]
+pub trait PayloadStore: Send + Sync {
+ async fn get(&self, payload_ref: &str) -> Result<Vec<u8>, PayloadError>;
+}
+
+/// Local filesystem reader.
+///
+/// * When `base_dir` is `Some`, `payload_ref` is resolved against it and
+/// the final (canonical) path MUST stay inside `base_dir`. Absolute refs
+/// are accepted only when they canonicalize under `base_dir`.
+/// * When `base_dir` is `None`, the store rejects all reads — this
+/// matches the gateway's refusal to publish payload_refs when the
+/// worker isn't configured with `SIE_PAYLOAD_STORE_URL`.
+pub struct LocalPayloadStore {
+ base_dir: Option<PathBuf>,
+}
+
+impl LocalPayloadStore {
+ pub fn new(base_dir: Option<impl Into<PathBuf>>) -> Self {
+ Self {
+ base_dir: base_dir.map(Into::into),
+ }
+ }
+
+ /// Resolve `payload_ref` to an absolute filesystem path that is
+ /// guaranteed to sit under `base_dir` (when configured).
+ ///
+ /// The caller is expected to treat the returned path as the _only_
+ /// safe target to read — do not re-interpret it or follow symlinks
+ /// at the application layer.
+ fn resolve(&self, payload_ref: &str) -> Result<PathBuf, PayloadError> {
+ if payload_ref.is_empty() {
+ return Err(PayloadError::InvalidRef(payload_ref.to_string()));
+ }
+ let Some(base) = &self.base_dir else {
+ return Err(PayloadError::InvalidRef(format!(
+ "payload store not configured; cannot resolve {payload_ref}"
+ )));
+ };
+
+ let base_canon = base.canonicalize().map_err(|e| {
+ PayloadError::InvalidRef(format!(
+ "configured base_dir {} is not canonicalizable: {e}",
+ base.display()
+ ))
+ })?;
+
+ let raw = Path::new(payload_ref);
+ let joined = if raw.is_absolute() {
+ raw.to_path_buf()
+ } else {
+ base_canon.join(raw)
+ };
+
+ // We canonicalize the resolved path to eliminate `..`, symlinks,
+ // and case-insensitive tricks, then check that it still sits
+ // under the canonical base_dir. `canonicalize` requires the
+ // target to exist; preserve missing-file semantics as an IO
+ // NotFound rather than masking it as an invalid ref.
+ let full = joined.canonicalize().map_err(|e| {
+ if e.kind() == std::io::ErrorKind::NotFound {
+ PayloadError::Io(e)
+ } else {
+ PayloadError::InvalidRef(format!(
+ "failed to canonicalize payload ref {payload_ref}: {e}"
+ ))
+ }
+ })?;
+ if !full.starts_with(&base_canon) {
+ return Err(PayloadError::InvalidRef(format!(
+ "payload ref {payload_ref} escapes base_dir {}",
+ base_canon.display()
+ )));
+ }
+ Ok(full)
+ }
+}
+
+#[async_trait]
+impl PayloadStore for LocalPayloadStore {
+ async fn get(&self, payload_ref: &str) -> Result<Vec<u8>, PayloadError> {
+ let path = self.resolve(payload_ref)?;
+ let bytes = tokio::fs::read(&path).await?;
+ debug!(path = %path.display(), bytes = bytes.len(), "read local payload");
+ Ok(bytes)
+ }
+}
+
+#[cfg(feature = "cloud-storage")]
+pub struct ObjectPayloadStore {
+ store: Box<dyn object_store::ObjectStore>,
+ prefix: object_store::path::Path,
+ url_prefix: String,
+ scheme: &'static str,
+}
+
+#[cfg(feature = "cloud-storage")]
+impl ObjectPayloadStore {
+ pub fn new_s3(path: &str) -> Result<Self, PayloadError> {
+ use object_store::aws::AmazonS3Builder;
+
+ let (bucket, prefix) = Self::parse_bucket_prefix(path)?;
+ let store = AmazonS3Builder::from_env()
+ .with_bucket_name(&bucket)
+ .build()
+ .map_err(|e| {
+ PayloadError::Unsupported(format!("failed to build S3 payload store: {e}"))
+ })?;
+ Ok(Self {
+ store: Box::new(store),
+ prefix: object_store::path::Path::from(prefix),
+ url_prefix: format!("s3://{}", path.trim_end_matches('/')),
+ scheme: "s3://",
+ })
+ }
+
+ pub fn new_gcs(path: &str) -> Result<Self, PayloadError> {
+ use object_store::gcp::GoogleCloudStorageBuilder;
+
+ let (bucket, prefix) = Self::parse_bucket_prefix(path)?;
+ let store = GoogleCloudStorageBuilder::from_env()
+ .with_bucket_name(&bucket)
+ .build()
+ .map_err(|e| {
+ PayloadError::Unsupported(format!("failed to build GCS payload store: {e}"))
+ })?;
+ Ok(Self {
+ store: Box::new(store),
+ prefix: object_store::path::Path::from(prefix),
+ url_prefix: format!("gs://{}", path.trim_end_matches('/')),
+ scheme: "gs://",
+ })
+ }
+
+ fn parse_bucket_prefix(path: &str) -> Result<(String, String), PayloadError> {
+ let path = path.trim_matches('/');
+ let Some((bucket, prefix)) = path.split_once('/') else {
+ if path.is_empty() {
+ return Err(PayloadError::InvalidRef(
+ "payload store bucket is empty".into(),
+ ));
+ }
+ return Ok((path.to_string(), String::new()));
+ };
+ if bucket.is_empty() {
+ return Err(PayloadError::InvalidRef(
+ "payload store bucket is empty".into(),
+ ));
+ }
+ Ok((bucket.to_string(), prefix.trim_matches('/').to_string()))
+ }
+
+ fn relative_key<'a>(&self, payload_ref: &'a str) -> Result<&'a str, PayloadError> {
+ if payload_ref.is_empty() {
+ return Err(PayloadError::InvalidRef(payload_ref.to_string()));
+ }
+
+ let key = if payload_ref.starts_with(self.scheme) {
+ let prefix = self.url_prefix.trim_end_matches('/');
+ let Some(rest) = payload_ref.strip_prefix(prefix) else {
+ return Err(PayloadError::InvalidRef(format!(
+ "payload ref {payload_ref} is outside configured store {prefix}"
+ )));
+ };
+ let Some(rest) = rest.strip_prefix('/') else {
+ return Err(PayloadError::InvalidRef(format!(
+ "payload ref {payload_ref} is outside configured store {prefix}"
+ )));
+ };
+ rest
+ } else if payload_ref.starts_with("s3://") || payload_ref.starts_with("gs://") {
+ return Err(PayloadError::InvalidRef(format!(
+ "payload ref {payload_ref} uses a different object-store scheme"
+ )));
+ } else {
+ payload_ref
+ };
+
+ Self::validate_relative_key(key)?;
+ Ok(key)
+ }
+
+ fn validate_relative_key(key: &str) -> Result<(), PayloadError> {
+ if key.is_empty()
+ || key.starts_with('/')
+ || key.contains('\\')
+ || key
+ .split('/')
+ .any(|part| part.is_empty() || part == "." || part == "..")
+ {
+ return Err(PayloadError::InvalidRef(key.to_string()));
+ }
+ Ok(())
+ }
+
+ fn object_key(&self, key: &str) -> object_store::path::Path {
+ if self.prefix.as_ref().is_empty() {
+ object_store::path::Path::from(key)
+ } else {
+ object_store::path::Path::from(format!("{}/{}", self.prefix, key))
+ }
+ }
+}
+
+#[cfg(feature = "cloud-storage")]
+#[async_trait]
+impl PayloadStore for ObjectPayloadStore {
+ async fn get(&self, payload_ref: &str) -> Result<Vec<u8>, PayloadError> {
+ let key = self.relative_key(payload_ref)?;
+ let object_key = self.object_key(key);
+ let result = self.store.get(&object_key).await.map_err(|e| match e {
+ object_store::Error::NotFound { .. } => {
+ PayloadError::InvalidRef(format!("payload ref not found: {payload_ref}"))
+ }
+ other => PayloadError::ObjectStore(format!("get payload {object_key}: {other}")),
+ })?;
+ let bytes = result
+ .bytes()
+ .await
+ .map_err(|e| PayloadError::ObjectStore(format!("read payload {object_key}: {e}")))?;
+ debug!(key = %object_key, bytes = bytes.len(), "read object-store payload");
+ Ok(bytes.to_vec())
+ }
+}
+
+/// Metrics-observing wrapper — counts fetches, broken-out errors, and
+/// records latency + payload size histograms. Kept separate from the
+/// concrete stores so the metrics registry dependency doesn't leak into
+/// their traits / tests.
+pub struct MeteredPayloadStore {
+ inner: std::sync::Arc<dyn PayloadStore>,
+ metrics: std::sync::Arc<crate::metrics::MetricsRegistry>,
+}
+
+impl MeteredPayloadStore {
+ pub fn new(
+ inner: std::sync::Arc<dyn PayloadStore>,
+ metrics: std::sync::Arc<crate::metrics::MetricsRegistry>,
+ ) -> Self {
+ Self { inner, metrics }
+ }
+}
+
+#[async_trait]
+impl PayloadStore for MeteredPayloadStore {
+ async fn get(&self, payload_ref: &str) -> Result<Vec<u8>, PayloadError> {
+ let start = std::time::Instant::now();
+ self.metrics.payload_fetch_total.inc();
+ let result = self.inner.get(payload_ref).await;
+ let elapsed = start.elapsed().as_secs_f64();
+ match &result {
+ Ok(bytes) => {
+ self.metrics
+ .payload_fetch_seconds
+ .with_label_values(&["ok"])
+ .observe(elapsed);
+ self.metrics
+ .payload_bytes
+ .with_label_values(&["ok"])
+ .observe(bytes.len() as f64);
+ }
+ Err(e) => {
+ let reason = match e {
+ PayloadError::Io(io) => match io.kind() {
+ std::io::ErrorKind::NotFound => "not_found",
+ std::io::ErrorKind::PermissionDenied => "permission_denied",
+ _ => "io",
+ },
+ PayloadError::InvalidRef(_) => "invalid_ref",
+ PayloadError::Unsupported(_) => "unsupported",
+ PayloadError::ObjectStore(_) => "object_store",
+ };
+ self.metrics
+ .payload_fetch_errors_total
+ .with_label_values(&[reason])
+ .inc();
+ self.metrics
+ .payload_fetch_seconds
+ .with_label_values(&["error"])
+ .observe(elapsed);
+ }
+ }
+ result
+ }
+}
+
+/// Factory — mirrors the gateway's `create_payload_store`. Returns an
+/// opaque trait object so call sites don't care which backend is in use.
+///
+/// URL handling:
+/// * `None` or an empty string → local store with no base_dir (disabled,
+/// rejects all reads). Pods without offload configured stay safe.
+/// * `s3://…` / `gs://…` with the `cloud-storage` feature → object
+/// storage reader.
+/// * `s3://…` / `gs://…` without the feature → we can't read from
+/// object storage, and we MUST NOT silently treat the URL string as a
+/// filesystem path (`LocalPayloadStore::new(Some("s3://…"))` canonicalizes
+/// to a broken, confusing error on every request). Return an explicit
+/// `Unsupported` so the worker fails fast at startup instead of
+/// NAKing every item at runtime.
+/// * `file://path` → strip scheme, treat as local filesystem.
+/// * Anything else → treated as a local filesystem path.
+pub async fn create_payload_store(
+ url: Option<&str>,
+) -> Result<std::sync::Arc<dyn PayloadStore>, PayloadError> {
+ let Some(url) = url.filter(|u| !u.is_empty()) else {
+ return Ok(std::sync::Arc::new(LocalPayloadStore::new(None::<PathBuf>)));
+ };
+
+ if url.starts_with("s3://") || url.starts_with("gs://") {
+ #[cfg(feature = "cloud-storage")]
+ {
+ if let Some(rest) = url.strip_prefix("s3://") {
+ return Ok(std::sync::Arc::new(ObjectPayloadStore::new_s3(rest)?));
+ }
+ if let Some(rest) = url.strip_prefix("gs://") {
+ return Ok(std::sync::Arc::new(ObjectPayloadStore::new_gcs(rest)?));
+ }
+ }
+ #[cfg(not(feature = "cloud-storage"))]
+ {
+ return Err(PayloadError::Unsupported(format!(
+ "payload store URL {url} requires the 'cloud-storage' feature; \
+ rebuild the worker with --features cloud-storage or point \
+ SIE_PAYLOAD_STORE_URL at a local path"
+ )));
+ }
+ }
+
+ let path = url.strip_prefix("file://").unwrap_or(url);
+ Ok(std::sync::Arc::new(LocalPayloadStore::new(Some(path))))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tempfile::TempDir;
+
+ #[tokio::test]
+ async fn local_get_absolute_path_inside_base_dir() {
+ // Gateway writes absolute paths (e.g. /var/cache/sie/uuid.bin);
+ // those are accepted as long as they sit under the configured
+ // base_dir.
+ let dir = TempDir::new().unwrap();
+ let path = dir.path().join("req-1_0.bin");
+ tokio::fs::write(&path, b"hello").await.unwrap();
+
+ let store = LocalPayloadStore::new(Some(dir.path().to_path_buf()));
+ let got = store.get(path.to_str().unwrap()).await.unwrap();
+ assert_eq!(got, b"hello");
+ }
+
+ #[tokio::test]
+ async fn local_get_relative_with_base() {
+ let dir = TempDir::new().unwrap();
+ let path = dir.path().join("req-2_0.bin");
+ tokio::fs::write(&path, b"world").await.unwrap();
+
+ let store = LocalPayloadStore::new(Some(dir.path().to_path_buf()));
+ let got = store.get("req-2_0.bin").await.unwrap();
+ assert_eq!(got, b"world");
+ }
+
+ #[tokio::test]
+ async fn missing_ref_surfaces_not_found_io() {
+ let dir = TempDir::new().unwrap();
+ let store = LocalPayloadStore::new(Some(dir.path().to_path_buf()));
+ let err = store.get("missing.bin").await.unwrap_err();
+ assert!(
+ matches!(err, PayloadError::Io(ref e) if e.kind() == std::io::ErrorKind::NotFound),
+ "expected NotFound IO for missing payload, got {err:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn local_get_without_base_dir_is_disabled() {
+ // Safety: without a configured base_dir, the reader is disabled
+ // so a compromised gateway can't feed us arbitrary paths.
+ let store = LocalPayloadStore::new(None::<PathBuf>);
+ let err = store.get("/etc/passwd").await.unwrap_err();
+ assert!(matches!(err, PayloadError::InvalidRef(_)));
+ }
+
+ #[tokio::test]
+ async fn absolute_ref_outside_base_dir_is_rejected() {
+ // Classic path-traversal: base_dir is a tempdir, attacker sends
+ // an absolute path pointing outside it (here: /tmp root, which
+ // exists on every macOS/Linux box). The canonical check must
+ // refuse.
+ let base = TempDir::new().unwrap();
+ let store = LocalPayloadStore::new(Some(base.path().to_path_buf()));
+ let err = store.get("/etc/hosts").await.unwrap_err();
+ assert!(
+ matches!(err, PayloadError::InvalidRef(_)),
+ "expected InvalidRef for out-of-base absolute, got {err:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn relative_dotdot_ref_cannot_escape_base_dir() {
+ // Same thing as a relative ref that tries to climb out.
+ let parent = TempDir::new().unwrap();
+ let base = parent.path().join("sub");
+ tokio::fs::create_dir(&base).await.unwrap();
+ // Touch a file in the parent that an attacker might want to read.
+ tokio::fs::write(parent.path().join("secret.bin"), b"secret")
+ .await
+ .unwrap();
+
+ let store = LocalPayloadStore::new(Some(base.clone()));
+ let err = store.get("../secret.bin").await.unwrap_err();
+ assert!(
+ matches!(err, PayloadError::InvalidRef(_)),
+ "expected InvalidRef for dotdot escape, got {err:?}"
+ );
+ }
+
+ #[tokio::test]
+ async fn empty_ref_rejected() {
+ let dir = TempDir::new().unwrap();
+ let store = LocalPayloadStore::new(Some(dir.path().to_path_buf()));
+ let err = store.get("").await.unwrap_err();
+ assert!(matches!(err, PayloadError::InvalidRef(_)));
+ }
+
+ #[tokio::test]
+ async fn factory_none_yields_disabled_store() {
+ let store = create_payload_store(None).await.unwrap();
+ let err = store.get("/etc/passwd").await.unwrap_err();
+ assert!(matches!(err, PayloadError::InvalidRef(_)));
+ }
+
+ #[tokio::test]
+ async fn factory_empty_url_yields_disabled_store() {
+ // Treat `SIE_PAYLOAD_STORE_URL=` the same as unset, not as "the
+ // current directory". The previous behaviour tried to use "" as a
+ // filesystem path which canonicalized to CWD.
+ let store = create_payload_store(Some("")).await.unwrap();
+ let err = store.get("foo.bin").await.unwrap_err();
+ assert!(matches!(err, PayloadError::InvalidRef(_)));
+ }
+
+ #[tokio::test]
+ async fn factory_local_path_roundtrips() {
+ let dir = TempDir::new().unwrap();
+ let path = dir.path().join("pay.bin");
+ tokio::fs::write(&path, b"ok").await.unwrap();
+
+ let store = create_payload_store(Some(dir.path().to_str().unwrap()))
+ .await
+ .unwrap();
+ let got = store.get("pay.bin").await.unwrap();
+ assert_eq!(got, b"ok");
+ }
+
+ #[tokio::test]
+ async fn factory_file_scheme_is_stripped() {
+ let dir = TempDir::new().unwrap();
+ let path = dir.path().join("pay.bin");
+ tokio::fs::write(&path, b"ok").await.unwrap();
+
+ let url = format!("file://{}", dir.path().display());
+ let store = create_payload_store(Some(&url)).await.unwrap();
+ let got = store.get("pay.bin").await.unwrap();
+ assert_eq!(got, b"ok");
+ }
+
+ #[cfg(feature = "cloud-storage")]
+ #[tokio::test]
+ async fn object_store_get_accepts_full_ref_inside_prefix() {
+ use object_store::path::Path;
+ use object_store::{ObjectStore, PutPayload};
+
+ let memory = object_store::memory::InMemory::new();
+ memory
+ .put(
+ &Path::from("payloads/pay.bin"),
+ PutPayload::from(b"cloud".to_vec()),
+ )
+ .await
+ .unwrap();
+
+ let store = ObjectPayloadStore {
+ store: Box::new(memory),
+ prefix: Path::from("payloads"),
+ url_prefix: "s3://bucket/payloads".into(),
+ scheme: "s3://",
+ };
+ let got = store.get("s3://bucket/payloads/pay.bin").await.unwrap();
+ assert_eq!(got, b"cloud");
+ }
+
+ #[cfg(feature = "cloud-storage")]
+ #[tokio::test]
+ async fn object_store_get_rejects_ref_outside_prefix() {
+ use object_store::path::Path;
+
+ let store = ObjectPayloadStore {
+ store: Box::new(object_store::memory::InMemory::new()),
+ prefix: Path::from("payloads"),
+ url_prefix: "s3://bucket/payloads".into(),
+ scheme: "s3://",
+ };
+ let err = store.get("s3://bucket/other/pay.bin").await.unwrap_err();
+ assert!(matches!(err, PayloadError::InvalidRef(_)));
+ }
+
+ #[cfg(feature = "cloud-storage")]
+ #[tokio::test]
+ async fn object_store_get_accepts_plain_key_under_configured_prefix() {
+ use object_store::path::Path;
+ use object_store::{ObjectStore, PutPayload};
+
+ let memory = object_store::memory::InMemory::new();
+ memory
+ .put(
+ &Path::from("payloads/pay.bin"),
+ PutPayload::from(b"cloud".to_vec()),
+ )
+ .await
+ .unwrap();
+
+ let store = ObjectPayloadStore {
+ store: Box::new(memory),
+ prefix: Path::from("payloads"),
+ url_prefix: "s3://bucket/payloads".into(),
+ scheme: "s3://",
+ };
+ let got = store.get("pay.bin").await.unwrap();
+ assert_eq!(got, b"cloud");
+ }
+
+ #[cfg(not(feature = "cloud-storage"))]
+ #[tokio::test]
+ async fn factory_s3_without_feature_errors_loudly() {
+ // Previously this would silently fall back to a LocalPayloadStore
+ // whose base_dir was the literal string "s3://…", guaranteeing
+ // every read produced a confusing `canonicalize` error. We now
+ // refuse at construction time.
+ match create_payload_store(Some("s3://bucket/prefix")).await {
+ Ok(_) => panic!("expected Unsupported for s3:// without cloud-storage feature"),
+ Err(e) => assert!(
+ matches!(e, PayloadError::Unsupported(_)),
+ "expected Unsupported for s3://, got {e:?}"
+ ),
+ }
+ }
+}
diff --git a/packages/sie_server_sidecar/src/pool_admission.rs b/packages/sie_server_sidecar/src/pool_admission.rs
new file mode 100644
index 000000000..fbe29627a
--- /dev/null
+++ b/packages/sie_server_sidecar/src/pool_admission.rs
@@ -0,0 +1,374 @@
+//! Worker-side pool admission gate.
+//!
+//! The gateway owns pool assignment. Capped pools publish their assigned
+//! workers in `/v1/pools/{name}`; a worker that is not assigned must not pull
+//! from that pool's JetStream consumer, otherwise direct NATS publishes can
+//! bypass the gateway's admission decision.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use serde_json::{Map, Value};
+use tokio::sync::Mutex;
+use tokio::time::{interval, MissedTickBehavior};
+use tracing::{debug, info};
+
+use crate::config::WorkerConfig;
+use crate::shutdown::Shutdown;
+
+const HTTP_TIMEOUT: Duration = Duration::from_secs(5);
+
+#[derive(Debug)]
+struct GateState {
+ last_check_at: Option<Instant>,
+ last_success_at: Option<Instant>,
+ admitted: bool,
+ last_reason: String,
+}
+
+/// Runtime admission guard shared by the pool pull loop and generation
+/// worker-direct pull loop.
+#[derive(Debug)]
+pub struct PoolAdmissionGate {
+ pool_name: String,
+ worker_id: String,
+ machine_profile: String,
+ gateway_url: String,
+ api_key: Option<String>,
+ check_interval: Duration,
+ pause: Duration,
+ stale_after: Duration,
+ http: reqwest::Client,
+ admitted: AtomicBool,
+ state: Mutex<GateState>,
+}
+
+impl PoolAdmissionGate {
+ pub fn from_worker_config(config: &WorkerConfig) -> anyhow::Result<Option<Arc<Self>>> {
+ if !config.pool_admission_enabled {
+ info!("pool-admission: disabled by SIE_POOL_ADMISSION_ENABLED=false");
+ return Ok(None);
+ }
+ let Some(gateway_url) = config.gateway_url.as_deref().map(str::trim) else {
+ debug!("pool-admission: disabled because SIE_GATEWAY_URL is unset");
+ return Ok(None);
+ };
+ if gateway_url.is_empty() {
+ debug!("pool-admission: disabled because SIE_GATEWAY_URL is empty");
+ return Ok(None);
+ }
+
+ let http = reqwest::Client::builder().timeout(HTTP_TIMEOUT).build()?;
+ let initially_admitted = normalize_pool_name(&config.pool) == "default";
+ let gate = Self {
+ pool_name: config.pool.clone(),
+ worker_id: config.worker_id.clone(),
+ machine_profile: config.machine_profile.clone(),
+ gateway_url: gateway_url.trim_end_matches('/').to_string(),
+ api_key: config.gateway_api_key.clone(),
+ check_interval: Duration::from_millis(config.pool_admission_check_interval_ms),
+ pause: Duration::from_millis(config.pool_admission_pause_ms),
+ stale_after: Duration::from_millis(config.pool_admission_stale_after_ms),
+ http,
+ admitted: AtomicBool::new(initially_admitted),
+ state: Mutex::new(GateState {
+ last_check_at: None,
+ last_success_at: None,
+ admitted: initially_admitted,
+ last_reason: "initial".to_string(),
+ }),
+ };
+ info!(
+ pool = %gate.pool_name,
+ worker_id = %gate.worker_id,
+ machine_profile = %gate.machine_profile,
+ check_interval_ms = gate.check_interval.as_millis() as u64,
+ pause_ms = gate.pause.as_millis() as u64,
+ stale_after_ms = gate.stale_after.as_millis() as u64,
+ "pool-admission: enabled"
+ );
+ Ok(Some(Arc::new(gate)))
+ }
+
+ pub async fn run(self: Arc<Self>, shutdown: Arc<Shutdown>) {
+ let mut ticker = interval(self.check_interval);
+ ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
+ loop {
+ tokio::select! {
+ biased;
+ _ = shutdown.wait() => return,
+ _ = ticker.tick() => self.refresh().await,
+ }
+ }
+ }
+
+ pub fn pause_duration(&self) -> Duration {
+ self.pause
+ }
+
+ pub fn admitted(&self) -> bool {
+ self.admitted.load(Ordering::Acquire)
+ }
+
+ async fn refresh(&self) {
+ let now = Instant::now();
+ {
+ let mut state = self.state.lock().await;
+ state.last_check_at = Some(now);
+ }
+
+ let fetched = self.fetch_pool().await;
+ let mut state = self.state.lock().await;
+ match fetched {
+ Ok(pool) => {
+ state.last_success_at = Some(Instant::now());
+ let (admitted, reason) = decide_pool_admission(
+ pool.as_ref(),
+ &self.pool_name,
+ &self.worker_id,
+ &self.machine_profile,
+ );
+ self.set_admitted(&mut state, admitted, reason);
+ }
+ Err(error) => {
+ self.handle_error(&mut state, Instant::now(), error);
+ }
+ }
+ }
+
+ async fn fetch_pool(&self) -> Result<Option<Value>, String> {
+ let url = format!("{}/v1/pools/{}", self.gateway_url, self.pool_name);
+ let mut req = self.http.get(&url).header("accept", "application/json");
+ if let Some(token) = self.api_key.as_deref().filter(|token| !token.is_empty()) {
+ req = req.bearer_auth(token);
+ }
+ let resp = req.send().await.map_err(|e| e.to_string())?;
+ let status = resp.status();
+ if status.as_u16() == 404 {
+ return Ok(None);
+ }
+ if !status.is_success() {
+ let body = resp.text().await.unwrap_or_default();
+ return Err(format!(
+ "status {} from pool status endpoint: {}",
+ status.as_u16(),
+ body.chars().take(120).collect::<String>()
+ ));
+ }
+ resp.json::<Value>()
+ .await
+ .map(Some)
+ .map_err(|e| e.to_string())
+ }
+
+ fn handle_error(&self, state: &mut GateState, now: Instant, error: String) {
+ if state
+ .last_success_at
+ .is_some_and(|last| now.duration_since(last) <= self.stale_after)
+ {
+ debug!(
+ pool = %self.pool_name,
+ worker_id = %self.worker_id,
+ error = %error,
+ "pool-admission: keeping cached decision during stale window"
+ );
+ return;
+ }
+
+ // Keep the default pool available during gateway/status glitches.
+ // Named pools fail closed because their caps are isolation contracts.
+ let fail_open = normalize_pool_name(&self.pool_name) == "default";
+ self.set_admitted(state, fail_open, format!("status_error:{error}"));
+ }
+
+ fn set_admitted(&self, state: &mut GateState, admitted: bool, reason: String) {
+ self.admitted.store(admitted, Ordering::Release);
+ if admitted == state.admitted && reason == state.last_reason {
+ return;
+ }
+ state.admitted = admitted;
+ state.last_reason = reason.clone();
+ info!(
+ pool = %self.pool_name,
+ worker_id = %self.worker_id,
+ machine_profile = %self.machine_profile,
+ reason = %reason,
+ "pool-admission: {}",
+ if admitted { "granted" } else { "paused" }
+ );
+ }
+}
+
+fn normalize_pool_name(name: &str) -> String {
+ let value = name.trim().to_ascii_lowercase();
+ if value.is_empty() || value == "_default" {
+ "default".to_string()
+ } else {
+ value
+ }
+}
+
+fn object_field<'a>(value: &'a Value, key: &str) -> Option<&'a Map<String, Value>> {
+ value.get(key).and_then(Value::as_object)
+}
+
+fn lookup_case_insensitive<'a>(mapping: &'a Map<String, Value>, key: &str) -> Option<&'a Value> {
+ let key_lower = key.to_ascii_lowercase();
+ mapping
+ .iter()
+ .find(|(candidate, _)| candidate.to_ascii_lowercase() == key_lower)
+ .map(|(_, value)| value)
+}
+
+fn cap_as_i64(value: &Value) -> Option<i64> {
+ value
+ .as_i64()
+ .or_else(|| value.as_u64().and_then(|n| i64::try_from(n).ok()))
+ .or_else(|| value.as_str().and_then(|s| s.parse::<i64>().ok()))
+}
+
+fn decide_pool_admission(
+ pool: Option<&Value>,
+ pool_name: &str,
+ worker_id: &str,
+ machine_profile: &str,
+) -> (bool, String) {
+ let Some(pool) = pool else {
+ return (
+ normalize_pool_name(pool_name) == "default",
+ "pool_missing".to_string(),
+ );
+ };
+
+ let Some(spec) = object_field(pool, "spec") else {
+ return (true, "uncapped".to_string());
+ };
+ let Some(caps) = spec.get("gpu_caps").and_then(Value::as_object) else {
+ return (true, "uncapped".to_string());
+ };
+ if caps.is_empty() {
+ return (true, "uncapped".to_string());
+ }
+
+ let cap = if machine_profile.trim().is_empty() {
+ None
+ } else {
+ lookup_case_insensitive(caps, machine_profile)
+ };
+ let Some(cap) = cap else {
+ return (true, "profile_uncapped".to_string());
+ };
+ match cap_as_i64(cap) {
+ Some(n) if n > 0 => {}
+ Some(_) => return (false, "cap_exhausted".to_string()),
+ None => return (false, "malformed_gpu_cap".to_string()),
+ }
+
+ let Some(status) = object_field(pool, "status") else {
+ return (false, "malformed_assigned_workers".to_string());
+ };
+ let Some(assigned) = status.get("assigned_workers").and_then(Value::as_array) else {
+ return (false, "malformed_assigned_workers".to_string());
+ };
+
+ for worker in assigned {
+ if worker
+ .as_object()
+ .and_then(|w| w.get("name"))
+ .and_then(Value::as_str)
+ == Some(worker_id)
+ {
+ return (true, "assigned".to_string());
+ }
+ }
+ (false, "not_assigned".to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ #[test]
+ fn pool_missing_fails_open_only_for_default_pool() {
+ assert_eq!(
+ decide_pool_admission(None, "default", "w1", "l4"),
+ (true, "pool_missing".to_string())
+ );
+ assert_eq!(
+ decide_pool_admission(None, "eval", "w1", "l4"),
+ (false, "pool_missing".to_string())
+ );
+ }
+
+ #[test]
+ fn uncapped_pool_is_admitted() {
+ let pool = json!({"spec": {"gpu_caps": {}}, "status": {"assigned_workers": []}});
+ assert_eq!(
+ decide_pool_admission(Some(&pool), "eval", "w1", "l4"),
+ (true, "uncapped".to_string())
+ );
+ }
+
+ #[test]
+ fn capped_pool_requires_worker_assignment() {
+ let pool = json!({
+ "spec": {"gpu_caps": {"L4": 2}},
+ "status": {"assigned_workers": [{"name": "w1", "url": "http://w1", "gpu": "l4"}]}
+ });
+ assert_eq!(
+ decide_pool_admission(Some(&pool), "eval", "w1", "l4"),
+ (true, "assigned".to_string())
+ );
+ assert_eq!(
+ decide_pool_admission(Some(&pool), "eval", "w2", "l4"),
+ (false, "not_assigned".to_string())
+ );
+ }
+
+ #[test]
+ fn capped_pool_profile_without_cap_is_admitted() {
+ let pool = json!({
+ "spec": {"gpu_caps": {"h100": 1}},
+ "status": {"assigned_workers": []}
+ });
+ assert_eq!(
+ decide_pool_admission(Some(&pool), "eval", "w1", "l4"),
+ (true, "profile_uncapped".to_string())
+ );
+ }
+
+ #[test]
+ fn exhausted_or_malformed_caps_fail_closed() {
+ let exhausted = json!({
+ "spec": {"gpu_caps": {"l4": 0}},
+ "status": {"assigned_workers": [{"name": "w1"}]}
+ });
+ assert_eq!(
+ decide_pool_admission(Some(&exhausted), "eval", "w1", "l4"),
+ (false, "cap_exhausted".to_string())
+ );
+
+ let malformed = json!({
+ "spec": {"gpu_caps": {"l4": "many"}},
+ "status": {"assigned_workers": [{"name": "w1"}]}
+ });
+ assert_eq!(
+ decide_pool_admission(Some(&malformed), "eval", "w1", "l4"),
+ (false, "malformed_gpu_cap".to_string())
+ );
+ }
+
+ #[test]
+ fn malformed_assignment_list_fails_closed_for_capped_profile() {
+ let pool = json!({
+ "spec": {"gpu_caps": {"l4": 1}},
+ "status": {"assigned_workers": {"name": "w1"}}
+ });
+ assert_eq!(
+ decide_pool_admission(Some(&pool), "eval", "w1", "l4"),
+ (false, "malformed_assigned_workers".to_string())
+ );
+ }
+}
diff --git a/packages/sie_server_sidecar/src/prep/error.rs b/packages/sie_server_sidecar/src/prep/error.rs
new file mode 100644
index 000000000..f9218eba7
--- /dev/null
+++ b/packages/sie_server_sidecar/src/prep/error.rs
@@ -0,0 +1,39 @@
+//! Adapter-local error taxonomy.
+//!
+//! Mirrors the variant set of `sie_server_sidecar::backend::BackendError`
+//! at the wire level so we can map straight onto the same per-method
+//! response semantics in the IPC server (P2). The two enums are
+//! deliberately separate types: the sidecar's `BackendError` carries
+//! backend-selection fall-through semantics (see `is_retryable`) that don't
+//! apply on the adapter side, and we don't want to drag the
+//! `async_trait` `InferenceBackend` plumbing into this crate just to
+//! reuse one enum.
+//!
+//! Variant semantics:
+//! * [`BackendError::Transient`] — transport-level failure (file
+//! I/O, GPU OOM that may resolve with a retry). The IPC server
+//! surfaces this as a non-`ok` `ResponseEnvelope`; the sidecar
+//! NAKs the JetStream group with the base delay.
+//! * [`BackendError::Inference`] — batch-level forward-pass failure.
+//! Reserved; new code paths should fan errors out per-item inside
+//! `Ok(BatchOutcome)` instead.
+//! * [`BackendError::UnsupportedModel`] — model_id not in the engine
+//! registry, or wrong op for an encoder-only engine. The sidecar
+//! uses this as the backend-selection fall-through trigger.
+//! * [`BackendError::Draining`] — adapter is shutting down. NAK
+//! fast.
+
+#[derive(Debug, thiserror::Error)]
+pub enum BackendError {
+ #[error("transient: {0}")]
+ Transient(String),
+
+ #[error("inference: {0}")]
+ Inference(String),
+
+ #[error("unsupported model: {0}")]
+ UnsupportedModel(String),
+
+ #[error("draining")]
+ Draining,
+}
diff --git a/packages/sie_server_sidecar/src/prep/mod.rs b/packages/sie_server_sidecar/src/prep/mod.rs
new file mode 100644
index 000000000..d403f495c
--- /dev/null
+++ b/packages/sie_server_sidecar/src/prep/mod.rs
@@ -0,0 +1,13 @@
+//! GPU-independent inference preparation for the SIE worker sidecar.
+//!
+//! This module owns the prep/protocol helpers that previously lived in a
+//! standalone prep crate: text-template application, numpy-sentinel
+//! encoding, typed output payload builders, and the sidecar-side error
+//! taxonomy. Keeping them in-tree avoids a second local Rust package while
+//! preserving the same wire behavior.
+
+pub mod error;
+pub mod numpy_sentinel;
+pub mod outcome;
+pub mod output_types;
+pub mod text_prep;
diff --git a/packages/sie_server_sidecar/src/prep/numpy_sentinel.rs b/packages/sie_server_sidecar/src/prep/numpy_sentinel.rs
new file mode 100644
index 000000000..71bc4cdd1
--- /dev/null
+++ b/packages/sie_server_sidecar/src/prep/numpy_sentinel.rs
@@ -0,0 +1,216 @@
+//! Build msgpack bytes that match `msgpack_numpy`'s on-wire format.
+//!
+//! NOTE: This is the adapter-side copy. The sidecar carries an
+//! identical implementation at
+//! `packages/sie_server_sidecar/src/output/numpy_sentinel.rs`; both
+//! must produce byte-for-byte identical output because the gateway
+//! / SDK decoders are oblivious to which side framed the bytes.
+//!
+//! The Python queue executor serializes a successful encode outcome
+//! with `msgpack.packb(output, use_bin_type=True)` after
+//! `msgpack_numpy.patch()` has installed a `default` encoder hook.
+//! That hook rewrites any `numpy.ndarray` into a 5-key map — the
+//! so-called **numpy sentinel**:
+//!
+//! ```text
+//! {
+//! b"nd": true,
+//! b"type": "<f4", // ndarray.dtype.str
+//! b"kind": b"", // ndarray.dtype.kind for structured dtypes
+//! b"shape": [d0, d1, ...], // ndarray.shape
+//! b"data": <raw bytes>, // ndarray.tobytes() (little-endian, C-order)
+//! }
+//! ```
+//!
+//! All five keys are packed as **bin8** (not str) because
+//! `msgpack_numpy.encode` uses Python `bytes` literals. The SDK's
+//! decoder relies on this exact shape (see `_shared.py::parse_encode_results`
+//! and gateway `convert_numpy_for_json::is_numpy_sentinel`), so we have
+//! to match it byte-for-byte.
+//!
+//! Keeping this in one place also makes it trivial to unit-test the
+//! output against a golden blob captured from Python.
+
+use std::io::Write;
+
+use rmp::encode::{write_array_len, write_bin, write_bool, write_map_len, write_str, write_uint};
+
+/// Internal error type for sentinel writers. All writes go to a
+/// `Vec<u8>`, so I/O can't fail in practice — the error exists so
+/// callers can propagate without unwrapping.
+#[derive(Debug, thiserror::Error)]
+pub enum SentinelError {
+ #[error("msgpack write: {0}")]
+ MsgpackWrite(String),
+ #[error("invalid matrix shape: rows*cols ({expected}) != data.len() ({actual})")]
+ InvalidMatrixShape { expected: usize, actual: usize },
+}
+
+/// Small helper so the writers below stay readable: stringify any
+/// error we get from `rmp::encode` and wrap it as `SentinelError`.
+fn wrap_err<E: std::fmt::Display>(e: E) -> SentinelError {
+ SentinelError::MsgpackWrite(e.to_string())
+}
+
+/// msgpack-numpy dtype string for a contiguous little-endian float32
+/// array. This is `numpy.dtype("float32").str` on a little-endian
+/// host, which is what the SDK expects.
+pub const DTYPE_F32: &str = "<f4";
+
+/// msgpack-numpy dtype string for int32 little-endian, used for
+/// sparse indices.
+pub const DTYPE_I32: &str = "<i4";
+
+/// Write the 5-key numpy sentinel map into `buf`, with pre-encoded
+/// raw bytes and explicit shape. The caller supplies:
+///
+/// * `dtype_str` — the `"<f4"`, `"<i4"`, etc. code. Must match the
+/// byte layout of `data`.
+/// * `shape` — dimensions in C order (`[rows, cols]` for 2D).
+/// * `data` — raw little-endian bytes, `prod(shape) * itemsize`.
+pub fn write_numpy_sentinel(
+ buf: &mut Vec<u8>,
+ dtype_str: &str,
+ shape: &[u32],
+ data: &[u8],
+) -> Result<(), SentinelError> {
+ // 5-key map: nd, type, kind, shape, data.
+ write_map_len(buf, 5).map_err(wrap_err)?;
+
+ write_bin(buf, b"nd").map_err(wrap_err)?;
+ write_bool(buf, true).map_err(wrap_err)?;
+
+ write_bin(buf, b"type").map_err(wrap_err)?;
+ write_str(buf, dtype_str).map_err(wrap_err)?;
+
+ write_bin(buf, b"kind").map_err(wrap_err)?;
+ write_bin(buf, b"").map_err(wrap_err)?;
+
+ write_bin(buf, b"shape").map_err(wrap_err)?;
+ write_array_len(buf, shape.len() as u32).map_err(wrap_err)?;
+ for dim in shape {
+ // Shapes are always non-negative. Python packs these as the
+ // smallest positive int — msgpack-numpy does the equivalent
+ // of `msgpack.packb(int)`, which for `3` is `0x03` (fixint).
+ // `write_uint` picks the shortest encoding (fixint for
+ // values ≤127) to stay byte-identical with Python.
+ write_uint(buf, u64::from(*dim)).map_err(wrap_err)?;
+ }
+
+ write_bin(buf, b"data").map_err(wrap_err)?;
+ write_bin(buf, data).map_err(wrap_err)?;
+
+ Ok(())
+}
+
+/// Convenience: write a 1-D float32 array as a numpy sentinel.
+pub fn write_f32_vector(buf: &mut Vec<u8>, vec: &[f32]) -> Result<(), SentinelError> {
+ // Flatten f32 slice into little-endian bytes. The host is
+ // little-endian for every platform we ship on, so a bytemuck
+ // cast would be zero-copy — but we keep it explicit and portable.
+ let mut data = Vec::with_capacity(vec.len() * 4);
+ for &f in vec {
+ data.write_all(&f.to_le_bytes()).map_err(wrap_err)?;
+ }
+ write_numpy_sentinel(buf, DTYPE_F32, &[vec.len() as u32], &data)
+}
+
+/// Convenience: write a 1-D int32 array as a numpy sentinel.
+pub fn write_i32_vector(buf: &mut Vec<u8>, vec: &[i32]) -> Result<(), SentinelError> {
+ let mut data = Vec::with_capacity(vec.len() * 4);
+ for &i in vec {
+ data.write_all(&i.to_le_bytes()).map_err(wrap_err)?;
+ }
+ write_numpy_sentinel(buf, DTYPE_I32, &[vec.len() as u32], &data)
+}
+
+/// Convenience: write a 2-D float32 matrix `[rows, cols]` as a numpy
+/// sentinel. `data` must be flattened in C (row-major) order —
+/// exactly what `np.ndarray.tobytes()` emits for a contiguous array.
+///
+pub fn write_f32_matrix_2d(
+ buf: &mut Vec<u8>,
+ data: &[f32],
+ rows: u32,
+ cols: u32,
+) -> Result<(), SentinelError> {
+ let expected = (rows as usize).saturating_mul(cols as usize);
+ if data.len() != expected {
+ return Err(SentinelError::InvalidMatrixShape {
+ expected,
+ actual: data.len(),
+ });
+ }
+ let mut bytes = Vec::with_capacity(data.len() * 4);
+ for &f in data {
+ bytes.write_all(&f.to_le_bytes()).map_err(wrap_err)?;
+ }
+ write_numpy_sentinel(buf, DTYPE_F32, &[rows, cols], &bytes)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Golden: `msgpack.packb(np.array([1.0, 2.0, 3.0], dtype=np.float32))`
+ /// after `msgpack_numpy.patch()`. Captured from CPython
+ /// (see docs: 53 bytes).
+ const GOLDEN_F32_123: &[u8] = &[
+ 0x85, 0xc4, 0x02, 0x6e, 0x64, 0xc3, 0xc4, 0x04, 0x74, 0x79, 0x70, 0x65, 0xa3, 0x3c, 0x66,
+ 0x34, 0xc4, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0xc4, 0x00, 0xc4, 0x05, 0x73, 0x68, 0x61, 0x70,
+ 0x65, 0x91, 0x03, 0xc4, 0x04, 0x64, 0x61, 0x74, 0x61, 0xc4, 0x0c, 0x00, 0x00, 0x80, 0x3f,
+ 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40,
+ ];
+
+ /// Golden: `msgpack.packb(np.array([5, 17, 99], dtype=np.int32))`.
+ const GOLDEN_I32: &[u8] = &[
+ 0x85, 0xc4, 0x02, 0x6e, 0x64, 0xc3, 0xc4, 0x04, 0x74, 0x79, 0x70, 0x65, 0xa3, 0x3c, 0x69,
+ 0x34, 0xc4, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0xc4, 0x00, 0xc4, 0x05, 0x73, 0x68, 0x61, 0x70,
+ 0x65, 0x91, 0x03, 0xc4, 0x04, 0x64, 0x61, 0x74, 0x61, 0xc4, 0x0c, 0x05, 0x00, 0x00, 0x00,
+ 0x11, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00,
+ ];
+
+ #[test]
+ fn f32_vector_matches_python_golden() {
+ let mut buf = Vec::new();
+ write_f32_vector(&mut buf, &[1.0, 2.0, 3.0]).unwrap();
+ assert_eq!(
+ buf, GOLDEN_F32_123,
+ "f32 vector sentinel doesn't match msgpack-numpy wire format"
+ );
+ }
+
+ #[test]
+ fn i32_vector_matches_python_golden() {
+ let mut buf = Vec::new();
+ write_i32_vector(&mut buf, &[5, 17, 99]).unwrap();
+ assert_eq!(
+ buf, GOLDEN_I32,
+ "i32 vector sentinel doesn't match msgpack-numpy wire format"
+ );
+ }
+
+ #[test]
+ fn empty_f32_vector_roundtrips() {
+ let mut buf = Vec::new();
+ write_f32_vector(&mut buf, &[]).unwrap();
+ // An empty vector should still be a 5-key map, shape [0], data zero bytes.
+ assert_eq!(&buf[0..1], &[0x85], "should be map-of-5");
+ // The last 3 bytes: c4 00 (empty bin data)
+ assert_eq!(&buf[buf.len() - 2..], &[0xc4, 0x00]);
+ }
+
+ #[test]
+ fn f32_matrix_rejects_shape_mismatch() {
+ let mut buf = Vec::new();
+ let err = write_f32_matrix_2d(&mut buf, &[1.0, 2.0, 3.0], 2, 2).unwrap_err();
+ assert!(matches!(
+ err,
+ SentinelError::InvalidMatrixShape {
+ expected: 4,
+ actual: 3
+ }
+ ));
+ assert!(buf.is_empty());
+ }
+}
diff --git a/packages/sie_server_sidecar/src/prep/outcome.rs b/packages/sie_server_sidecar/src/prep/outcome.rs
new file mode 100644
index 000000000..b15a41b39
--- /dev/null
+++ b/packages/sie_server_sidecar/src/prep/outcome.rs
@@ -0,0 +1,181 @@
+//! Per-item [`ItemOutcome`] helpers shared by every native backend.
+//!
+//! A native dense encoder ends up producing the same two payload
+//! shapes: a successful dense-vector outcome and a failure outcome
+//! with `PublishErrorAndAck` + an error code. Keep the boilerplate
+//! here so the engine code in each architecture stays focused on the
+//! forward pass.
+
+use rmp::encode::{write_map_len, write_str};
+
+use super::numpy_sentinel::{write_f32_vector, SentinelError};
+use crate::ipc_types::{Disposition, EncodeBatchItem, ItemOutcome, ScoreBatchItem};
+
+/// Routing handles we stash per-item *before* moving `items` into a
+/// blocking task, so the failure path can synthesise outcomes
+/// without cloning the full batch payload.
+pub struct EncodeItemHandle {
+ pub work_item_id: String,
+ pub request_id: String,
+ pub item_index: u32,
+}
+
+impl EncodeItemHandle {
+ pub fn from_encode(bi: &EncodeBatchItem) -> Self {
+ Self {
+ work_item_id: bi.work_item_id.clone(),
+ request_id: bi.request_id.clone(),
+ item_index: bi.item_index,
+ }
+ }
+
+ /// Convert the handle into a `PublishErrorAndAck` outcome.
+ /// Used in the blocking-task panic / error fan-out paths where
+ /// we no longer have the original `EncodeBatchItem`.
+ pub fn into_error(self, code: &'static str, message: String) -> ItemOutcome {
+ ItemOutcome {
+ work_item_id: self.work_item_id,
+ request_id: self.request_id,
+ item_index: self.item_index,
+ disposition: Disposition::PublishErrorAndAck,
+ result_msgpack: Vec::new(),
+ nak_delay_ms: None,
+ error: Some(message),
+ error_code: Some(code.into()),
+ inference_ms: None,
+ tokenization_ms: None,
+ postprocessing_ms: None,
+ raw_output: None,
+ }
+ }
+}
+
+/// Build an `PublishErrorAndAck` outcome from a live
+/// [`EncodeBatchItem`]. Used inside the engine when we still hold
+/// the original item and want to emit a per-item error alongside
+/// other successful results.
+pub fn encode_error_outcome(item: &EncodeBatchItem, code: &str, message: String) -> ItemOutcome {
+ ItemOutcome {
+ work_item_id: item.work_item_id.clone(),
+ request_id: item.request_id.clone(),
+ item_index: item.item_index,
+ disposition: Disposition::PublishErrorAndAck,
+ result_msgpack: Vec::new(),
+ nak_delay_ms: None,
+ error: Some(message),
+ error_code: Some(code.into()),
+ inference_ms: None,
+ tokenization_ms: None,
+ postprocessing_ms: None,
+ raw_output: None,
+ }
+}
+
+/// Same as [`encode_error_outcome`] but for score-batch items.
+pub fn encode_error_outcome_score(
+ item: &ScoreBatchItem,
+ code: &str,
+ message: String,
+) -> ItemOutcome {
+ ItemOutcome {
+ work_item_id: item.work_item_id.clone(),
+ request_id: item.request_id.clone(),
+ item_index: item.item_index,
+ disposition: Disposition::PublishErrorAndAck,
+ result_msgpack: Vec::new(),
+ nak_delay_ms: None,
+ error: Some(message),
+ error_code: Some(code.into()),
+ inference_ms: None,
+ tokenization_ms: None,
+ postprocessing_ms: None,
+ raw_output: None,
+ }
+}
+
+/// Build the per-item `result_msgpack` bytes for a dense-only
+/// encoder outcome, matching the Python queue executor's wire shape
+/// verbatim:
+///
+/// ```text
+/// {
+/// "dense": {
+/// "dims": <hidden>,
+/// "dtype": "float32",
+/// "values": <numpy_sentinel for [hidden] f32>,
+/// },
+/// }
+/// ```
+///
+/// Top-level keys are packed as msgpack **str** (Python source
+/// strings). The `values` entry uses the [`numpy_sentinel`][super::numpy_sentinel]
+/// map form so the SDK's `msgpack_numpy.patch()`ed decoder round-
+/// trips the array back into a real `numpy.ndarray`, exactly as it
+/// does for the HTTP/queue Python paths.
+///
+/// If you later extend this to emit sparse / multivector, add the
+/// corresponding sibling keys (`"sparse"`, `"multivector"`) before
+/// the final map-len update; see `_wrap_encode_output` in
+/// `sie_server/queue_executor.py` for the reference shape.
+pub fn build_dense_payload(vec: &[f32], hidden: usize) -> Result<Vec<u8>, SentinelError> {
+ if vec.len() != hidden {
+ return Err(SentinelError::MsgpackWrite(format!(
+ "dense dims mismatch: hidden={} vec_len={}",
+ hidden,
+ vec.len()
+ )));
+ }
+ let mut buf = Vec::with_capacity(32 + vec.len() * 4);
+
+ // Top-level map: {"dense": ...}.
+ write_map_len(&mut buf, 1).map_err(|e| SentinelError::MsgpackWrite(e.to_string()))?;
+ write_str(&mut buf, "dense").map_err(|e| SentinelError::MsgpackWrite(e.to_string()))?;
+
+ // Inner "dense" envelope: {"dims", "dtype", "values"}.
+ write_map_len(&mut buf, 3).map_err(|e| SentinelError::MsgpackWrite(e.to_string()))?;
+ write_str(&mut buf, "dims").map_err(|e| SentinelError::MsgpackWrite(e.to_string()))?;
+ rmp::encode::write_uint(&mut buf, hidden as u64)
+ .map_err(|e| SentinelError::MsgpackWrite(e.to_string()))?;
+ write_str(&mut buf, "dtype").map_err(|e| SentinelError::MsgpackWrite(e.to_string()))?;
+ write_str(&mut buf, "float32").map_err(|e| SentinelError::MsgpackWrite(e.to_string()))?;
+ write_str(&mut buf, "values").map_err(|e| SentinelError::MsgpackWrite(e.to_string()))?;
+ write_f32_vector(&mut buf, vec)?;
+
+ Ok(buf)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Golden: Python side runs
+ /// `msgpack.packb({"dense": {"dims": 3, "dtype": "float32",
+ /// "values": np.array([1,2,3], dtype=f32)}},
+ /// use_bin_type=True)`
+ /// after `msgpack_numpy.patch()`. Captured from CPython (88 bytes).
+ /// If you change the dense envelope, regenerate this with:
+ /// `msgpack.packb(...).hex()` and paste the new hex here.
+ const GOLDEN_DENSE_123: &[u8] = &[
+ 0x81, 0xa5, 0x64, 0x65, 0x6e, 0x73, 0x65, 0x83, 0xa4, 0x64, 0x69, 0x6d, 0x73, 0x03, 0xa5,
+ 0x64, 0x74, 0x79, 0x70, 0x65, 0xa7, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x33, 0x32, 0xa6, 0x76,
+ 0x61, 0x6c, 0x75, 0x65, 0x73, 0x85, 0xc4, 0x02, 0x6e, 0x64, 0xc3, 0xc4, 0x04, 0x74, 0x79,
+ 0x70, 0x65, 0xa3, 0x3c, 0x66, 0x34, 0xc4, 0x04, 0x6b, 0x69, 0x6e, 0x64, 0xc4, 0x00, 0xc4,
+ 0x05, 0x73, 0x68, 0x61, 0x70, 0x65, 0x91, 0x03, 0xc4, 0x04, 0x64, 0x61, 0x74, 0x61, 0xc4,
+ 0x0c, 0x00, 0x00, 0x80, 0x3f, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x40,
+ ];
+
+ #[test]
+ fn build_dense_payload_matches_python_wire_format() {
+ let buf = build_dense_payload(&[1.0, 2.0, 3.0], 3).unwrap();
+ assert_eq!(
+ buf, GOLDEN_DENSE_123,
+ "dense payload must be byte-identical to msgpack-numpy Python output"
+ );
+ }
+
+ #[test]
+ fn build_dense_payload_rejects_dim_mismatch() {
+ let err = build_dense_payload(&[1.0, 2.0], 3).unwrap_err();
+ assert!(err.to_string().contains("dense dims mismatch"));
+ }
+}
diff --git a/packages/sie_server_sidecar/src/prep/output_types.rs b/packages/sie_server_sidecar/src/prep/output_types.rs
new file mode 100644
index 000000000..c330f4666
--- /dev/null
+++ b/packages/sie_server_sidecar/src/prep/output_types.rs
@@ -0,0 +1,69 @@
+//! Shared `output_types` validation for every native encoder
+//! backend.
+//!
+//! A dense-only backend (i.e. anything that isn't hybrid / ColBERT)
+//! must explicitly reject requests for `"sparse"`, `"multivector"`,
+//! or any unknown type — silently returning dense for those would
+//! corrupt downstream consumers that thought they were getting
+//! sparse / ColBERT vectors.
+
+/// Return the first unsupported output type in `requested`, or
+/// `None` if every requested type is something this dense-only
+/// backend can produce.
+///
+/// Rules:
+/// * `None` → client didn't specify → default to dense → accepted.
+/// * `Some(&[])` → client explicitly asked for no outputs →
+/// **rejected** (ambiguous — probably a client bug).
+/// * `Some([..."dense"...])` with only `dense` (case-insensitive) →
+/// accepted.
+/// * Anything else (`sparse`, `multivector`, unknown) → rejected,
+/// returning that offending value for the error message.
+pub fn first_unsupported_output_type(requested: Option<&[String]>) -> Option<String> {
+ match requested {
+ None => None,
+ Some([]) => Some("<empty list>".to_string()),
+ Some(list) => list
+ .iter()
+ .find(|t| !t.eq_ignore_ascii_case("dense"))
+ .cloned(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn accepts_none_and_dense_only() {
+ assert_eq!(first_unsupported_output_type(None), None);
+ assert_eq!(
+ first_unsupported_output_type(Some(&["dense".to_string()])),
+ None
+ );
+ assert_eq!(
+ first_unsupported_output_type(Some(&["DENSE".to_string()])),
+ None
+ );
+ }
+
+ #[test]
+ fn rejects_empty_list_and_other_types() {
+ assert_eq!(
+ first_unsupported_output_type(Some(&[])),
+ Some("<empty list>".to_string())
+ );
+ assert_eq!(
+ first_unsupported_output_type(Some(&["sparse".to_string()])),
+ Some("sparse".to_string())
+ );
+ assert_eq!(
+ first_unsupported_output_type(Some(&["dense".to_string(), "multivector".to_string()])),
+ Some("multivector".to_string())
+ );
+ assert_eq!(
+ first_unsupported_output_type(Some(&["garbage".to_string()])),
+ Some("garbage".to_string())
+ );
+ }
+}
diff --git a/packages/sie_server_sidecar/src/prep/text_prep.rs b/packages/sie_server_sidecar/src/prep/text_prep.rs
new file mode 100644
index 000000000..bb83e2483
--- /dev/null
+++ b/packages/sie_server_sidecar/src/prep/text_prep.rs
@@ -0,0 +1,257 @@
+//! Apply instruction / is_query / query_template / doc_template
+//! to raw item text before tokenisation.
+//!
+//! This matches Python's `sie_server.adapters._utils.extract_texts`
+//! so a future native encoder sees the exact same tokens the Python
+//! path sees. Without this, asymmetric-retrieval models (`BAAI/bge-*`,
+//! `intfloat/e5-*`, `nomic-embed-*`, `gte-Qwen2-*-instruct`) produce
+//! the wrong embedding when the caller sets `is_query=true` or passes
+//! `instruction` — the embedding silently scores against the wrong
+//! subspace and recall collapses.
+//!
+//! # Precedence (identical to Python)
+//!
+//! 1. **Template path.** If the matching template is non-empty
+//! (`query_template` when `is_query`, `doc_template` otherwise),
+//! run `template.format(text=..., instruction=...)`. Python's
+//! `str.format` here supports `{text}` and `{instruction}`
+//! placeholders (plus `{instruction or ""}` at call site). Any
+//! other braces in the template are treated as literal braces.
+//! 2. **Bare instruction.** No template, but `instruction` is set:
+//! the result is `"{instruction} {text}"` (single space join).
+//! 3. **Passthrough.** Neither template nor instruction: the text
+//! is used verbatim.
+//!
+//! Templates are read from `item.options` (per-request override) and
+//! fall back to backend-level defaults supplied by the caller.
+
+/// Resolved text-prep knobs for a single [`crate::ipc_types::EncodeBatchItem`]. Kept
+/// as a struct so the per-item call sites in `EncoderEngine` stay
+/// short.
+pub struct TextPrep<'a> {
+ /// Optional instruction string applied to the text (retrieval
+ /// models like BGE / E5 / GTE treat this as a prompt prefix).
+ pub instruction: Option<&'a str>,
+ /// `true` if the caller marked this item as a search query
+ /// (affects which template is picked).
+ pub is_query: bool,
+ /// Query-side template (Python `{text}` / `{instruction}` substitution).
+ pub query_template: Option<&'a str>,
+ /// Document-side template.
+ pub doc_template: Option<&'a str>,
+}
+
+impl TextPrep<'_> {
+ /// Apply the template / instruction rules. Returns the
+ /// transformed string, or borrows the input if no changes are
+ /// needed.
+ pub fn apply(&self, text: &str) -> String {
+ let template = if self.is_query {
+ self.query_template
+ } else {
+ self.doc_template
+ };
+ if let Some(tpl) = template.filter(|t| !t.is_empty()) {
+ return format_template(tpl, text, self.instruction.unwrap_or(""));
+ }
+ if let Some(instr) = self.instruction.filter(|i| !i.is_empty()) {
+ return format!("{instr} {text}");
+ }
+ text.to_string()
+ }
+}
+
+/// Cheap Python-`str.format`-workalike for the two known
+/// placeholders (`{text}` and `{instruction}`). We avoid pulling in
+/// a full templating crate because the Python side only ever uses
+/// those two names — everything else is treated as literal text.
+///
+/// `{{` and `}}` are literal `{` / `}` (matching Python behavior).
+fn format_template(tpl: &str, text: &str, instruction: &str) -> String {
+ let mut out = String::with_capacity(tpl.len() + text.len() + instruction.len());
+ let mut chars = tpl.chars().peekable();
+ while let Some(c) = chars.next() {
+ match c {
+ '{' => {
+ if chars.peek() == Some(&'{') {
+ out.push('{');
+ chars.next();
+ continue;
+ }
+ // Collect placeholder name until '}'.
+ let mut name = String::new();
+ let mut closed = false;
+ for next in chars.by_ref() {
+ if next == '}' {
+ closed = true;
+ break;
+ }
+ name.push(next);
+ }
+ if !closed {
+ // Unterminated placeholder — emit as-is, Python
+ // would raise here but we prefer to degrade
+ // gracefully at the edge.
+ out.push('{');
+ out.push_str(&name);
+ continue;
+ }
+ match name.as_str() {
+ "text" => out.push_str(text),
+ "instruction" => out.push_str(instruction),
+ other => {
+ // Unknown placeholder — preserve literal.
+ out.push('{');
+ out.push_str(other);
+ out.push('}');
+ }
+ }
+ }
+ '}' => {
+ if chars.peek() == Some(&'}') {
+ out.push('}');
+ chars.next();
+ } else {
+ // Stray '}' — emit literally.
+ out.push('}');
+ }
+ }
+ _ => out.push(c),
+ }
+ }
+ out
+}
+
+/// Pull `query_template` / `doc_template` overrides out of an item's
+/// `options` field. Mirrors Python's
+/// `opts.get("query_template", default)` path.
+pub fn extract_templates_from_options<'a>(
+ options: Option<&'a serde_json::Value>,
+ default_query: Option<&'a str>,
+ default_doc: Option<&'a str>,
+) -> (Option<&'a str>, Option<&'a str>) {
+ let Some(obj) = options.and_then(|v| v.as_object()) else {
+ return (default_query, default_doc);
+ };
+ let query_template = obj
+ .get("query_template")
+ .and_then(|v| v.as_str())
+ .or(default_query);
+ let doc_template = obj
+ .get("doc_template")
+ .and_then(|v| v.as_str())
+ .or(default_doc);
+ (query_template, doc_template)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn passthrough_when_neither_template_nor_instruction() {
+ let prep = TextPrep {
+ instruction: None,
+ is_query: false,
+ query_template: None,
+ doc_template: None,
+ };
+ assert_eq!(prep.apply("hello"), "hello");
+ }
+
+ #[test]
+ fn bare_instruction_when_no_template() {
+ let prep = TextPrep {
+ instruction: Some("Represent this:"),
+ is_query: true,
+ query_template: None,
+ doc_template: None,
+ };
+ assert_eq!(prep.apply("hello world"), "Represent this: hello world");
+ }
+
+ #[test]
+ fn query_template_selected_when_is_query() {
+ let prep = TextPrep {
+ instruction: None,
+ is_query: true,
+ query_template: Some("query: {text}"),
+ doc_template: Some("passage: {text}"),
+ };
+ assert_eq!(prep.apply("cats"), "query: cats");
+ }
+
+ #[test]
+ fn doc_template_selected_when_not_query() {
+ let prep = TextPrep {
+ instruction: None,
+ is_query: false,
+ query_template: Some("query: {text}"),
+ doc_template: Some("passage: {text}"),
+ };
+ assert_eq!(prep.apply("cats"), "passage: cats");
+ }
+
+ #[test]
+ fn instruction_substituted_into_template() {
+ let prep = TextPrep {
+ instruction: Some("retrieve relevant passages"),
+ is_query: true,
+ query_template: Some("Instruct: {instruction}\nQuery: {text}"),
+ doc_template: None,
+ };
+ assert_eq!(
+ prep.apply("what is love"),
+ "Instruct: retrieve relevant passages\nQuery: what is love"
+ );
+ }
+
+ #[test]
+ fn empty_template_falls_back_to_bare_instruction() {
+ let prep = TextPrep {
+ instruction: Some("Represent this"),
+ is_query: true,
+ query_template: Some(""),
+ doc_template: None,
+ };
+ assert_eq!(prep.apply("hello"), "Represent this hello");
+ }
+
+ #[test]
+ fn escaped_braces_are_literal() {
+ let prep = TextPrep {
+ instruction: None,
+ is_query: true,
+ query_template: Some("{{literal}} {text}"),
+ doc_template: None,
+ };
+ assert_eq!(prep.apply("x"), "{literal} x");
+ }
+
+ #[test]
+ fn unknown_placeholder_is_preserved() {
+ let prep = TextPrep {
+ instruction: None,
+ is_query: true,
+ query_template: Some("{foo}:{text}"),
+ doc_template: None,
+ };
+ assert_eq!(prep.apply("x"), "{foo}:x");
+ }
+
+ #[test]
+ fn extract_templates_from_options_falls_back() {
+ let opts = serde_json::json!({"query_template": "q: {text}"});
+ let (q, d) = extract_templates_from_options(Some(&opts), None, Some("passage: {text}"));
+ assert_eq!(q, Some("q: {text}"));
+ assert_eq!(d, Some("passage: {text}"));
+ }
+
+ #[test]
+ fn extract_templates_returns_defaults_when_options_missing() {
+ let (q, d) =
+ extract_templates_from_options(None, Some("q: {text}"), Some("passage: {text}"));
+ assert_eq!(q, Some("q: {text}"));
+ assert_eq!(d, Some("passage: {text}"));
+ }
+}
diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rs
new file mode 100644
index 000000000..b4712d800
--- /dev/null
+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs
@@ -0,0 +1,1019 @@
+//! IPC wire types — these MUST stay in lockstep with:
+//!
+//! 1. `packages/sie_server_sidecar/src/ipc_types.rs` (the **sidecar** —
+//! consumer of this adapter's responses).
+//! 2. `packages/sie_server/src/sie_server/ipc_types.py` (the **Python
+//! adapter** — peer adapter speaking the same wire surface).
+//!
+//! All three are deliberately duplicated rather than extracted to a
+//! shared Python/Rust package: adapters are standalone deliverables, and
+//! we want adapter authors to vendor the
+//! protocol like any other API client. CI checks the three copies are
+//! field-compatible (see `tools/ci/check_ipc_types_parity.py`).
+//!
+//! Wire format: `[4-byte BE length][msgpack body]`, where `body` is a
+//! msgpack **map** encoding `RequestEnvelope` / `ResponseEnvelope`.
+//! `rmp_serde::to_vec_named` + `serde(default)` for forward-compat
+//! field absorption.
+
+use serde::{Deserialize, Serialize};
+
+pub const IPC_VERSION: u32 = 1;
+
+pub const METHOD_PING: &str = "Ping";
+pub const METHOD_ENSURE_MODEL_READY: &str = "EnsureModelReady";
+pub const METHOD_PROCESS_ENCODE_BATCH: &str = "ProcessEncodeBatch";
+pub const METHOD_PROCESS_SCORE_BATCH: &str = "ProcessScoreBatch";
+pub const METHOD_PROCESS_EXTRACT_BATCH: &str = "ProcessExtractBatch";
+pub const METHOD_PROCESS_GENERATE: &str = "ProcessGenerate";
+pub const METHOD_WORKER_CAPABILITIES: &str = "WorkerCapabilities";
+pub const METHOD_SIGNAL_GENERATE_CANCEL: &str = "SignalGenerateCancel";
+/// RPC that accepts a whole pre-formed batch (mixed op kinds illegal —
+/// one `RunBatchRequest` is a single op) and returns today's
+/// [`BatchOutcome`] unchanged. Carries every batch emitted by the
+/// Rust-side scheduler; per-op Process* RPCs stay in the wire contract
+/// for backends that don't implement `run_batch` and for unit tests
+/// that don't wire a scheduler.
+pub const METHOD_RUN_BATCH: &str = "RunBatch";
+pub const METHOD_APPLY_MODEL_CONFIG: &str = "ApplyModelConfig";
+pub const METHOD_DRAIN: &str = "Drain";
+
+// -----------------------------------------------------------------------------
+// Envelope
+// -----------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize)]
+pub struct RequestEnvelope<'a, B: Serialize> {
+ pub version: u32,
+ pub method: &'a str,
+ pub request_id: String,
+ pub body: B,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ResponseEnvelope<B> {
+ pub version: u32,
+ pub request_id: String,
+ pub ok: bool,
+ #[serde(default = "none_option")]
+ pub body: Option<B>,
+ #[serde(default)]
+ pub error: Option<String>,
+}
+
+fn none_option<T>() -> Option<T> {
+ None
+}
+
+/// Deserialize a msgpack field that is EITHER a byte array OR `nil`. Used
+/// for `ItemOutcome::result_msgpack`, which Python types as `bytes | None`;
+/// `msgspec` / `msgpack.packb` happily emits `nil` when the field is
+/// `None`, and `serde_bytes` alone rejects that with "invalid type: unit
+/// value, expected byte array", sinking the whole `BatchOutcome` into a
+/// transport-level decode error and triggering a batch NAK.
+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)
+}
+
+// -----------------------------------------------------------------------------
+// Ping
+// -----------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PingRequest {
+ pub timestamp_ms: f64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PingResponse {
+ #[serde(default)]
+ pub timestamp_ms: f64,
+ #[serde(default)]
+ pub worker_id: String,
+ #[serde(default)]
+ pub bundle_config_hash: String,
+}
+
+// -----------------------------------------------------------------------------
+// EnsureModelReady
+// -----------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EnsureModelReadyRequest {
+ pub model_id: String,
+}
+
+/// Readiness state reported by the Python executor.
+/// Wire format is a plain string (see Python `ReadinessState` Literal).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ReadinessState {
+ Ready,
+ LoadingStarted,
+ LoadingInProgress,
+ RetryLater,
+}
+
+/// Model descriptor carried on the `EnsureModelReady` handshake.
+///
+/// Replaces legacy per-model env lists with a per-model handshake:
+/// the adapter declares its tokeniser path / id / max-seq-len / output
+/// types / `RunBatch` capability on first ready, and the sidecar caches
+/// the descriptor for Rust-side tokenisation and output shaping. Every
+/// field is optional / defaulted because capabilities are model-dependent;
+/// a missing descriptor means "no Rust-side tokenisation for this model".
+///
+/// See `packages/sie_server_sidecar/docs/architecture-guide.md`
+/// for the contract.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct ModelDescriptor {
+ /// Absolute path inside a filesystem the sidecar can read
+ /// (single-container deploy: HF cache; split-container: shared
+ /// `emptyDir` under `/var/run/sie/...`). `None` -> adapter has not
+ /// materialised its tokeniser to a sidecar-visible path; Rust
+ /// skips Rust-side tokenisation for this model and Python tokenises.
+ #[serde(default)]
+ pub tokenizer_path: Option<String>,
+ /// BLAKE3 (truncated to 32 hex chars) of the canonical tokenizer
+ /// JSON. Lets the sidecar verify byte-identity with the adapter's
+ /// loaded tokeniser before enabling the fast path.
+ #[serde(default)]
+ pub tokenizer_id: Option<String>,
+ /// Per-model truncation cap. `None` falls back to the registry's
+ /// `DEFAULT_MAX_SEQ_LEN`.
+ #[serde(default)]
+ pub max_seq_len: Option<u32>,
+ /// Output keys the adapter knows how to emit (`"dense"`,
+ /// `"sparse"`, `"multivector"`, `"score"`). Informational — the
+ /// Rust-side framing path is gated per-request by
+ /// `_maybe_*_raw_output` shape checks on the Python side, not by
+ /// this field.
+ #[serde(default)]
+ pub output_types: Vec<String>,
+ /// True iff the adapter has implemented the `RunBatch` IPC method.
+ /// False for adapters still on the per-op `Process*Batch` RPCs.
+ #[serde(default)]
+ pub supports_run_batch: bool,
+ /// Model-default `query_template` (Python side: per-adapter
+ /// `query_template` ctor arg, sourced from the model YAML). Used
+ /// by the sidecar to apply asymmetric-retrieval prompts in Rust
+ /// before tokenisation when an item arrives with `is_query=true`,
+ /// matching Python's `_utils.extract_texts` precedence:
+ /// template &gt; bare instruction &gt; passthrough. `None` keeps
+ /// today's behaviour: Python applies templates and Rust either
+ /// skips `prepared_tokens` or matches the unaltered text.
+ ///
+ /// Per-request `options.query_template` still wins; this is only
+ /// the model-default fallback. Wire format is the raw Python
+ /// `str.format`-style template (e.g. `"query: {text}"` or
+ /// `"Instruct: {instruction}\nQuery: {text}"`) — the sidecar's
+ /// [`crate::prep::text_prep::TextPrep`] is byte-identical to Python's
+ /// `_utils.extract_texts` for the two known placeholders.
+ #[serde(default)]
+ pub default_query_template: Option<String>,
+ /// Model-default `doc_template` (Python side: per-adapter
+ /// `doc_template` ctor arg). Same wire contract as
+ /// [`Self::default_query_template`] but selected when
+ /// `is_query=false`.
+ #[serde(default)]
+ pub default_doc_template: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EnsureModelReadyResponse {
+ pub state: ReadinessState,
+ /// Per-model batch budget for fair dispatch. Mirrors
+ /// `sie_server.ipc_types.EnsureModelReadyResponse.batch_budget`. Only
+ /// populated when `state == Ready`; falls back to a default budget on
+ /// the Rust side when unset.
+ #[serde(default)]
+ pub batch_budget: Option<u32>,
+ /// Model descriptor. Populated by Python adapters that expose a HF
+ /// fast tokeniser + structured `output_types`; absent for older /
+ /// image / audio adapters that don't yet emit it.
+ /// See [`ModelDescriptor`] for the per-field semantics and the
+ /// fallback policy.
+ #[serde(default)]
+ pub descriptor: Option<ModelDescriptor>,
+}
+
+// -----------------------------------------------------------------------------
+// ApplyModelConfig
+// -----------------------------------------------------------------------------
+
+/// Bundle-scoped config delta applied by the worker-sidecar's
+/// `sie.config.models.<bundle>` subscriber.
+///
+/// Rust owns the NATS subscription, producer validation, epoch gating, and
+/// health hash publication. Python owns schema validation and mutation of the
+/// adapter-local `ModelRegistry`, so the actual registry write remains in the
+/// process that serves inference.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ApplyModelConfigRequest {
+ pub bundle_id: String,
+ pub model_id: String,
+ pub epoch: u64,
+ pub bundle_config_hash: String,
+ #[serde(default)]
+ pub profiles_added: Vec<String>,
+ pub model_config: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ApplyModelConfigResponse {
+ pub applied: bool,
+ pub bundle_config_hash: String,
+ #[serde(default)]
+ pub config_version: u64,
+}
+
+// -----------------------------------------------------------------------------
+// ProcessGenerate: streaming generation over IPC
+// -----------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProcessGenerateRequest {
+ pub model_id: String,
+ #[serde(with = "serde_bytes")]
+ pub work_item_msgpack: Vec<u8>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum GenerateEventKind {
+ Publish,
+ Ack,
+ Nak,
+ InProgress,
+ Done,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct GenerateEvent {
+ pub kind: String,
+ #[serde(default)]
+ pub reply_subject: String,
+ #[serde(default, with = "serde_bytes")]
+ pub payload: Vec<u8>,
+ #[serde(default)]
+ pub delay_ms: Option<u64>,
+ #[serde(default)]
+ pub error: Option<String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct WorkerCapabilitiesRequest {
+ // No fields: the method asks Python to describe its local registry.
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct WorkerCapabilitiesResponse {
+ #[serde(default)]
+ pub has_generation_models: bool,
+ #[serde(default)]
+ pub generation_models: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SignalGenerateCancelRequest {
+ pub request_id: String,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct SignalGenerateCancelResponse {
+ #[serde(default)]
+ pub matched: bool,
+}
+
+// -----------------------------------------------------------------------------
+// PreparedTokens: Rust-side tokenisation
+// -----------------------------------------------------------------------------
+
+/// Ragged per-item token output, attached by the Rust dispatcher to
+/// `EncodeBatchItem` / `ScoreBatchItem` when the sidecar has
+/// pre-tokenised the text. The Python adapter compares
+/// `tokenizer_id` against its own loaded tokenizer's content hash:
+/// match → use the tokens directly, mismatch / absence → tokenise in
+/// Python as today. See
+/// `packages/sie_server_sidecar/docs/architecture-guide.md`
+/// for the full contract, parity rules, and fallback policy.
+///
+/// Each inner `Vec<u32>` is the `input_ids` for a single text item
+/// (ragged, no batch padding — mirrors Python's
+/// `padding=False, truncation=True, max_length=N`). `attention_mask`
+/// and `token_type_ids` run in lockstep with `input_ids` when
+/// populated; empty inner vectors signal "tokenizer didn't emit this
+/// field" and the Python adapter falls back to `[1] * len(input_ids)`
+/// / all-zero segments.
+///
+/// The containing `EncodeBatchItem` / `ScoreBatchItem` keeps a
+/// `prepared_tokens: Option<PreparedTokens>` with `#[serde(default)]` because
+/// the worker-sidecar only attaches it when tokenizer materialization and
+/// hashing succeed.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PreparedTokens {
+ pub input_ids: Vec<Vec<u32>>,
+ /// Attention mask per item. Same shape as `input_ids`. Empty
+ /// outer vec signals "not emitted" (Python fills all-ones).
+ #[serde(default)]
+ pub attention_mask: Vec<Vec<u32>>,
+ /// Segment ids per item. Same shape as `input_ids`. Empty outer
+ /// vec signals "tokenizer doesn't produce segments" (Python
+ /// treats as all-zero when the adapter needs it).
+ #[serde(default)]
+ pub token_type_ids: Vec<Vec<u32>>,
+ /// Stable content hash of the `tokenizer.json` bytes. Python
+ /// recomputes the same hash on its loaded tokenizer; mismatch
+ /// triggers fallback to Python tokenise for this request.
+ pub tokenizer_id: String,
+ /// Per-model truncation bound the Rust side used (same as the
+ /// `max_length` kwarg on the Python tokenise call). Carried for
+ /// metrics / debugging only — Python does not enforce it.
+ #[serde(default)]
+ pub max_seq_len: u32,
+}
+
+// -----------------------------------------------------------------------------
+// RawOutput: Rust-side output shaping / result framing
+// -----------------------------------------------------------------------------
+
+/// Typed raw inference output returned by the Python adapter when
+/// the worker-sidecar owns final wire framing.
+///
+/// Each [`ItemOutcome`] carries **either**:
+///
+/// * a pre-framed `result_msgpack` (legacy path; Python built the
+/// full msgpack envelope exactly like today), **or**
+/// * a `raw_output` with one of the typed variants populated — in
+/// which case the Rust publisher calls the matching output shaper to
+/// produce byte-identical `result_msgpack` bytes.
+///
+/// Wire format is additive and tolerant:
+///
+/// * All variants are `Option<_>` with `#[serde(default)]` so an old
+/// Python adapter process round-trips as `raw_output = None` and the legacy
+/// `result_msgpack` takes over.
+/// * New variants can add another `Option<_>` field on this struct; old
+/// Rust builds ignore them and fall back to the Python-framed bytes.
+///
+/// See
+/// `packages/sie_server_sidecar/docs/architecture-guide.md`
+/// for the full contract and fallback matrix.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct RawOutput {
+ /// Dense `[dim]` embedding for a single encode item. One per
+ /// `EncodeBatchItem` because the IPC batch is per-item; the
+ /// adapter's internal GPU batch is flattened back on the way
+ /// out to match today's framing.
+ #[serde(default)]
+ pub dense: Option<DenseOutput>,
+ /// Rerank scores for one score item (`query + N docs`). Rust
+ /// performs the sort-by-score-desc + rank assignment and emits
+ /// the `[{item_id, score, rank}, ...]` list.
+ #[serde(default)]
+ pub score: Option<ScoreOutputRaw>,
+ /// Sparse `(indices, values)` pair for one encode item —
+ /// v1 scope is f32 values + i32 indices only. See
+ /// [`crate::output::build_sparse_payload`] for the wire shape
+ /// and `_maybe_sparse_raw_output` (Python side) for the safety
+ /// gate that keeps float16 / non-i32 / binary variants on the
+ /// Python-framed fallback path.
+ #[serde(default)]
+ pub sparse: Option<SparseOutput>,
+ /// Multivector `[num_tokens, token_dims]` matrix for one encode
+ /// item — v1 scope is f32 only. `float16` and the bit-packed
+ /// binary-multivector variant (token row size `< token_dims`)
+ /// stay on the Python path via the same gate.
+ #[serde(default)]
+ pub multivector: Option<MultivectorOutput>,
+}
+
+/// Flat dense-vector payload, dtype is always float32 for v1.
+///
+/// Shape guarantees: `values.len() == dim`. If this invariant is
+/// violated the shaper returns
+/// [`crate::output::ShapeError::DenseDimMismatch`] and the
+/// publisher emits an `error` `WorkResult` — we never send a
+/// truncated / oversized array over the wire.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DenseOutput {
+ pub values: Vec<f32>,
+ pub dim: u32,
+ /// If `true`, Rust L2-normalizes `values` before packing.
+ /// v1: Python adapters normalize themselves (unchanged) and
+ /// always emit `normalize = false`; kept on the wire so a later
+ /// stage can delegate the normalize step to Rust without a
+ /// schema bump.
+ #[serde(default)]
+ pub normalize: bool,
+}
+
+/// Rerank score payload: parallel `scores` + `item_ids` lists.
+///
+/// The Rust shaper sorts by score **descending** (stable tie-break
+/// preserving input order, matching Python's
+/// `list.sort(key=..., reverse=True)`) and assigns `rank = 0..`.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ScoreOutputRaw {
+ /// One score per scored document, in input order. `f32` to
+ /// match the `np.float32` origin inside the Python adapter;
+ /// the shaper widens each via `f64::from(f32)` before emitting
+ /// msgpack float64 — byte-identical to Python's
+ /// `float(np.float32(x))` widening path (see golden in
+ /// `crate::output::tests`).
+ pub scores: Vec<f32>,
+ /// Document ids in the same order as `scores`. Empty strings
+ /// must be filled in by Python (e.g. synthesised `"item-{i}"`)
+ /// before reaching Rust so the wire shape matches the Python
+ /// fallback verbatim.
+ pub item_ids: Vec<String>,
+}
+
+/// Sparse embedding payload: parallel `indices` + `values` lists.
+///
+/// Matches the adapter-side `SparseVector` shape (`np.int32`
+/// indices, `np.float32` values) used by every in-tree sparse
+/// encoder (`splade_flash`, `gte_sparse_flash`, `sentence_transformer`,
+/// ...).
+///
+/// Shape guarantees:
+///
+/// * `indices.len() == values.len()` — the Rust shaper returns
+/// [`crate::output::ShapeError::SparseLenMismatch`] otherwise.
+/// * `dims` is optional on the wire (matches the Python
+/// `{"dims": None, ...}` convention for vocab-less sparse); when
+/// `Some`, it's the full sparse vocabulary size the SDK needs to
+/// rehydrate the vector.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct SparseOutput {
+ /// Non-zero indices, int32 per adapter-layer convention.
+ pub indices: Vec<i32>,
+ /// Non-zero values, parallel to `indices`.
+ pub values: Vec<f32>,
+ /// Full sparse dimension (vocab size); `None` when the model
+ /// does not expose a stable vocab size. Packed as msgpack `nil`
+ /// in the latter case, matching `msgpack.packb({"dims": None, ...})`.
+ #[serde(default)]
+ pub dims: Option<u32>,
+}
+
+/// Multivector (per-token) embedding payload — `[num_tokens, token_dims]`
+/// contiguous f32 matrix in C (row-major) order.
+///
+/// Shape guarantees: `values.len() == num_tokens * token_dims`. The
+/// shaper returns [`crate::output::ShapeError::MultivectorShapeMismatch`]
+/// when that invariant is violated, and the publisher converts the
+/// outcome into an error `WorkResult` instead of emitting garbage
+/// bytes.
+///
+/// v1 scope is `float32` only. Bit-packed binary multivector
+/// (`shape[1] < token_dims`, `dim/8` bytes per token) and `float16`
+/// remain on the Python framing path — the Python gate
+/// `_maybe_multivector_raw_output` refuses to emit this variant for
+/// those dtypes.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MultivectorOutput {
+ /// Flattened `[num_tokens, token_dims]` f32 matrix in row-major
+ /// (C) order. Matches `np.ndarray.tobytes()` for a contiguous
+ /// array.
+ pub values: Vec<f32>,
+ /// Number of tokens (rows).
+ pub num_tokens: u32,
+ /// Per-token embedding dimension (columns).
+ pub token_dims: u32,
+}
+
+// -----------------------------------------------------------------------------
+// ProcessEncodeBatch
+// -----------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct EncodeBatchItem {
+ pub work_item_id: String,
+ pub request_id: String,
+ pub item_index: u32,
+ pub total_items: u32,
+ pub timestamp: f64,
+ pub item: serde_json::Value,
+ #[serde(default)]
+ pub output_types: Option<Vec<String>>,
+ #[serde(default)]
+ pub instruction: Option<String>,
+ #[serde(default)]
+ pub is_query: bool,
+ #[serde(default)]
+ pub options: Option<serde_json::Value>,
+ #[serde(default)]
+ pub profile_id: Option<String>,
+ #[serde(default)]
+ pub bundle_config_hash: Option<String>,
+ #[serde(default)]
+ pub payload_fetch_ms: f64,
+ /// Rust-side pre-tokenised input. `None` when the model has no
+ /// registered tokenizer, when the item is not safe to tokenize in
+ /// Rust, or when the registry returned an error. See
+ /// [`PreparedTokens`] for the full fallback matrix.
+ #[serde(default)]
+ pub prepared_tokens: Option<PreparedTokens>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProcessEncodeBatchRequest {
+ pub model_id: String,
+ pub items: Vec<EncodeBatchItem>,
+}
+
+// -----------------------------------------------------------------------------
+// ProcessScoreBatch
+// -----------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ScoreBatchItem {
+ pub work_item_id: String,
+ pub request_id: String,
+ pub item_index: u32,
+ pub total_items: u32,
+ pub timestamp: f64,
+ pub query_item: serde_json::Value,
+ pub score_items: Vec<serde_json::Value>,
+ #[serde(default)]
+ pub instruction: Option<String>,
+ #[serde(default)]
+ pub options: Option<serde_json::Value>,
+ #[serde(default)]
+ pub profile_id: Option<String>,
+ #[serde(default)]
+ pub payload_fetch_ms: f64,
+ /// Rust-side pre-tokenised input, ordering `[query, doc_0, doc_1, ...]`.
+ /// `None` for v1 by default: the dispatcher only attaches tokens for
+ /// single-text score items (one query + one doc). Cross-encoder
+ /// pair-tokenisation lives in the Python adapter for now — see the
+ /// architecture guide.
+ #[serde(default)]
+ pub prepared_tokens: Option<PreparedTokens>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProcessScoreBatchRequest {
+ pub model_id: String,
+ pub items: Vec<ScoreBatchItem>,
+}
+
+// -----------------------------------------------------------------------------
+// ProcessExtractBatch
+// -----------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ExtractBatchItem {
+ pub work_item_id: String,
+ pub request_id: String,
+ pub item_index: u32,
+ pub total_items: u32,
+ pub timestamp: f64,
+ pub item: serde_json::Value,
+ #[serde(default)]
+ pub labels: Option<Vec<String>>,
+ #[serde(default)]
+ pub output_schema: Option<serde_json::Value>,
+ #[serde(default)]
+ pub instruction: Option<String>,
+ #[serde(default)]
+ pub options: Option<serde_json::Value>,
+ #[serde(default)]
+ pub profile_id: Option<String>,
+ #[serde(default)]
+ pub bundle_config_hash: Option<String>,
+ #[serde(default)]
+ pub payload_fetch_ms: f64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ProcessExtractBatchRequest {
+ pub model_id: String,
+ pub items: Vec<ExtractBatchItem>,
+}
+
+// -----------------------------------------------------------------------------
+// Batch outcome
+// -----------------------------------------------------------------------------
+
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Disposition {
+ PublishAndAck,
+ PublishErrorAndAck,
+ NakRetry,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ItemOutcome {
+ pub work_item_id: String,
+ pub request_id: String,
+ pub item_index: u32,
+ pub disposition: Disposition,
+ #[serde(default)]
+ pub nak_delay_ms: Option<u64>,
+ /// `result_msgpack` is the opaque payload a successful item publishes.
+ /// For `publish_error_and_ack` / `nak_retry` Python omits it, which
+ /// `msgpack` encodes as either key-absent OR key-present-with-nil. The
+ /// custom deserializer accepts both (and treats missing/nil as empty)
+ /// so per-item error outcomes don't sink the whole batch into a NAK.
+ #[serde(
+ default,
+ serialize_with = "serde_bytes::serialize",
+ deserialize_with = "deserialize_optional_bytes"
+ )]
+ pub result_msgpack: Vec<u8>,
+ #[serde(default)]
+ pub error: Option<String>,
+ #[serde(default)]
+ pub error_code: Option<String>,
+ #[serde(default)]
+ pub inference_ms: Option<f64>,
+ #[serde(default)]
+ pub tokenization_ms: Option<f64>,
+ #[serde(default)]
+ pub postprocessing_ms: Option<f64>,
+ /// Typed raw inference output. Present only when the Python adapter
+ /// defers final wire framing to Rust after per-request safety checks.
+ /// When `Some`, `result_msgpack` is expected to be empty and the
+ /// publisher runs the Rust-side shapers to produce the final bytes.
+ /// On any shaper error the outcome is converted into an error
+ /// `WorkResult`, so a misconfigured model cannot silently drop
+ /// results. See [`RawOutput`] for the wire-format fallback matrix.
+ #[serde(default)]
+ pub raw_output: Option<RawOutput>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct BatchOutcome {
+ pub outcomes: Vec<ItemOutcome>,
+}
+
+// -----------------------------------------------------------------------------
+// RunBatch
+// -----------------------------------------------------------------------------
+
+/// One item inside a [`RunBatchRequest`]. Exactly one of the three
+/// `Option` fields must be `Some`, matching the `op` discriminator.
+///
+/// Tagged struct rather than a `serde` enum because:
+/// * msgpack → msgspec prefers explicit discriminators over untagged
+/// unions (decoder tries each variant in order, which is both slow
+/// and brittle when field sets overlap between `EncodeBatchItem`
+/// and `ExtractBatchItem`).
+/// * All three item types already have `#[serde(default)]` on most
+/// fields so the "absent two" serialize as either nil or omitted —
+/// no wasted bytes.
+/// * Forward-compatible: adding a new op in the future is a new
+/// optional field + a new `op` string, no breaking change for
+/// readers that don't know it.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RunBatchItem {
+ /// Discriminator: `"encode"`, `"score"`, or `"extract"`.
+ /// `adapter_call_loop.py` switches on this to pick the right
+ /// handler without having to inspect which optional field is
+ /// populated.
+ pub op: String,
+ /// Identity copied from the wrapped per-op item. This is redundant
+ /// on the happy path, but it lets Python publish a deterministic
+ /// per-item error if the wrapped payload is malformed or absent.
+ #[serde(default)]
+ pub work_item_id: String,
+ #[serde(default)]
+ pub request_id: String,
+ #[serde(default)]
+ pub item_index: u32,
+ #[serde(default)]
+ pub encode: Option<EncodeBatchItem>,
+ #[serde(default)]
+ pub score: Option<ScoreBatchItem>,
+ #[serde(default)]
+ pub extract: Option<ExtractBatchItem>,
+}
+
+impl RunBatchItem {
+ /// Build a RunBatchItem wrapping an encode item, with the
+ /// `op` discriminator set to `"encode"`. Exists so callers don't
+ /// have to remember to sync the tag and the field.
+ #[must_use]
+ pub fn encode(item: EncodeBatchItem) -> Self {
+ let work_item_id = item.work_item_id.clone();
+ let request_id = item.request_id.clone();
+ let item_index = item.item_index;
+ Self {
+ op: "encode".to_owned(),
+ work_item_id,
+ request_id,
+ item_index,
+ encode: Some(item),
+ score: None,
+ extract: None,
+ }
+ }
+
+ /// Build a RunBatchItem wrapping a score item.
+ #[must_use]
+ pub fn score(item: ScoreBatchItem) -> Self {
+ let work_item_id = item.work_item_id.clone();
+ let request_id = item.request_id.clone();
+ let item_index = item.item_index;
+ Self {
+ op: "score".to_owned(),
+ work_item_id,
+ request_id,
+ item_index,
+ encode: None,
+ score: Some(item),
+ extract: None,
+ }
+ }
+
+ /// Build a RunBatchItem wrapping an extract item.
+ #[must_use]
+ pub fn extract(item: ExtractBatchItem) -> Self {
+ let work_item_id = item.work_item_id.clone();
+ let request_id = item.request_id.clone();
+ let item_index = item.item_index;
+ Self {
+ op: "extract".to_owned(),
+ work_item_id,
+ request_id,
+ item_index,
+ encode: None,
+ score: None,
+ extract: Some(item),
+ }
+ }
+}
+
+/// Pre-formed batch dispatched through the Rust scheduler.
+///
+/// The scheduler forms a batch of *homogeneous* op (FCFS picks one
+/// batcher per call; a batcher only holds one op by construction),
+/// so every [`RunBatchItem`] in `items` shares the same `op` tag.
+/// The Python adapter loop validates this on receipt.
+///
+/// `total_cost` is sent redundantly so the Python side can log it
+/// without walking `items` — matches the current per-RPC logging
+/// pattern where batch-level stats are peeled off without descending
+/// into the payload.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RunBatchRequest {
+ pub model_id: String,
+ /// Rust-assigned id for cross-log correlation. Unique within the
+ /// worker process lifetime; generation strategy is a plain
+ /// monotonic `u64` on the dispatcher side.
+ pub batch_id: u64,
+ /// LoRA adapter the batch targets. Empty string == base model.
+ /// Python's `adapter.set_active_lora` accepts `""` to mean base,
+ /// matching this convention.
+ pub lora_key: String,
+ /// Sum of per-item costs (typically `PreparedTokens.seq_len` or
+ /// the Python fallback estimate). Informational; Python
+ /// recomputes when it needs the exact value.
+ pub total_cost: u64,
+ pub items: Vec<RunBatchItem>,
+}
+
+// -----------------------------------------------------------------------------
+// Drain
+// -----------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DrainRequest {
+ #[serde(default)]
+ pub deadline_ms: u64,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct DrainResponse {
+ #[serde(default)]
+ pub acknowledged: bool,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn readiness_state_serde_matches_python_literal() {
+ // Python side uses Literal["ready","loading_started","loading_in_progress","retry_later"].
+ let bytes = rmp_serde::to_vec_named(&ReadinessState::LoadingInProgress).unwrap();
+ let back: ReadinessState = rmp_serde::from_slice(&bytes).unwrap();
+ assert_eq!(back, ReadinessState::LoadingInProgress);
+
+ // JSON form — easiest to assert the string value.
+ let s = serde_json::to_string(&ReadinessState::LoadingInProgress).unwrap();
+ assert_eq!(s, "\"loading_in_progress\"");
+
+ let s = serde_json::to_string(&ReadinessState::RetryLater).unwrap();
+ assert_eq!(s, "\"retry_later\"");
+ }
+
+ #[test]
+ fn disposition_serde_matches_python_literal() {
+ let s = serde_json::to_string(&Disposition::PublishAndAck).unwrap();
+ assert_eq!(s, "\"publish_and_ack\"");
+ let s = serde_json::to_string(&Disposition::PublishErrorAndAck).unwrap();
+ assert_eq!(s, "\"publish_error_and_ack\"");
+ let s = serde_json::to_string(&Disposition::NakRetry).unwrap();
+ assert_eq!(s, "\"nak_retry\"");
+ }
+
+ #[test]
+ fn item_outcome_roundtrip_with_bytes() {
+ let outcome = ItemOutcome {
+ work_item_id: "r.0".into(),
+ request_id: "r".into(),
+ item_index: 0,
+ disposition: Disposition::PublishAndAck,
+ nak_delay_ms: None,
+ result_msgpack: vec![1, 2, 3, 4, 5],
+ error: None,
+ error_code: None,
+ inference_ms: Some(42.0),
+ tokenization_ms: None,
+ postprocessing_ms: None,
+ raw_output: None,
+ };
+ let bytes = rmp_serde::to_vec_named(&outcome).unwrap();
+ let back: ItemOutcome = rmp_serde::from_slice(&bytes).unwrap();
+ assert_eq!(back.request_id, "r");
+ assert_eq!(back.result_msgpack, vec![1, 2, 3, 4, 5]);
+ assert_eq!(back.inference_ms, Some(42.0));
+ assert_eq!(back.disposition, Disposition::PublishAndAck);
+ }
+
+ #[test]
+ fn item_outcome_decodes_when_python_sends_nil_bytes() {
+ // Python (`msgspec.to_builtins` + `msgpack.packb`) can serialise
+ // `result_msgpack: bytes | None = None` as either (a) key-absent or
+ // (b) key-present with a `nil` value. `#[serde(default, with =
+ // "serde_bytes")]` must handle both gracefully, otherwise every
+ // per-item error outcome decodes as a transport failure and the
+ // worker-sidecar NAKs the whole batch — a latent blocker the
+ // pre-deploy audit flagged.
+ let mut buf = Vec::new();
+ rmp::encode::write_map_len(&mut buf, 9).unwrap();
+ rmp::encode::write_str(&mut buf, "work_item_id").unwrap();
+ rmp::encode::write_str(&mut buf, "r.0").unwrap();
+ rmp::encode::write_str(&mut buf, "request_id").unwrap();
+ rmp::encode::write_str(&mut buf, "r").unwrap();
+ rmp::encode::write_str(&mut buf, "item_index").unwrap();
+ rmp::encode::write_uint(&mut buf, 0).unwrap();
+ rmp::encode::write_str(&mut buf, "disposition").unwrap();
+ rmp::encode::write_str(&mut buf, "publish_error_and_ack").unwrap();
+ rmp::encode::write_str(&mut buf, "nak_delay_ms").unwrap();
+ rmp::encode::write_nil(&mut buf).unwrap();
+ rmp::encode::write_str(&mut buf, "result_msgpack").unwrap();
+ rmp::encode::write_nil(&mut buf).unwrap();
+ rmp::encode::write_str(&mut buf, "error").unwrap();
+ rmp::encode::write_str(&mut buf, "boom").unwrap();
+ rmp::encode::write_str(&mut buf, "error_code").unwrap();
+ rmp::encode::write_str(&mut buf, "inference_error").unwrap();
+ rmp::encode::write_str(&mut buf, "inference_ms").unwrap();
+ rmp::encode::write_nil(&mut buf).unwrap();
+
+ let back: ItemOutcome = rmp_serde::from_slice(&buf)
+ .expect("ItemOutcome must decode when Python sends nil for optional bytes");
+ assert_eq!(back.disposition, Disposition::PublishErrorAndAck);
+ assert!(back.result_msgpack.is_empty());
+ assert_eq!(back.error.as_deref(), Some("boom"));
+ assert_eq!(back.error_code.as_deref(), Some("inference_error"));
+ assert!(back.nak_delay_ms.is_none());
+ }
+
+ #[test]
+ fn item_outcome_decodes_when_python_omits_optional_fields() {
+ let mut buf = Vec::new();
+ rmp::encode::write_map_len(&mut buf, 4).unwrap();
+ rmp::encode::write_str(&mut buf, "work_item_id").unwrap();
+ rmp::encode::write_str(&mut buf, "r.0").unwrap();
+ rmp::encode::write_str(&mut buf, "request_id").unwrap();
+ rmp::encode::write_str(&mut buf, "r").unwrap();
+ rmp::encode::write_str(&mut buf, "item_index").unwrap();
+ rmp::encode::write_uint(&mut buf, 0).unwrap();
+ rmp::encode::write_str(&mut buf, "disposition").unwrap();
+ rmp::encode::write_str(&mut buf, "publish_and_ack").unwrap();
+
+ let back: ItemOutcome = rmp_serde::from_slice(&buf)
+ .expect("ItemOutcome must decode when Python omits optional fields entirely");
+ assert!(back.result_msgpack.is_empty());
+ assert!(back.error.is_none());
+ assert!(back.inference_ms.is_none());
+ }
+
+ #[test]
+ fn prepared_tokens_roundtrips_msgpack() {
+ // Additive field on EncodeBatchItem: both "field present, Some"
+ // and "field absent" must roundtrip so Rust ↔ Python can roll
+ // out in either order.
+ let pt = PreparedTokens {
+ input_ids: vec![vec![101, 2023, 2003, 1037, 3231, 102], vec![101, 2061, 102]],
+ attention_mask: vec![vec![1, 1, 1, 1, 1, 1], vec![1, 1, 1]],
+ token_type_ids: vec![vec![0, 0, 0, 0, 0, 0], vec![0, 0, 0]],
+ tokenizer_id: "deadbeefcafef00dba5eba11c0ffee42".into(),
+ max_seq_len: 512,
+ };
+ let bytes = rmp_serde::to_vec_named(&pt).unwrap();
+ let back: PreparedTokens = rmp_serde::from_slice(&bytes).unwrap();
+ assert_eq!(back.input_ids, pt.input_ids);
+ assert_eq!(back.attention_mask, pt.attention_mask);
+ assert_eq!(back.token_type_ids, pt.token_type_ids);
+ assert_eq!(back.tokenizer_id, pt.tokenizer_id);
+ assert_eq!(back.max_seq_len, 512);
+ }
+
+ #[test]
+ fn encode_batch_item_default_prepared_tokens_absent_on_wire() {
+ // Old Python sending an EncodeBatchItem without the
+ // `prepared_tokens` key — new Rust must decode successfully
+ // and see `None`. This guards the additive wire contract.
+ let bi = EncodeBatchItem {
+ work_item_id: "r.0".into(),
+ request_id: "r".into(),
+ item_index: 0,
+ total_items: 1,
+ timestamp: 0.0,
+ item: serde_json::json!({"text": "hello"}),
+ output_types: Some(vec!["dense".into()]),
+ instruction: None,
+ is_query: false,
+ options: None,
+ profile_id: None,
+ bundle_config_hash: None,
+ payload_fetch_ms: 0.0,
+ prepared_tokens: None,
+ };
+ let bytes = rmp_serde::to_vec_named(&bi).unwrap();
+ let back: EncodeBatchItem = rmp_serde::from_slice(&bytes).unwrap();
+ assert!(back.prepared_tokens.is_none());
+ }
+
+ #[test]
+ fn ping_response_decodes_from_minimal_map() {
+ let bytes = rmp_serde::to_vec_named(&serde_json::json!({
+ "timestamp_ms": 123.0,
+ "worker_id": "w-1",
+ }))
+ .unwrap();
+ let back: PingResponse = rmp_serde::from_slice(&bytes).unwrap();
+ assert_eq!(back.worker_id, "w-1");
+ assert_eq!(back.timestamp_ms, 123.0);
+ assert_eq!(back.bundle_config_hash, "");
+ }
+}
diff --git a/packages/sie_server_sidecar/src/protocol/mod.rs b/packages/sie_server_sidecar/src/protocol/mod.rs
new file mode 100644
index 000000000..ecafd6c0e
--- /dev/null
+++ b/packages/sie_server_sidecar/src/protocol/mod.rs
@@ -0,0 +1,7 @@
+//! Wire protocol definitions shared by the sidecar and Python adapter.
+//!
+//! The Rust IPC schema is intentionally kept in one module and checked against
+//! `packages/sie_server/src/sie_server/ipc_types.py` by
+//! `tools/ci/check_ipc_types_parity.py`.
+
+pub mod ipc_types;
diff --git a/packages/sie_server_sidecar/src/publisher.rs b/packages/sie_server_sidecar/src/publisher.rs
new file mode 100644
index 000000000..366b041ed
--- /dev/null
+++ b/packages/sie_server_sidecar/src/publisher.rs
@@ -0,0 +1,678 @@
+//! Encode an `ItemOutcome` into a `WorkResult` and publish it to the
+//! gateway's reply subject.
+
+use async_nats::Client;
+use thiserror::Error;
+use tracing::debug;
+
+use crate::ipc_types::{Disposition, ItemOutcome, RawOutput};
+use crate::output::{
+ build_dense_payload, build_multivector_payload, build_score_payload, build_sparse_payload,
+ l2_normalize_in_place, ShapeError,
+};
+use crate::work_types::WorkResult;
+
+#[derive(Debug, Error)]
+pub enum PublishError {
+ #[error("nats publish: {0}")]
+ Nats(#[from] async_nats::PublishError),
+ #[error("encode WorkResult: {0}")]
+ Encode(#[from] rmp_serde::encode::Error),
+ #[error("empty reply_subject — cannot publish")]
+ EmptyReplySubject,
+}
+
+/// Per-item timings stamped onto `WorkResult` by the worker.
+///
+/// * `queue_ms` — wall-clock from gateway publish (`WorkItem.timestamp`)
+/// to worker result publish.
+/// * `payload_fetch_ms` — time spent resolving `payload_ref` /
+/// `query_payload_ref` against the payload store; `0.0` for inline items.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct Timings {
+ pub queue_ms: f64,
+ pub payload_fetch_ms: f64,
+}
+
+pub struct WorkPublisher {
+ client: Client,
+ worker_id: String,
+}
+
+impl WorkPublisher {
+ pub fn new(client: Client, worker_id: impl Into<String>) -> Self {
+ Self {
+ client,
+ worker_id: worker_id.into(),
+ }
+ }
+
+ pub fn worker_id(&self) -> &str {
+ &self.worker_id
+ }
+
+ /// Publish a `WorkResult` built from `outcome` + worker-side `timings`.
+ /// Returns `PublishError::EmptyReplySubject` on empty subject so the
+ /// caller can treat the publish (and ACK) as fire-and-forget.
+ pub async fn publish_result(
+ &self,
+ reply_subject: &str,
+ outcome: &ItemOutcome,
+ timings: Option<Timings>,
+ ) -> 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);
+ let bytes = rmp_serde::to_vec_named(&result)?;
+ debug!(
+ reply = %reply_subject,
+ request_id = %result.request_id,
+ bytes = bytes.len(),
+ "publishing WorkResult"
+ );
+ self.client
+ .publish(reply_subject.to_string(), bytes.into())
+ .await?;
+ Ok(())
+ }
+
+ /// Publish a pre-encoded generation chunk produced by Python's
+ /// `StreamingProcessor`. The sidecar owns NATS I/O; Python owns the
+ /// chunk envelope bytes.
+ pub async fn publish_raw(
+ &self,
+ reply_subject: &str,
+ payload: Vec<u8>,
+ ) -> Result<(), PublishError> {
+ check_reply_subject(reply_subject)?;
+ self.client
+ .publish(reply_subject.to_string(), payload.into())
+ .await?;
+ Ok(())
+ }
+}
+
+/// Result of inspecting an `ItemOutcome.raw_output` for Rust-side
+/// shaping: either pass through unchanged, or emit a replacement
+/// outcome with `result_msgpack` filled in (success or error).
+///
+/// `Shaped` carries a full `ItemOutcome` (~360 B) so the enum is
+/// variant-heavy. Boxing the inner outcome to shrink the enum is a
+/// mechanical refactor tracked for its own cleanup cycle — every
+/// consumer site would have to thread a `Box` through, which is noise
+/// for this hot path. Scoped `#[allow]` here rather than a
+/// crate-wide one so the warning re-fires if anyone else builds a
+/// heavyweight enum elsewhere.
+#[allow(clippy::large_enum_variant)]
+enum ShapeOutcome {
+ Unchanged,
+ Shaped(ItemOutcome),
+}
+
+/// Attempt to shape `outcome.raw_output` into `outcome.result_msgpack`
+/// bytes using the Rust-side output shapers.
+///
+/// Rules:
+///
+/// * `raw_output == None` → `Unchanged`. Legacy Python path.
+/// * `raw_output == Some(_)` but `result_msgpack` is non-empty →
+/// `Unchanged`. Python gave us pre-framed bytes; trust them. The
+/// Python side gates `raw_output` emission behind an env var, so
+/// a mixed outcome is a wire artefact of a rolling deploy and
+/// we take the safer, already-framed path.
+/// * `raw_output == Some(_)` with empty `result_msgpack` and a
+/// recognised variant → run the shaper; on success emit
+/// `PublishAndAck` with the produced bytes, on failure emit
+/// `PublishErrorAndAck` with the error message. Never silently
+/// sinks the work item.
+/// * `raw_output == Some(_)` with no recognised variant populated
+/// (e.g. a future Rust build sees a variant it doesn't know) →
+/// emit `PublishErrorAndAck` so we don't hand back an empty
+/// `result_msgpack` that the SDK would misinterpret as "success
+/// but no embeddings".
+fn shape_raw_output_for_wire(outcome: &ItemOutcome) -> ShapeOutcome {
+ let Some(raw) = outcome.raw_output.as_ref() else {
+ return ShapeOutcome::Unchanged;
+ };
+ if !outcome.result_msgpack.is_empty() {
+ return ShapeOutcome::Unchanged;
+ }
+ // Only shape on success outcomes. Error dispositions carry no
+ // payload anyway, so fall through to legacy handling.
+ if !matches!(outcome.disposition, Disposition::PublishAndAck) {
+ return ShapeOutcome::Unchanged;
+ }
+
+ match shape(raw) {
+ Ok(bytes) => ShapeOutcome::Shaped(ItemOutcome {
+ result_msgpack: bytes,
+ // Drop the raw_output so we never pay the serialisation
+ // cost for the inner arrays again in `rmp_serde::to_vec`.
+ raw_output: None,
+ ..outcome.clone()
+ }),
+ Err(e) => {
+ tracing::warn!(
+ work_item_id = %outcome.work_item_id,
+ request_id = %outcome.request_id,
+ error = %e,
+ "raw_output shape failed; downgrading to error WorkResult"
+ );
+ ShapeOutcome::Shaped(ItemOutcome {
+ disposition: Disposition::PublishErrorAndAck,
+ result_msgpack: Vec::new(),
+ error: Some(format!("raw_output shape: {e}")),
+ error_code: Some("raw_output_shape_error".into()),
+ raw_output: None,
+ ..outcome.clone()
+ })
+ }
+ }
+}
+
+/// Dispatch a [`RawOutput`] to the appropriate shaper. Returns a
+/// `RawOutputUnknown` error if no recognised variant is populated;
+/// callers turn that into a `PublishErrorAndAck` so unknown future
+/// variants surface as a typed error rather than an empty success.
+fn shape(raw: &RawOutput) -> Result<Vec<u8>, ShapeError> {
+ // Each outcome carries exactly one variant. Dispatch order is
+ // fixed so a test that accidentally populates two variants gets
+ // a deterministic result: dense → score → sparse → multivector.
+ // A legitimate multi-variant encode item (e.g. dense + sparse
+ // for the same text) is framed via the Python-framed fallback path —
+ // the Python gate refuses to mint a multi-variant `RawOutput`.
+ if let Some(dense) = raw.dense.as_ref() {
+ let mut values = dense.values.clone();
+ if dense.normalize {
+ l2_normalize_in_place(&mut values);
+ }
+ return build_dense_payload(&values, dense.dim as usize);
+ }
+ if let Some(score) = raw.score.as_ref() {
+ return build_score_payload(&score.scores, &score.item_ids);
+ }
+ if let Some(sparse) = raw.sparse.as_ref() {
+ return build_sparse_payload(&sparse.indices, &sparse.values, sparse.dims);
+ }
+ if let Some(mv) = raw.multivector.as_ref() {
+ return build_multivector_payload(&mv.values, mv.num_tokens, mv.token_dims);
+ }
+ Err(ShapeError::MsgpackWrite(
+ "raw_output had no recognised variant populated (forward-compat placeholder?)".into(),
+ ))
+}
+
+/// 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;
+/// error-only paths pass `None` and produce a bare error result.
+pub fn build_work_result(
+ outcome: &ItemOutcome,
+ worker_id: &str,
+ timings: Option<Timings>,
+) -> WorkResult {
+ let (success, error, error_code) = match outcome.disposition {
+ Disposition::PublishAndAck => (true, None, None),
+ Disposition::PublishErrorAndAck => {
+ (false, outcome.error.clone(), outcome.error_code.clone())
+ }
+ Disposition::NakRetry => {
+ // Shouldn't be published — if the caller passed one anyway,
+ // default to an error WorkResult so the gateway surfaces it.
+ (
+ false,
+ Some(
+ outcome
+ .error
+ .clone()
+ .unwrap_or_else(|| "nak_retry reached publisher".to_string()),
+ ),
+ outcome.error_code.clone(),
+ )
+ }
+ };
+
+ // Timing fields are only stamped on the success/publish path.
+ // Error results omit them entirely. `processing_ms = 0.0` is a
+ // placeholder the gateway ignores when inference_ms is set.
+ let (queue_ms, processing_ms, payload_fetch_ms) = match timings {
+ Some(t) => (
+ Some(t.queue_ms),
+ Some(0.0),
+ (t.payload_fetch_ms > 0.0).then_some(t.payload_fetch_ms),
+ ),
+ None => (None, None, None),
+ };
+
+ WorkResult {
+ work_item_id: outcome.work_item_id.clone(),
+ request_id: outcome.request_id.clone(),
+ item_index: outcome.item_index,
+ success,
+ result_msgpack: outcome.result_msgpack.clone(),
+ error,
+ error_code,
+ inference_ms: outcome.inference_ms,
+ queue_ms,
+ processing_ms,
+ worker_id: Some(worker_id.to_string()),
+ tokenization_ms: outcome.tokenization_ms,
+ postprocessing_ms: outcome.postprocessing_ms,
+ payload_fetch_ms,
+ }
+}
+
+/// Decide whether a disposition should be published at all.
+pub fn should_publish(disposition: &Disposition) -> bool {
+ matches!(
+ disposition,
+ Disposition::PublishAndAck | Disposition::PublishErrorAndAck
+ )
+}
+
+/// Reject empty / whitespace-only reply subjects so we never publish to
+/// an empty NATS subject (which the client would silently drop).
+pub(crate) fn check_reply_subject(subject: &str) -> Result<(), PublishError> {
+ if subject.trim().is_empty() {
+ return Err(PublishError::EmptyReplySubject);
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ipc_types::{DenseOutput, MultivectorOutput, ScoreOutputRaw, SparseOutput};
+ use crate::output::{build_multivector_payload, build_sparse_payload};
+
+ fn outcome() -> ItemOutcome {
+ ItemOutcome {
+ work_item_id: "req-1.0".into(),
+ request_id: "req-1".into(),
+ item_index: 0,
+ disposition: Disposition::PublishAndAck,
+ nak_delay_ms: None,
+ result_msgpack: vec![0x81, 0xa5, b'h', b'e', b'l', b'l', b'o', 0x05],
+ error: None,
+ error_code: None,
+ inference_ms: Some(17.5),
+ tokenization_ms: Some(1.1),
+ postprocessing_ms: Some(0.3),
+ raw_output: None,
+ }
+ }
+
+ #[test]
+ fn success_outcome_maps_to_success_result() {
+ let r = build_work_result(&outcome(), "worker-1", None);
+ assert!(r.success);
+ assert!(r.error.is_none());
+ assert_eq!(r.request_id, "req-1");
+ assert_eq!(r.item_index, 0);
+ assert_eq!(r.worker_id.as_deref(), Some("worker-1"));
+ assert_eq!(r.inference_ms, Some(17.5));
+ assert_eq!(r.tokenization_ms, Some(1.1));
+ assert_eq!(r.postprocessing_ms, Some(0.3));
+ assert_eq!(r.result_msgpack.len(), 8);
+ }
+
+ #[test]
+ fn publish_error_outcome_maps_to_failure_result() {
+ let mut o = outcome();
+ o.disposition = Disposition::PublishErrorAndAck;
+ o.error = Some("kapow".into());
+ o.error_code = Some("INTERNAL".into());
+ let r = build_work_result(&o, "w", None);
+ assert!(!r.success);
+ assert_eq!(r.error.as_deref(), Some("kapow"));
+ assert_eq!(r.error_code.as_deref(), Some("INTERNAL"));
+ }
+
+ #[test]
+ fn should_publish_rejects_nak_retry() {
+ assert!(should_publish(&Disposition::PublishAndAck));
+ assert!(should_publish(&Disposition::PublishErrorAndAck));
+ assert!(!should_publish(&Disposition::NakRetry));
+ }
+
+ #[test]
+ fn work_result_is_msgpack_round_trippable() {
+ let r = build_work_result(&outcome(), "w", None);
+ let bytes = rmp_serde::to_vec_named(&r).unwrap();
+ let back: WorkResult = rmp_serde::from_slice(&bytes).unwrap();
+ assert!(back.success);
+ assert_eq!(back.request_id, "req-1");
+ assert_eq!(back.result_msgpack.len(), 8);
+ }
+
+ #[test]
+ fn timings_populate_queue_and_processing_fields() {
+ let timings = Timings {
+ queue_ms: 12.5,
+ payload_fetch_ms: 3.2,
+ };
+ let r = build_work_result(&outcome(), "w", Some(timings));
+ assert_eq!(r.queue_ms, Some(12.5));
+ // Python sets processing_ms = 0.0 as a placeholder; we match exactly.
+ assert_eq!(r.processing_ms, Some(0.0));
+ assert_eq!(r.payload_fetch_ms, Some(3.2));
+ }
+
+ #[test]
+ fn zero_payload_fetch_ms_is_omitted() {
+ // Matches Python: `if payload_fetch_ms > 0:` before inclusion.
+ let timings = Timings {
+ queue_ms: 5.0,
+ payload_fetch_ms: 0.0,
+ };
+ let r = build_work_result(&outcome(), "w", Some(timings));
+ assert_eq!(r.queue_ms, Some(5.0));
+ assert!(r.payload_fetch_ms.is_none());
+ }
+
+ #[test]
+ fn check_reply_subject_rejects_empty_and_whitespace() {
+ assert!(matches!(
+ check_reply_subject(""),
+ Err(PublishError::EmptyReplySubject)
+ ));
+ assert!(matches!(
+ check_reply_subject(" "),
+ Err(PublishError::EmptyReplySubject)
+ ));
+ assert!(check_reply_subject("\t\n").is_err());
+ }
+
+ #[test]
+ fn check_reply_subject_accepts_normal_inbox() {
+ assert!(check_reply_subject("_INBOX.r1.abc").is_ok());
+ assert!(check_reply_subject("sie.results.q1").is_ok());
+ }
+
+ #[test]
+ fn error_path_omits_timings_fields() {
+ // Error-only publishes (payload resolution failure, unknown op) go
+ // through the `None` timings path and should not carry queue_ms etc.
+ let mut o = outcome();
+ o.disposition = Disposition::PublishErrorAndAck;
+ o.error = Some("oops".into());
+ o.error_code = Some("payload_error".into());
+ let r = build_work_result(&o, "w", None);
+ assert!(!r.success);
+ assert!(r.queue_ms.is_none());
+ assert!(r.processing_ms.is_none());
+ assert!(r.payload_fetch_ms.is_none());
+ }
+
+ // ---- raw_output shaping ---------------------------------------
+
+ #[test]
+ fn raw_output_none_leaves_outcome_unchanged() {
+ let o = outcome();
+ // `outcome()` pre-fills legacy `result_msgpack` and no
+ // `raw_output` — the shaper is a no-op.
+ match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Unchanged => {}
+ ShapeOutcome::Shaped(_) => {
+ panic!("raw_output shaper must not touch legacy outcomes that already have result_msgpack");
+ }
+ }
+ }
+
+ #[test]
+ fn raw_output_dense_is_shaped_into_msgpack() {
+ let mut o = outcome();
+ o.result_msgpack = Vec::new();
+ o.raw_output = Some(RawOutput {
+ dense: Some(DenseOutput {
+ values: vec![1.0, 2.0, 3.0],
+ dim: 3,
+ normalize: false,
+ }),
+ ..Default::default()
+ });
+ let shaped = match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Shaped(s) => s,
+ ShapeOutcome::Unchanged => panic!("expected raw_output shaping"),
+ };
+ // Byte-for-byte identical to the Python
+ // `_wrap_encode_output({"dense": np.float32([1,2,3])})` golden.
+ let expected = build_dense_payload(&[1.0, 2.0, 3.0], 3).unwrap();
+ assert_eq!(shaped.result_msgpack, expected);
+ assert!(matches!(shaped.disposition, Disposition::PublishAndAck));
+ assert!(
+ shaped.raw_output.is_none(),
+ "shaper must strip raw_output to avoid double-encoding"
+ );
+ assert_eq!(shaped.work_item_id, "req-1.0");
+ assert_eq!(
+ shaped.inference_ms,
+ Some(17.5),
+ "timing metadata must round-trip"
+ );
+ }
+
+ #[test]
+ fn raw_output_dense_with_normalize_l2s_before_packing() {
+ let mut o = outcome();
+ o.result_msgpack = Vec::new();
+ o.raw_output = Some(RawOutput {
+ dense: Some(DenseOutput {
+ values: vec![3.0, 4.0],
+ dim: 2,
+ normalize: true,
+ }),
+ ..Default::default()
+ });
+ let shaped = match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Shaped(s) => s,
+ _ => unreachable!(),
+ };
+ // [3,4] L2-normalised is [0.6, 0.8].
+ let expected = build_dense_payload(&[0.6, 0.8], 2).unwrap();
+ assert_eq!(shaped.result_msgpack, expected);
+ }
+
+ #[test]
+ fn raw_output_score_is_shaped_and_sorted() {
+ let mut o = outcome();
+ o.result_msgpack = Vec::new();
+ o.raw_output = Some(RawOutput {
+ score: Some(ScoreOutputRaw {
+ scores: vec![0.5, 0.9],
+ item_ids: vec!["b".into(), "a".into()],
+ }),
+ ..Default::default()
+ });
+ let shaped = match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Shaped(s) => s,
+ _ => unreachable!(),
+ };
+ // Rust shaper sorts desc: a(0.9,rank=0), b(0.5,rank=1).
+ let expected =
+ build_score_payload(&[0.5, 0.9], &["b".to_string(), "a".to_string()]).unwrap();
+ assert_eq!(shaped.result_msgpack, expected);
+ }
+
+ #[test]
+ fn raw_output_shape_error_becomes_error_outcome() {
+ // Mismatched dim → shaper returns ShapeError, publisher
+ // must NOT panic; it downgrades to PublishErrorAndAck with
+ // a typed error code so the gateway surfaces the incident.
+ let mut o = outcome();
+ o.result_msgpack = Vec::new();
+ o.raw_output = Some(RawOutput {
+ dense: Some(DenseOutput {
+ values: vec![1.0, 2.0],
+ dim: 3,
+ normalize: false,
+ }),
+ ..Default::default()
+ });
+ let shaped = match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Shaped(s) => s,
+ _ => unreachable!(),
+ };
+ assert!(matches!(
+ shaped.disposition,
+ Disposition::PublishErrorAndAck
+ ));
+ assert!(shaped.result_msgpack.is_empty());
+ assert_eq!(shaped.error_code.as_deref(), Some("raw_output_shape_error"));
+ assert!(shaped
+ .error
+ .as_deref()
+ .unwrap_or("")
+ .contains("raw_output shape"));
+ }
+
+ #[test]
+ fn raw_output_with_preexisting_msgpack_is_not_reshaped() {
+ // Mixed wire: Python sent both legacy and raw_output.
+ // Trust the already-framed bytes — shaper treats this as
+ // a rolling-deploy wire artefact.
+ let mut o = outcome(); // legacy result_msgpack populated
+ o.raw_output = Some(RawOutput {
+ dense: Some(DenseOutput {
+ values: vec![9.0, 9.0, 9.0],
+ dim: 3,
+ normalize: false,
+ }),
+ ..Default::default()
+ });
+ match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Unchanged => {}
+ ShapeOutcome::Shaped(_) => panic!("must prefer pre-framed result_msgpack"),
+ }
+ }
+
+ #[test]
+ fn raw_output_on_error_disposition_is_ignored() {
+ // Defensive: Python shouldn't attach raw_output to an
+ // error disposition, but if it does we don't shape.
+ let mut o = outcome();
+ o.disposition = Disposition::PublishErrorAndAck;
+ o.result_msgpack = Vec::new();
+ o.error = Some("upstream".into());
+ o.raw_output = Some(RawOutput {
+ dense: Some(DenseOutput {
+ values: vec![1.0],
+ dim: 1,
+ normalize: false,
+ }),
+ ..Default::default()
+ });
+ match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Unchanged => {}
+ ShapeOutcome::Shaped(_) => {
+ panic!("must not run shaper on error outcomes; raw_output should be ignored")
+ }
+ }
+ }
+
+ #[test]
+ fn raw_output_sparse_is_shaped_into_msgpack() {
+ // End-to-end publisher hook for sparse: the Python side
+ // sends only the typed `SparseOutput`; the publisher must
+ // pack exactly the bytes the legacy `_wrap_encode_output`
+ // path produces so SDK decoders see zero change.
+ let mut o = outcome();
+ o.result_msgpack = Vec::new();
+ o.raw_output = Some(RawOutput {
+ sparse: Some(SparseOutput {
+ indices: vec![3, 7, 42],
+ values: vec![0.5, 1.5, 2.5],
+ dims: Some(30522),
+ }),
+ ..Default::default()
+ });
+ let shaped = match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Shaped(s) => s,
+ ShapeOutcome::Unchanged => panic!("expected raw_output sparse shaping"),
+ };
+ let expected = build_sparse_payload(&[3, 7, 42], &[0.5, 1.5, 2.5], Some(30522)).unwrap();
+ assert_eq!(shaped.result_msgpack, expected);
+ assert!(shaped.raw_output.is_none());
+ assert!(matches!(shaped.disposition, Disposition::PublishAndAck));
+ }
+
+ #[test]
+ fn raw_output_sparse_length_mismatch_becomes_error() {
+ // indices/values length parity is a hard invariant; if the
+ // Python gate somehow lets a mismatched payload through
+ // the publisher must surface a typed error rather than
+ // crash or publish garbage.
+ let mut o = outcome();
+ o.result_msgpack = Vec::new();
+ o.raw_output = Some(RawOutput {
+ sparse: Some(SparseOutput {
+ indices: vec![1, 2, 3],
+ values: vec![0.5], // mismatched
+ dims: None,
+ }),
+ ..Default::default()
+ });
+ let shaped = match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Shaped(s) => s,
+ _ => unreachable!(),
+ };
+ assert!(matches!(
+ shaped.disposition,
+ Disposition::PublishErrorAndAck
+ ));
+ assert_eq!(shaped.error_code.as_deref(), Some("raw_output_shape_error"));
+ }
+
+ #[test]
+ fn raw_output_multivector_is_shaped_into_msgpack() {
+ let mut o = outcome();
+ o.result_msgpack = Vec::new();
+ let values: Vec<f32> = (0..12).map(|i| i as f32).collect();
+ o.raw_output = Some(RawOutput {
+ multivector: Some(MultivectorOutput {
+ values: values.clone(),
+ num_tokens: 3,
+ token_dims: 4,
+ }),
+ ..Default::default()
+ });
+ let shaped = match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Shaped(s) => s,
+ ShapeOutcome::Unchanged => panic!("expected raw_output multivector shaping"),
+ };
+ let expected = build_multivector_payload(&values, 3, 4).unwrap();
+ assert_eq!(shaped.result_msgpack, expected);
+ }
+
+ #[test]
+ fn raw_output_empty_variant_becomes_error_outcome() {
+ // Forward-compat: a future Rust build sees RawOutput with
+ // no recognised variant populated (all None). Must surface
+ // as a typed error, not a silent empty success.
+ let mut o = outcome();
+ o.result_msgpack = Vec::new();
+ o.raw_output = Some(RawOutput::default());
+ let shaped = match shape_raw_output_for_wire(&o) {
+ ShapeOutcome::Shaped(s) => s,
+ _ => unreachable!(),
+ };
+ assert!(matches!(
+ shaped.disposition,
+ Disposition::PublishErrorAndAck
+ ));
+ assert_eq!(shaped.error_code.as_deref(), Some("raw_output_shape_error"));
+ }
+}
diff --git a/packages/sie_server_sidecar/src/readiness.rs b/packages/sie_server_sidecar/src/readiness.rs
new file mode 100644
index 000000000..ad44e02a3
--- /dev/null
+++ b/packages/sie_server_sidecar/src/readiness.rs
@@ -0,0 +1,393 @@
+//! Sidecar readiness state — backs the `/readyz` HTTP endpoint and
+//! moves the K8s readiness contract off the Python adapter.
+//!
+//! # What "ready" means
+//!
+//! The sidecar is **ready** iff:
+//!
+//! 1. **Handshake complete.** At least one `Ping` round-trip to the
+//! adapter has succeeded since process start. (Not "every model
+//! `EnsureModelReady`'d" — models load lazily on first batch and a
+//! pod can sit `Ready` for hours before its first inference. The
+//! handshake-only definition matches what
+//! `IpcServer.is_heartbeat_fresh` checks on the Python side.)
+//! 2. **Heartbeat fresh.** The most recent successful `Ping` was
+//! within `freshness_ms` of now (monotonic). The default freshness
+//! window is `ping_interval_ms * 3`; operators can
+//! widen it via `SIE_WORKER_READYZ_STALE_MULT`.
+//! 3. **Not draining.** SIGTERM has not yet been observed. Once
+//! drain begins we want K8s to pull the pod out of the service
+//! immediately so new traffic stops landing on a sidecar that is
+//! about to disappear; the heartbeat freshness check would catch
+//! this only after the heartbeat task has stopped, which is too
+//! late.
+//!
+//! # Plumbing
+//!
+//! [`Readiness`] is owned by [`crate::run`], shared by [`std::sync::Arc`] into:
+//!
+//! * `crate::spawn_heartbeat` — calls
+//! [`Readiness::record_ping_success`] after every successful
+//! `IpcClient::ping`.
+//! * [`crate::metrics::spawn_metrics_server`] — reads via
+//! [`Readiness::snapshot`] on every `GET /readyz`.
+//! * The `run()` shutdown path — calls [`Readiness::mark_draining`]
+//! the moment the pull loop exits (which is itself driven by the
+//! `Shutdown` signal).
+//!
+//! # Why not put `last_ping` inside `IpcClient`?
+//!
+//! The IPC client is a transport — it knows how to round-trip a
+//! frame, not what "the sidecar is healthy" means at the operational
+//! layer. Tests instantiate `IpcClient` in isolation against a stub
+//! server; we don't want those test pings to bump a global readiness
+//! clock. Having `Readiness` be an explicit type at the
+//! `lib::run`-orchestrator layer keeps the policy / mechanism split
+//! that the rest of this crate already follows.
+//!
+//! # Performance
+//!
+//! Probe traffic in production is roughly `1 Hz × N pods × replicas`
+//! plus the load-balancer's healthcheck. The probe path here is:
+//!
+//! * one `AtomicBool::load(Relaxed)` for the drain bit,
+//! * one `AtomicU64::load(Relaxed)` for the last-ping timestamp,
+//! * one `Instant::now()`,
+//! * arithmetic.
+//!
+//! No lock; no allocation on the ready path. The 503-with-reason
+//! path allocates a small `String`.
+
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::time::Instant;
+
+/// Multiplier applied to `ping_interval_ms` to compute the staleness
+/// threshold. Operators tune via `SIE_WORKER_READYZ_STALE_MULT`.
+pub const DEFAULT_STALE_MULT: u32 = 3;
+
+/// Sentinel used in the `last_ping_nanos` atomic to mean "no ping
+/// has succeeded yet". Picking 0 is safe because `last_ping_nanos`
+/// stores `Instant::now() - origin` where `origin` is captured at
+/// `Readiness::new` time *before* the heartbeat task is spawned, so
+/// any real ping will record a strictly positive value.
+const HANDSHAKE_PENDING: u64 = 0;
+
+/// Lock-free shared state for the sidecar's readiness signal.
+pub struct Readiness {
+ /// Anchor for the monotonic timestamp stored in
+ /// `last_ping_nanos`. We can't put an [`Instant`] inside an
+ /// atomic, so we serialise as nanos-since-origin.
+ ///
+ /// [`Instant`] is monotonic by construction: `Instant::now() -
+ /// origin` never goes backwards on the same machine, and a u64
+ /// nanosecond counter has 584 years of headroom from process
+ /// start, so we never have to think about wraparound.
+ origin: Instant,
+ /// `Instant::now() - origin` in nanoseconds at the moment of the
+ /// most recent successful `Ping`. `0` means "no successful ping
+ /// yet" (see [`HANDSHAKE_PENDING`]).
+ ///
+ /// Reads use `Ordering::Relaxed`: a delayed-but-eventually-
+ /// consistent observation is fine — the worst case is one extra
+ /// "still stale" probe before we report ready, and probe interval
+ /// is already O(seconds). We never need this load to synchronise
+ /// with any other field.
+ last_ping_nanos: AtomicU64,
+ /// Set the instant SIGTERM is observed. `/readyz` flips to
+ /// `503 draining` immediately so the K8s service stops sending
+ /// new traffic before the in-flight drain even starts to run
+ /// down.
+ draining: AtomicBool,
+ /// `now - last_ping <= freshness_ms` ⇒ heartbeat fresh.
+ ///
+ /// Captured once at construction; the spec describes it as
+ /// `ping_interval_ms * stale_mult` so a runtime mutation would
+ /// be a footgun (the heartbeat schedule is also fixed at
+ /// construction).
+ freshness_ms: u64,
+}
+
+impl Readiness {
+ /// Build a readiness handle whose freshness window is
+ /// `ping_interval_ms * stale_mult`, clamped to a sane minimum so
+ /// a misconfigured `stale_mult = 0` doesn't make the pod look
+ /// stale on the very tick after a successful ping.
+ ///
+ /// `stale_mult = 0` is treated as the default ([`DEFAULT_STALE_MULT`])
+ /// rather than rejected; the sidecar should boot even with weird
+ /// env-var values, with a log warning at the call site.
+ #[must_use]
+ pub fn new(ping_interval_ms: u64, stale_mult: u32) -> Self {
+ let mult = if stale_mult == 0 {
+ DEFAULT_STALE_MULT
+ } else {
+ stale_mult
+ };
+ // `as u64 * u64` can overflow with adversarial inputs
+ // (`u32::MAX * u64::MAX`); saturate to keep behaviour
+ // predictable. In practice both are O(thousands).
+ let freshness_ms = ping_interval_ms.saturating_mul(u64::from(mult));
+ Self {
+ origin: Instant::now(),
+ last_ping_nanos: AtomicU64::new(HANDSHAKE_PENDING),
+ draining: AtomicBool::new(false),
+ freshness_ms,
+ }
+ }
+
+ /// Freshness window in milliseconds. Exposed so the metrics
+ /// server can include it in the 503 reason string for operator
+ /// debugging.
+ #[must_use]
+ pub fn freshness_ms(&self) -> u64 {
+ self.freshness_ms
+ }
+
+ /// Called by the heartbeat task on a successful `IpcClient::ping`.
+ ///
+ /// Stores `Instant::now() - origin` as nanos in the shared
+ /// atomic. The first call moves us from "handshake pending" to
+ /// "fresh"; subsequent calls just refresh the stamp.
+ pub fn record_ping_success(&self) {
+ // `as u64` truncation is a non-issue: `Instant - origin`
+ // produces a value bounded by the process uptime, and u64
+ // nanos = ~584 years.
+ let nanos = self.origin.elapsed().as_nanos() as u64;
+ // `nanos == 0` is theoretically possible if this fires on
+ // the same nanosecond `origin` was captured (impossible on
+ // any clock with ns resolution but still: belt + braces
+ // because 0 is our sentinel). Bump to 1 in that case so the
+ // sentinel stays unambiguous.
+ let stamp = if nanos == HANDSHAKE_PENDING { 1 } else { nanos };
+ self.last_ping_nanos.store(stamp, Ordering::Relaxed);
+ }
+
+ /// Called when the worker observes its shutdown signal. Once
+ /// set, `/readyz` returns `503 draining` until process exit.
+ /// Idempotent.
+ pub fn mark_draining(&self) {
+ self.draining.store(true, Ordering::Relaxed);
+ }
+
+ /// Cheap point-in-time view of the readiness state. Returned by
+ /// value (no lock held) so the HTTP handler can format the
+ /// reason string at its leisure.
+ #[must_use]
+ pub fn snapshot(&self) -> ReadinessSnapshot {
+ let draining = self.draining.load(Ordering::Relaxed);
+ let last_ping_nanos = self.last_ping_nanos.load(Ordering::Relaxed);
+
+ let heartbeat_age_ms = if last_ping_nanos == HANDSHAKE_PENDING {
+ None
+ } else {
+ // Recompute `now` AFTER reading the atomic so we never
+ // produce a negative age. Subtraction can still
+ // theoretically underflow if `last_ping_nanos` was
+ // captured in a future tick (impossible without clock
+ // skew on a single machine), so we saturate.
+ let now_nanos = self.origin.elapsed().as_nanos() as u64;
+ let elapsed_nanos = now_nanos.saturating_sub(last_ping_nanos);
+ Some(elapsed_nanos / 1_000_000)
+ };
+
+ ReadinessSnapshot {
+ handshaked: last_ping_nanos != HANDSHAKE_PENDING,
+ heartbeat_age_ms,
+ freshness_ms: self.freshness_ms,
+ draining,
+ }
+ }
+}
+
+/// Point-in-time view returned by [`Readiness::snapshot`]. Carrying
+/// the freshness window inside the snapshot keeps the formatting
+/// logic close to the data and lets us surface it in the 503 body
+/// for operator debugging without a second atomic load.
+#[derive(Debug, Clone, Copy)]
+pub struct ReadinessSnapshot {
+ /// True iff at least one `Ping` has succeeded since process start.
+ pub handshaked: bool,
+ /// Milliseconds since the most recent successful ping, or `None`
+ /// if no ping has succeeded yet.
+ pub heartbeat_age_ms: Option<u64>,
+ /// Staleness threshold from [`Readiness::freshness_ms`].
+ pub freshness_ms: u64,
+ /// True iff [`Readiness::mark_draining`] has been called.
+ pub draining: bool,
+}
+
+impl ReadinessSnapshot {
+ /// Whole-of-state predicate: ready iff all three sub-conditions
+ /// hold. Mirrors the AND-gating documented at the module top.
+ #[must_use]
+ pub fn is_ready(&self) -> bool {
+ if self.draining {
+ return false;
+ }
+ match self.heartbeat_age_ms {
+ None => false,
+ Some(age) => age <= self.freshness_ms,
+ }
+ }
+
+ /// Human-readable reason the snapshot is *not* ready. Returns an
+ /// empty string when [`Self::is_ready`] is true; the caller is
+ /// expected to gate on `is_ready()` before calling. Format is
+ /// stable enough for `curl /readyz`, but operators should rely
+ /// on the HTTP status code, not the body, for automated checks.
+ #[must_use]
+ pub fn reason(&self) -> String {
+ if self.draining {
+ return "draining".to_owned();
+ }
+ match self.heartbeat_age_ms {
+ None => "handshake pending".to_owned(),
+ Some(age) if age > self.freshness_ms => format!(
+ "heartbeat stale ({age} ms ago, threshold {} ms)",
+ self.freshness_ms,
+ ),
+ Some(_) => String::new(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::Arc;
+
+ #[test]
+ fn fresh_readiness_is_handshake_pending() {
+ let r = Readiness::new(2_000, 3);
+ let snap = r.snapshot();
+ assert!(!snap.handshaked, "fresh: handshake must be pending");
+ assert!(!snap.is_ready(), "fresh: not ready");
+ assert_eq!(snap.reason(), "handshake pending");
+ assert_eq!(snap.heartbeat_age_ms, None);
+ assert_eq!(snap.freshness_ms, 6_000);
+ }
+
+ #[test]
+ fn record_ping_success_makes_us_ready() {
+ let r = Readiness::new(2_000, 3);
+ r.record_ping_success();
+ let snap = r.snapshot();
+ assert!(snap.handshaked);
+ assert!(snap.is_ready(), "just-pinged should be ready");
+ assert_eq!(snap.reason(), "");
+ // Age must be small but non-negative; can't assert exactly
+ // 0 because of clock granularity on slow runners.
+ assert!(snap.heartbeat_age_ms.unwrap() < 1_000);
+ }
+
+ #[test]
+ fn drain_flips_us_unready_immediately() {
+ let r = Readiness::new(2_000, 3);
+ r.record_ping_success();
+ assert!(r.snapshot().is_ready());
+ r.mark_draining();
+ let snap = r.snapshot();
+ assert!(!snap.is_ready(), "draining must beat freshness");
+ assert_eq!(snap.reason(), "draining");
+ assert!(
+ snap.handshaked,
+ "draining doesn't erase the handshake bit — operators may want to see we *did* connect"
+ );
+ }
+
+ #[test]
+ fn stale_heartbeat_reports_age_in_reason() {
+ // Pinned-in-time test: synthesise a stale stamp by computing
+ // an age larger than `freshness_ms` and seeding
+ // `last_ping_nanos` directly. We can't time-travel a real
+ // ping's `Instant::now()` reading, so we splice the value.
+ let r = Readiness::new(100, 1); // freshness = 100 ms
+ r.record_ping_success();
+
+ // Wait long enough that the recorded ping is stale.
+ std::thread::sleep(std::time::Duration::from_millis(150));
+
+ let snap = r.snapshot();
+ assert!(snap.handshaked);
+ assert!(
+ !snap.is_ready(),
+ "100ms freshness must reject 150ms-old ping"
+ );
+ let reason = snap.reason();
+ assert!(
+ reason.starts_with("heartbeat stale"),
+ "reason should call out staleness, got {reason:?}"
+ );
+ assert!(
+ reason.contains("threshold 100 ms"),
+ "reason must surface the configured threshold, got {reason:?}"
+ );
+ }
+
+ #[test]
+ fn zero_stale_mult_falls_back_to_default() {
+ // Misconfigured env (`SIE_WORKER_READYZ_STALE_MULT=0`) must
+ // not make the pod look stale on the next tick after a
+ // successful ping.
+ let r = Readiness::new(2_000, 0);
+ assert_eq!(r.freshness_ms, 2_000 * u64::from(DEFAULT_STALE_MULT));
+ }
+
+ #[test]
+ fn freshness_ms_does_not_overflow_on_adversarial_input() {
+ // u32::MAX * u64::MAX would overflow; we saturate.
+ let r = Readiness::new(u64::MAX, u32::MAX);
+ assert_eq!(r.freshness_ms, u64::MAX);
+ // And the snapshot path still works.
+ let _ = r.snapshot();
+ }
+
+ #[test]
+ fn snapshot_is_lock_free_and_thread_safe() {
+ // Smoke: hammer record_ping_success / snapshot from many
+ // threads. The struct is `Send + Sync` via its atomics, so
+ // this test is mostly insurance against accidental
+ // refactors that reintroduce a Mutex.
+ let r = Arc::new(Readiness::new(2_000, 3));
+
+ let mut handles = Vec::new();
+ for _ in 0..8 {
+ let r = Arc::clone(&r);
+ handles.push(std::thread::spawn(move || {
+ for _ in 0..1_000 {
+ r.record_ping_success();
+ let _ = r.snapshot();
+ }
+ }));
+ }
+ for h in handles {
+ h.join().unwrap();
+ }
+ let final_snap = r.snapshot();
+ assert!(final_snap.handshaked);
+ assert!(final_snap.is_ready());
+ }
+
+ #[test]
+ fn ping_with_zero_age_is_promoted_off_the_sentinel() {
+ // The `if nanos == HANDSHAKE_PENDING { 1 }` branch is
+ // theoretical — `Instant::now()` advances every call on
+ // any modern OS — but the safety belt matters because a
+ // false-positive "handshake pending" would cause a flapping
+ // pod to look unready forever. Pinning the branch with a
+ // unit test keeps the invariant load-bearing.
+ let r = Readiness::new(2_000, 3);
+ // Force the underlying atomic to the sentinel directly...
+ r.last_ping_nanos
+ .store(HANDSHAKE_PENDING, Ordering::Relaxed);
+ // ...then fake a "ping arrived at origin" by writing a 1
+ // through the same path record_ping_success would have
+ // taken on a clock that didn't advance. We can't easily
+ // simulate the pinned-clock case in pure user code, but we
+ // can pin the sentinel-promotion contract on a regular call
+ // since it always goes through the same branch.
+ r.record_ping_success();
+ let v = r.last_ping_nanos.load(Ordering::Relaxed);
+ assert_ne!(v, HANDSHAKE_PENDING, "post-ping must never equal sentinel");
+ }
+}
diff --git a/packages/sie_server_sidecar/src/scheduler/adaptive.rs b/packages/sie_server_sidecar/src/scheduler/adaptive.rs
new file mode 100644
index 000000000..ca90392f4
--- /dev/null
+++ b/packages/sie_server_sidecar/src/scheduler/adaptive.rs
@@ -0,0 +1,1799 @@
+//! [`AdaptiveBatchController`] — PI loop on `max_batch_wait_ms`,
+//! proportional controller on `max_batch_cost`, auto-calibrated
+//! `target_p50_ms`, and a starvation-recovery escape hatch.
+//!
+//! Ported from `sie_server/core/adaptive_batching.py` with **bit-exact
+//! PI math**: both sides run f64 on the same formulas, so a given
+//! input trace produces the same output trace ULP-for-ULP. The
+//! validation harness exploits this property to diff Python vs Rust from
+//! captured production traces.
+//!
+//! The controller is a pure synchronous state machine — it does not
+//! own any async primitives and is safe to call under a mutex. Wall
+//! clock reads go through [`std::time::Instant::now`]; tests pause
+//! the clock via [`tokio::time::pause`] where they need determinism,
+//! but the controller itself has no Tokio dependency.
+
+use std::time::Instant;
+
+use super::batch_config::BatchConfig;
+use crate::latency::LatencyTracker;
+
+/// Production floor for `min_wait_ms`. Python's config dataclass defaults
+/// lower, but `ModelWorker.__init__` raises the runtime floor before
+/// constructing the controller.
+///
+/// The wait floor and `PRODUCTION_MIN_COST_DIVISOR` jointly enforce a
+/// "no sustained single-item waves" invariant under saturation: if both
+/// floors collapse, the negative-headroom branch can keep shrinking batches
+/// while latency rises, preventing recovery.
+const PRODUCTION_MIN_WAIT_MS: f64 = 15.0;
+
+/// Python-parity production multiplier for the `cost_gain` field —
+/// `ModelWorker.__init__` sets `cost_gain = ab.gain * 0.5` so
+/// the cost knob is half as aggressive as the wait knob. The
+/// dataclass default 0.15 happens to coincide with `0.3 * 0.5` for
+/// the default `gain`, but coupling them explicitly keeps parity
+/// when an operator overrides `gain`.
+const PRODUCTION_COST_GAIN_RATIO: f64 = 0.5;
+
+/// Python-parity production multiplier for `max_batch_cost`'s ceiling.
+/// `ModelWorker.__init__` sets `max_batch_cost = max(cost_floor,
+/// max_batch_tokens * 4)` — gives the cost knob room to grow above
+/// the model's nominal `max_batch_tokens` when saturated.
+const PRODUCTION_MAX_COST_MULT: u64 = 4;
+
+/// Production divisor for `min_batch_cost`. Mirrors
+/// `ModelWorker.__init__`'s `max(256, max_batch_tokens // 4)` — the
+/// cost knob never collapses below ~25 % of the model's nominal budget.
+///
+/// With `max_batch_tokens = 16384`, the floor is 4096 tokens —
+/// roughly 10 items per forward at gte's ~400 tokens/item.
+///
+/// Why this matters: when the cost knob is allowed to fall to the bare
+/// 256-token dataclass floor, the PI loop can form one-item waves under
+/// negative headroom; `observed_p50` rises further and the loop diverges
+/// instead of recovering.
+///
+/// Together with `PRODUCTION_MIN_WAIT_MS`, this floor is a
+/// *stability feature*, not a tunable performance knob.
+const PRODUCTION_MIN_COST_DIVISOR: u64 = 4;
+
+/// Default latency window (inference-only tracker used for
+/// auto-calibration). Matches Python's
+/// `LatencyTracker(window_size=50, min_samples=10)`.
+const INFERENCE_TRACKER_WINDOW: usize = 50;
+const INFERENCE_TRACKER_MIN_SAMPLES: usize = 10;
+
+/// Cap on `dt` between controller steps — prevents a huge idle gap
+/// from dumping an enormous integral contribution into the next step.
+/// Matches Python's `min(now - _last_step_time, 5.0)`.
+const DT_CAP_SECS: f64 = 5.0;
+
+/// Dispatch between the production wall-clock path and the
+/// shadow-trace replay path in [`AdaptiveBatchController::step_impl`].
+/// See [`AdaptiveBatchController::step_replay`] for why the replay
+/// path is built on a separate f64 clock instead of [`Instant`].
+#[derive(Debug, Clone, Copy)]
+enum TimeSource {
+ Wall,
+ Replay,
+}
+
+/// When a step's `dt` exceeds this (seconds), decay the integrator
+/// by `0.5 ^ (dt - threshold)`. Mirrors Python's idle-decay block:
+/// `if dt_s > 2.0: decay = 0.5 ** (dt_s - 2.0)`.
+const IDLE_DECAY_THRESHOLD_SECS: f64 = 2.0;
+
+/// Immutable snapshot of controller state. Used by the WebSocket
+/// status and gateway health probes to expose controller internals
+/// without leaking the mutable struct.
+///
+/// Field-for-field parity with Python's `AdaptiveBatchState`.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct AdaptiveBatchState {
+ pub enabled: bool,
+ pub calibrated: bool,
+ pub target_p50_ms: Option<f64>,
+ pub current_wait_ms: f64,
+ pub current_batch_cost: u64,
+ pub observed_p50_ms: Option<f64>,
+ pub headroom_ms: Option<f64>,
+ pub fill_ratio: Option<f64>,
+ pub integral: f64,
+ pub starvation_streak: u32,
+ pub starvation_resets: u32,
+}
+
+/// PI controller plus companion proportional controller.
+///
+/// Constructed via [`AdaptiveBatchController::builder`] in tests /
+/// production; the plain `new` path uses Python-parity defaults
+/// everywhere.
+///
+/// ## Knobs
+///
+/// * `max_batch_wait_ms` — PI-controlled. Proportional on
+/// `headroom_ms`, integrator in `ms·s` time-normalised, clamped
+/// to `[min_wait_ms, max_wait_ms]`, saturation-aware anti-windup.
+/// * `max_batch_cost` — proportional-only, gated on
+/// `fill_ratio ≥ fill_ratio_threshold`. The gate behaves as a
+/// conditional integrator: only adjusts when the GPU is saturated.
+/// * `target_p50_ms` — either set explicitly (then `calibrated = true`
+/// from construction) or auto-derived as
+/// `inference_p50 × calibration_multiplier`, clamped to
+/// `[min_target_p50_ms, max_target_p50_ms]`.
+///
+/// ## Starvation recovery
+///
+/// Python's docs call out a pathological attractor: sustained
+/// above-target p50 can drive both knobs to their floors, at which
+/// point each batch becomes a single item, p50 stays high, and the
+/// loop is stuck. Recovery:
+///
+/// 1. Count consecutive batches where `batch_size ≤
+/// starvation_batch_size`.
+/// 2. If the streak hits `starvation_window` **and** both knobs are
+/// at their floors, hard-reset to a midway point between floors
+/// and the operator-provided initial values.
+/// 3. Zero the integrator and the step-time so the PI loop restarts
+/// from clean state.
+///
+/// The streak counter only advances when `step()` is called with
+/// `Some(batch_size)`. Idle ticks or legacy test callers that pass
+/// `None` are no-ops. Mirrors Python exactly.
+#[derive(Debug, Clone)]
+pub struct AdaptiveBatchController {
+ // ── Configuration (mirror of Python's field defaults) ──────────
+ target_p50_ms: Option<f64>,
+ pub calibration_multiplier: f64,
+ pub min_target_p50_ms: f64,
+ pub max_target_p50_ms: f64,
+
+ pub min_wait_ms: f64,
+ pub max_wait_ms: f64,
+
+ pub min_batch_cost: u64,
+ pub max_batch_cost: u64,
+
+ pub gain: f64,
+ pub integral_gain: f64,
+ pub cost_gain: f64,
+ pub update_interval: u32,
+ pub fill_ratio_threshold: f64,
+
+ pub starvation_recovery_enabled: bool,
+ pub starvation_window: u32,
+ pub starvation_batch_size: u32,
+
+ // ── Recovery anchors captured from the operator-provided start
+ // values — Python does this in `__post_init__`. ────────────────
+ initial_wait_ms: f64,
+ initial_batch_cost: u64,
+
+ // ── Runtime state ──────────────────────────────────────────────
+ current_wait_ms: f64,
+ current_batch_cost: u64,
+ steps_since_update: u32,
+
+ auto_calibrate: bool,
+ calibrated: bool,
+ inference_tracker: LatencyTracker,
+
+ integral: f64,
+ integral_max: f64,
+ last_step_time: Option<Instant>,
+
+ starvation_streak: u32,
+ starvation_resets: u32,
+
+ /// Virtual clock used only by [`Self::step_replay`]. Holds the
+ /// total `dt_s` accumulated across replay calls (in seconds, f64)
+ /// and the last-step snapshot that mirrors Python's
+ /// `_last_step_time`. Using raw f64 here — instead of an
+ /// [`Instant`] plus [`std::time::Duration`] — is deliberate:
+ /// [`Duration`] truncates to nanoseconds, which breaks ULP
+ /// identity with Python's `time.monotonic()` (a plain f64).
+ /// Never read by the wall-clock [`Self::step`] path.
+ replay_now_s: f64,
+ replay_last_step_s: Option<f64>,
+}
+
+impl AdaptiveBatchController {
+ /// Construct with Python-parity defaults, optionally overridden
+ /// by env vars. Used by `Scheduler::builder()` when no explicit
+ /// controller is supplied so every per-model scheduler picks up
+ /// the same operator knobs.
+ ///
+ /// # Env vars
+ ///
+ /// All vars are `f64` (or `u64` for cost) and *override the
+ /// matching field on top of the Python-parity default*. Unset =
+ /// use default. Bad values (non-numeric, NaN, etc.) are logged
+ /// and ignored — the controller falls back to defaults rather
+ /// than crashing.
+ ///
+ /// | Var | Field | Default | Production |
+ /// |-------------------------------------------|--------------------------|---------|------------|
+ /// | `SIE_ADAPTIVE_BATCH_MAX_WAIT_MS` | `max_wait_ms` | 50.0 | 50.0 |
+ /// | `SIE_ADAPTIVE_BATCH_MIN_WAIT_MS` | `min_wait_ms` | 1.0 | 15.0 |
+ /// | `SIE_ADAPTIVE_BATCH_INITIAL_WAIT_MS` | `initial_wait_ms` | 10.0 | 10.0 |
+ /// | `SIE_ADAPTIVE_BATCH_TARGET_P50_MS` | `target_p50_ms` | None | None |
+ /// | `SIE_ADAPTIVE_BATCH_MIN_TARGET_P50_MS` | `min_target_p50_ms` | 5.0 | 5.0 |
+ /// | `SIE_ADAPTIVE_BATCH_MAX_TARGET_P50_MS` | `max_target_p50_ms` | 500.0 | 500.0 |
+ /// | `SIE_ADAPTIVE_BATCH_CALIBRATION_MULT` | `calibration_multiplier` | 1.5 | 1.5 |
+ /// | `SIE_ADAPTIVE_BATCH_MAX_COST` | `max_batch_cost` | 65536 | `max(cost_floor, max_batch_tokens * 4)` |
+ /// | `SIE_ADAPTIVE_BATCH_MIN_COST` | `min_batch_cost` | 256 | `max(256, max_batch_tokens / 4)` |
+ /// | `SIE_ADAPTIVE_BATCH_INITIAL_COST` | `initial_batch_cost` | 16384 | 16384 |
+ ///
+ /// The production floor values are intentionally higher than the
+ /// dataclass-style defaults used in small unit tests. Lower wait/cost
+ /// floors make the controller more eager to flush tiny batches; change
+ /// them only with a fresh validation baseline.
+ ///
+ /// The `BATCH` infix distinguishes these from the existing
+ /// `SIE_ADAPTIVE_*_QUANTUM_MS` family, which control the NATS
+ /// fetch quantum (see [`crate::latency::FetchExpiryController`]).
+ #[must_use]
+ pub fn from_env_or_default() -> Self {
+ let mut c = Self::default();
+
+ fn get_f64(var: &str) -> Option<f64> {
+ std::env::var(var).ok().and_then(|s| {
+ s.parse::<f64>().ok().filter(|v| v.is_finite()).or_else(|| {
+ tracing::warn!(
+ var = var,
+ raw = s.as_str(),
+ "adaptive-batch env var: ignoring non-numeric/non-finite value"
+ );
+ None
+ })
+ })
+ }
+ fn get_u64(var: &str) -> Option<u64> {
+ std::env::var(var).ok().and_then(|s| s.parse::<u64>().ok())
+ }
+
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_MAX_WAIT_MS") {
+ c.max_wait_ms = v;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_MIN_WAIT_MS") {
+ c.min_wait_ms = v;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_INITIAL_WAIT_MS") {
+ c.initial_wait_ms = v;
+ c.current_wait_ms = clamp(v, c.min_wait_ms, c.max_wait_ms);
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_TARGET_P50_MS") {
+ c.target_p50_ms = Some(v);
+ c.auto_calibrate = false;
+ c.calibrated = true;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_MIN_TARGET_P50_MS") {
+ c.min_target_p50_ms = v;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_MAX_TARGET_P50_MS") {
+ c.max_target_p50_ms = v;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_CALIBRATION_MULT") {
+ c.calibration_multiplier = v;
+ }
+ if let Some(v) = get_u64("SIE_ADAPTIVE_BATCH_MAX_COST") {
+ c.max_batch_cost = v;
+ }
+ if let Some(v) = get_u64("SIE_ADAPTIVE_BATCH_MIN_COST") {
+ c.min_batch_cost = v;
+ }
+ if let Some(v) = get_u64("SIE_ADAPTIVE_BATCH_INITIAL_COST") {
+ c.initial_batch_cost = v;
+ c.current_batch_cost = clamp_u64(v, c.min_batch_cost, c.max_batch_cost);
+ }
+
+ // Re-clamp current values in case env vars compressed the
+ // bounds beneath the defaults.
+ c.current_wait_ms = clamp(c.current_wait_ms, c.min_wait_ms, c.max_wait_ms);
+ c.current_batch_cost = clamp_u64(c.current_batch_cost, c.min_batch_cost, c.max_batch_cost);
+
+ tracing::info!(
+ min_wait_ms = c.min_wait_ms,
+ max_wait_ms = c.max_wait_ms,
+ initial_wait_ms = c.initial_wait_ms,
+ current_wait_ms = c.current_wait_ms,
+ min_batch_cost = c.min_batch_cost,
+ max_batch_cost = c.max_batch_cost,
+ initial_batch_cost = c.initial_batch_cost,
+ target_p50_ms = ?c.target_p50_ms,
+ min_target_p50_ms = c.min_target_p50_ms,
+ max_target_p50_ms = c.max_target_p50_ms,
+ calibration_multiplier = c.calibration_multiplier,
+ auto_calibrate = c.auto_calibrate,
+ "adaptive-batch: controller constructed from env+defaults"
+ );
+
+ c
+ }
+
+ /// Construct with Python-parity defaults.
+ #[must_use]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Production-parity constructor: derive every field that
+ /// `sie_server/core/worker/model_worker.py::ModelWorker.__init__`
+ /// derives from `BatchConfig` + `AdaptiveBatchingConfig`, then
+ /// apply env-var overrides on top.
+ ///
+ /// Why this exists distinct from [`Self::from_env_or_default`]:
+ /// the bare dataclass defaults in [`Self::default`] mirror
+ /// Python's *module-level* defaults
+ /// (`adaptive_batching.AdaptiveBatchController` field defaults),
+ /// which are intentionally test-only floors. Production deploys
+ /// always go through `ModelWorker.__init__`, which substitutes:
+ ///
+ /// | Field | Python production wiring |
+ /// |-------------------|------------------------------------------------------------------|
+ /// | `min_wait_ms` | `ab.min_wait_ms` (engine default **15.0**) |
+ /// | `_current_wait_ms`| `cfg.max_batch_wait_ms` (default **15.0**) |
+ /// | `min_batch_cost` | `max(256, max_batch_tokens // 4)` — model-scaled |
+ /// | `max_batch_cost` | `max(cost_floor, max_batch_tokens * 4)` — model-scaled |
+ /// | `cost_gain` | `gain * 0.5` — coupled, not free |
+ /// | `_current_batch_cost` | `max_batch_tokens` (default **16_384**) |
+ ///
+ /// These production floors matter: deployed Python does not run the
+ /// low module-level defaults. If Rust falls back to those bare
+ /// values, the PI loop flushes tiny batches too eagerly under
+ /// saturation. Restoring the model-derived floors here is the
+ /// equivalent of the Python production constructor and is what every
+ /// deployed `ModelWorker` in `sie-internal` already runs.
+ ///
+ /// Env vars (`SIE_ADAPTIVE_BATCH_*`) are then applied on top of
+ /// the production-derived defaults — operators can still pin
+ /// individual knobs without recompiling. Production-parity is
+ /// the *fallback*, env is the *override*.
+ #[must_use]
+ #[allow(
+ clippy::field_reassign_with_default,
+ reason = "Sequential derivations from cfg are clearer step-by-step than \
+ inline struct-update syntax — cost_floor depends on \
+ max_batch_tokens, cost_ceiling depends on cost_floor, etc."
+ )]
+ pub fn from_batch_config(cfg: &BatchConfig) -> Self {
+ let mut c = Self::default();
+
+ // Wait-knob floor + initial value follow Python production.
+ c.min_wait_ms = PRODUCTION_MIN_WAIT_MS;
+ c.initial_wait_ms = cfg.max_batch_wait_ms;
+
+ // Cost-knob floor + ceiling are derived from the model's
+ // `max_batch_tokens` budget (= cfg.max_batch_cost in Rust).
+ // Python's expression captured here verbatim.
+ let max_batch_tokens = cfg.max_batch_cost;
+ let cost_floor = u64::max(256, max_batch_tokens / PRODUCTION_MIN_COST_DIVISOR);
+ let cost_floor = u64::min(cost_floor, max_batch_tokens.max(1));
+ let cost_ceiling = u64::max(
+ cost_floor,
+ max_batch_tokens.saturating_mul(PRODUCTION_MAX_COST_MULT),
+ );
+ c.min_batch_cost = cost_floor;
+ c.max_batch_cost = cost_ceiling;
+ c.initial_batch_cost = max_batch_tokens.max(cost_floor).min(cost_ceiling);
+
+ // Cost-knob gain coupled to wait-knob gain (Python
+ // `cost_gain = ab.gain * 0.5`).
+ c.cost_gain = c.gain * PRODUCTION_COST_GAIN_RATIO;
+
+ // Re-clamp current values into the new bounds before any
+ // step runs.
+ c.current_wait_ms = clamp(c.initial_wait_ms, c.min_wait_ms, c.max_wait_ms);
+ c.current_batch_cost = clamp_u64(c.initial_batch_cost, c.min_batch_cost, c.max_batch_cost);
+
+ c
+ }
+
+ /// Production-parity constructor with env-var overrides applied
+ /// on top. This is what [`super::SchedulerBuilder::build`] uses
+ /// when the operator hasn't supplied an explicit controller —
+ /// every deployed Rust scheduler picks up Python production
+ /// defaults plus operator env tuning in one shot.
+ #[must_use]
+ pub fn from_batch_config_and_env(cfg: &BatchConfig) -> Self {
+ let mut c = Self::from_batch_config(cfg);
+ Self::apply_env_overrides(&mut c);
+
+ tracing::info!(
+ min_wait_ms = c.min_wait_ms,
+ max_wait_ms = c.max_wait_ms,
+ initial_wait_ms = c.initial_wait_ms,
+ current_wait_ms = c.current_wait_ms,
+ min_batch_cost = c.min_batch_cost,
+ max_batch_cost = c.max_batch_cost,
+ initial_batch_cost = c.initial_batch_cost,
+ cost_gain = c.cost_gain,
+ target_p50_ms = ?c.target_p50_ms,
+ "adaptive-batch: controller constructed from BatchConfig+env (production-parity)"
+ );
+
+ c
+ }
+
+ /// Apply `SIE_ADAPTIVE_BATCH_*` env-var overrides to an already
+ /// constructed controller. Bad values log and fall through —
+ /// never crash.
+ fn apply_env_overrides(c: &mut Self) {
+ fn get_f64(var: &str) -> Option<f64> {
+ std::env::var(var).ok().and_then(|s| {
+ s.parse::<f64>().ok().filter(|v| v.is_finite()).or_else(|| {
+ tracing::warn!(
+ var = var,
+ raw = s.as_str(),
+ "adaptive-batch env var: ignoring non-numeric/non-finite value"
+ );
+ None
+ })
+ })
+ }
+ fn get_u64(var: &str) -> Option<u64> {
+ std::env::var(var).ok().and_then(|s| s.parse::<u64>().ok())
+ }
+
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_MAX_WAIT_MS") {
+ c.max_wait_ms = v;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_MIN_WAIT_MS") {
+ c.min_wait_ms = v;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_INITIAL_WAIT_MS") {
+ c.initial_wait_ms = v;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_TARGET_P50_MS") {
+ c.target_p50_ms = Some(v);
+ c.auto_calibrate = false;
+ c.calibrated = true;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_MIN_TARGET_P50_MS") {
+ c.min_target_p50_ms = v;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_MAX_TARGET_P50_MS") {
+ c.max_target_p50_ms = v;
+ }
+ if let Some(v) = get_f64("SIE_ADAPTIVE_BATCH_CALIBRATION_MULT") {
+ c.calibration_multiplier = v;
+ }
+ if let Some(v) = get_u64("SIE_ADAPTIVE_BATCH_MAX_COST") {
+ c.max_batch_cost = v;
+ }
+ if let Some(v) = get_u64("SIE_ADAPTIVE_BATCH_MIN_COST") {
+ c.min_batch_cost = v;
+ }
+ if let Some(v) = get_u64("SIE_ADAPTIVE_BATCH_INITIAL_COST") {
+ c.initial_batch_cost = v;
+ }
+
+ // Resolve floor/ceiling conflicts before clamping current
+ // values. If the operator's env-supplied ceiling sits below
+ // the production-parity floor (e.g.
+ // `SIE_ADAPTIVE_BATCH_MAX_WAIT_MS=10` with the new default
+ // `min_wait_ms = 15`), the more specific override wins:
+ // drag the floor down to the ceiling so the PI loop has a
+ // valid operating range. Without this guard `clamp(x, 15,
+ // 10) == 15` and the wait knob silently exceeds its declared
+ // cap.
+ if c.min_wait_ms > c.max_wait_ms {
+ tracing::warn!(
+ min_wait_ms = c.min_wait_ms,
+ max_wait_ms = c.max_wait_ms,
+ "adaptive-batch: min_wait_ms > max_wait_ms after env overrides; \
+ lowering floor to match ceiling"
+ );
+ c.min_wait_ms = c.max_wait_ms;
+ }
+ if c.min_batch_cost > c.max_batch_cost {
+ tracing::warn!(
+ min_batch_cost = c.min_batch_cost,
+ max_batch_cost = c.max_batch_cost,
+ "adaptive-batch: min_batch_cost > max_batch_cost after env overrides; \
+ lowering floor to match ceiling"
+ );
+ c.min_batch_cost = c.max_batch_cost;
+ }
+
+ // Re-clamp current values in case env vars compressed bounds
+ // beneath the production-derived defaults.
+ c.current_wait_ms = clamp(c.initial_wait_ms, c.min_wait_ms, c.max_wait_ms);
+ c.current_batch_cost = clamp_u64(c.initial_batch_cost, c.min_batch_cost, c.max_batch_cost);
+ }
+
+ /// Fluent builder. Prefer this over direct field assignment
+ /// because `initial_wait_ms` / `initial_batch_cost` are anchored
+ /// in `finish()` — bypassing the builder leaves the recovery
+ /// anchors zeroed.
+ #[must_use]
+ pub fn builder() -> AdaptiveBatchControllerBuilder {
+ AdaptiveBatchControllerBuilder::default()
+ }
+
+ // ---- Calibration / sampling ----
+
+ /// Record an inference-only latency sample. Consumed by the
+ /// auto-calibration path; once calibration completes, this is a
+ /// no-op (Python parity).
+ pub fn record_inference_sample(&mut self, inference_ms: f64) {
+ if !self.calibrated {
+ self.inference_tracker.record(inference_ms);
+ }
+ }
+
+ // ---- Main step ----
+
+ /// Advance the controller by one batch. Returns the caps the
+ /// batcher should now honour `(wait_ms, batch_cost)`.
+ ///
+ /// `observed_p50_ms` is the **total** p50 (queue + inference +
+ /// postprocess), fed from `LatencyTracker.record(total_ms)`
+ /// upstream. `fill_ratio` is the mean of
+ /// [`crate::scheduler::BatchEfficiencyTracker`]. `batch_size` is the size of the
+ /// batch whose completion triggered this step — required for
+ /// starvation tracking.
+ pub fn step(
+ &mut self,
+ observed_p50_ms: Option<f64>,
+ fill_ratio: Option<f64>,
+ batch_size: Option<usize>,
+ ) -> (f64, u64) {
+ self.step_impl(TimeSource::Wall, observed_p50_ms, fill_ratio, batch_size)
+ }
+
+ /// Deterministic variant of [`Self::step`] that bypasses
+ /// [`Instant::now`] by advancing an internal virtual f64-seconds
+ /// clock by `dt_s` before running the controller. Intended
+ /// **exclusively** for shadow-trace replay — see
+ /// `examples/replay_controller_trace.rs` and
+ /// `scripts/perf/replay-scheduler-trace.py`.
+ ///
+ /// The virtual clock advances on **every** call (including calls
+ /// that early-return under `update_interval`), matching the Python
+ /// semantics where `time.monotonic()` runs on every real-world
+ /// tick even though `_last_step_time` is only updated in the
+ /// branch that consumes `dt_s`. Using raw f64 seconds (rather than
+ /// an [`Instant`] + [`std::time::Duration`]) is deliberate:
+ /// `Duration` truncates to nanoseconds, which breaks ULP identity
+ /// against Python's `float - float` arithmetic on `time.monotonic()`.
+ ///
+ /// Production code must use [`Self::step`]; using this entry
+ /// point in the hot path would decouple the integrator from real
+ /// elapsed time and silently break the PI tuning.
+ #[doc(hidden)]
+ pub fn step_replay(
+ &mut self,
+ dt_s: f64,
+ observed_p50_ms: Option<f64>,
+ fill_ratio: Option<f64>,
+ batch_size: Option<usize>,
+ ) -> (f64, u64) {
+ self.replay_now_s += dt_s;
+ self.step_impl(TimeSource::Replay, observed_p50_ms, fill_ratio, batch_size)
+ }
+
+ fn step_impl(
+ &mut self,
+ time_source: TimeSource,
+ observed_p50_ms: Option<f64>,
+ fill_ratio: Option<f64>,
+ batch_size: Option<usize>,
+ ) -> (f64, u64) {
+ // Starvation counter runs on every call — it's a batch-rate
+ // signal, not a controller-rate one.
+ self.update_starvation_tracker(batch_size);
+
+ self.steps_since_update += 1;
+ if self.steps_since_update < self.update_interval {
+ return (self.current_wait_ms, self.current_batch_cost);
+ }
+ self.steps_since_update = 0;
+
+ // Auto-calibration branch: infer the target from observed
+ // backend latency until an explicit env target is set.
+ if !self.calibrated {
+ if let Some(inference_p50) = self.inference_tracker.p50() {
+ let t = clamp(
+ inference_p50 * self.calibration_multiplier,
+ self.min_target_p50_ms,
+ self.max_target_p50_ms,
+ );
+ self.target_p50_ms = Some(t);
+ self.calibrated = true;
+ self.integral = 0.0;
+ self.last_step_time = None;
+ self.replay_last_step_s = None;
+ tracing::info!(
+ target_p50_ms = t,
+ inference_p50_ms = inference_p50,
+ calibration_multiplier = self.calibration_multiplier,
+ min_target_p50_ms = self.min_target_p50_ms,
+ max_target_p50_ms = self.max_target_p50_ms,
+ "adaptive: auto-calibrated latency target"
+ );
+ }
+ // Hold knobs at initial values until calibrated.
+ return (self.current_wait_ms, self.current_batch_cost);
+ }
+
+ let (Some(observed), Some(target)) = (observed_p50_ms, self.target_p50_ms) else {
+ return (self.current_wait_ms, self.current_batch_cost);
+ };
+
+ // ── Starvation recovery runs *before* the PI update so a
+ // reset this step doesn't fight the math on the same tick. ─
+ if self.maybe_recover_from_starvation() {
+ return (self.current_wait_ms, self.current_batch_cost);
+ }
+
+ let headroom_ms = target - observed;
+ let headroom_frac = headroom_ms / target;
+
+ // ── dt for time-normalised integral ───────────────────────
+ // Two entry points: the production path sources `dt_s` from
+ // `Instant::now() - last_step_time`; the `step_replay` path
+ // uses a virtual f64-seconds clock so a Python and Rust run
+ // of the same trace agree ULP-for-ULP. See
+ // `step_replay`'s docstring for why f64 (not Duration) is
+ // mandatory for the replay side.
+ let dt_s = match time_source {
+ TimeSource::Wall => {
+ let now = Instant::now();
+ let dt = match self.last_step_time {
+ Some(prev) => {
+ let gap = now.saturating_duration_since(prev).as_secs_f64();
+ f64::min(gap, DT_CAP_SECS)
+ }
+ None => 0.0, // first step after calibration
+ };
+ self.last_step_time = Some(now);
+ dt
+ }
+ TimeSource::Replay => {
+ let now_s = self.replay_now_s;
+ let dt = match self.replay_last_step_s {
+ Some(prev) => f64::min(now_s - prev, DT_CAP_SECS),
+ None => 0.0,
+ };
+ self.replay_last_step_s = Some(now_s);
+ dt
+ }
+ };
+
+ // ── Idle decay (prevents stale error from bleeding into the
+ // next burst after a long pause). ─────────────────────────
+ if dt_s > IDLE_DECAY_THRESHOLD_SECS {
+ let decay = 0.5f64.powf(dt_s - IDLE_DECAY_THRESHOLD_SECS);
+ self.integral *= decay;
+ }
+
+ // ── Saturation-aware anti-windup on the wait knob ─────────
+ let output_at_max = self.current_wait_ms >= self.max_wait_ms;
+ let output_at_min = self.current_wait_ms <= self.min_wait_ms;
+
+ let mut can_integrate = true;
+ if output_at_max && headroom_ms > 0.0 {
+ can_integrate = false;
+ }
+ if output_at_min && headroom_ms < 0.0 {
+ can_integrate = false;
+ }
+ if can_integrate && self.integral_gain > 0.0 {
+ self.integral += headroom_ms * dt_s;
+ self.integral = clamp(self.integral, -self.integral_max, self.integral_max);
+ }
+
+ // ── Knob 1: wait ──────────────────────────────────────────
+ let wait_adjustment = headroom_ms * self.gain + self.integral * self.integral_gain;
+ let new_wait = self.current_wait_ms + wait_adjustment;
+ self.current_wait_ms = clamp(new_wait, self.min_wait_ms, self.max_wait_ms);
+
+ // ── Knob 2: cost (proportional, gated on fill_ratio) ──────
+ // Anti-windup mirrors the wait knob: don't push further into
+ // saturation in the direction the error wants. Without this,
+ // the cost collapses to `min_batch_cost` once p50 > target;
+ // see the regression doc referenced in the Python source.
+ if let Some(fill) = fill_ratio {
+ if fill >= self.fill_ratio_threshold {
+ let cost_at_max = self.current_batch_cost >= self.max_batch_cost;
+ let cost_at_min = self.current_batch_cost <= self.min_batch_cost;
+ let mut can_adjust = true;
+ if cost_at_max && headroom_ms > 0.0 {
+ can_adjust = false;
+ }
+ if cost_at_min && headroom_ms < 0.0 {
+ can_adjust = false;
+ }
+ if can_adjust {
+ let adj = self.current_batch_cost as f64 * headroom_frac * self.cost_gain;
+ let new_cost = self.current_batch_cost as f64 + adj;
+ let clamped = clamp(
+ new_cost,
+ self.min_batch_cost as f64,
+ self.max_batch_cost as f64,
+ );
+ // Python uses `int(clamp(...))` which truncates
+ // toward zero; f64 → u64 `as` conversion
+ // truncates identically for the non-negative
+ // range we clamp to.
+ self.current_batch_cost = clamped as u64;
+ }
+ }
+ }
+
+ tracing::debug!(
+ observed_p50_ms = observed,
+ target_p50_ms = target,
+ headroom_ms,
+ integral = self.integral,
+ fill_ratio = fill_ratio.unwrap_or(0.0),
+ current_wait_ms = self.current_wait_ms,
+ current_batch_cost = self.current_batch_cost,
+ starvation_streak = self.starvation_streak,
+ "adaptive: step"
+ );
+
+ (self.current_wait_ms, self.current_batch_cost)
+ }
+
+ // ---- Starvation detector helpers ----
+
+ fn update_starvation_tracker(&mut self, batch_size: Option<usize>) {
+ let Some(size) = batch_size else {
+ return;
+ };
+ if size > self.starvation_batch_size as usize {
+ self.starvation_streak = 0;
+ } else {
+ self.starvation_streak = self.starvation_streak.saturating_add(1);
+ }
+ }
+
+ fn maybe_recover_from_starvation(&mut self) -> bool {
+ if !self.starvation_recovery_enabled {
+ return false;
+ }
+ if self.starvation_streak < self.starvation_window {
+ return false;
+ }
+ let at_wait_floor = self.current_wait_ms <= self.min_wait_ms;
+ let at_cost_floor = self.current_batch_cost <= self.min_batch_cost;
+ if !(at_wait_floor && at_cost_floor) {
+ return false;
+ }
+
+ let recovery_wait = clamp(
+ (self.min_wait_ms + self.initial_wait_ms) / 2.0,
+ self.min_wait_ms,
+ self.max_wait_ms,
+ );
+ // Mirrors Python: max(initial // 2, min_cost * 4), then clamp.
+ // `initial_batch_cost / 2` is integer division in Python
+ // (`//`); same in u64 here.
+ let candidate = std::cmp::max(
+ self.initial_batch_cost / 2,
+ self.min_batch_cost.saturating_mul(4),
+ );
+ let recovery_cost = clamp(
+ candidate as f64,
+ self.min_batch_cost as f64,
+ self.max_batch_cost as f64,
+ ) as u64;
+
+ tracing::warn!(
+ streak = self.starvation_streak,
+ starvation_batch_size = self.starvation_batch_size,
+ old_wait_ms = self.current_wait_ms,
+ old_cost = self.current_batch_cost,
+ recovery_wait_ms = recovery_wait,
+ recovery_cost,
+ "adaptive: starvation recovery triggered"
+ );
+
+ self.current_wait_ms = recovery_wait;
+ self.current_batch_cost = recovery_cost;
+ self.integral = 0.0;
+ self.last_step_time = None;
+ self.replay_last_step_s = None;
+ self.starvation_streak = 0;
+ self.starvation_resets = self.starvation_resets.saturating_add(1);
+ true
+ }
+
+ // ---- Snapshots / accessors ----
+
+ #[must_use]
+ pub fn current_wait_ms(&self) -> f64 {
+ self.current_wait_ms
+ }
+
+ #[must_use]
+ pub fn current_batch_cost(&self) -> u64 {
+ self.current_batch_cost
+ }
+
+ #[must_use]
+ pub fn calibrated(&self) -> bool {
+ self.calibrated
+ }
+
+ #[must_use]
+ pub fn target_p50_ms(&self) -> Option<f64> {
+ self.target_p50_ms
+ }
+
+ #[must_use]
+ pub fn starvation_streak(&self) -> u32 {
+ self.starvation_streak
+ }
+
+ #[must_use]
+ pub fn starvation_resets(&self) -> u32 {
+ self.starvation_resets
+ }
+
+ #[must_use]
+ pub fn snapshot(
+ &self,
+ observed_p50_ms: Option<f64>,
+ fill_ratio: Option<f64>,
+ ) -> AdaptiveBatchState {
+ let headroom = match (self.target_p50_ms, observed_p50_ms) {
+ (Some(t), Some(o)) => Some(t - o),
+ _ => None,
+ };
+ AdaptiveBatchState {
+ enabled: true,
+ calibrated: self.calibrated,
+ target_p50_ms: self.target_p50_ms,
+ current_wait_ms: self.current_wait_ms,
+ current_batch_cost: self.current_batch_cost,
+ observed_p50_ms,
+ headroom_ms: headroom,
+ fill_ratio,
+ integral: self.integral,
+ starvation_streak: self.starvation_streak,
+ starvation_resets: self.starvation_resets,
+ }
+ }
+
+ /// Reset to operator-provided initial state.
+ ///
+ /// If the controller was constructed in auto-calibrate mode,
+ /// `target_p50_ms` and `calibrated` are cleared so the next
+ /// inference-sample stream can re-derive the target. If a
+ /// target was set explicitly, calibration state is preserved.
+ ///
+ /// `starvation_resets` is deliberately *not* cleared — it's a
+ /// monotonic operational counter (scraped by Prometheus) and
+ /// resetting it would erase evidence of incidents.
+ pub fn reset(&mut self) {
+ self.current_wait_ms = clamp(self.initial_wait_ms, self.min_wait_ms, self.max_wait_ms);
+ self.current_batch_cost = clamp(
+ self.initial_batch_cost as f64,
+ self.min_batch_cost as f64,
+ self.max_batch_cost as f64,
+ ) as u64;
+ self.steps_since_update = 0;
+ self.integral = 0.0;
+ self.last_step_time = None;
+ self.replay_now_s = 0.0;
+ self.replay_last_step_s = None;
+ self.starvation_streak = 0;
+ if self.auto_calibrate {
+ self.calibrated = false;
+ self.target_p50_ms = None;
+ self.inference_tracker.reset();
+ }
+ }
+}
+
+impl Default for AdaptiveBatchController {
+ fn default() -> Self {
+ // Mirrors Python's dataclass field defaults exactly. Tests
+ // pin every value so this can't drift silently.
+ let initial_wait_ms = 10.0;
+ let initial_batch_cost: u64 = 16_384;
+
+ Self {
+ target_p50_ms: None,
+ calibration_multiplier: 1.5,
+ min_target_p50_ms: 5.0,
+ max_target_p50_ms: 500.0,
+
+ min_wait_ms: 1.0,
+ max_wait_ms: 50.0,
+
+ min_batch_cost: 256,
+ max_batch_cost: 65_536,
+
+ gain: 0.3,
+ integral_gain: 0.05,
+ cost_gain: 0.15,
+ update_interval: 10,
+ fill_ratio_threshold: 0.7,
+
+ starvation_recovery_enabled: true,
+ starvation_window: 20,
+ starvation_batch_size: 1,
+
+ initial_wait_ms,
+ initial_batch_cost,
+
+ current_wait_ms: initial_wait_ms,
+ current_batch_cost: initial_batch_cost,
+ steps_since_update: 0,
+
+ auto_calibrate: true, // because `target_p50_ms == None`
+ calibrated: false,
+
+ inference_tracker: LatencyTracker::new(
+ INFERENCE_TRACKER_WINDOW,
+ INFERENCE_TRACKER_MIN_SAMPLES,
+ ),
+
+ integral: 0.0,
+ integral_max: 20.0,
+ last_step_time: None,
+
+ starvation_streak: 0,
+ starvation_resets: 0,
+
+ replay_now_s: 0.0,
+ replay_last_step_s: None,
+ }
+ }
+}
+
+// ---- Builder ----
+
+/// Builder for [`AdaptiveBatchController`].
+///
+/// All fields default to the same Python-parity values as
+/// [`AdaptiveBatchController::default`]. Fields set via the builder
+/// override those defaults; everything else stays at parity.
+#[derive(Debug, Clone, Default)]
+pub struct AdaptiveBatchControllerBuilder {
+ target_p50_ms: Option<Option<f64>>, // double-Option: outer=unset, inner=explicit None
+ calibration_multiplier: Option<f64>,
+ min_target_p50_ms: Option<f64>,
+ max_target_p50_ms: Option<f64>,
+ min_wait_ms: Option<f64>,
+ max_wait_ms: Option<f64>,
+ min_batch_cost: Option<u64>,
+ max_batch_cost: Option<u64>,
+ gain: Option<f64>,
+ integral_gain: Option<f64>,
+ cost_gain: Option<f64>,
+ update_interval: Option<u32>,
+ fill_ratio_threshold: Option<f64>,
+ starvation_recovery_enabled: Option<bool>,
+ starvation_window: Option<u32>,
+ starvation_batch_size: Option<u32>,
+ initial_wait_ms: Option<f64>,
+ initial_batch_cost: Option<u64>,
+}
+
+macro_rules! builder_setter {
+ ($name:ident, $ty:ty) => {
+ #[must_use]
+ pub fn $name(mut self, v: $ty) -> Self {
+ self.$name = Some(v);
+ self
+ }
+ };
+}
+
+impl AdaptiveBatchControllerBuilder {
+ pub fn target_p50_ms(mut self, v: Option<f64>) -> Self {
+ self.target_p50_ms = Some(v);
+ self
+ }
+
+ builder_setter!(calibration_multiplier, f64);
+ builder_setter!(min_target_p50_ms, f64);
+ builder_setter!(max_target_p50_ms, f64);
+ builder_setter!(min_wait_ms, f64);
+ builder_setter!(max_wait_ms, f64);
+ builder_setter!(min_batch_cost, u64);
+ builder_setter!(max_batch_cost, u64);
+ builder_setter!(gain, f64);
+ builder_setter!(integral_gain, f64);
+ builder_setter!(cost_gain, f64);
+ builder_setter!(update_interval, u32);
+ builder_setter!(fill_ratio_threshold, f64);
+ builder_setter!(starvation_recovery_enabled, bool);
+ builder_setter!(starvation_window, u32);
+ builder_setter!(starvation_batch_size, u32);
+ builder_setter!(initial_wait_ms, f64);
+ builder_setter!(initial_batch_cost, u64);
+
+ #[must_use]
+ pub fn build(self) -> AdaptiveBatchController {
+ let mut c = AdaptiveBatchController::default();
+ if let Some(v) = self.target_p50_ms {
+ c.target_p50_ms = v;
+ c.auto_calibrate = v.is_none();
+ c.calibrated = v.is_some();
+ }
+ if let Some(v) = self.calibration_multiplier {
+ c.calibration_multiplier = v;
+ }
+ if let Some(v) = self.min_target_p50_ms {
+ c.min_target_p50_ms = v;
+ }
+ if let Some(v) = self.max_target_p50_ms {
+ c.max_target_p50_ms = v;
+ }
+ if let Some(v) = self.min_wait_ms {
+ c.min_wait_ms = v;
+ }
+ if let Some(v) = self.max_wait_ms {
+ c.max_wait_ms = v;
+ }
+ if let Some(v) = self.min_batch_cost {
+ c.min_batch_cost = v;
+ }
+ if let Some(v) = self.max_batch_cost {
+ c.max_batch_cost = v;
+ }
+ if let Some(v) = self.gain {
+ c.gain = v;
+ }
+ if let Some(v) = self.integral_gain {
+ c.integral_gain = v;
+ }
+ if let Some(v) = self.cost_gain {
+ c.cost_gain = v;
+ }
+ if let Some(v) = self.update_interval {
+ c.update_interval = v;
+ }
+ if let Some(v) = self.fill_ratio_threshold {
+ c.fill_ratio_threshold = v;
+ }
+ if let Some(v) = self.starvation_recovery_enabled {
+ c.starvation_recovery_enabled = v;
+ }
+ if let Some(v) = self.starvation_window {
+ c.starvation_window = v;
+ }
+ if let Some(v) = self.starvation_batch_size {
+ c.starvation_batch_size = v;
+ }
+ if let Some(v) = self.initial_wait_ms {
+ c.initial_wait_ms = v;
+ c.current_wait_ms = v;
+ }
+ if let Some(v) = self.initial_batch_cost {
+ c.initial_batch_cost = v;
+ c.current_batch_cost = v;
+ }
+ c
+ }
+}
+
+fn clamp(value: f64, lo: f64, hi: f64) -> f64 {
+ f64::max(lo, f64::min(hi, value))
+}
+
+fn clamp_u64(value: u64, lo: u64, hi: u64) -> u64 {
+ value.clamp(lo, hi)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Duration;
+
+ fn make_explicit_target(target: f64) -> AdaptiveBatchController {
+ AdaptiveBatchController::builder()
+ .target_p50_ms(Some(target))
+ .update_interval(1) // step on every call in tests
+ .build()
+ }
+
+ #[test]
+ fn default_uses_python_parity_values() {
+ let c = AdaptiveBatchController::default();
+ assert!((c.calibration_multiplier - 1.5).abs() < f64::EPSILON);
+ assert!((c.min_target_p50_ms - 5.0).abs() < f64::EPSILON);
+ assert!((c.max_target_p50_ms - 500.0).abs() < f64::EPSILON);
+ assert_eq!(c.min_batch_cost, 256);
+ assert_eq!(c.max_batch_cost, 65_536);
+ assert!((c.gain - 0.3).abs() < f64::EPSILON);
+ assert!((c.integral_gain - 0.05).abs() < f64::EPSILON);
+ assert!((c.cost_gain - 0.15).abs() < f64::EPSILON);
+ assert_eq!(c.update_interval, 10);
+ assert_eq!(c.starvation_window, 20);
+ assert_eq!(c.starvation_batch_size, 1);
+ assert!(c.auto_calibrate);
+ assert!(!c.calibrated);
+ assert_eq!(c.current_wait_ms, c.initial_wait_ms);
+ assert_eq!(c.current_batch_cost, c.initial_batch_cost);
+ }
+
+ /// Helper: run `f` with a stable, isolated env. Writes to a
+ /// process-wide table so the body must not touch any other env
+ /// vars that another test could be reading concurrently — here
+ /// we serialise via a `parking_lot::Mutex` shared across env
+ /// tests to keep `cargo test --jobs` deterministic.
+ fn with_env_lock(f: impl FnOnce()) {
+ // Use a static mutex so concurrent tests don't trample each
+ // other's env. `std::sync::Mutex` is sufficient — the env
+ // ops are sub-microsecond and we never hold across an
+ // `await`.
+ static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
+ let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
+ f();
+ }
+
+ fn clear_env() {
+ for v in [
+ "SIE_ADAPTIVE_BATCH_MAX_WAIT_MS",
+ "SIE_ADAPTIVE_BATCH_MIN_WAIT_MS",
+ "SIE_ADAPTIVE_BATCH_INITIAL_WAIT_MS",
+ "SIE_ADAPTIVE_BATCH_TARGET_P50_MS",
+ "SIE_ADAPTIVE_BATCH_MIN_TARGET_P50_MS",
+ "SIE_ADAPTIVE_BATCH_MAX_TARGET_P50_MS",
+ "SIE_ADAPTIVE_BATCH_CALIBRATION_MULT",
+ "SIE_ADAPTIVE_BATCH_MAX_COST",
+ "SIE_ADAPTIVE_BATCH_MIN_COST",
+ "SIE_ADAPTIVE_BATCH_INITIAL_COST",
+ ] {
+ // SAFETY: env mutation is unsafe in 2024-edition; the
+ // surrounding `with_env_lock` serialises all callers.
+ unsafe { std::env::remove_var(v) };
+ }
+ }
+
+ #[test]
+ fn from_env_or_default_no_env_matches_default() {
+ with_env_lock(|| {
+ clear_env();
+ let c = AdaptiveBatchController::from_env_or_default();
+ let d = AdaptiveBatchController::default();
+ assert!((c.max_wait_ms - d.max_wait_ms).abs() < f64::EPSILON);
+ assert!((c.min_wait_ms - d.min_wait_ms).abs() < f64::EPSILON);
+ assert!((c.initial_wait_ms - d.initial_wait_ms).abs() < f64::EPSILON);
+ assert_eq!(c.max_batch_cost, d.max_batch_cost);
+ assert_eq!(c.target_p50_ms, d.target_p50_ms);
+ assert_eq!(c.auto_calibrate, d.auto_calibrate);
+ });
+ }
+
+ #[test]
+ fn from_env_or_default_overrides_max_wait_ms() {
+ // Cap the controller's wait knob at 10 ms and ensure the
+ // current value is clamped with it.
+ with_env_lock(|| {
+ clear_env();
+ unsafe { std::env::set_var("SIE_ADAPTIVE_BATCH_MAX_WAIT_MS", "10.0") };
+ let c = AdaptiveBatchController::from_env_or_default();
+ assert!((c.max_wait_ms - 10.0).abs() < f64::EPSILON);
+ // current_wait_ms (init = 10.0) is at the new ceiling
+ // post-clamp — fine, it just means the first PI step
+ // can only push it down.
+ assert!((c.current_wait_ms - 10.0).abs() < f64::EPSILON);
+ clear_env();
+ });
+ }
+
+ #[test]
+ fn from_env_or_default_target_p50_disables_autocalibration() {
+ // Setting an explicit target via env makes the controller
+ // skip inference-tracker calibration entirely — useful when
+ // we already know the steady-state inference time and want
+ // deterministic startup.
+ with_env_lock(|| {
+ clear_env();
+ unsafe { std::env::set_var("SIE_ADAPTIVE_BATCH_TARGET_P50_MS", "45.0") };
+ let c = AdaptiveBatchController::from_env_or_default();
+ assert_eq!(c.target_p50_ms, Some(45.0));
+ assert!(!c.auto_calibrate);
+ assert!(c.calibrated);
+ clear_env();
+ });
+ }
+
+ #[test]
+ fn from_env_or_default_clamps_initial_to_new_max() {
+ // If the operator drops max_wait below the default initial
+ // value (10 ms), the constructor must clamp current_wait
+ // down — otherwise the first batch sees a wait larger than
+ // its declared ceiling and the PI loop fights it.
+ with_env_lock(|| {
+ clear_env();
+ unsafe { std::env::set_var("SIE_ADAPTIVE_BATCH_MAX_WAIT_MS", "5.0") };
+ let c = AdaptiveBatchController::from_env_or_default();
+ assert!((c.max_wait_ms - 5.0).abs() < f64::EPSILON);
+ assert!(c.current_wait_ms <= c.max_wait_ms);
+ clear_env();
+ });
+ }
+
+ #[test]
+ fn from_env_or_default_ignores_garbage_values() {
+ // Operator typo (eg. `SIE_ADAPTIVE_BATCH_MAX_WAIT_MS=ten`)
+ // must not crash worker init — log + fall back to default.
+ with_env_lock(|| {
+ clear_env();
+ unsafe { std::env::set_var("SIE_ADAPTIVE_BATCH_MAX_WAIT_MS", "not-a-number") };
+ unsafe { std::env::set_var("SIE_ADAPTIVE_BATCH_INITIAL_WAIT_MS", "NaN") };
+ let c = AdaptiveBatchController::from_env_or_default();
+ // Both garbage env vars dropped → defaults preserved.
+ assert!((c.max_wait_ms - 50.0).abs() < f64::EPSILON);
+ assert!((c.initial_wait_ms - 10.0).abs() < f64::EPSILON);
+ clear_env();
+ });
+ }
+
+ #[test]
+ fn from_env_or_default_overrides_calibration_knobs() {
+ // Raise the auto-calibration floor / multiplier so cold-start
+ // GPU samples do not pin `target_p50_ms` too low and force the
+ // controller to permanently shrink batches under load.
+ with_env_lock(|| {
+ clear_env();
+ unsafe { std::env::set_var("SIE_ADAPTIVE_BATCH_MIN_TARGET_P50_MS", "50.0") };
+ unsafe { std::env::set_var("SIE_ADAPTIVE_BATCH_MAX_TARGET_P50_MS", "300.0") };
+ unsafe { std::env::set_var("SIE_ADAPTIVE_BATCH_CALIBRATION_MULT", "2.5") };
+ let c = AdaptiveBatchController::from_env_or_default();
+ assert!((c.min_target_p50_ms - 50.0).abs() < f64::EPSILON);
+ assert!((c.max_target_p50_ms - 300.0).abs() < f64::EPSILON);
+ assert!((c.calibration_multiplier - 2.5).abs() < f64::EPSILON);
+ // Auto-calibration still on (no explicit target set).
+ assert!(c.auto_calibrate);
+ clear_env();
+ });
+ }
+
+ // ---- Production-parity wiring (`from_batch_config*`) ----
+
+ #[test]
+ fn from_batch_config_uses_python_production_floors() {
+ // Mirror Python `ModelWorker.__init__` exactly:
+ // min_wait_ms = ab.min_wait_ms (engine default 15.0)
+ // _current_wait_ms = cfg.max_batch_wait_ms (default 15.0)
+ // min_batch_cost = max(256, max_batch_tokens // 4)
+ // max_batch_cost = max(cost_floor, max_batch_tokens * 4)
+ // cost_gain = ab.gain * 0.5
+ // _current_batch_cost = max_batch_tokens
+ let cfg = BatchConfig::default(); // max_batch_cost = 16_384, max_batch_wait_ms = 15.0
+ let c = AdaptiveBatchController::from_batch_config(&cfg);
+
+ assert!(
+ (c.min_wait_ms - 15.0).abs() < f64::EPSILON,
+ "min_wait_ms should match Python production (15.0), got {}",
+ c.min_wait_ms
+ );
+ assert!(
+ (c.initial_wait_ms - 15.0).abs() < f64::EPSILON,
+ "initial_wait_ms should equal cfg.max_batch_wait_ms (15.0)"
+ );
+ assert!(
+ (c.current_wait_ms - 15.0).abs() < f64::EPSILON,
+ "current_wait_ms should be initialised to initial_wait_ms"
+ );
+ assert_eq!(
+ c.min_batch_cost, 4_096,
+ "min_batch_cost should equal max_batch_tokens / 4 = 16384/4 = 4096"
+ );
+ assert_eq!(
+ c.max_batch_cost, 65_536,
+ "max_batch_cost should equal max_batch_tokens * 4 = 16384*4 = 65536"
+ );
+ assert_eq!(
+ c.initial_batch_cost, 16_384,
+ "initial_batch_cost should equal max_batch_tokens"
+ );
+ assert!(
+ (c.cost_gain - (c.gain * 0.5)).abs() < f64::EPSILON,
+ "cost_gain should be coupled to gain * 0.5 (Python production wiring)"
+ );
+ }
+
+ #[test]
+ fn from_batch_config_min_cost_floor_at_256_for_tiny_models() {
+ // Tiny model with max_batch_tokens=512: 512/4 = 128, but the
+ // Python floor is `max(256, max_batch_tokens // 4)` so the
+ // floor must clamp to 256 here. Then the further `min(floor,
+ // max_batch_tokens)` keeps it from exceeding the model
+ // budget itself.
+ let cfg = BatchConfig {
+ max_batch_cost: 512,
+ ..BatchConfig::default()
+ };
+ let c = AdaptiveBatchController::from_batch_config(&cfg);
+ assert_eq!(c.min_batch_cost, 256, "tiny-model floor clamps up to 256");
+ assert_eq!(
+ c.max_batch_cost, 2_048,
+ "max_batch_cost = max_batch_tokens * 4"
+ );
+ }
+
+ #[test]
+ fn from_batch_config_min_cost_clamps_to_budget_for_micro_models() {
+ // Pathological model with max_batch_tokens=128: 128/4 = 32,
+ // floor would clamp to 256 — but Python guards this with
+ // `min(cost_floor, max_batch_tokens)` so the floor never
+ // exceeds the model's own budget. Mirror that guard here.
+ let cfg = BatchConfig {
+ max_batch_cost: 128,
+ ..BatchConfig::default()
+ };
+ let c = AdaptiveBatchController::from_batch_config(&cfg);
+ assert_eq!(
+ c.min_batch_cost, 128,
+ "floor must not exceed max_batch_tokens for micro models"
+ );
+ assert_eq!(
+ c.max_batch_cost, 512,
+ "max_batch_cost = max_batch_tokens * 4 for micro models"
+ );
+ }
+
+ #[test]
+ fn from_batch_config_uses_cfg_max_batch_wait_ms() {
+ // Operator who tunes `BatchConfig.max_batch_wait_ms` via
+ // `SIE_BATCHER_MAX_BATCH_WAIT_MS` should see the controller's
+ // initial wait pick that value up — Python's
+ // `_current_wait_ms = self._config.max_batch_wait_ms`
+ // captures the relationship.
+ let cfg = BatchConfig {
+ max_batch_wait_ms: 25.0,
+ ..BatchConfig::default()
+ };
+ let c = AdaptiveBatchController::from_batch_config(&cfg);
+ assert!((c.initial_wait_ms - 25.0).abs() < f64::EPSILON);
+ assert!((c.current_wait_ms - 25.0).abs() < f64::EPSILON);
+ }
+
+ #[test]
+ fn from_batch_config_and_env_no_env_matches_from_batch_config() {
+ // With no env vars set, env-overlay constructor and bare
+ // production-parity constructor must agree exactly.
+ with_env_lock(|| {
+ clear_env();
+ let cfg = BatchConfig::default();
+ let bare = AdaptiveBatchController::from_batch_config(&cfg);
+ let with_env = AdaptiveBatchController::from_batch_config_and_env(&cfg);
+
+ assert!((bare.min_wait_ms - with_env.min_wait_ms).abs() < f64::EPSILON);
+ assert!((bare.initial_wait_ms - with_env.initial_wait_ms).abs() < f64::EPSILON);
+ assert!((bare.current_wait_ms - with_env.current_wait_ms).abs() < f64::EPSILON);
+ assert_eq!(bare.min_batch_cost, with_env.min_batch_cost);
+ assert_eq!(bare.max_batch_cost, with_env.max_batch_cost);
+ assert!((bare.cost_gain - with_env.cost_gain).abs() < f64::EPSILON);
+ });
+ }
+
+ #[test]
+ fn from_batch_config_and_env_max_wait_overrides_production_default() {
+ // `SIE_ADAPTIVE_BATCH_MAX_WAIT_MS=10` must override the
+ // production-parity default (50.0) and clamp `current_wait_ms`
+ // down accordingly.
+ with_env_lock(|| {
+ clear_env();
+ unsafe { std::env::set_var("SIE_ADAPTIVE_BATCH_MAX_WAIT_MS", "10.0") };
+ let cfg = BatchConfig::default();
+ let c = AdaptiveBatchController::from_batch_config_and_env(&cfg);
+ assert!((c.max_wait_ms - 10.0).abs() < f64::EPSILON);
+ assert!(
+ c.current_wait_ms <= 10.0,
+ "current_wait_ms must clamp to new ceiling"
+ );
+ clear_env();
+ });
+ }
+
+ #[test]
+ fn from_batch_config_and_env_min_wait_env_wins_over_production_default() {
+ // Operator sets `SIE_ADAPTIVE_BATCH_MIN_WAIT_MS=5` to
+ // experimentally drop the floor below Python production's
+ // 15.0. Env must win.
+ with_env_lock(|| {
+ clear_env();
+ unsafe { std::env::set_var("SIE_ADAPTIVE_BATCH_MIN_WAIT_MS", "5.0") };
+ let cfg = BatchConfig::default();
+ let c = AdaptiveBatchController::from_batch_config_and_env(&cfg);
+ assert!((c.min_wait_ms - 5.0).abs() < f64::EPSILON);
+ clear_env();
+ });
+ }
+
+ #[test]
+ fn explicit_target_skips_calibration() {
+ let c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(25.0))
+ .build();
+ assert!(c.calibrated);
+ assert_eq!(c.target_p50_ms(), Some(25.0));
+ assert!(!c.auto_calibrate);
+ }
+
+ #[test]
+ fn auto_calibration_derives_target_from_inference_p50() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(None) // auto-calibrate
+ .calibration_multiplier(2.0)
+ .update_interval(1)
+ .build();
+ assert!(!c.calibrated);
+
+ // Seed the inference tracker with enough samples to cross
+ // the min_samples threshold (10).
+ for _ in 0..20 {
+ c.record_inference_sample(10.0);
+ }
+ // First step with calibration pending: target gets set from
+ // inference_p50 (=10ms) × multiplier (=2.0) = 20ms.
+ let _ = c.step(None, None, Some(32));
+ assert!(c.calibrated);
+ assert_eq!(c.target_p50_ms(), Some(20.0));
+ }
+
+ #[test]
+ fn auto_calibration_target_is_clamped() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(None)
+ .calibration_multiplier(100.0) // absurd → will clamp high
+ .min_target_p50_ms(5.0)
+ .max_target_p50_ms(50.0)
+ .update_interval(1)
+ .build();
+ for _ in 0..20 {
+ c.record_inference_sample(5.0); // 5 * 100 = 500 → clamps to 50
+ }
+ c.step(None, None, Some(32));
+ assert_eq!(c.target_p50_ms(), Some(50.0));
+ }
+
+ #[test]
+ fn pre_calibration_holds_initial_knobs() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(None)
+ .update_interval(1)
+ .build();
+ let (w0, b0) = (c.current_wait_ms(), c.current_batch_cost());
+ // Step with no inference samples → no calibration → knobs held.
+ let (w1, b1) = c.step(Some(999.0), Some(0.99), Some(1));
+ assert_eq!(w0, w1);
+ assert_eq!(b0, b1);
+ }
+
+ #[test]
+ fn positive_headroom_grows_wait_knob() {
+ let mut c = make_explicit_target(50.0);
+ let (w0, _) = (c.current_wait_ms(), c.current_batch_cost());
+ // observed=10ms < target=50ms → headroom=+40 → wait grows.
+ let (w1, _) = c.step(Some(10.0), None, Some(32));
+ assert!(w1 > w0, "positive headroom must grow wait: {w0} → {w1}");
+ }
+
+ #[test]
+ fn negative_headroom_shrinks_wait_knob() {
+ let mut c = make_explicit_target(10.0);
+ let (w0, _) = (c.current_wait_ms(), c.current_batch_cost());
+ // observed=50ms > target=10ms → headroom=-40 → wait shrinks.
+ let (w1, _) = c.step(Some(50.0), None, Some(32));
+ assert!(w1 < w0, "negative headroom must shrink wait: {w0} → {w1}");
+ }
+
+ #[test]
+ fn wait_knob_clamped_to_bounds() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(50.0))
+ .min_wait_ms(5.0)
+ .max_wait_ms(30.0)
+ .update_interval(1)
+ .build();
+ // Drive a huge positive headroom many times → must clamp at max.
+ for _ in 0..100 {
+ c.step(Some(0.0), None, Some(32));
+ }
+ assert!((c.current_wait_ms() - 30.0).abs() < 1e-9);
+
+ // Flip: huge negative headroom → must clamp at min.
+ for _ in 0..100 {
+ c.step(Some(999.0), None, Some(32));
+ }
+ assert!((c.current_wait_ms() - 5.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn cost_knob_only_adjusts_when_fill_ratio_above_threshold() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(50.0))
+ .fill_ratio_threshold(0.7)
+ .update_interval(1)
+ .build();
+ let b0 = c.current_batch_cost();
+
+ // fill_ratio below threshold → cost must not change.
+ let (_, b1) = c.step(Some(10.0), Some(0.5), Some(32));
+ assert_eq!(b1, b0);
+
+ // fill_ratio above threshold → cost can move.
+ let (_, b2) = c.step(Some(10.0), Some(0.9), Some(32));
+ assert!(
+ b2 > b0,
+ "saturated + positive headroom must grow cost: {b0} → {b2}"
+ );
+ }
+
+ #[test]
+ fn cost_knob_clamped_to_bounds() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(50.0))
+ .min_batch_cost(1000)
+ .max_batch_cost(5000)
+ .initial_batch_cost(2500)
+ .fill_ratio_threshold(0.1) // always saturated
+ .cost_gain(1.0) // big moves
+ .update_interval(1)
+ .build();
+
+ for _ in 0..100 {
+ c.step(Some(0.0), Some(0.9), Some(32));
+ }
+ assert!(c.current_batch_cost() <= 5000);
+ assert!(c.current_batch_cost() >= 1000);
+ }
+
+ #[test]
+ fn starvation_recovery_fires_at_floors_with_streak() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(10.0))
+ .min_wait_ms(1.0)
+ .max_wait_ms(50.0)
+ .min_batch_cost(100)
+ .max_batch_cost(10_000)
+ .initial_wait_ms(20.0)
+ .initial_batch_cost(4000)
+ .starvation_window(5)
+ .starvation_batch_size(1)
+ .update_interval(1)
+ .build();
+
+ // Manually pin knobs at floors (would take many negative-headroom
+ // steps to get there organically; we short-circuit for the test).
+ c.current_wait_ms = c.min_wait_ms;
+ c.current_batch_cost = c.min_batch_cost;
+
+ // Feed 5 tiny batches — streak threshold met.
+ for _ in 0..c.starvation_window {
+ c.step(Some(100.0), Some(1.0), Some(1));
+ }
+ assert!(
+ c.starvation_resets() >= 1,
+ "at floors + streak should trigger recovery"
+ );
+ // Recovery wait = (1.0 + 20.0)/2 = 10.5
+ assert!((c.current_wait_ms() - 10.5).abs() < 1e-9);
+ // Recovery cost = max(4000/2=2000, 100*4=400) = 2000
+ assert_eq!(c.current_batch_cost(), 2000);
+ // Streak is cleared after reset.
+ assert_eq!(c.starvation_streak(), 0);
+ }
+
+ #[test]
+ fn starvation_not_triggered_if_not_at_floors() {
+ // Feed observed == target so headroom is zero and the PI
+ // loop never drives either knob off its initial value.
+ // (Large negative headroom, as in the sibling test, crashes
+ // both knobs into their floors on the first step, which
+ // would trigger recovery — that path is covered by
+ // `starvation_recovery_fires_at_floors_with_streak`.)
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(10.0))
+ .starvation_window(3)
+ .update_interval(1)
+ .build();
+ for _ in 0..10 {
+ c.step(Some(10.0), Some(0.0 /* below fill threshold */), Some(1));
+ }
+ assert_eq!(c.starvation_resets(), 0);
+ assert!(c.current_wait_ms() > c.min_wait_ms);
+ assert!(c.current_batch_cost() > c.min_batch_cost);
+ }
+
+ #[test]
+ fn starvation_counter_resets_on_healthy_batch() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(10.0))
+ .starvation_window(5)
+ .starvation_batch_size(1)
+ .update_interval(1)
+ .build();
+ c.current_wait_ms = c.min_wait_ms;
+ c.current_batch_cost = c.min_batch_cost;
+
+ // 4 tiny batches — one short of recovery.
+ for _ in 0..4 {
+ c.step(Some(100.0), Some(1.0), Some(1));
+ }
+ assert_eq!(c.starvation_resets(), 0);
+
+ // One healthy batch resets the streak.
+ c.step(Some(100.0), Some(1.0), Some(32));
+ assert_eq!(c.starvation_streak(), 0);
+
+ // Next 4 tiny batches must not trigger — streak restarts.
+ for _ in 0..4 {
+ c.step(Some(100.0), Some(1.0), Some(1));
+ }
+ assert_eq!(c.starvation_resets(), 0);
+ }
+
+ #[test]
+ fn starvation_recovery_can_be_disabled() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(10.0))
+ .starvation_recovery_enabled(false)
+ .starvation_window(2)
+ .update_interval(1)
+ .build();
+ c.current_wait_ms = c.min_wait_ms;
+ c.current_batch_cost = c.min_batch_cost;
+ for _ in 0..50 {
+ c.step(Some(100.0), Some(1.0), Some(1));
+ }
+ assert_eq!(c.starvation_resets(), 0);
+ }
+
+ #[test]
+ fn none_batch_size_does_not_touch_streak() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(10.0))
+ .starvation_window(3)
+ .update_interval(1)
+ .build();
+ c.current_wait_ms = c.min_wait_ms;
+ c.current_batch_cost = c.min_batch_cost;
+ for _ in 0..10 {
+ c.step(Some(100.0), Some(1.0), None);
+ }
+ assert_eq!(c.starvation_streak(), 0);
+ assert_eq!(c.starvation_resets(), 0);
+ }
+
+ #[test]
+ fn reset_restores_initial_state_and_recovers_autocal() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(None)
+ .update_interval(1)
+ .initial_wait_ms(15.0)
+ .initial_batch_cost(2000)
+ .build();
+ // Calibrate manually.
+ for _ in 0..20 {
+ c.record_inference_sample(10.0);
+ }
+ c.step(None, None, Some(32));
+ assert!(c.calibrated());
+ // Drive the knobs around.
+ for _ in 0..5 {
+ c.step(Some(0.0), Some(0.9), Some(32));
+ }
+ // Bump the `starvation_resets` counter so we can verify it's
+ // NOT reset.
+ c.starvation_resets = 3;
+
+ c.reset();
+ assert_eq!(c.current_wait_ms(), 15.0);
+ assert_eq!(c.current_batch_cost(), 2000);
+ assert!(
+ !c.calibrated(),
+ "auto-calibrate controllers re-enter calibration"
+ );
+ assert_eq!(c.target_p50_ms(), None);
+ assert_eq!(
+ c.starvation_resets(),
+ 3,
+ "starvation_resets is monotonic across reset"
+ );
+ }
+
+ #[test]
+ fn reset_preserves_calibrated_target_for_explicit_target() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(30.0))
+ .update_interval(1)
+ .build();
+ assert!(c.calibrated());
+ c.reset();
+ assert!(
+ c.calibrated(),
+ "explicit-target controllers keep calibrated=true across reset"
+ );
+ assert_eq!(c.target_p50_ms(), Some(30.0));
+ }
+
+ #[test]
+ fn update_interval_gates_controller_steps() {
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(50.0))
+ .update_interval(5) // only every 5th call moves the knobs
+ .build();
+ let w0 = c.current_wait_ms();
+
+ // 4 steps → no movement.
+ for _ in 0..4 {
+ c.step(Some(10.0), None, Some(32));
+ }
+ assert_eq!(c.current_wait_ms(), w0);
+
+ // 5th step → move.
+ c.step(Some(10.0), None, Some(32));
+ assert!(c.current_wait_ms() > w0);
+ }
+
+ #[test]
+ fn snapshot_reports_headroom_and_state() {
+ let c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(20.0))
+ .build();
+ let s = c.snapshot(Some(15.0), Some(0.8));
+ assert!(s.enabled);
+ assert!(s.calibrated);
+ assert_eq!(s.target_p50_ms, Some(20.0));
+ assert_eq!(s.observed_p50_ms, Some(15.0));
+ assert_eq!(s.fill_ratio, Some(0.8));
+ assert_eq!(s.headroom_ms, Some(5.0));
+ }
+
+ #[test]
+ fn integrator_saturation_antiwindup_blocks_at_max() {
+ // Drive max headroom long enough to saturate wait at max.
+ // Then confirm the integrator doesn't keep growing.
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(100.0))
+ .min_wait_ms(1.0)
+ .max_wait_ms(5.0) // tiny range, easy to saturate
+ .gain(2.0)
+ .integral_gain(1.0)
+ .update_interval(1)
+ .build();
+ for _ in 0..50 {
+ c.step(Some(0.0), None, Some(32));
+ }
+ let integ_saturated = c.integral;
+ // Another batch of saturated steps — integral must not grow
+ // further (saturation anti-windup).
+ for _ in 0..50 {
+ c.step(Some(0.0), None, Some(32));
+ }
+ assert!(
+ (c.integral - integ_saturated).abs() < 1e-9,
+ "integrator must stop growing while output is saturated at max"
+ );
+ }
+
+ #[test]
+ fn idle_decay_shrinks_integrator_after_long_gap() {
+ // This is a timing-sensitive test; we synthesise the gap by
+ // mutating `last_step_time` directly instead of sleeping.
+ let mut c = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(50.0))
+ .integral_gain(1.0)
+ .update_interval(1)
+ .build();
+ // One step to seed `last_step_time`.
+ c.step(Some(0.0), None, Some(32));
+ // Manually build up integral without the decay firing.
+ c.integral = 10.0;
+ // Back-date the last_step_time by 5 seconds.
+ c.last_step_time = Some(Instant::now() - Duration::from_secs(5));
+ // Next step — dt ≈ 5s, decay should apply (0.5^(5-2) = 0.125).
+ c.step(Some(50.0), None, Some(32)); // headroom=0 so no fresh integration
+ assert!(
+ c.integral < 10.0 * 0.5,
+ "idle decay must shrink the integrator: got {}",
+ c.integral
+ );
+ }
+}
diff --git a/packages/sie_server_sidecar/src/scheduler/batch_config.rs b/packages/sie_server_sidecar/src/scheduler/batch_config.rs
new file mode 100644
index 000000000..a1cb974eb
--- /dev/null
+++ b/packages/sie_server_sidecar/src/scheduler/batch_config.rs
@@ -0,0 +1,247 @@
+//! [`BatchConfig`] — the shared-mutable caps the batcher consults on
+//! every flush decision. Ported from `sie_server/core/batcher.py`.
+//!
+//! The Python implementation holds this as a plain mutable object and
+//! relies on the GIL to serialise reads and writes from the controller
+//! vs the batcher loop. In the Rust port we keep the shape identical
+//! but hand the `AdaptiveBatchController` an `arc_swap::ArcSwap`
+//! snapshot so a flush decision always sees a consistent set of knobs
+//! even mid-update — see [`crate::scheduler::BatchFormer`] and
+//! [`crate::scheduler::AdaptiveBatchController`] for the wiring.
+//!
+//! `ArcSwap` isn't pulled in as a dep for this first landing; the
+//! controller → batcher channel is a simple `ArcSwap`-equivalent in
+//! the follow-up wiring. For now the `BatchFormer` takes a
+//! `BatchConfig` by value (with per-former update via
+//! `update_config`), which matches Python's "mutate the field in
+//! place" semantics closely enough for the primitive tests.
+//!
+//! Most default values match the Python defaults line-for-line; the
+//! two intentional divergences (`coalesce_ms` and `max_batch_requests`)
+//! are documented on [`BatchConfig::default`] and locked by the
+//! `defaults_diverge_from_python_intentionally` test below.
+
+/// Batch formation caps.
+///
+/// Ported from `sie_server.core.batcher.BatchConfig`.
+///
+/// Cost semantics are modality-agnostic:
+/// * Text: `cost = token count`
+/// * Images: `cost = 1` per image
+/// * Mixed: component sum
+///
+/// Defaults intentionally mirror Python's defaults for parity testing.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct BatchConfig {
+ /// Maximum total cost across all items in a batch before a flush.
+ pub max_batch_cost: u64,
+
+ /// Maximum number of items in a batch before a flush.
+ pub max_batch_requests: usize,
+
+ /// Maximum wall-clock wait since the *first* pending item arrived
+ /// before a timeout flush.
+ pub max_batch_wait_ms: f64,
+
+ /// Coalesce window ceiling. See [`BatchConfig::effective_coalesce_ms`]
+ /// for the effective value at runtime.
+ ///
+ /// Intent: set this to the upstream IPC inter-arrival jitter so
+ /// a burst of 64 requests lands in a single GPU forward rather
+ /// than being split across 2–3 under-filled ones.
+ pub coalesce_ms: f64,
+
+ /// Coalesce window as a fraction of [`Self::max_batch_wait_ms`].
+ ///
+ /// The effective window is
+ /// `min(coalesce_ms, max_batch_wait_ms * coalesce_ratio)` — this
+ /// keeps the coalesce time proportional when the adaptive
+ /// controller mutates `max_batch_wait_ms`.
+ pub coalesce_ratio: f64,
+}
+
+impl BatchConfig {
+ /// Construct with Python-parity defaults.
+ #[must_use]
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ /// Construct with Python-parity defaults, optionally overridden
+ /// by env vars. Used by the scheduler registry on startup.
+ ///
+ /// | Var | Field | Default | Notes |
+ /// |-------------------------------------|----------------------|---------|-------|
+ /// | `SIE_BATCHER_MAX_BATCH_WAIT_MS` | `max_batch_wait_ms` | 15.0 | Static flush-trigger ceiling — `AdaptiveBatchController` overwrites this on every step but the initial value matters during cold-start (see Python `core/batcher.py:BatchConfig`). |
+ /// | `SIE_BATCHER_MAX_BATCH_COST` | `max_batch_cost` | 16384 | Static cost cap initial value. |
+ /// | `SIE_BATCHER_MAX_BATCH_REQUESTS` | `max_batch_requests` | **12** | Hard count cap (controller does not move). **Diverges from Python's 64** — see [`BatchConfig::default`] for the runtime rationale. |
+ /// | `SIE_BATCHER_COALESCE_MS` | `coalesce_ms` | **5.0** | Coalesce window ceiling. **Diverges from Python's 15.0** — see [`BatchConfig::default`] for the runtime rationale. |
+ /// | `SIE_BATCHER_COALESCE_RATIO` | `coalesce_ratio` | 0.5 | Coalesce as fraction of `max_batch_wait_ms`. |
+ ///
+ /// Bad values (non-numeric, NaN) log a warning and fall back to
+ /// the default — never crash the registry init.
+ #[must_use]
+ pub fn from_env_or_default() -> Self {
+ let mut c = Self::default();
+
+ fn get_f64(var: &str) -> Option<f64> {
+ std::env::var(var).ok().and_then(|s| {
+ s.parse::<f64>().ok().filter(|v| v.is_finite()).or_else(|| {
+ tracing::warn!(
+ var = var,
+ raw = s.as_str(),
+ "batcher env var: ignoring non-numeric/non-finite value"
+ );
+ None
+ })
+ })
+ }
+ fn get_u64(var: &str) -> Option<u64> {
+ std::env::var(var).ok().and_then(|s| s.parse::<u64>().ok())
+ }
+ fn get_usize(var: &str) -> Option<usize> {
+ std::env::var(var)
+ .ok()
+ .and_then(|s| s.parse::<usize>().ok())
+ }
+
+ if let Some(v) = get_f64("SIE_BATCHER_MAX_BATCH_WAIT_MS") {
+ c.max_batch_wait_ms = v;
+ }
+ if let Some(v) = get_u64("SIE_BATCHER_MAX_BATCH_COST") {
+ c.max_batch_cost = v;
+ }
+ if let Some(v) = get_usize("SIE_BATCHER_MAX_BATCH_REQUESTS") {
+ c.max_batch_requests = v;
+ }
+ if let Some(v) = get_f64("SIE_BATCHER_COALESCE_MS") {
+ c.coalesce_ms = v;
+ }
+ if let Some(v) = get_f64("SIE_BATCHER_COALESCE_RATIO") {
+ c.coalesce_ratio = v;
+ }
+
+ tracing::info!(
+ max_batch_cost = c.max_batch_cost,
+ max_batch_requests = c.max_batch_requests,
+ max_batch_wait_ms = c.max_batch_wait_ms,
+ coalesce_ms = c.coalesce_ms,
+ coalesce_ratio = c.coalesce_ratio,
+ "batcher: BatchConfig constructed from env+defaults"
+ );
+
+ c
+ }
+
+ /// Effective coalesce window used by the batcher.
+ ///
+ /// Mirrors Python's
+ /// `min(coalesce_ms, max_batch_wait_ms * coalesce_ratio)` exactly
+ /// — f64 math on both sides means identical outputs bit-for-bit
+ /// within IEEE 754 determinism.
+ #[must_use]
+ pub fn effective_coalesce_ms(&self) -> f64 {
+ f64::min(
+ self.coalesce_ms,
+ self.max_batch_wait_ms * self.coalesce_ratio,
+ )
+ }
+
+ /// Python-parity alias for [`Self::max_batch_cost`] mirroring the
+ /// Python `max_batch_tokens` property.
+ #[must_use]
+ pub fn max_batch_tokens(&self) -> u64 {
+ self.max_batch_cost
+ }
+}
+
+impl Default for BatchConfig {
+ /// Defaults: most fields mirror Python's `BatchConfig` line-for-line.
+ ///
+ /// **Two intentional divergences** from Python:
+ ///
+ /// | Field | Python default | Rust default | Why diverge |
+ /// |----------------------|----------------|--------------|-------------|
+ /// | `coalesce_ms` | 15.0 | **5.0** | The tight `FetchExpiryController` already flushes the upstream pull-loop on a 2-15 ms quantum, so another 15 ms downstream wait is latency padding. 5 ms keeps a small coalesce window without crossing into under-batching. |
+ /// | `max_batch_requests` | 64 | **12** | The tight pull quantum naturally produces small fetch batches. 12 is comfortable headroom for arrival bursts without allowing pathological single-batch growth. |
+ ///
+ /// The divergences are locked by
+ /// `tests::defaults_diverge_from_python_intentionally` so Python parity
+ /// is not restored by accident; retunes should update this rationale and
+ /// the test together.
+ fn default() -> Self {
+ Self {
+ max_batch_cost: 16_384,
+ max_batch_requests: 12,
+ max_batch_wait_ms: 15.0,
+ coalesce_ms: 5.0,
+ coalesce_ratio: 0.5,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn defaults_match_python_for_non_diverged_fields() {
+ let c = BatchConfig::default();
+ // Python-parity fields (must NOT silently drift):
+ assert_eq!(c.max_batch_cost, 16_384);
+ assert!((c.max_batch_wait_ms - 15.0).abs() < f64::EPSILON);
+ assert!((c.coalesce_ratio - 0.5).abs() < f64::EPSILON);
+ }
+
+ #[test]
+ fn defaults_diverge_from_python_intentionally() {
+ // Locks the two intentional divergences from Python defaults.
+ // Retunes should update `BatchConfig::default` and this test
+ // together so the runtime rationale stays attached to the guard.
+ let c = BatchConfig::default();
+ // Python's `BatchConfig.coalesce_ms = 15.0`; we ship 5.0.
+ assert!(
+ (c.coalesce_ms - 5.0).abs() < f64::EPSILON,
+ "expected coalesce_ms=5.0 (Rust-side worker default), got {}",
+ c.coalesce_ms,
+ );
+ // Python's `BatchConfig.max_batch_requests = 64`; we ship 12.
+ assert_eq!(
+ c.max_batch_requests, 12,
+ "expected max_batch_requests=12 (Rust-side worker default)"
+ );
+ }
+
+ #[test]
+ fn effective_coalesce_is_min_of_ceiling_and_proportional() {
+ let c = BatchConfig {
+ coalesce_ms: 15.0,
+ max_batch_wait_ms: 10.0, // proportional = 5.0
+ coalesce_ratio: 0.5,
+ ..BatchConfig::default()
+ };
+ // proportional wins because 5.0 < 15.0
+ assert!((c.effective_coalesce_ms() - 5.0).abs() < f64::EPSILON);
+ }
+
+ #[test]
+ fn effective_coalesce_ceiling_clamps_upward() {
+ let c = BatchConfig {
+ coalesce_ms: 2.0,
+ max_batch_wait_ms: 100.0, // proportional = 50.0
+ coalesce_ratio: 0.5,
+ ..BatchConfig::default()
+ };
+ // ceiling wins because 2.0 < 50.0
+ assert!((c.effective_coalesce_ms() - 2.0).abs() < f64::EPSILON);
+ }
+
+ #[test]
+ fn max_batch_tokens_alias() {
+ let c = BatchConfig {
+ max_batch_cost: 4242,
+ ..BatchConfig::default()
+ };
+ assert_eq!(c.max_batch_tokens(), 4242);
+ }
+}
diff --git a/packages/sie_server_sidecar/src/scheduler/batch_former.rs b/packages/sie_server_sidecar/src/scheduler/batch_former.rs
new file mode 100644
index 000000000..c97a4226a
--- /dev/null
+++ b/packages/sie_server_sidecar/src/scheduler/batch_former.rs
@@ -0,0 +1,763 @@
+//! [`BatchFormer`] — async pending queue + flush loop.
+//!
+//! Ported from `sie_server/core/batcher.py::BatchFormer`. The port
+//! preserves every behavioural invariant of the Python implementation:
+//!
+//! 1. **Flush triggers**: cost cap, count cap, `max_batch_wait_ms`
+//! timeout since the *first* item, or the coalesce window
+//! (`effective_coalesce_ms`) elapsing since the *last* submit.
+//! 2. **Oversize item**: a single item whose cost already exceeds
+//! `max_batch_cost` still flushes (alone) so it can't starve
+//! forever.
+//! 3. **Cost-sorted sub-batch**: `_pending` is sorted by `cost`
+//! ascending before each extract; packing is greedy under the cost
+//! and count caps. Remaining items stay in the queue for the next
+//! extract, preserving FIFO-within-cost-bucket ordering.
+//! 4. **Timer reset**: once the queue empties, both `first_request_time`
+//! and `last_submit_time` are cleared so the next submit starts a
+//! fresh coalesce/timeout window.
+//!
+//! The async primitives differ from Python (Rust uses [`tokio::sync`]
+//! rather than asyncio), but the externally observable semantics are
+//! identical. The Python test suite in `tests/core/test_batcher.py` is
+//! the behavioural contract; every relevant case is ported below as
+//! `#[tokio::test]`.
+
+use std::marker::PhantomData;
+use std::time::{Duration, Instant};
+
+use tokio::sync::{Mutex, Notify};
+use tokio::time::sleep;
+
+use super::batch_config::BatchConfig;
+
+/// Trait for any item that carries a batching cost and an original
+/// position within a request.
+///
+/// Ported from Python's `HasCost` Protocol. `PreparedItem` (built on
+/// the Rust-tokenise fast path) implements this directly; test-only
+/// stubs in this module do too.
+pub trait HasCost {
+ /// Batching cost — token count for text, 1 per image, etc.
+ fn cost(&self) -> u64;
+
+ /// Original position within the originating request's item list.
+ /// Used by the adapter-side output router to zip results back to
+ /// the correct request item.
+ fn original_index(&self) -> usize;
+}
+
+/// A single request waiting to be batched, together with
+/// caller-provided routing metadata.
+#[derive(Debug, Clone)]
+pub struct PendingRequest<I: HasCost, T> {
+ pub item: I,
+ pub metadata: T,
+ pub arrival_time: Instant,
+}
+
+/// A flushed batch ready for downstream dispatch.
+///
+/// Items and metadata are kept in parallel `Vec`s so the adapter-side
+/// zip continues to work unchanged.
+#[derive(Debug)]
+pub struct FormattedBatch<I: HasCost, T> {
+ pub items: Vec<I>,
+ pub metadata: Vec<T>,
+ pub total_cost: u64,
+}
+
+impl<I: HasCost, T> FormattedBatch<I, T> {
+ /// Number of items in the batch.
+ #[must_use]
+ pub fn size(&self) -> usize {
+ self.items.len()
+ }
+
+ /// Python-parity alias for [`Self::total_cost`] mirroring the
+ /// Python `total_tokens` property.
+ #[must_use]
+ pub fn total_tokens(&self) -> u64 {
+ self.total_cost
+ }
+
+ /// Return a new batch sorted by cost (ascending). Preserves the
+ /// `items[i] ↔ metadata[i]` correspondence.
+ ///
+ /// Mostly redundant now that `extract_batch` sorts
+ /// in place before slicing, but kept for symmetry with the Python
+ /// API where some callers sort explicitly.
+ #[must_use]
+ pub fn sorted_by_cost(self) -> Self
+ where
+ I: Clone,
+ T: Clone,
+ {
+ // Build index permutation so we don't pay a double-clone on T.
+ let mut idx: Vec<usize> = (0..self.items.len()).collect();
+ idx.sort_by_key(|&i| self.items[i].cost());
+
+ let items = idx.iter().map(|&i| self.items[i].clone()).collect();
+ let metadata = idx.iter().map(|&i| self.metadata[i].clone()).collect();
+ Self {
+ items,
+ metadata,
+ total_cost: self.total_cost,
+ }
+ }
+}
+
+/// Internal mutable state, guarded by a single [`Mutex`].
+///
+/// Kept compact on purpose: every batch formation decision reads and
+/// mutates this struct, so the lock is hot. No allocations happen
+/// under the lock beyond the two parallel `Vec`s.
+#[derive(Debug)]
+struct Inner<I: HasCost, T> {
+ pending: Vec<PendingRequest<I, T>>,
+ total_cost: u64,
+ first_request_time: Option<Instant>,
+ last_submit_time: Option<Instant>,
+ /// Cached snapshot of the current knobs. Mutations happen via
+ /// [`BatchFormer::update_config`] which takes the same lock so
+ /// reads of `config` and reads of `pending` stay consistent.
+ config: BatchConfig,
+}
+
+/// Async batch former.
+///
+/// Thread-safe for concurrent submits from many tasks. A single
+/// consumer task should call [`BatchFormer::get_batch`] in a loop;
+/// calling it concurrently from multiple consumers is allowed but has
+/// no benefit (and will race over pending items — the consumer is
+/// typically the per-model worker loop).
+#[derive(Debug)]
+pub struct BatchFormer<I: HasCost, T> {
+ inner: Mutex<Inner<I, T>>,
+ /// Edge-triggered readiness signal. A submit that transitions the
+ /// batcher to "first item" or "batch ready" notifies here; the
+ /// consumer uses [`Notified::enable`] *inside* the lock to avoid
+ /// missed notifications across the drop.
+ ready: Notify,
+ // Generic parameters are consumed by `inner` only; `PhantomData`
+ // keeps the type system honest when `Inner` is refactored.
+ _phantom: PhantomData<(I, T)>,
+}
+
+impl<I: HasCost, T> BatchFormer<I, T> {
+ /// Construct a new batch former with the given caps. Use
+ /// [`BatchConfig::default`] for Python-parity defaults.
+ pub fn new(config: BatchConfig) -> Self {
+ Self {
+ inner: Mutex::new(Inner {
+ pending: Vec::new(),
+ total_cost: 0,
+ first_request_time: None,
+ last_submit_time: None,
+ config,
+ }),
+ ready: Notify::new(),
+ _phantom: PhantomData,
+ }
+ }
+
+ /// Current cap snapshot. Returned by value — the caller sees a
+ /// consistent view even if another task updates the config
+ /// concurrently.
+ pub async fn config(&self) -> BatchConfig {
+ self.inner.lock().await.config
+ }
+
+ /// Update the caps atomically. The adaptive controller calls this
+ /// after each `step()`.
+ pub async fn update_config(&self, config: BatchConfig) {
+ let mut guard = self.inner.lock().await;
+ guard.config = config;
+ // Config shrinks can make the pending queue instantly
+ // yieldable (e.g. new `max_batch_cost` < current `total_cost`
+ // or new `max_batch_requests` < `pending.len()`). Wake the
+ // consumer so it re-evaluates the flush triggers.
+ if should_yield_batch(&guard) {
+ self.ready.notify_one();
+ }
+ }
+
+ /// Number of pending items. Cheap snapshot under the lock.
+ pub async fn pending_count(&self) -> usize {
+ self.inner.lock().await.pending.len()
+ }
+
+ /// Total cost across all pending items.
+ pub async fn pending_cost(&self) -> u64 {
+ self.inner.lock().await.total_cost
+ }
+
+ /// Python-parity alias for [`Self::pending_cost`].
+ pub async fn pending_tokens(&self) -> u64 {
+ self.pending_cost().await
+ }
+
+ /// Snapshot of `first_request_time`. Used by the FCFS fairness
+ /// primitive (`scheduler::pick_next_lora`) to sort per-LoRA
+ /// batchers by oldest head.
+ ///
+ /// Python accessed `_first_request_time` directly (private field);
+ /// the Rust scheduler formalises that coupling as a public method.
+ pub async fn first_request_time(&self) -> Option<Instant> {
+ self.inner.lock().await.first_request_time
+ }
+
+ /// Enqueue a single item.
+ pub async fn submit(&self, item: I, metadata: T) {
+ let mut guard = self.inner.lock().await;
+ let notify = append_item(&mut guard, item, metadata);
+ drop(guard);
+ if notify {
+ self.ready.notify_one();
+ }
+ }
+
+ /// Enqueue many items under a single lock acquisition. More
+ /// efficient than looping over [`Self::submit`] for multi-item
+ /// requests (each external request can carry up to 64 items).
+ pub async fn submit_many(&self, items: Vec<(I, T)>) {
+ if items.is_empty() {
+ return;
+ }
+ let mut guard = self.inner.lock().await;
+ let mut notify = false;
+ for (item, metadata) in items {
+ notify |= append_item(&mut guard, item, metadata);
+ }
+ drop(guard);
+ if notify {
+ self.ready.notify_one();
+ }
+ }
+
+ /// Block until the next batch is ready, then return it.
+ ///
+ /// Readiness is one of: cost cap hit, count cap hit, timeout
+ /// elapsed since first item, or coalesce window elapsed since
+ /// last submit.
+ ///
+ /// Setting `immediate = true` short-circuits the wait: if any
+ /// items are pending, they flush immediately. Used by the worker
+ /// loop after an idle period to eliminate an unnecessary batch
+ /// wait at low concurrency.
+ pub async fn get_batch(&self, immediate: bool) -> FormattedBatch<I, T> {
+ loop {
+ // Arm the notification *before* we drop the lock so a
+ // submit that fires between "decide to wait" and "start
+ // waiting" is not missed. See the Tokio docs on
+ // `Notified::enable` for the pattern.
+ let notified = self.ready.notified();
+ tokio::pin!(notified);
+
+ let wait = {
+ let mut guard = self.inner.lock().await;
+ if !guard.pending.is_empty() && (should_yield_batch(&guard) || immediate) {
+ return extract_batch(&mut guard);
+ }
+ notified.as_mut().enable();
+ wait_timeout(&guard)
+ };
+
+ match wait {
+ None => {
+ // No pending items → wait indefinitely for the
+ // first submit.
+ notified.await;
+ }
+ Some(dur) if dur.is_zero() => {
+ // The timer is already expired — loop and flush
+ // on the next lock acquisition. This path fires
+ // when `get_batch` is called with `immediate=false`
+ // and the timers have already elapsed (e.g. a
+ // slow consumer catching up).
+ continue;
+ }
+ Some(dur) => {
+ tokio::select! {
+ biased;
+ () = &mut notified => {}
+ () = sleep(dur) => {}
+ }
+ }
+ }
+ }
+ }
+
+ /// Non-blocking: return a batch if the flush conditions already
+ /// 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
+ }
+ }
+
+ /// Drain whatever is pending right now, bypassing the flush
+ /// conditions. Matches Python's `try_drain` — the continuous
+ /// batching tail called after each forward pass.
+ pub async fn try_drain(&self) -> Option<FormattedBatch<I, T>> {
+ let mut guard = self.inner.lock().await;
+ if guard.pending.is_empty() {
+ None
+ } else {
+ Some(extract_batch(&mut guard))
+ }
+ }
+}
+
+// ---------------------------------------------------------------------
+// Free-standing helpers. Kept outside the `BatchFormer` impl so the
+// hot-path decisions are easy to test in isolation (see the `tests`
+// module below) and so they don't borrow `self` implicitly.
+// ---------------------------------------------------------------------
+
+fn append_item<I: HasCost, T>(inner: &mut Inner<I, T>, item: I, metadata: T) -> bool {
+ let cost = item.cost();
+ let now = Instant::now();
+
+ inner.pending.push(PendingRequest {
+ item,
+ metadata,
+ arrival_time: now,
+ });
+ inner.total_cost += cost;
+ inner.last_submit_time = Some(now);
+
+ let is_first = inner.first_request_time.is_none();
+ if is_first {
+ inner.first_request_time = Some(now);
+ }
+
+ // Wake the consumer if the batch is now full, OR if this is the
+ // very first item (so the consumer can start the timeout window
+ // instead of blocking on an indefinite `notified()`).
+ 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;
+ };
+ let elapsed_ms = first.elapsed().as_secs_f64() * 1000.0;
+ elapsed_ms >= inner.config.max_batch_wait_ms
+}
+
+fn coalesce_expired<I: HasCost, T>(inner: &Inner<I, T>) -> bool {
+ let Some(last) = inner.last_submit_time else {
+ return false;
+ };
+ if inner.pending.is_empty() {
+ return false;
+ }
+ let elapsed_ms = last.elapsed().as_secs_f64() * 1000.0;
+ elapsed_ms >= inner.config.effective_coalesce_ms()
+}
+
+fn should_yield_batch<I: HasCost, T>(inner: &Inner<I, T>) -> bool {
+ if inner.pending.is_empty() {
+ return false;
+ }
+ batch_is_full(inner) || batch_timeout_expired(inner) || coalesce_expired(inner)
+}
+
+/// Time remaining until the next guaranteed flush, given current
+/// state. `None` means "wait indefinitely" (no pending items).
+fn wait_timeout<I: HasCost, T>(inner: &Inner<I, T>) -> Option<Duration> {
+ let first = inner.first_request_time?;
+ let now = Instant::now();
+
+ let elapsed_ms = now.saturating_duration_since(first).as_secs_f64() * 1000.0;
+ let batch_remaining_ms = (inner.config.max_batch_wait_ms - elapsed_ms).max(0.0);
+
+ let coalesce_ms = inner.config.effective_coalesce_ms();
+ let coalesce_remaining_ms = match inner.last_submit_time {
+ Some(last) => {
+ let since_last = now.saturating_duration_since(last).as_secs_f64() * 1000.0;
+ (coalesce_ms - since_last).max(0.0)
+ }
+ None => coalesce_ms,
+ };
+
+ let effective_ms = batch_remaining_ms.min(coalesce_remaining_ms);
+ // ms → Duration, clamping tiny negatives to zero.
+ 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> {
+ // 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
+ // (matches Python's stable `list.sort`).
+ inner.pending.sort_by_key(|r| r.item.cost());
+
+ let max_cost = inner.config.max_batch_cost;
+ let max_requests = inner.config.max_batch_requests;
+
+ // Greedy pack. Always take at least one item so a single large
+ // request (cost ≥ max_cost) doesn't starve.
+ let mut batch_cost: u64 = 0;
+ let mut take_count: usize = 0;
+ for req in &inner.pending {
+ let c = req.item.cost();
+ // Stop if taking this item would exceed the cost cap — but
+ // only if we already have at least one item in the batch.
+ // Otherwise (take_count == 0) fall through and take a single
+ // oversize item alone: Python does the same, to avoid starving
+ // a request whose cost is simply larger than the cap.
+ if batch_cost + c > max_cost && take_count > 0 {
+ break;
+ }
+ batch_cost += c;
+ take_count += 1;
+ if take_count >= max_requests {
+ break;
+ }
+ }
+
+ // Drain the taken prefix into parallel vecs.
+ let drained: Vec<PendingRequest<I, T>> = inner.pending.drain(..take_count).collect();
+ inner.total_cost -= batch_cost;
+
+ let mut items = Vec::with_capacity(drained.len());
+ let mut metadata = Vec::with_capacity(drained.len());
+ for req in drained {
+ items.push(req.item);
+ metadata.push(req.metadata);
+ }
+
+ // Queue emptied → reset both timers so the next submit starts a
+ // fresh coalesce/timeout window.
+ if inner.pending.is_empty() {
+ inner.first_request_time = None;
+ inner.last_submit_time = None;
+ }
+
+ FormattedBatch {
+ items,
+ metadata,
+ total_cost: batch_cost,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Duration;
+ use tokio::time::{sleep as tsleep, Duration as TDuration};
+
+ /// Minimal `HasCost` stub: carries a fixed cost and a position.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ struct StubItem {
+ cost: u64,
+ idx: usize,
+ }
+
+ impl StubItem {
+ fn new(cost: u64) -> Self {
+ Self { cost, idx: 0 }
+ }
+
+ fn with_idx(cost: u64, idx: usize) -> Self {
+ Self { cost, idx }
+ }
+ }
+
+ impl HasCost for StubItem {
+ fn cost(&self) -> u64 {
+ self.cost
+ }
+ fn original_index(&self) -> usize {
+ self.idx
+ }
+ }
+
+ #[tokio::test]
+ async fn submit_and_drain_roundtrip() {
+ let b = BatchFormer::<StubItem, u32>::new(BatchConfig::default());
+ b.submit(StubItem::new(10), 1).await;
+ b.submit(StubItem::new(20), 2).await;
+ assert_eq!(b.pending_count().await, 2);
+ assert_eq!(b.pending_cost().await, 30);
+
+ let batch = b.try_drain().await.expect("drain should succeed");
+ assert_eq!(batch.size(), 2);
+ assert_eq!(batch.total_cost, 30);
+ assert_eq!(b.pending_count().await, 0);
+ assert_eq!(b.pending_cost().await, 0);
+ }
+
+ #[tokio::test]
+ async fn cost_cap_triggers_extract() {
+ let cfg = BatchConfig {
+ max_batch_cost: 30,
+ max_batch_requests: 64,
+ max_batch_wait_ms: 10_000.0, // big so only cost triggers
+ coalesce_ms: 10_000.0,
+ coalesce_ratio: 1.0,
+ };
+ let b = BatchFormer::<StubItem, u32>::new(cfg);
+ b.submit(StubItem::new(15), 1).await;
+ b.submit(StubItem::new(15), 2).await;
+ // total_cost (30) >= max_batch_cost (30) → should_yield now.
+ let batch = b.try_get_batch().await.expect("cost cap should trigger");
+ assert_eq!(batch.size(), 2);
+ assert_eq!(batch.total_cost, 30);
+ }
+
+ #[tokio::test]
+ async fn count_cap_triggers_extract() {
+ let cfg = BatchConfig {
+ max_batch_cost: 1_000_000,
+ max_batch_requests: 3,
+ max_batch_wait_ms: 10_000.0,
+ coalesce_ms: 10_000.0,
+ coalesce_ratio: 1.0,
+ };
+ let b = BatchFormer::<StubItem, u32>::new(cfg);
+ b.submit(StubItem::new(1), 1).await;
+ b.submit(StubItem::new(1), 2).await;
+ b.submit(StubItem::new(1), 3).await;
+ let batch = b.try_get_batch().await.expect("count cap should trigger");
+ assert_eq!(batch.size(), 3);
+ }
+
+ #[tokio::test]
+ async fn cost_sort_reorders_pending_ascending() {
+ let cfg = BatchConfig {
+ max_batch_cost: 1_000_000,
+ max_batch_requests: 64,
+ ..BatchConfig::default()
+ };
+ let b = BatchFormer::<StubItem, usize>::new(cfg);
+ // Insert out-of-order costs.
+ b.submit(StubItem::with_idx(50, 0), 0).await;
+ b.submit(StubItem::with_idx(10, 1), 1).await;
+ b.submit(StubItem::with_idx(30, 2), 2).await;
+
+ let batch = b.try_drain().await.unwrap();
+ let costs: Vec<u64> = batch.items.iter().map(|i| i.cost()).collect();
+ assert_eq!(costs, vec![10, 30, 50], "must be sorted ascending");
+ }
+
+ #[tokio::test]
+ async fn oversize_item_flushes_alone() {
+ let cfg = BatchConfig {
+ max_batch_cost: 100,
+ max_batch_requests: 64,
+ ..BatchConfig::default()
+ };
+ 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");
+ assert_eq!(batch.size(), 1);
+ assert_eq!(batch.total_cost, 500);
+ }
+
+ #[tokio::test]
+ async fn extract_leaves_remainder_in_queue() {
+ let cfg = BatchConfig {
+ max_batch_cost: 25,
+ max_batch_requests: 64,
+ ..BatchConfig::default()
+ };
+ let b = BatchFormer::<StubItem, u32>::new(cfg);
+ b.submit(StubItem::new(10), 1).await;
+ b.submit(StubItem::new(10), 2).await;
+ b.submit(StubItem::new(10), 3).await;
+ // total_cost = 30 ≥ 25 → should_yield; extract packs two (sum 20),
+ // drops the third because 20+10=30 > 25.
+ let batch = b.try_get_batch().await.unwrap();
+ assert_eq!(batch.size(), 2);
+ assert_eq!(batch.total_cost, 20);
+ assert_eq!(b.pending_count().await, 1);
+ assert_eq!(b.pending_cost().await, 10);
+ }
+
+ #[tokio::test]
+ async fn empty_batcher_returns_none_from_try_paths() {
+ let b = BatchFormer::<StubItem, u32>::new(BatchConfig::default());
+ assert!(b.try_get_batch().await.is_none());
+ assert!(b.try_drain().await.is_none());
+ }
+
+ #[tokio::test]
+ async fn immediate_get_batch_flushes_without_timeout() {
+ let cfg = BatchConfig {
+ max_batch_wait_ms: 10_000.0, // would block for 10 seconds otherwise
+ coalesce_ms: 10_000.0,
+ coalesce_ratio: 1.0,
+ ..BatchConfig::default()
+ };
+ let b = BatchFormer::<StubItem, u32>::new(cfg);
+ b.submit(StubItem::new(1), 1).await;
+
+ // This would hang without `immediate = true`; with it, it
+ // returns as soon as the single pending item is visible.
+ let batch = b.get_batch(true).await;
+ assert_eq!(batch.size(), 1);
+ }
+
+ #[tokio::test]
+ async fn timers_reset_when_queue_empties() {
+ let b = BatchFormer::<StubItem, u32>::new(BatchConfig::default());
+ b.submit(StubItem::new(1), 1).await;
+ assert!(b.first_request_time().await.is_some());
+ let _ = b.try_drain().await.unwrap();
+ assert!(
+ b.first_request_time().await.is_none(),
+ "emptying the queue must reset the first-request timer"
+ );
+ }
+
+ #[tokio::test]
+ async fn get_batch_times_out_after_max_wait() {
+ // Real-clock test: `wait_timeout` reads `std::Instant::now`,
+ // so mixing tokio's pause() with wall time causes spin loops.
+ // A real 40 ms ceiling keeps the test fast enough to run in
+ // the hot suite.
+ let cfg = BatchConfig {
+ max_batch_cost: 1_000_000,
+ 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
+ };
+ let b = BatchFormer::<StubItem, u32>::new(cfg);
+ b.submit(StubItem::new(1), 1).await;
+
+ // Expect get_batch to complete between the wait window and
+ // the timeout ceiling.
+ let start = std::time::Instant::now();
+ let batch = tokio::time::timeout(TDuration::from_millis(200), b.get_batch(false))
+ .await
+ .expect("must flush on timeout within 200 ms");
+ let elapsed_ms = start.elapsed().as_millis();
+ assert_eq!(batch.size(), 1);
+ assert!(
+ elapsed_ms >= 15,
+ "must wait at least ~max_batch_wait_ms before flushing (waited {elapsed_ms} ms)"
+ );
+ }
+
+ #[tokio::test]
+ async fn submit_many_takes_one_lock() {
+ // Functional check: all items end up pending in arrival order.
+ let b = BatchFormer::<StubItem, u32>::new(BatchConfig::default());
+ let items: Vec<(StubItem, u32)> = (0..5)
+ .map(|i| (StubItem::with_idx(i as u64 + 1, i), i as u32))
+ .collect();
+ b.submit_many(items).await;
+ assert_eq!(b.pending_count().await, 5);
+ assert_eq!(b.pending_cost().await, 1 + 2 + 3 + 4 + 5);
+ }
+
+ #[tokio::test]
+ async fn update_config_wakes_consumer_when_new_cap_already_satisfied() {
+ // NB: don't pause() here — the consumer races a real submit
+ // through Notify, and the pattern is intrinsically clock-free
+ // once the Notified future is enabled inside the lock.
+ let original = BatchConfig {
+ max_batch_cost: 1_000_000,
+ max_batch_requests: 1000,
+ max_batch_wait_ms: 1_000_000.0,
+ coalesce_ms: 1_000_000.0,
+ coalesce_ratio: 1.0,
+ };
+ let b = std::sync::Arc::new(BatchFormer::<StubItem, u32>::new(original));
+ b.submit(StubItem::new(5), 1).await;
+
+ // Spawn a consumer that will block in `get_batch`.
+ let consumer = {
+ let b = std::sync::Arc::clone(&b);
+ tokio::spawn(async move { b.get_batch(false).await })
+ };
+
+ // Yield so the consumer can reach the await point.
+ tokio::task::yield_now().await;
+ tsleep(TDuration::from_millis(1)).await;
+
+ // Shrink the cap so the one pending item now trips
+ // `batch_is_full`; the update must wake the consumer.
+ //
+ // Build the new config from a plain copy of `original` so we
+ // don't re-acquire the inner lock while `update_config` is
+ // about to acquire it — that would deadlock.
+ let shrunk = BatchConfig {
+ max_batch_cost: 1,
+ max_batch_requests: 1,
+ ..original
+ };
+ b.update_config(shrunk).await;
+
+ let batch = tokio::time::timeout(TDuration::from_secs(2), consumer)
+ .await
+ .expect("consumer must finish within 2s of the config shrink")
+ .unwrap();
+ assert_eq!(batch.size(), 1);
+ }
+
+ #[test]
+ fn wait_timeout_shrinks_as_time_passes() {
+ // Build an `Inner` directly so we can test the sync helper.
+ let cfg = BatchConfig {
+ max_batch_wait_ms: 20.0,
+ coalesce_ms: 1_000_000.0,
+ coalesce_ratio: 1.0,
+ ..BatchConfig::default()
+ };
+ let now = Instant::now();
+ let inner: Inner<StubItem, u32> = Inner {
+ pending: vec![PendingRequest {
+ item: StubItem::new(1),
+ metadata: 1,
+ arrival_time: now,
+ }],
+ total_cost: 1,
+ first_request_time: Some(now - Duration::from_millis(5)),
+ last_submit_time: Some(now),
+ config: cfg,
+ };
+ let t = wait_timeout(&inner).expect("pending → Some");
+ // roughly 15 ms remaining (20 - 5), ±5 ms slop for clock jitter.
+ assert!(t <= Duration::from_millis(20));
+ }
+
+ #[test]
+ fn wait_timeout_none_when_no_pending() {
+ let cfg = BatchConfig::default();
+ let inner: Inner<StubItem, u32> = Inner {
+ pending: vec![],
+ total_cost: 0,
+ first_request_time: None,
+ last_submit_time: None,
+ config: cfg,
+ };
+ assert!(wait_timeout(&inner).is_none());
+ }
+
+ #[test]
+ fn coalesce_clamps_to_proportional_under_short_wait() {
+ // Coalesce window = min(15, 4 * 0.5) = 2 ms.
+ let cfg = BatchConfig {
+ coalesce_ms: 15.0,
+ coalesce_ratio: 0.5,
+ max_batch_wait_ms: 4.0,
+ ..BatchConfig::default()
+ };
+ assert!((cfg.effective_coalesce_ms() - 2.0).abs() < f64::EPSILON);
+ }
+}
diff --git a/packages/sie_server_sidecar/src/scheduler/engine.rs b/packages/sie_server_sidecar/src/scheduler/engine.rs
new file mode 100644
index 000000000..e8e546cf1
--- /dev/null
+++ b/packages/sie_server_sidecar/src/scheduler/engine.rs
@@ -0,0 +1,1271 @@
+//! [`Scheduler`] — the per-model scheduler glue that ties
+//! [`BatchFormer`], [`AdaptiveBatchController`],
+//! [`BatchEfficiencyTracker`], and [`LatencyTracker`] together.
+//!
+//! Ported from `sie_server/core/worker/model_worker.py::ModelWorker`
+//! but **only the scheduling half** — admission, per-LoRA batch
+//! formation, FCFS fairness, and the adaptive-controller step after
+//! each batch. The forward pass + adapter I/O still happen
+//! Python-side; this module decides *which batch* to dispatch and
+//! *when*, then hands it off.
+//!
+//! ## Routing
+//!
+//! Matches Python's asymmetric policy exactly:
+//!
+//! * **Encode / Extract** route by `options["lora"]` → per-LoRA batcher.
+//! `None` (or the empty-string normalisation, see [`LoraKey`]) means
+//! the base model.
+//! * **Score** always goes to the base batcher regardless of
+//! `options["lora"]`. Keeping score on the base queue avoids a
+//! head-of-line-blocking class of incidents that fired the last
+//! time this was unified — comment is in
+//! `model_worker.py::_submit_score`.
+//!
+//! ## Fairness
+//!
+//! A batcher's head age is the arrival time of its oldest still-pending
+//! item. Each `BatcherEntry` tracks this as a lock-free
+//! [`AtomicU64`] (nanos since the scheduler's epoch; `0` means the
+//! batcher is empty). `pick_oldest` scans every entry with a single
+//! `Relaxed` load per entry; under the scheduler's expected O(tens) of
+//! entries this is cheaper than a mutex in every hot path.
+//!
+//! The per-batcher head is set on the *first* submit and cleared only
+//! when an extract drains the queue to empty — mid-flush, it still
+//! reflects the original first-submit time. Python does the same;
+//! see `batcher.py::_extract_batch` "Reset timers if we've emptied
+//! the queue". This is the correct fairness primitive: "how long has
+//! the oldest item in this LoRA been waiting".
+
+use std::collections::HashMap;
+use std::hash::Hash;
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::Arc;
+use std::time::Instant;
+
+use tokio::sync::{Mutex, Notify, RwLock};
+
+use crate::latency::LatencyTracker;
+
+use super::adaptive::AdaptiveBatchController;
+use super::batch_config::BatchConfig;
+use super::batch_former::{BatchFormer, FormattedBatch, HasCost};
+use super::trackers::BatchEfficiencyTracker;
+
+/// Snapshot returned by [`Scheduler::record_completion`] for the
+/// caller to feed into Prometheus / structured logs after a batch
+/// completes. Mirrors the post-step block in Python's
+/// `model_worker.py::_step_adaptive_controller` (~lines 752-765)
+/// where `ADAPTIVE_BATCH_WAIT`, `ADAPTIVE_BATCH_COST`,
+/// `ADAPTIVE_P50`, `ADAPTIVE_HEADROOM`, `ADAPTIVE_FILL_RATIO`,
+/// `ADAPTIVE_STARVATION_STREAK`, and `ADAPTIVE_STARVATION_RESETS`
+/// are pushed.
+///
+/// The dispatcher consumes this and emits the corresponding
+/// `sie_worker_scheduler_adaptive_*` Prometheus families. Returning
+/// the snapshot (rather than emitting metrics from inside the
+/// scheduler) keeps the scheduler module free of label-vocabulary
+/// concerns and keeps the Prometheus dependency boundary at the
+/// dispatcher seam.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct RecordCompletionOutcome {
+ /// New `max_batch_wait_ms` cap after the controller step.
+ pub new_wait_ms: f64,
+ /// New `max_batch_cost` cap after the controller step.
+ pub new_batch_cost: u64,
+ /// p50 of the latency tracker at step time, if enough samples
+ /// have accumulated. `None` during warm-up.
+ pub observed_p50_ms: Option<f64>,
+ /// Controller's current target p50, either explicit or
+ /// auto-calibrated. `None` until calibration completes.
+ pub target_p50_ms: Option<f64>,
+ /// Mean fill ratio reported by the efficiency tracker.
+ pub fill_ratio: Option<f64>,
+ /// Consecutive sub-`starvation_batch_size` batches as of this
+ /// step. Reset to 0 when recovery fires.
+ pub starvation_streak: u32,
+ /// Increase in `AdaptiveBatchController::starvation_resets()`
+ /// since the previous `record_completion` call. Callers
+ /// `inc_by` their starvation-reset counter by this delta — the
+ /// underlying counter is monotonic so a delta is the right
+ /// shape for a Prometheus `IntCounter`.
+ pub starvation_resets_delta: u32,
+ /// Size of the batch whose completion drove this step. Echoed
+ /// back so callers don't have to re-thread it through.
+ pub batch_size: usize,
+}
+
+/// Operation class of a submitted item.
+///
+/// Kept separate from `work_types::WorkItem::op` so the scheduler
+/// module has no dependency on the NATS-facing wire types. The
+/// dispatcher translates at the call site.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum Op {
+ Encode,
+ Score,
+ Extract,
+}
+
+/// LoRA routing key. Normalises both `None` and `Some("")` to the
+/// single canonical base key so the map doesn't fragment on empty
+/// strings coming off the wire.
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct LoraKey(Option<String>);
+
+impl LoraKey {
+ /// The base model key — used explicitly by score submits and by
+ /// encode/extract submits with no `options["lora"]`.
+ #[must_use]
+ pub fn base() -> Self {
+ Self(None)
+ }
+
+ /// Build from a raw string; empty strings normalise to `base()`.
+ ///
+ /// Named `from_name` rather than `from_str` so it doesn't collide
+ /// with [`std::str::FromStr`]'s convention (which expects a
+ /// `Result` return + an associated error type). This cannot fail,
+ /// and adding a bogus infallible error type just to satisfy the
+ /// trait would be churn for no caller benefit.
+ #[must_use]
+ pub fn from_name(s: &str) -> Self {
+ if s.is_empty() {
+ Self::base()
+ } else {
+ Self(Some(s.to_owned()))
+ }
+ }
+
+ /// Build from `Option<String>`, normalising `Some("")` to `None`.
+ #[must_use]
+ pub fn from_option(o: Option<String>) -> Self {
+ match o {
+ Some(s) if s.is_empty() => Self::base(),
+ other => Self(other),
+ }
+ }
+
+ /// `true` when this key refers to the base model (no LoRA).
+ #[must_use]
+ pub fn is_base(&self) -> bool {
+ self.0.is_none()
+ }
+
+ /// Borrow the LoRA name, or `None` if this is the base key.
+ #[must_use]
+ pub fn as_str(&self) -> Option<&str> {
+ self.0.as_deref()
+ }
+}
+
+/// Map key for the scheduler's batcher registry. Named alias keeps
+/// signatures readable and silences `clippy::type_complexity` on the
+/// `RwLock<HashMap<...>>` field of [`Scheduler`].
+type BatcherKey = (Op, LoraKey);
+
+/// Map of live batchers keyed by `(op, lora)`. See
+/// [`BatcherEntry`] for what each value holds.
+type BatcherMap<I, T> = HashMap<BatcherKey, Arc<BatcherEntry<I, T>>>;
+
+/// One entry in the scheduler's (op, lora) → batcher map. Holds the
+/// [`BatchFormer`] plus a lock-free head-age atomic the FCFS scan
+/// reads.
+#[derive(Debug)]
+struct BatcherEntry<I: HasCost, T> {
+ op: Op,
+ lora: LoraKey,
+ former: Arc<BatchFormer<I, T>>,
+ /// Nanos since [`Scheduler::epoch`]. `0` ⇒ batcher has no pending
+ /// items. Any nonzero value is the timestamp at which the first
+ /// *currently-pending* item was submitted — i.e. the arrival time
+ /// of this batcher's oldest waiter.
+ head_ns: AtomicU64,
+}
+
+/// The per-model scheduler.
+///
+/// Generic over the item type `I` (must implement [`HasCost`]) and
+/// the caller-supplied per-item metadata `T`. Production wires this as
+/// `Scheduler<SchedulerItem, WorkMeta>` at the dispatcher boundary;
+/// tests use simple stubs.
+pub struct Scheduler<I: HasCost, T> {
+ batchers: RwLock<BatcherMap<I, T>>,
+ controller: Mutex<AdaptiveBatchController>,
+ latency: Mutex<LatencyTracker>,
+ efficiency: Mutex<BatchEfficiencyTracker>,
+ /// Current caps used for *newly created* batchers. Existing
+ /// batchers receive updates via [`Scheduler::record_completion`]
+ /// after each controller step. Kept behind an async `RwLock`
+ /// because readers are rare (new-batcher creation only).
+ config: RwLock<BatchConfig>,
+ /// Fired on every submit that inserts into a previously empty
+ /// batcher. [`Scheduler::consume_next`] uses this to wake its
+ /// FCFS scan without polling.
+ new_item: Notify,
+ /// Wall-clock origin for per-batcher `head_ns` atomics. Stored as
+ /// `Instant` (monotonic) so head-age comparisons are unaffected by
+ /// wall-clock jumps. `Arc`'d only because the struct is sometimes
+ /// cloned in tests; the field itself is `Copy`.
+ epoch: Instant,
+}
+
+impl<I, T> Scheduler<I, T>
+where
+ I: HasCost + Send + Sync + 'static,
+ T: Send + Sync + 'static,
+{
+ /// Construct a scheduler with the given initial caps and a
+ /// default [`AdaptiveBatchController`] (auto-calibrating target,
+ /// Python-parity defaults elsewhere).
+ ///
+ /// Most callers want [`Scheduler::builder`] to customise the
+ /// controller / tracker windows.
+ #[must_use]
+ pub fn new(config: BatchConfig) -> Self {
+ Self::builder().config(config).build()
+ }
+
+ /// Fluent builder. See [`SchedulerBuilder`].
+ #[must_use]
+ pub fn builder() -> SchedulerBuilder<I, T> {
+ SchedulerBuilder::default()
+ }
+
+ // ---- Introspection helpers (used by `consume_next` and tests) ----
+
+ /// Current snapshot of the batch caps. Held by value — callers
+ /// always get a consistent view even if another task is in the
+ /// middle of [`Scheduler::record_completion`].
+ pub async fn config(&self) -> BatchConfig {
+ *self.config.read().await
+ }
+
+ /// Sum of pending items across every (op, lora) batcher.
+ pub async fn total_pending_count(&self) -> usize {
+ let map = self.batchers.read().await;
+ let mut total = 0usize;
+ for e in map.values() {
+ total += e.former.pending_count().await;
+ }
+ total
+ }
+
+ /// Sum of pending cost across every (op, lora) batcher.
+ pub async fn total_pending_cost(&self) -> u64 {
+ let map = self.batchers.read().await;
+ let mut total = 0u64;
+ for e in map.values() {
+ total += e.former.pending_cost().await;
+ }
+ total
+ }
+
+ /// Snapshot of the adaptive controller's observable state. Useful
+ /// for dashboards / readiness probes.
+ pub async fn controller_snapshot(&self) -> super::adaptive::AdaptiveBatchState {
+ let ctrl = self.controller.lock().await;
+ let observed = self.latency.lock().await.p50();
+ let fill = self.efficiency.lock().await.mean_fill_ratio();
+ ctrl.snapshot(observed, fill)
+ }
+
+ // ---- Submit path ----
+
+ /// Enqueue a single item. Routing rules: encode/extract go to
+ /// `(op, lora)`; score always forces `lora = base` regardless of
+ /// what the caller passed.
+ pub async fn submit(&self, op: Op, lora: LoraKey, item: I, metadata: T) {
+ let key = Self::route_key(op, lora);
+ let entry = self.get_or_create(&key).await;
+ self.mark_head_on_first_submit(&entry);
+ entry.former.submit(item, metadata).await;
+ }
+
+ /// Bulk submit under a single BatchFormer-lock. Use this for
+ /// multi-item requests (SDK batches of ≤ 64 are common).
+ pub async fn submit_many(&self, op: Op, lora: LoraKey, items: Vec<(I, T)>) {
+ if items.is_empty() {
+ return;
+ }
+ let key = Self::route_key(op, lora);
+ let entry = self.get_or_create(&key).await;
+ self.mark_head_on_first_submit(&entry);
+ entry.former.submit_many(items).await;
+ }
+
+ // ---- Consume path ----
+
+ /// Block until some batcher has pending items, FCFS-pick the one
+ /// whose oldest-head is oldest, and return its flushed batch.
+ ///
+ /// `immediate = true` forwards directly to
+ /// [`BatchFormer::get_batch`] so a single pending item flushes at
+ /// once without the `max_batch_wait_ms` wait — used when the
+ /// caller was idle and knows no further arrivals are likely.
+ pub async fn consume_next(&self, immediate: bool) -> (Op, LoraKey, FormattedBatch<I, T>) {
+ loop {
+ // Arm the notification *before* scanning: a submit that
+ // fires between scan and await is captured in the
+ // Notified's permit slot (see `Notified::enable` docs).
+ let notified = self.new_item.notified();
+ tokio::pin!(notified);
+ notified.as_mut().enable();
+
+ if let Some(entry) = self.pick_oldest().await {
+ let batch = entry.former.get_batch(immediate).await;
+ self.maybe_clear_head(&entry).await;
+ return (entry.op, entry.lora.clone(), batch);
+ }
+ notified.await;
+ }
+ }
+
+ /// Non-blocking variant of [`Self::consume_next`]. Returns `None`
+ /// if no batcher has pending items *or* if the FCFS-picked batcher
+ /// isn't yet ready to flush (flush triggers haven't fired).
+ pub async fn try_consume_next(&self) -> Option<(Op, LoraKey, FormattedBatch<I, T>)> {
+ let entry = self.pick_oldest().await?;
+ let batch = entry.former.try_get_batch().await?;
+ self.maybe_clear_head(&entry).await;
+ Some((entry.op, entry.lora.clone(), batch))
+ }
+
+ /// Continuous-batching tail: drain whatever's left in `(op, lora)`'s
+ /// batcher immediately, bypassing flush triggers. Returns `None`
+ /// when the batcher has no pending items (or doesn't exist).
+ ///
+ /// Matches the Python adapter process's `try_drain` call after each forward
+ /// pass. Expected usage: after consume_next returns a batch for
+ /// `(op, lora)`, loop on `try_drain_same(op, lora)` until it
+ /// returns `None`.
+ pub async fn try_drain_same(&self, op: Op, lora: LoraKey) -> Option<FormattedBatch<I, T>> {
+ let key = Self::route_key(op, lora);
+ let entry = self.batchers.read().await.get(&key).cloned()?;
+ let batch = entry.former.try_drain().await?;
+ self.maybe_clear_head(&entry).await;
+ Some(batch)
+ }
+
+ // ---- Controller step + efficiency / latency plumbing ----
+
+ /// Feed the auto-calibration tracker with an inference-only
+ /// sample (GPU forward pass, no queue / no postprocess).
+ ///
+ /// Python's ModelWorker calls this with `RequestTiming.inference_ms`;
+ /// once the controller is calibrated this is a cheap no-op.
+ pub async fn record_inference_sample(&self, inference_ms: f64) {
+ let mut ctrl = self.controller.lock().await;
+ ctrl.record_inference_sample(inference_ms);
+ }
+
+ /// Record one item's total latency (queue + inference +
+ /// postprocess) — call **once per item** in a completed batch.
+ ///
+ /// Mirrors Python's `_check_partial_results` block at
+ /// `model_worker.py:1004` which calls
+ /// `_latency_tracker.record(metadata.timing.total_ms)` for every
+ /// completed item. Per-item recording is mathematically critical
+ /// for the controller: feeding per-batch MAX values would bias
+ /// `observed_p50_ms` toward the per-item p99 of the underlying
+ /// distribution and drive `max_batch_wait_ms` to its floor under
+ /// concurrent load.
+ pub async fn record_latency_sample(&self, total_ms: f64) {
+ self.latency.lock().await.record(total_ms);
+ }
+
+ /// Bulk variant of [`Self::record_latency_sample`] — pushes
+ /// every value in `samples` under a single mutex acquire. Use
+ /// when the caller already has the per-item totals collected
+ /// (e.g. the dispatcher's per-item zip over `outcomes` x
+ /// `metadata`); avoids N lock acquires for typical batches of
+ /// 16–32 items.
+ pub async fn record_latency_samples(&self, samples: &[f64]) {
+ if samples.is_empty() {
+ return;
+ }
+ let mut t = self.latency.lock().await;
+ for s in samples {
+ t.record(*s);
+ }
+ }
+
+ /// Record a batch's completion metrics (efficiency + controller
+ /// step) and propagate the new caps to every live batcher.
+ ///
+ /// **Latency samples must be fed beforehand** via
+ /// [`Self::record_latency_sample`] / [`Self::record_latency_samples`].
+ /// This call only consumes the *current* tracker p50 — it does
+ /// not record any latency itself. Splitting the surface that
+ /// way keeps the per-item-vs-per-batch sample-rate question
+ /// purely a caller concern.
+ ///
+ /// `batch_cost` = total cost of the batch that just completed
+ /// (used by the efficiency tracker → fill_ratio knob). `batch_size`
+ /// = item count (used by the starvation detector).
+ ///
+ /// Returns a [`RecordCompletionOutcome`] for the caller to push
+ /// to Prometheus. Mirrors Python's `model_worker.py:752-765`.
+ pub async fn record_completion(
+ &self,
+ batch_cost: u64,
+ batch_size: usize,
+ ) -> RecordCompletionOutcome {
+ let current_cap = self.config.read().await.max_batch_cost;
+ self.efficiency.lock().await.record(batch_cost, current_cap);
+
+ // Snapshot the trackers *before* the controller step so the
+ // returned outcome reflects the same observation the
+ // controller acted on (Python's `_step_adaptive_controller`
+ // does the same — it reads `observed_p50` once and reuses
+ // the value for both the step and the metric push).
+ let observed_p50 = self.latency.lock().await.p50();
+ let fill = self.efficiency.lock().await.mean_fill_ratio();
+
+ let (new_wait, new_cost, target_p50, starvation_streak, starvation_resets_delta) = {
+ let mut ctrl = self.controller.lock().await;
+ let prev_resets = ctrl.starvation_resets();
+ let (w, c) = ctrl.step(observed_p50, fill, Some(batch_size));
+ let new_resets = ctrl.starvation_resets();
+ (
+ w,
+ c,
+ ctrl.target_p50_ms(),
+ ctrl.starvation_streak(),
+ new_resets.saturating_sub(prev_resets),
+ )
+ };
+
+ // Update the shared snapshot. Short critical section under
+ // the write lock — we only mutate two fields.
+ let new_cfg = {
+ let mut cfg = self.config.write().await;
+ cfg.max_batch_wait_ms = new_wait;
+ cfg.max_batch_cost = new_cost;
+ *cfg
+ };
+
+ // Propagate to every live batcher. We snapshot the Vec of
+ // Arcs under the read lock and drop it before the async
+ // `update_config` calls so a concurrent submit that creates a
+ // new batcher doesn't deadlock. A batcher created *after*
+ // this snapshot sees `new_cfg` via `config.read()` in
+ // `get_or_create`, so we don't lose the update.
+ let entries: Vec<Arc<BatcherEntry<I, T>>> = {
+ let map = self.batchers.read().await;
+ map.values().cloned().collect()
+ };
+ for entry in entries {
+ entry.former.update_config(new_cfg).await;
+ }
+
+ RecordCompletionOutcome {
+ new_wait_ms: new_wait,
+ new_batch_cost: new_cost,
+ observed_p50_ms: observed_p50,
+ target_p50_ms: target_p50,
+ fill_ratio: fill,
+ starvation_streak,
+ starvation_resets_delta,
+ batch_size,
+ }
+ }
+
+ // ---- Internal helpers ----
+
+ fn route_key(op: Op, lora: LoraKey) -> BatcherKey {
+ match op {
+ // Score always lives on the base queue, regardless of
+ // what the caller asked for. Matches Python's
+ // `_submit_score` behaviour; see the module-level
+ // doc-comment for why this is load-bearing.
+ Op::Score => (Op::Score, LoraKey::base()),
+ _ => (op, lora),
+ }
+ }
+
+ async fn get_or_create(&self, key: &BatcherKey) -> Arc<BatcherEntry<I, T>> {
+ // Fast path: read lock, return existing.
+ if let Some(e) = self.batchers.read().await.get(key) {
+ return Arc::clone(e);
+ }
+ // Slow path: take the write lock and double-check — another
+ // task may have inserted concurrently.
+ let mut map = self.batchers.write().await;
+ if let Some(e) = map.get(key) {
+ return Arc::clone(e);
+ }
+ let cfg = *self.config.read().await;
+ let entry = Arc::new(BatcherEntry {
+ op: key.0,
+ lora: key.1.clone(),
+ former: Arc::new(BatchFormer::new(cfg)),
+ head_ns: AtomicU64::new(0),
+ });
+ map.insert(key.clone(), Arc::clone(&entry));
+ entry
+ }
+
+ /// Set `head_ns` to "now" if the entry was empty. If it was
+ /// already non-zero (i.e. this batcher already has pending items
+ /// from an earlier submit), leave the existing value alone —
+ /// Python keeps the original first-submit time across mid-flush
+ /// churn for fairness accounting.
+ fn mark_head_on_first_submit(&self, entry: &BatcherEntry<I, T>) {
+ let now_ns = self.epoch.elapsed().as_nanos() as u64;
+ // Ensure we never store 0 on a real submit — 0 is reserved
+ // for "empty". Instants that round to 0 ns are
+ // astronomically unlikely (would require submit in the
+ // first tick of the runtime's clock), but saturating_add
+ // here keeps the invariant airtight.
+ let ts = now_ns.saturating_add(1);
+ let _ = entry
+ .head_ns
+ .compare_exchange(0, ts, Ordering::AcqRel, Ordering::Relaxed);
+ // If the CAS fails, head_ns was already non-zero — keep
+ // the older timestamp. Also fire the ready-notify so the
+ // consumer's FCFS loop picks this up even on the first
+ // submit into a brand-new LoRA.
+ self.new_item.notify_one();
+ }
+
+ /// Zero `head_ns` iff the batcher has no pending items after an
+ /// extract. Leaves non-zero values alone otherwise.
+ async fn maybe_clear_head(&self, entry: &BatcherEntry<I, T>) {
+ if entry.former.pending_count().await == 0 {
+ entry.head_ns.store(0, Ordering::Release);
+ }
+ }
+
+ async fn pick_oldest(&self) -> Option<Arc<BatcherEntry<I, T>>> {
+ let map = self.batchers.read().await;
+ let mut best: Option<(u64, Arc<BatcherEntry<I, T>>)> = None;
+ for entry in map.values() {
+ let head = entry.head_ns.load(Ordering::Acquire);
+ if head == 0 {
+ continue;
+ }
+ match &best {
+ None => best = Some((head, Arc::clone(entry))),
+ Some((ts, _)) if head < *ts => {
+ best = Some((head, Arc::clone(entry)));
+ }
+ _ => {}
+ }
+ }
+ best.map(|(_, e)| e)
+ }
+}
+
+// `Scheduler` intentionally doesn't derive `Clone`; the expected
+// pattern is `Arc<Scheduler<...>>`. Making it clonable would hide
+// the aliasing and let a test accidentally fork the adaptive
+// controller state.
+impl<I: HasCost, T> std::fmt::Debug for Scheduler<I, T> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Scheduler")
+ .field("epoch", &self.epoch)
+ .finish_non_exhaustive()
+ }
+}
+
+// ---- Builder ----
+
+/// Builder for [`Scheduler`]. Separated from the plain `new` path so
+/// operators can tune the controller / tracker windows per model
+/// without the `new` signature growing indefinitely.
+pub struct SchedulerBuilder<I: HasCost, T> {
+ config: BatchConfig,
+ controller: Option<AdaptiveBatchController>,
+ latency_window: usize,
+ latency_min_samples: usize,
+ efficiency_window: usize,
+ _phantom: std::marker::PhantomData<(I, T)>,
+}
+
+impl<I: HasCost, T> Default for SchedulerBuilder<I, T> {
+ fn default() -> Self {
+ Self {
+ config: BatchConfig::default(),
+ controller: None,
+ // Python's `LatencyTracker(window_size=200, min_samples=10)`.
+ latency_window: 200,
+ latency_min_samples: 10,
+ efficiency_window: 50,
+ _phantom: std::marker::PhantomData,
+ }
+ }
+}
+
+impl<I, T> SchedulerBuilder<I, T>
+where
+ I: HasCost + Send + Sync + 'static,
+ T: Send + Sync + 'static,
+{
+ /// Override the initial batch caps.
+ #[must_use]
+ pub fn config(mut self, config: BatchConfig) -> Self {
+ self.config = config;
+ self
+ }
+
+ /// Supply a pre-configured adaptive controller. If omitted the
+ /// scheduler uses [`AdaptiveBatchController::default`].
+ #[must_use]
+ pub fn controller(mut self, ctrl: AdaptiveBatchController) -> Self {
+ self.controller = Some(ctrl);
+ self
+ }
+
+ /// Override the latency tracker window. Default 200 samples,
+ /// 10-sample warm-up.
+ #[must_use]
+ pub fn latency_window(mut self, window: usize, min_samples: usize) -> Self {
+ self.latency_window = window;
+ self.latency_min_samples = min_samples;
+ self
+ }
+
+ /// Override the efficiency tracker window. Default 50.
+ #[must_use]
+ pub fn efficiency_window(mut self, window: usize) -> Self {
+ self.efficiency_window = window;
+ self
+ }
+
+ #[must_use]
+ pub fn build(self) -> Scheduler<I, T> {
+ // Default controller mirrors Python's
+ // `ModelWorker.__init__` *production* wiring against the
+ // current `BatchConfig` (model `max_batch_tokens` =
+ // `cfg.max_batch_cost`, initial wait = `cfg.max_batch_wait_ms`,
+ // cost floor / ceiling = `max_batch_tokens // 4` ..
+ // `max_batch_tokens * 4`, `cost_gain = gain * 0.5`,
+ // `min_wait_ms = 15.0`). The bare `default()` / module-level
+ // dataclass values are test-only floors — `SchedulerBuilder`
+ // is the production entry point and matches what the Python
+ // worker has been deploying.
+ //
+ // `SIE_ADAPTIVE_BATCH_*` env vars override on top, so
+ // operators can pin individual knobs without a recompile.
+ // Tests using `.controller(...)` continue to bypass both env
+ // and BatchConfig derivation entirely (deterministic).
+ let cfg = self.config;
+ Scheduler {
+ batchers: RwLock::new(HashMap::new()),
+ controller: Mutex::new(
+ self.controller
+ .unwrap_or_else(|| AdaptiveBatchController::from_batch_config_and_env(&cfg)),
+ ),
+ latency: Mutex::new(LatencyTracker::new(
+ self.latency_window,
+ self.latency_min_samples,
+ )),
+ efficiency: Mutex::new(BatchEfficiencyTracker::new(self.efficiency_window)),
+ config: RwLock::new(self.config),
+ new_item: Notify::new(),
+ epoch: Instant::now(),
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use tokio::time::{sleep as tsleep, timeout, Duration as TDuration};
+
+ // ---- Stub item type ----
+
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ struct StubItem {
+ cost: u64,
+ idx: usize,
+ }
+ impl HasCost for StubItem {
+ fn cost(&self) -> u64 {
+ self.cost
+ }
+ fn original_index(&self) -> usize {
+ self.idx
+ }
+ }
+
+ fn make() -> Scheduler<StubItem, u32> {
+ Scheduler::builder()
+ .config(BatchConfig {
+ max_batch_cost: 1_000_000,
+ max_batch_requests: 1000,
+ max_batch_wait_ms: 10_000.0,
+ coalesce_ms: 10_000.0,
+ coalesce_ratio: 1.0,
+ })
+ .build()
+ }
+
+ // ---- Routing ----
+
+ #[tokio::test]
+ async fn encode_routes_per_lora() {
+ let s = make();
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name("a"),
+ StubItem { cost: 1, idx: 0 },
+ 0,
+ )
+ .await;
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name("b"),
+ StubItem { cost: 2, idx: 0 },
+ 1,
+ )
+ .await;
+ assert_eq!(s.total_pending_count().await, 2);
+ let map = s.batchers.read().await;
+ assert!(map.contains_key(&(Op::Encode, LoraKey::from_name("a"))));
+ assert!(map.contains_key(&(Op::Encode, LoraKey::from_name("b"))));
+ }
+
+ #[tokio::test]
+ async fn extract_routes_per_lora() {
+ let s = make();
+ s.submit(
+ Op::Extract,
+ LoraKey::from_name("a"),
+ StubItem { cost: 1, idx: 0 },
+ 0,
+ )
+ .await;
+ let map = s.batchers.read().await;
+ assert!(map.contains_key(&(Op::Extract, LoraKey::from_name("a"))));
+ }
+
+ #[tokio::test]
+ async fn score_always_routes_to_base_even_with_lora_arg() {
+ let s = make();
+ s.submit(
+ Op::Score,
+ LoraKey::from_name("should-be-ignored"),
+ StubItem { cost: 1, idx: 0 },
+ 0,
+ )
+ .await;
+ let map = s.batchers.read().await;
+ // Must not have created a LoRA-keyed score batcher.
+ assert!(
+ !map.contains_key(&(Op::Score, LoraKey::from_name("should-be-ignored"))),
+ "score submit with lora arg must not fragment the score queue"
+ );
+ assert!(map.contains_key(&(Op::Score, LoraKey::base())));
+ }
+
+ #[tokio::test]
+ async fn empty_string_lora_normalises_to_base() {
+ // Empty string and `base()` are indistinguishable as keys —
+ // which is the whole point of the normalisation. We verify
+ // that both submits hit the *same* batcher (map size stays 1)
+ // and that the surviving key is `base()`.
+ let s = make();
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name(""),
+ StubItem { cost: 1, idx: 0 },
+ 0,
+ )
+ .await;
+ s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 1, idx: 1 }, 1)
+ .await;
+ let map = s.batchers.read().await;
+ assert_eq!(map.len(), 1, "empty-string lora must not fragment the map");
+ assert!(map.contains_key(&(Op::Encode, LoraKey::base())));
+ // `LoraKey::from_name("") == LoraKey::base()` by construction —
+ // pin that invariant here so a future refactor can't silently
+ // break the fragment-prevention.
+ assert_eq!(LoraKey::from_name(""), LoraKey::base());
+ }
+
+ #[tokio::test]
+ async fn submit_many_funnels_into_one_batcher() {
+ let s = make();
+ let items: Vec<(StubItem, u32)> = (0..5)
+ .map(|i| (StubItem { cost: 1, idx: i }, i as u32))
+ .collect();
+ s.submit_many(Op::Encode, LoraKey::base(), items).await;
+ assert_eq!(s.total_pending_count().await, 5);
+ }
+
+ // ---- FCFS fairness ----
+
+ #[tokio::test]
+ async fn fcfs_picks_oldest_head_across_loras() {
+ let s = make();
+ // LoRA A arrives first.
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name("a"),
+ StubItem { cost: 1, idx: 0 },
+ 1,
+ )
+ .await;
+ // Tiny real delay so the head_ns values are distinguishable.
+ tsleep(TDuration::from_millis(2)).await;
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name("b"),
+ StubItem { cost: 1, idx: 0 },
+ 2,
+ )
+ .await;
+
+ let (op, lora, batch) = s.consume_next(true).await;
+ assert_eq!(op, Op::Encode);
+ assert_eq!(lora, LoraKey::from_name("a"));
+ assert_eq!(batch.size(), 1);
+ assert_eq!(batch.metadata[0], 1);
+ }
+
+ #[tokio::test]
+ async fn fcfs_ignores_empty_batchers() {
+ let s = make();
+ // Populate LoRA A first, drain it.
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name("a"),
+ StubItem { cost: 1, idx: 0 },
+ 1,
+ )
+ .await;
+ let (_, _, _) = s.consume_next(true).await;
+ assert_eq!(s.total_pending_count().await, 0);
+
+ // Now submit to LoRA B; FCFS must pick B (A is empty).
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name("b"),
+ StubItem { cost: 1, idx: 0 },
+ 2,
+ )
+ .await;
+ let (_, lora, _) = s.consume_next(true).await;
+ assert_eq!(lora, LoraKey::from_name("b"));
+ }
+
+ #[tokio::test]
+ async fn head_ns_clears_only_when_batcher_drains_to_empty() {
+ let s = Scheduler::<StubItem, u32>::builder()
+ .config(BatchConfig {
+ max_batch_cost: 5, // small cap so extract leaves remainder
+ max_batch_requests: 1000,
+ max_batch_wait_ms: 10_000.0,
+ coalesce_ms: 10_000.0,
+ coalesce_ratio: 1.0,
+ })
+ .build();
+ // Two items, cost 3 each. First extract takes one (3 ≤ 5),
+ // stops because 3+3 > 5.
+ s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 3, idx: 0 }, 1)
+ .await;
+ s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 3, idx: 0 }, 2)
+ .await;
+
+ let (_, _, batch) = s.consume_next(false).await;
+ assert_eq!(batch.size(), 1);
+ assert_eq!(s.total_pending_count().await, 1, "one item must remain");
+
+ // The entry's head_ns must still be non-zero so FCFS keeps
+ // honouring it on the next scan.
+ let entry = {
+ let map = s.batchers.read().await;
+ Arc::clone(map.get(&(Op::Encode, LoraKey::base())).unwrap())
+ };
+ let head = entry.head_ns.load(Ordering::Acquire);
+ assert_ne!(
+ head, 0,
+ "head_ns must stay non-zero while pending items remain"
+ );
+
+ // Drain the rest; head should clear.
+ let (_, _, _) = s.consume_next(true).await;
+ assert_eq!(s.total_pending_count().await, 0);
+ let head = entry.head_ns.load(Ordering::Acquire);
+ assert_eq!(head, 0, "head_ns must clear when queue empties");
+ }
+
+ #[tokio::test]
+ async fn consume_next_blocks_when_empty_and_wakes_on_submit() {
+ let s = Arc::new(make());
+ let consumer = {
+ let s = Arc::clone(&s);
+ tokio::spawn(async move { s.consume_next(true).await })
+ };
+
+ // Let the consumer register.
+ tsleep(TDuration::from_millis(5)).await;
+
+ s.submit(
+ Op::Encode,
+ LoraKey::base(),
+ StubItem { cost: 1, idx: 0 },
+ 42,
+ )
+ .await;
+
+ let (op, lora, batch) = timeout(TDuration::from_secs(2), consumer)
+ .await
+ .expect("consumer must wake within 2 s")
+ .unwrap();
+ assert_eq!(op, Op::Encode);
+ assert!(lora.is_base());
+ assert_eq!(batch.metadata[0], 42);
+ }
+
+ #[tokio::test]
+ async fn try_consume_next_returns_none_when_empty() {
+ let s = make();
+ assert!(s.try_consume_next().await.is_none());
+ }
+
+ #[tokio::test]
+ async fn try_drain_same_returns_continuous_batching_tail() {
+ let s = make();
+ // Two separate submits so we can drain one now and the other
+ // via try_drain_same.
+ s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 1, idx: 0 }, 1)
+ .await;
+ let (_, _, _) = s.consume_next(true).await;
+
+ s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 2, idx: 0 }, 2)
+ .await;
+ let drain = s
+ .try_drain_same(Op::Encode, LoraKey::base())
+ .await
+ .expect("must drain pending tail");
+ assert_eq!(drain.size(), 1);
+ assert_eq!(drain.metadata[0], 2);
+ }
+
+ // ---- Adaptive controller wiring ----
+
+ #[tokio::test]
+ async fn record_completion_propagates_config_to_all_batchers() {
+ let ctrl = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(50.0))
+ .update_interval(1) // step on every record_completion
+ .min_wait_ms(1.0)
+ .max_wait_ms(100.0)
+ .min_batch_cost(100)
+ .max_batch_cost(100_000)
+ .initial_wait_ms(20.0)
+ .initial_batch_cost(5_000)
+ .build();
+ let s = Scheduler::<StubItem, u32>::builder()
+ .config(BatchConfig {
+ max_batch_cost: 5_000,
+ max_batch_requests: 1000,
+ max_batch_wait_ms: 20.0,
+ coalesce_ms: 20.0,
+ coalesce_ratio: 0.5,
+ })
+ .controller(ctrl)
+ // Short warm-up so a handful of completions is enough to
+ // drive p50 — the default is 10 samples which would force
+ // a noisier test.
+ .latency_window(20, 3)
+ .build();
+
+ // Submit to two distinct LoRAs so we can observe propagation
+ // to both.
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name("a"),
+ StubItem { cost: 1, idx: 0 },
+ 0,
+ )
+ .await;
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name("b"),
+ StubItem { cost: 1, idx: 0 },
+ 0,
+ )
+ .await;
+
+ // Simulate several completions with observed < target so the
+ // latency tracker crosses its warm-up threshold and the PI
+ // loop bumps `wait_ms` upward.
+ for _ in 0..5 {
+ s.record_latency_sample(10.0).await;
+ let _ = s.record_completion(32, 32).await;
+ }
+
+ let cfg_a = {
+ let map = s.batchers.read().await;
+ map[&(Op::Encode, LoraKey::from_name("a"))]
+ .former
+ .config()
+ .await
+ };
+ let cfg_b = {
+ let map = s.batchers.read().await;
+ map[&(Op::Encode, LoraKey::from_name("b"))]
+ .former
+ .config()
+ .await
+ };
+ assert!(
+ cfg_a.max_batch_wait_ms > 20.0,
+ "wait must have grown from 20 (positive headroom); got {}",
+ cfg_a.max_batch_wait_ms
+ );
+ assert_eq!(
+ cfg_a, cfg_b,
+ "all batchers must see the same caps after record_completion"
+ );
+ // Scheduler's own snapshot tracks the same value.
+ assert_eq!(s.config().await, cfg_a);
+ }
+
+ #[tokio::test]
+ async fn record_completion_feeds_efficiency_tracker() {
+ // Efficiency tracker must see a fill ratio; confirm by
+ // running enough completions to tighten cost knob.
+ let ctrl = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(50.0))
+ .update_interval(1)
+ .fill_ratio_threshold(0.1) // always saturated in test terms
+ .cost_gain(1.0)
+ .initial_batch_cost(1_000)
+ .min_batch_cost(100)
+ .max_batch_cost(10_000)
+ .build();
+ let s = Scheduler::<StubItem, u32>::builder()
+ .config(BatchConfig {
+ max_batch_cost: 1_000,
+ max_batch_requests: 1000,
+ max_batch_wait_ms: 15.0,
+ coalesce_ms: 15.0,
+ coalesce_ratio: 0.5,
+ })
+ .controller(ctrl)
+ .build();
+ s.submit(Op::Encode, LoraKey::base(), StubItem { cost: 1, idx: 0 }, 0)
+ .await;
+
+ // Many completions with observed < target and a high fill
+ // ratio → cost must grow.
+ let before = s.config().await.max_batch_cost;
+ for _ in 0..20 {
+ s.record_latency_sample(10.0).await;
+ let _ = s.record_completion(800, 32).await;
+ }
+ let after = s.config().await.max_batch_cost;
+ assert!(after > before, "cost cap must grow: {before} → {after}");
+ }
+
+ #[tokio::test]
+ async fn controller_snapshot_reflects_latency_and_fill() {
+ let s = Scheduler::<StubItem, u32>::builder()
+ .config(BatchConfig::default())
+ .controller(
+ AdaptiveBatchController::builder()
+ .target_p50_ms(Some(50.0))
+ .update_interval(1)
+ .build(),
+ )
+ .build();
+ // Seed enough samples to cross the latency tracker's min.
+ for _ in 0..12 {
+ s.record_latency_sample(10.0).await;
+ let _ = s.record_completion(32, 32).await;
+ }
+ let snap = s.controller_snapshot().await;
+ assert_eq!(snap.target_p50_ms, Some(50.0));
+ assert_eq!(snap.observed_p50_ms, Some(10.0));
+ assert_eq!(snap.headroom_ms, Some(40.0));
+ assert!(snap.fill_ratio.is_some());
+ }
+
+ #[tokio::test]
+ async fn drain_feeds_do_not_step_controller() {
+ // Regression for #4: Python's `_process_loop` steps the
+ // adaptive controller exactly once per wave, with the
+ // primary batch's size (`model_worker.py:828, 855-870`).
+ // Drains feed inference + latency samples but must not
+ // advance the controller's internal state.
+ //
+ // Encoded here at the scheduler level: the dispatcher
+ // routes Primary → `record_completion`, Drain →
+ // `record_inference_sample` + `record_latency_samples`
+ // (no `record_completion`). This test exercises the
+ // scheduler-side surface contract; the
+ // [`crate::dispatcher::WaveRole`] enum + the
+ // `scheduler_drain_loop` plumbing make sure drains take
+ // the second path.
+ let ctrl = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(50.0))
+ .update_interval(1) // step on every record_completion
+ .starvation_batch_size(1) // size>1 resets streak; we use
+ // batch_size=1 so each `step()` strictly increments.
+ .build();
+ let s = Scheduler::<StubItem, u32>::builder()
+ .config(BatchConfig::default())
+ .controller(ctrl)
+ .latency_window(20, 1)
+ .build();
+
+ // Wave 1 — primary at batch_size=1 increments the streak.
+ s.record_latency_sample(10.0).await;
+ let _ = s.record_completion(1, 1).await;
+ assert_eq!(
+ s.controller_snapshot().await.starvation_streak,
+ 1,
+ "primary must advance streak"
+ );
+
+ // Three drains — feed inference + latency only. Streak
+ // must NOT advance.
+ for _ in 0..3 {
+ s.record_inference_sample(8.0).await;
+ s.record_latency_samples(&[10.0]).await;
+ }
+ assert_eq!(
+ s.controller_snapshot().await.starvation_streak,
+ 1,
+ "drain feeds must not step the controller (streak should stay at 1, got {})",
+ s.controller_snapshot().await.starvation_streak,
+ );
+
+ // Wave 2 — next primary advances exactly once again.
+ s.record_latency_sample(10.0).await;
+ let _ = s.record_completion(1, 1).await;
+ assert_eq!(
+ s.controller_snapshot().await.starvation_streak,
+ 2,
+ "second primary must advance streak by exactly one wave",
+ );
+ }
+
+ #[tokio::test]
+ async fn inference_sample_feeds_autocalibration() {
+ let ctrl = AdaptiveBatchController::builder()
+ .target_p50_ms(None) // auto-calibrate
+ .calibration_multiplier(2.0)
+ .update_interval(1)
+ .build();
+ let s = Scheduler::<StubItem, u32>::builder()
+ .controller(ctrl)
+ .build();
+
+ // Feed 20 inference samples at 10 ms so inference_p50 = 10.
+ for _ in 0..20 {
+ s.record_inference_sample(10.0).await;
+ }
+ // One completion triggers the calibration step.
+ let _ = s.record_completion(0, 1).await;
+ let snap = s.controller_snapshot().await;
+ assert!(snap.calibrated);
+ assert_eq!(snap.target_p50_ms, Some(20.0));
+ }
+
+ #[tokio::test]
+ async fn record_completion_returns_populated_outcome_shape() {
+ // Verify the new outcome plumbing: every field is populated
+ // with the post-step controller state. The starvation
+ // recovery itself is already exhaustively tested in
+ // `adaptive.rs::tests::starvation_recovery_*`; here we just
+ // confirm the snapshot wiring carries the values through.
+ let ctrl = AdaptiveBatchController::builder()
+ .target_p50_ms(Some(50.0))
+ .update_interval(1)
+ .initial_wait_ms(20.0)
+ .initial_batch_cost(4_000)
+ .build();
+ let s = Scheduler::<StubItem, u32>::builder()
+ .config(BatchConfig::default())
+ .controller(ctrl)
+ .latency_window(20, 1)
+ .build();
+
+ s.record_latency_sample(10.0).await;
+ let snap = s.record_completion(800, 32).await;
+
+ assert!(snap.new_wait_ms > 0.0);
+ assert!(snap.new_batch_cost > 0);
+ assert_eq!(snap.batch_size, 32);
+ assert_eq!(snap.target_p50_ms, Some(50.0));
+ assert_eq!(snap.observed_p50_ms, Some(10.0));
+ assert!(snap.fill_ratio.is_some());
+ // No starvation triggered yet → delta is zero.
+ assert_eq!(snap.starvation_resets_delta, 0);
+
+ // After the step the scheduler's shared config snapshot
+ // carries the same caps as the returned outcome — operators
+ // reading `s.config()` after a completion see the same
+ // numbers Prometheus does.
+ let cfg = s.config().await;
+ assert_eq!(cfg.max_batch_wait_ms, snap.new_wait_ms);
+ assert_eq!(cfg.max_batch_cost, snap.new_batch_cost);
+ }
+
+ // ---- BatchConfig-derived production-parity defaults ----
+
+ #[tokio::test]
+ async fn builder_default_controller_uses_production_parity_floors() {
+ // No `.controller(...)` supplied → builder must derive the
+ // controller from the BatchConfig with Python production
+ // wiring (min_wait_ms=15, min_batch_cost=cfg.max_batch_cost/4,
+ // cost_gain=gain*0.5). This is the production code path —
+ // every deployed Rust scheduler hits this branch.
+ let s: Scheduler<StubItem, u32> = Scheduler::builder()
+ .config(BatchConfig::default()) // max_batch_cost = 16_384
+ .build();
+ let snap = s.controller_snapshot().await;
+ // Snapshot doesn't expose floors directly; reach into the
+ // controller via the lock for these invariants.
+ let ctrl = s.controller.lock().await;
+ assert!(
+ (ctrl.min_wait_ms - 15.0).abs() < f64::EPSILON,
+ "builder must produce production-parity min_wait_ms=15.0, got {}",
+ ctrl.min_wait_ms
+ );
+ assert_eq!(
+ ctrl.min_batch_cost, 4_096,
+ "builder must produce production-parity min_batch_cost=max_batch_tokens/4"
+ );
+ assert!(
+ (ctrl.cost_gain - (ctrl.gain * 0.5)).abs() < f64::EPSILON,
+ "builder must produce coupled cost_gain = gain*0.5"
+ );
+ // Sanity: snapshot still reflects an uncalibrated auto-mode
+ // scheduler — production deploys auto-calibrate target_p50.
+ assert!(!snap.calibrated);
+ assert!(snap.target_p50_ms.is_none());
+ }
+
+ // ---- Aggregates ----
+
+ #[tokio::test]
+ async fn pending_count_and_cost_sum_across_batchers() {
+ let s = make();
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name("a"),
+ StubItem { cost: 5, idx: 0 },
+ 0,
+ )
+ .await;
+ s.submit(
+ Op::Encode,
+ LoraKey::from_name("b"),
+ StubItem { cost: 7, idx: 0 },
+ 0,
+ )
+ .await;
+ s.submit(Op::Score, LoraKey::base(), StubItem { cost: 3, idx: 0 }, 0)
+ .await;
+ assert_eq!(s.total_pending_count().await, 3);
+ assert_eq!(s.total_pending_cost().await, 15);
+ }
+}
diff --git a/packages/sie_server_sidecar/src/scheduler/item.rs b/packages/sie_server_sidecar/src/scheduler/item.rs
new file mode 100644
index 000000000..c01e55148
--- /dev/null
+++ b/packages/sie_server_sidecar/src/scheduler/item.rs
@@ -0,0 +1,412 @@
+//! Concrete item + metadata types used by the dispatcher-level
+//! [`crate::scheduler::Scheduler`].
+//!
+//! The [`Scheduler`](super::engine::Scheduler) is generic over the
+//! item type `I: HasCost` and the caller-supplied metadata `T`. The
+//! generic surface keeps the scheduler engine testable against simple
+//! stubs (see `engine.rs::tests::StubItem`), but production needs one
+//! concrete choice of `(I, T)` so the dispatcher can pass a single
+//! [`super::SchedulerRegistry`] Arc around.
+//!
+//! That's what this module is: the single production choice.
+//!
+//! * [`SchedulerItem`] is a tagged union over the three op-specific
+//! batch items the Python adapter already consumes. Same on-wire
+//! types — no re-encoding when we pack them into a
+//! [`crate::ipc_types::RunBatchRequest`].
+//! * [`SchedulerMeta`] carries everything the dispatcher's
+//! `apply_outcomes` path needs — the [`WorkItem`] for publishing
+//! the result, the JetStream [`Message`] for the ACK, and the
+//! payload-fetch timing we already record per item. Submit time is
+//! stashed as an [`Instant`] for queue-age telemetry (opt-in; the
+//! scheduler engine has its own per-batcher head-of-line atomic
+//! for FCFS, which is cheaper for the hot path).
+//!
+//! ## Cost semantics
+//!
+//! Scheduler flush triggers fire on **cost-cap** (sum of item costs),
+//! **count-cap**, or **wait-cap**. The cost of a single item matches
+//! Python's `PreparedTokens.total_tokens` when the dispatcher
+//! tokenised Rust-side, and falls back to `1` otherwise:
+//!
+//! * **Encode / Extract**: sum of `prepared_tokens.input_ids[i].len()`
+//! — there is usually exactly one inner sequence per item, but we
+//! sum defensively. `1` when `prepared_tokens` is `None` (Python
+//! will retokenise).
+//! * **Score**: same sum (the score items emit the
+//! `[query, doc_0]` layout), `1` when absent.
+//!
+//! The adaptive controller auto-calibrates against observed latency,
+//! so being "approximately right" on cost is enough; what matters is
+//! that the same cost function runs in both the cap check and the
+//! `record_completion` → controller-step path so the controller
+//! never over/under-counts its own flushes. That's what this module
+//! pins down in one place.
+
+use std::time::Instant;
+
+use async_nats::jetstream::Message;
+
+use crate::ipc_types::{
+ EncodeBatchItem, ExtractBatchItem, PreparedTokens, RunBatchItem, ScoreBatchItem,
+};
+use crate::work_types::WorkItem;
+
+use super::batch_former::HasCost;
+use super::engine::{LoraKey, Op};
+
+/// Sum of per-inner-sequence token counts on a [`PreparedTokens`]
+/// blob, clamped to `>= 1` so an empty-tokens payload doesn't yield
+/// a zero-cost batcher (which would break the min-cost cap check in
+/// the adaptive controller). `None` → `1` (same as Python's
+/// "no prepared tokens, assume unit cost" fallback).
+fn cost_from_prepared(pt: Option<&PreparedTokens>) -> u64 {
+ let Some(pt) = pt else {
+ return 1;
+ };
+ let total: u64 = pt.input_ids.iter().map(|seq| seq.len() as u64).sum::<u64>();
+ total.max(1)
+}
+
+/// Concrete per-item payload the production scheduler carries. One of
+/// the three variants, all of which are already the on-wire types the
+/// Python adapter loop consumes — so packing a batch into a
+/// [`crate::ipc_types::RunBatchRequest`] is O(items) moves and zero re-serialisation.
+///
+/// Named `SchedulerItem` rather than `Item` to avoid collision with
+/// the `item: serde_json::Value` field that lives inside the inner
+/// variants.
+#[derive(Debug, Clone)]
+pub enum SchedulerItem {
+ Encode(EncodeBatchItem),
+ Score(ScoreBatchItem),
+ Extract(ExtractBatchItem),
+}
+
+impl SchedulerItem {
+ /// Operation class — used by the dispatcher to pick the right
+ /// batcher key when submitting into the scheduler, and by the
+ /// drain loop to tag metrics + logs.
+ #[must_use]
+ pub fn op(&self) -> Op {
+ match self {
+ Self::Encode(_) => Op::Encode,
+ Self::Score(_) => Op::Score,
+ Self::Extract(_) => Op::Extract,
+ }
+ }
+
+ /// Convert into the IPC-level [`RunBatchItem`] tagged-struct.
+ /// Matches the helper constructors in [`crate::ipc_types`] so
+ /// the `op` discriminator is always synced with the populated
+ /// optional field — never construct the struct by hand.
+ #[must_use]
+ pub fn into_run_batch_item(self) -> RunBatchItem {
+ match self {
+ Self::Encode(e) => RunBatchItem::encode(e),
+ Self::Score(s) => RunBatchItem::score(s),
+ Self::Extract(x) => RunBatchItem::extract(x),
+ }
+ }
+}
+
+impl HasCost for SchedulerItem {
+ fn cost(&self) -> u64 {
+ match self {
+ Self::Encode(e) => cost_from_prepared(e.prepared_tokens.as_ref()),
+ Self::Score(s) => cost_from_prepared(s.prepared_tokens.as_ref()),
+ // Extract doesn't emit prepared tokens on the Rust side in
+ // the current path (Python owns extract tokenisation — see
+ // `docs/architecture-guide.md`), so
+ // there is no per-item seq_len to pay with. Unit cost
+ // matches Python's fallback.
+ Self::Extract(_) => 1,
+ }
+ }
+
+ fn original_index(&self) -> usize {
+ // Original request-local index is what the cost-sorted
+ // packer uses to restore order inside a flushed batch so
+ // downstream outcomes line back up with `item_index`. Same
+ // wiid → same original_index → stable ordering across retries.
+ let idx = match self {
+ Self::Encode(e) => e.item_index,
+ Self::Score(s) => s.item_index,
+ Self::Extract(x) => x.item_index,
+ };
+ idx as usize
+ }
+}
+
+/// Caller-supplied per-item metadata the dispatcher needs to carry
+/// 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
+/// 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,
+ /// Payload-store fetch latency (ms). Surfaced on the published
+ /// [`crate::publisher::Timings`] and on the `payload_fetch_seconds`
+ /// histogram.
+ pub fetch_ms: f64,
+ /// When the dispatcher enqueued this item into the scheduler.
+ /// Used only for queue-age telemetry; the engine's FCFS pick is
+ /// driven by its own `head_ns` atomic (see
+ /// [`super::engine::Scheduler`]).
+ pub submitted_at: Instant,
+}
+
+impl SchedulerMeta {
+ /// Construct the standard triple stamped with `Instant::now`.
+ #[must_use]
+ pub fn new(wi: WorkItem, msg: Message, fetch_ms: f64) -> Self {
+ Self {
+ wi,
+ msg,
+ fetch_ms,
+ submitted_at: Instant::now(),
+ }
+ }
+}
+
+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.
+ 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("submitted_at", &self.submitted_at)
+ .finish_non_exhaustive()
+ }
+}
+
+/// Read the LoRA key off a `WorkItem.options["lora"]`. Empty string
+/// and absent both normalise to [`LoraKey::base`] via
+/// [`LoraKey::from_option`]. Unknown-shape options (e.g. `lora` present
+/// as a number) fall through to base so a misbehaving client can't
+/// fragment the batcher map.
+///
+/// Defined here (not in `work_types.rs`) because routing policy is a
+/// scheduler concern — keeping it adjacent to the scheduler's
+/// [`LoraKey`] definition means one grep surfaces both the parser and
+/// the consumer.
+#[must_use]
+pub fn lora_from_options(options: &Option<serde_json::Value>) -> LoraKey {
+ let Some(opts) = options.as_ref() else {
+ return LoraKey::base();
+ };
+ match opts.get("lora").and_then(|v| v.as_str()) {
+ Some(s) => LoraKey::from_name(s),
+ None => LoraKey::base(),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn pt_with_lens(lens: &[usize]) -> PreparedTokens {
+ let input_ids: Vec<Vec<u32>> = lens
+ .iter()
+ .map(|&n| (0..n as u32).collect::<Vec<u32>>())
+ .collect();
+ PreparedTokens {
+ input_ids,
+ attention_mask: vec![],
+ token_type_ids: vec![],
+ tokenizer_id: "test".into(),
+ max_seq_len: 512,
+ }
+ }
+
+ fn encode_item(idx: u32, prepared: Option<PreparedTokens>) -> EncodeBatchItem {
+ EncodeBatchItem {
+ work_item_id: format!("r.{idx}"),
+ request_id: "r".into(),
+ item_index: idx,
+ total_items: 1,
+ timestamp: 0.0,
+ item: serde_json::json!({"text": "x"}),
+ output_types: None,
+ instruction: None,
+ is_query: false,
+ options: None,
+ profile_id: None,
+ bundle_config_hash: None,
+ payload_fetch_ms: 0.0,
+ prepared_tokens: prepared,
+ }
+ }
+
+ #[test]
+ fn cost_prefers_prepared_tokens_sum() {
+ let it = SchedulerItem::Encode(encode_item(0, Some(pt_with_lens(&[17]))));
+ assert_eq!(it.cost(), 17);
+ }
+
+ #[test]
+ fn cost_sums_multiple_inner_sequences() {
+ // Score emits `[query, doc_0]` as two inner sequences on the
+ // same PreparedTokens — the flushed batch cost must count
+ // both so the controller sees the real forward-pass cost.
+ let it = SchedulerItem::Score(ScoreBatchItem {
+ work_item_id: "r.0".into(),
+ request_id: "r".into(),
+ item_index: 0,
+ total_items: 1,
+ timestamp: 0.0,
+ query_item: serde_json::json!({"text": "q"}),
+ score_items: vec![serde_json::json!({"text": "d"})],
+ instruction: None,
+ options: None,
+ profile_id: None,
+ payload_fetch_ms: 0.0,
+ prepared_tokens: Some(pt_with_lens(&[5, 13])),
+ });
+ assert_eq!(it.cost(), 18);
+ }
+
+ #[test]
+ fn cost_clamps_to_one_on_empty_prepared() {
+ // An empty `PreparedTokens` (no inner sequences) returns 0
+ // without the clamp — that would let a submit land on a
+ // scheduler whose min_batch_cost cap never trips. Clamping
+ // to 1 matches Python's "unknown cost → assume one" fallback.
+ let it = SchedulerItem::Encode(encode_item(0, Some(pt_with_lens(&[]))));
+ assert_eq!(it.cost(), 1);
+ }
+
+ #[test]
+ fn cost_falls_back_to_one_without_prepared() {
+ let it = SchedulerItem::Encode(encode_item(0, None));
+ assert_eq!(it.cost(), 1);
+ }
+
+ #[test]
+ fn extract_cost_is_unit_by_policy() {
+ let it = SchedulerItem::Extract(ExtractBatchItem {
+ work_item_id: "r.0".into(),
+ request_id: "r".into(),
+ item_index: 0,
+ total_items: 1,
+ timestamp: 0.0,
+ item: serde_json::json!({"text": "x"}),
+ labels: None,
+ output_schema: None,
+ instruction: None,
+ options: None,
+ profile_id: None,
+ bundle_config_hash: None,
+ payload_fetch_ms: 0.0,
+ });
+ assert_eq!(it.cost(), 1);
+ }
+
+ #[test]
+ fn original_index_matches_item_index() {
+ let it = SchedulerItem::Encode(encode_item(7, None));
+ assert_eq!(it.original_index(), 7);
+ }
+
+ #[test]
+ fn op_matches_variant() {
+ let e = SchedulerItem::Encode(encode_item(0, None));
+ assert_eq!(e.op(), Op::Encode);
+ let s = SchedulerItem::Score(ScoreBatchItem {
+ work_item_id: "".into(),
+ request_id: "".into(),
+ item_index: 0,
+ total_items: 1,
+ timestamp: 0.0,
+ query_item: serde_json::json!(null),
+ score_items: vec![],
+ instruction: None,
+ options: None,
+ profile_id: None,
+ payload_fetch_ms: 0.0,
+ prepared_tokens: None,
+ });
+ assert_eq!(s.op(), Op::Score);
+ let x = SchedulerItem::Extract(ExtractBatchItem {
+ work_item_id: "".into(),
+ request_id: "".into(),
+ item_index: 0,
+ total_items: 1,
+ timestamp: 0.0,
+ item: serde_json::json!(null),
+ labels: None,
+ output_schema: None,
+ instruction: None,
+ options: None,
+ profile_id: None,
+ bundle_config_hash: None,
+ payload_fetch_ms: 0.0,
+ });
+ assert_eq!(x.op(), Op::Extract);
+ }
+
+ #[test]
+ fn into_run_batch_item_syncs_discriminator() {
+ let rbi = SchedulerItem::Encode(encode_item(3, None)).into_run_batch_item();
+ assert_eq!(rbi.op, "encode");
+ assert_eq!(rbi.work_item_id, "r.3");
+ assert_eq!(rbi.request_id, "r");
+ assert_eq!(rbi.item_index, 3);
+ assert!(rbi.encode.is_some());
+ assert!(rbi.score.is_none());
+ assert!(rbi.extract.is_none());
+ }
+
+ // ---- LoraKey from options ----
+
+ #[test]
+ fn lora_from_options_none_is_base() {
+ assert!(lora_from_options(&None).is_base());
+ }
+
+ #[test]
+ fn lora_from_options_missing_key_is_base() {
+ let opts = Some(serde_json::json!({"other": "x"}));
+ assert!(lora_from_options(&opts).is_base());
+ }
+
+ #[test]
+ fn lora_from_options_empty_string_is_base() {
+ // Empty string must normalise the same way `LoraKey::from_name`
+ // does, else the batcher map fragments on `""` vs `None`.
+ let opts = Some(serde_json::json!({"lora": ""}));
+ assert!(lora_from_options(&opts).is_base());
+ }
+
+ #[test]
+ fn lora_from_options_string_preserved() {
+ let opts = Some(serde_json::json!({"lora": "tenant-a"}));
+ let key = lora_from_options(&opts);
+ assert_eq!(key.as_str(), Some("tenant-a"));
+ }
+
+ #[test]
+ fn lora_from_options_non_string_falls_back_to_base() {
+ // A client sending `{"lora": 42}` by accident must not
+ // fragment the map on a non-str key. The parser returns
+ // base; Python would do the same via its `options.get("lora")`
+ // call chain (numbers coerce to str there, but the Rust
+ // policy is stricter — prefer base to a silent weird key).
+ let opts = Some(serde_json::json!({"lora": 42}));
+ assert!(lora_from_options(&opts).is_base());
+ }
+}
diff --git a/packages/sie_server_sidecar/src/scheduler/metrics.rs b/packages/sie_server_sidecar/src/scheduler/metrics.rs
new file mode 100644
index 000000000..8288a2530
--- /dev/null
+++ b/packages/sie_server_sidecar/src/scheduler/metrics.rs
@@ -0,0 +1,307 @@
+//! Scheduler-family Prometheus metrics.
+//!
+//! Registered at startup alongside the rest of the
+//! [`crate::metrics::MetricsRegistry`] surface. The scheduler currently
+//! populates a deliberately small subset — just enough to
+//! answer "is the Rust scheduler doing work, for what, and how big
+//! are the batches?":
+//!
+//! * [`SchedulerMetrics::enqueued_items_total`] — per-op enqueue
+//! counter (dispatcher enqueue site).
+//! * [`SchedulerMetrics::batch_items`] — per-batch item-count
+//! histogram (drain-loop site).
+//! * [`SchedulerMetrics::batch_cost`] — per-batch cost histogram
+//! (drain-loop site).
+//! * [`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.
+//!
+//! ## Label cardinality
+//!
+//! Every metric with a `model` label routes through
+//! [`crate::metrics::MetricsRegistry::model_label`] at the observe
+//! site to honour `SIE_METRIC_MODEL_ALLOWLIST`. `lora` label values
+//! are either a real LoRA name or the sentinel `"base"` for the
+//! base-model batcher — matches Python's `model_worker.py` string
+//! representation so dashboards can filter with a single predicate.
+
+use prometheus::{
+ Gauge, GaugeVec, HistogramOpts, HistogramVec, IntCounterVec, IntGauge, Opts, Registry,
+};
+
+/// Histogram buckets for batch item counts. Chosen to cover the
+/// realistic range (1 to `max_batch_requests`) with enough resolution
+/// around the common 4–32 band where the adaptive controller spends
+/// most of its time.
+const BATCH_ITEMS_BUCKETS: &[f64] = &[1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0];
+
+/// Histogram buckets for batch cost (tokens by default; may be any
+/// monotonic cost metric). Tuned for embedding models where common
+/// batch costs are 1–100 k tokens.
+const BATCH_COST_BUCKETS: &[f64] = &[
+ 128.0, 512.0, 1024.0, 2048.0, 4096.0, 8192.0, 16_384.0, 32_768.0, 65_536.0, 131_072.0,
+ 262_144.0,
+];
+
+/// Flush-reason label values. Mirrors the triggers in
+/// [`super::batch_former::FormattedBatch`] + `BatchFormer::should_yield_batch`.
+/// Kept as a `const` array so the label set is discoverable from one
+/// place and dashboards can enumerate it without grepping code.
+pub const FLUSH_REASONS: &[&str] = &[
+ "cost_cap",
+ "count_cap",
+ "timeout",
+ "coalesce",
+ "single_oversize",
+ "update_tightened",
+ "drain",
+];
+
+/// Prometheus metrics owned by the Rust scheduler. All gauges start
+/// at 0; histograms have no samples. Values populate as the scheduler
+/// does work.
+#[derive(Clone)]
+pub struct SchedulerMetrics {
+ /// Batch size (item count) observed on every flushed batch.
+ /// `operation` ∈ {encode, score, extract}; `lora` = LoRA name or
+ /// `"base"`.
+ pub batch_items: HistogramVec,
+
+ /// Batch cost (token total by default) observed on every flushed
+ /// batch.
+ pub batch_cost: HistogramVec,
+
+ /// Counter keyed by the flush trigger that fired. See
+ /// [`FLUSH_REASONS`] for the label domain.
+ pub flush_reason_total: IntCounterVec,
+
+ /// Counts every time the adaptive controller's starvation
+ /// recovery fires (knobs were floored + wall-time starved).
+ /// A persistently non-zero rate means either the target-p50 is
+ /// too aggressive or the load just doesn't saturate the GPU.
+ pub starvation_resets_total: IntCounterVec,
+
+ /// Current `max_batch_wait_ms` the adaptive controller is
+ /// asking batchers to honour. Set after every controller step.
+ pub adaptive_wait_ms: GaugeVec,
+
+ /// Current `max_batch_cost` cap, ditto.
+ pub adaptive_cost: GaugeVec,
+
+ /// Rolling mean fill ratio seen by the efficiency tracker.
+ /// `None` → not enough samples yet; gauge simply stays at its
+ /// previous value in that case.
+ pub adaptive_fill_ratio: GaugeVec,
+
+ /// Observed p50 latency (ms) from the [`crate::latency::LatencyTracker`].
+ pub adaptive_observed_p50_ms: GaugeVec,
+
+ /// Target p50 (ms). Either the explicit operator setting or the
+ /// auto-calibrated value once the inference tracker has enough
+ /// samples.
+ pub adaptive_target_p50_ms: GaugeVec,
+
+ /// Count of models that currently have a materialised scheduler.
+ /// Incremented live from `crate::dispatcher::Dispatcher::resolve_scheduler`
+ /// the first time a given model's scheduler is created; schedulers
+ /// aren't torn down mid-process so there's no decrement path.
+ pub models_total: IntGauge,
+
+ /// Currently instantiated per-LoRA batchers per model. Lets
+ /// operators see LoRA-fleet size without enumerating from logs.
+ pub active_batchers: GaugeVec,
+
+ /// Mean head-of-line latency (ms) across all non-empty batchers.
+ /// Useful companion to fill_ratio — rising HoL while fill_ratio
+ /// stays low = tail starvation, often a hint that `max_batch_wait_ms`
+ /// is too large.
+ pub hol_wait_ms_mean: Gauge,
+
+ /// Items the dispatcher submitted into the scheduler (counted
+ /// *after* payload resolution, so this tracks real enqueues —
+ /// items that failed to resolve and got publish_error-ACK'd are
+ /// not included). Divergence from `batch_items.sum()` is the
+ /// number of items still waiting in a batcher; divergence beyond
+ /// a few seconds is a stall signal.
+ pub enqueued_items_total: IntCounterVec,
+}
+
+impl SchedulerMetrics {
+ /// Register every metric family against the supplied registry.
+ /// Panics-free; any registration error is bubbled up so the
+ /// worker fails fast at startup rather than running with a
+ /// partial metric surface.
+ pub fn register(registry: &Registry) -> anyhow::Result<Self> {
+ let batch_items = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_scheduler_batch_items",
+ "Scheduler-formed batch sizes in items",
+ )
+ .buckets(BATCH_ITEMS_BUCKETS.to_vec()),
+ &["model", "operation", "lora"],
+ )?;
+ let batch_cost = HistogramVec::new(
+ HistogramOpts::new(
+ "sie_worker_scheduler_batch_cost",
+ "Scheduler-formed batch cost (tokens or other monotonic cost)",
+ )
+ .buckets(BATCH_COST_BUCKETS.to_vec()),
+ &["model", "operation", "lora"],
+ )?;
+ 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",
+ ),
+ &["model", "operation", "lora", "reason"],
+ )?;
+ let starvation_resets_total = IntCounterVec::new(
+ Opts::new(
+ "sie_worker_scheduler_starvation_resets_total",
+ "Adaptive controller starvation recovery events",
+ ),
+ &["model"],
+ )?;
+ let adaptive_wait_ms = GaugeVec::new(
+ Opts::new(
+ "sie_worker_scheduler_adaptive_wait_ms",
+ "Adaptive controller's current max_batch_wait_ms cap",
+ ),
+ &["model"],
+ )?;
+ let adaptive_cost = GaugeVec::new(
+ Opts::new(
+ "sie_worker_scheduler_adaptive_cost",
+ "Adaptive controller's current max_batch_cost cap",
+ ),
+ &["model"],
+ )?;
+ let adaptive_fill_ratio = GaugeVec::new(
+ Opts::new(
+ "sie_worker_scheduler_adaptive_fill_ratio",
+ "Rolling mean batch fill ratio seen by the efficiency tracker",
+ ),
+ &["model"],
+ )?;
+ let adaptive_observed_p50_ms = GaugeVec::new(
+ Opts::new(
+ "sie_worker_scheduler_adaptive_observed_p50_ms",
+ "Observed p50 batch latency in ms",
+ ),
+ &["model"],
+ )?;
+ let adaptive_target_p50_ms = GaugeVec::new(
+ Opts::new(
+ "sie_worker_scheduler_adaptive_target_p50_ms",
+ "Adaptive controller target p50 latency (explicit or auto-calibrated) in ms",
+ ),
+ &["model"],
+ )?;
+ let models_total = IntGauge::new(
+ "sie_worker_scheduler_models_total",
+ "Count of models with a materialised Rust scheduler",
+ )?;
+ let active_batchers = GaugeVec::new(
+ Opts::new(
+ "sie_worker_scheduler_active_batchers",
+ "Count of per-(op, lora) batchers currently instantiated for a model",
+ ),
+ &["model"],
+ )?;
+ let hol_wait_ms_mean = Gauge::new(
+ "sie_worker_scheduler_hol_wait_ms_mean",
+ "Mean head-of-line wait (ms) across non-empty batchers worker-wide",
+ )?;
+ let enqueued_items_total = IntCounterVec::new(
+ Opts::new(
+ "sie_worker_scheduler_enqueued_items_total",
+ "Items submitted into the Rust scheduler after payload resolution",
+ ),
+ &["model", "operation"],
+ )?;
+
+ registry.register(Box::new(batch_items.clone()))?;
+ registry.register(Box::new(batch_cost.clone()))?;
+ registry.register(Box::new(flush_reason_total.clone()))?;
+ registry.register(Box::new(starvation_resets_total.clone()))?;
+ registry.register(Box::new(adaptive_wait_ms.clone()))?;
+ registry.register(Box::new(adaptive_cost.clone()))?;
+ registry.register(Box::new(adaptive_fill_ratio.clone()))?;
+ registry.register(Box::new(adaptive_observed_p50_ms.clone()))?;
+ registry.register(Box::new(adaptive_target_p50_ms.clone()))?;
+ registry.register(Box::new(models_total.clone()))?;
+ registry.register(Box::new(active_batchers.clone()))?;
+ registry.register(Box::new(hol_wait_ms_mean.clone()))?;
+ registry.register(Box::new(enqueued_items_total.clone()))?;
+
+ Ok(Self {
+ batch_items,
+ batch_cost,
+ flush_reason_total,
+ starvation_resets_total,
+ adaptive_wait_ms,
+ adaptive_cost,
+ adaptive_fill_ratio,
+ adaptive_observed_p50_ms,
+ adaptive_target_p50_ms,
+ models_total,
+ active_batchers,
+ hol_wait_ms_mean,
+ enqueued_items_total,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn register_is_idempotent_per_registry() {
+ // Two independent registries must both accept SchedulerMetrics.
+ // Registering twice against the *same* registry is illegal
+ // (Prometheus rejects duplicate names), so we don't assert
+ // that — we only verify the happy path + label layout.
+ let r1 = Registry::new();
+ let _ = SchedulerMetrics::register(&r1).expect("first registry");
+ let r2 = Registry::new();
+ let _ = SchedulerMetrics::register(&r2).expect("second registry");
+ }
+
+ #[test]
+ fn flush_reasons_cover_every_trigger() {
+ // If someone adds a new flush trigger in BatchFormer, this
+ // test forces them to update the reason vocabulary here so
+ // dashboards can enumerate the full label domain.
+ for r in FLUSH_REASONS {
+ assert!(!r.is_empty());
+ }
+ // 7 triggers today: cost_cap, count_cap, timeout, coalesce,
+ // single_oversize, update_tightened, drain.
+ assert_eq!(FLUSH_REASONS.len(), 7);
+ }
+
+ #[test]
+ fn metric_names_follow_prefix_convention() {
+ // Every scheduler metric must be under `sie_worker_scheduler_`.
+ // Verified indirectly by constructing a fresh registry and
+ // gathering metric families.
+ let r = Registry::new();
+ let _ = SchedulerMetrics::register(&r).unwrap();
+ for mf in r.gather() {
+ // `prometheus::proto::MetricFamily::name` is a private
+ // field, but the protobuf accessor `get_name` is public.
+ let name = mf.get_name();
+ assert!(
+ name.starts_with("sie_worker_scheduler_"),
+ "scheduler metric '{name}' must use the sie_worker_scheduler_ prefix"
+ );
+ }
+ }
+}
diff --git a/packages/sie_server_sidecar/src/scheduler/mod.rs b/packages/sie_server_sidecar/src/scheduler/mod.rs
new file mode 100644
index 000000000..0a4ee47d9
--- /dev/null
+++ b/packages/sie_server_sidecar/src/scheduler/mod.rs
@@ -0,0 +1,66 @@
+//! Rust-side batch formation, adaptive control, and worker scheduling.
+//!
+//! This module is **live** in the dispatcher hot path. Every model
+//! served by a worker-sidecar routes encode / score / extract
+//! traffic through [`Scheduler`]: each request lands in a per-
+//! `(operation, LoRA)` [`BatchFormer`], an [`AdaptiveBatchController`]
+//! governs the flush caps, and a per-model drain loop (spawned
+//! lazily on first traffic by
+//! `crate::dispatcher::Dispatcher::resolve_scheduler`) packs the
+//! flushed batch into a [`crate::ipc_types::RunBatchRequest`] and
+//! hands it to the [`crate::backend::InferenceBackend`].
+//!
+//! Byte/semantics-for-byte ports of the Python originals in:
+//!
+//! * `sie_server/core/batcher.py` → [`BatchConfig`], [`FormattedBatch`],
+//! [`PendingRequest`], [`HasCost`], [`BatchFormer`].
+//! * `sie_server/core/adaptive_batching.py` →
+//! [`BatchEfficiencyTracker`], [`AdaptiveBatchController`],
+//! [`AdaptiveBatchState`]. (The `LatencyTracker` used by the
+//! controller is shared with the existing IPC-fetch controller in
+//! [`crate::latency`].)
+//!
+//! See `docs/architecture-guide.md` for the current design notes. The
+//! old per-model scheduler env list has been retired: the question of
+//! "does this active model run under the Rust scheduler" is answered by
+//! which worker pool handles the model, not by a per-worker env var.
+//!
+//! Invariants to preserve (same as the Python code; any deviation is a
+//! production bug, not a design call):
+//!
+//! * **Flush triggers**: cost cap, count cap, `max_batch_wait_ms`
+//! timeout, or the adaptive coalesce window.
+//! * **Oversize item**: a single item ≥ `max_batch_cost` flushes alone.
+//! * **Cost-sorted sub-batch packing** on every extract.
+//! * **Starvation recovery**: consecutive tiny batches at both floors
+//! trip a deadlock reset.
+//! * **Auto-calibration**: inference-only p50 × `calibration_multiplier`
+//! sets the controller target when none was configured.
+
+pub mod adaptive;
+pub mod batch_config;
+pub mod batch_former;
+pub mod engine;
+pub mod item;
+pub mod metrics;
+pub mod registry;
+pub mod trackers;
+
+pub use adaptive::{AdaptiveBatchController, AdaptiveBatchControllerBuilder, AdaptiveBatchState};
+pub use batch_config::BatchConfig;
+pub use batch_former::{BatchFormer, 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};
+pub use registry::SchedulerRegistry;
+pub use trackers::BatchEfficiencyTracker;
+
+/// The concrete per-model scheduler type wired into the dispatcher
+/// hot path — a [`Scheduler`] parameterised by the production item /
+/// metadata pair from [`item`]. Type aliases keep the big signatures
+/// readable in `dispatcher.rs` and `lib.rs` without forcing callers
+/// to repeat the generic parameters.
+pub type ProductionScheduler = Scheduler<SchedulerItem, SchedulerMeta>;
+
+/// The concrete [`SchedulerRegistry`] type passed into the dispatcher.
+pub type ProductionSchedulerRegistry = SchedulerRegistry<SchedulerItem, SchedulerMeta>;
diff --git a/packages/sie_server_sidecar/src/scheduler/registry.rs b/packages/sie_server_sidecar/src/scheduler/registry.rs
new file mode 100644
index 000000000..61689d32a
--- /dev/null
+++ b/packages/sie_server_sidecar/src/scheduler/registry.rs
@@ -0,0 +1,162 @@
+//! Per-model scheduler registry.
+//!
+//! The registry owns one [`Scheduler`] per `model_id` and hands it
+//! back on demand:
+//!
+//! * [`SchedulerRegistry::get_or_create`] returns `(Arc<Scheduler<..>>, created)`.
+//! A `created == true` flag signals the dispatcher that this was
+//! the first call for the model and a per-model drain loop needs
+//! to be spawned now; subsequent calls return the same shared
+//! [`Arc`] with `created == false`, so the scheduler's adaptive
+//! controller state and per-LoRA batcher map persist across
+//! requests.
+//! * Schedulers are lazily created — models that never receive
+//! traffic never allocate one.
+//!
+//! There is no per-model scheduler env list any more. Active models route
+//! through the Rust scheduler when their worker pool is the sidecar pool.
+//! Every model that lands on a worker-sidecar goes through the
+//! scheduler.
+//!
+//! Kept generic over `<I: HasCost, T>` so this module is testable in
+//! isolation against the concrete dispatcher item / work metadata
+//! types.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use tokio::sync::RwLock;
+
+use super::batch_config::BatchConfig;
+use super::batch_former::HasCost;
+use super::engine::Scheduler;
+
+/// Per-model scheduler registry.
+pub struct SchedulerRegistry<I: HasCost, T> {
+ /// Default caps + per-scheduler defaults every lazily created
+ /// [`Scheduler`] starts with. Operators override by setting
+ /// model-specific tunables at the `Scheduler::builder()` seam
+ /// when per-model tuning lands.
+ default_config: BatchConfig,
+ schedulers: RwLock<HashMap<String, Arc<Scheduler<I, T>>>>,
+}
+
+impl<I, T> std::fmt::Debug for SchedulerRegistry<I, T>
+where
+ I: HasCost,
+{
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SchedulerRegistry")
+ .field("default_config", &self.default_config)
+ .finish_non_exhaustive()
+ }
+}
+
+impl<I, T> SchedulerRegistry<I, T>
+where
+ I: HasCost + Send + Sync + 'static,
+ T: Send + Sync + 'static,
+{
+ /// Build with the given default per-scheduler config.
+ #[must_use]
+ pub fn new(default_config: BatchConfig) -> Self {
+ Self {
+ default_config,
+ schedulers: RwLock::new(HashMap::new()),
+ }
+ }
+
+ /// Return the scheduler for `model_id`, lazily creating it on
+ /// first call.
+ ///
+ /// The second tuple element is `true` only on the call that
+ /// actually materialised the scheduler. The dispatcher uses it
+ /// to spawn exactly one drain loop per model — see
+ /// `crate::dispatcher::Dispatcher::resolve_scheduler`.
+ ///
+ /// Thread-safe: the hot path is a read-lock + hashmap lookup;
+ /// only the very first call for a given `model_id` takes the
+ /// write lock, and concurrent callers double-check under it.
+ pub async fn get_or_create(&self, model_id: &str) -> (Arc<Scheduler<I, T>>, bool) {
+ if let Some(s) = self.schedulers.read().await.get(model_id) {
+ return (Arc::clone(s), false);
+ }
+ let mut map = self.schedulers.write().await;
+ if let Some(s) = map.get(model_id) {
+ return (Arc::clone(s), false);
+ }
+ let sched = Arc::new(Scheduler::new(self.default_config));
+ map.insert(model_id.to_owned(), Arc::clone(&sched));
+ (sched, true)
+ }
+
+ /// List the model ids that currently have an instantiated
+ /// scheduler. Useful for dashboards and for the shadow-trace
+ /// replay which needs to enumerate live per-model state.
+ pub async fn active_models(&self) -> Vec<String> {
+ self.schedulers.read().await.keys().cloned().collect()
+ }
+
+ /// Number of active schedulers. Cheap — one read-lock acquire.
+ pub async fn active_count(&self) -> usize {
+ self.schedulers.read().await.len()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[derive(Debug, Clone, Copy)]
+ struct StubItem;
+ impl HasCost for StubItem {
+ fn cost(&self) -> u64 {
+ 1
+ }
+ fn original_index(&self) -> usize {
+ 0
+ }
+ }
+
+ #[tokio::test]
+ async fn get_or_create_marks_first_call_as_created() {
+ let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());
+ let (_, created1) = reg.get_or_create("foo").await;
+ assert!(created1, "first call for a model must report created=true");
+ let (_, created2) = reg.get_or_create("foo").await;
+ assert!(
+ !created2,
+ "subsequent call for the same model must report created=false"
+ );
+ }
+
+ #[tokio::test]
+ async fn get_or_create_returns_same_arc_on_repeat_calls() {
+ let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());
+ let (a, _) = reg.get_or_create("foo").await;
+ let (b, _) = reg.get_or_create("foo").await;
+ // Pointer equality — lazy creation must memoize the Arc so
+ // adaptive-controller state persists across dispatcher calls.
+ assert!(Arc::ptr_eq(&a, &b));
+ }
+
+ #[tokio::test]
+ async fn different_models_get_different_schedulers() {
+ let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());
+ let (a, _) = reg.get_or_create("foo").await;
+ let (b, _) = reg.get_or_create("bar").await;
+ assert!(!Arc::ptr_eq(&a, &b));
+ }
+
+ #[tokio::test]
+ async fn active_models_reports_materialised_schedulers() {
+ let reg: SchedulerRegistry<StubItem, ()> = SchedulerRegistry::new(BatchConfig::default());
+ assert!(reg.active_models().await.is_empty());
+ let _ = reg.get_or_create("foo").await;
+ let _ = reg.get_or_create("bar").await;
+ let mut active = reg.active_models().await;
+ active.sort();
+ assert_eq!(active, vec!["bar".to_string(), "foo".to_string()]);
+ assert_eq!(reg.active_count().await, 2);
+ }
+}
diff --git a/packages/sie_server_sidecar/src/scheduler/trackers.rs b/packages/sie_server_sidecar/src/scheduler/trackers.rs
new file mode 100644
index 000000000..684fbbb90
--- /dev/null
+++ b/packages/sie_server_sidecar/src/scheduler/trackers.rs
@@ -0,0 +1,133 @@
+//! Rolling trackers used by the adaptive controller:
+//!
+//! * [`BatchEfficiencyTracker`] — mean fill ratio
+//! `actual_cost / max_cost` over the last N batches.
+//!
+//! The latency tracker is *not* re-ported here; the controller shares
+//! [`crate::latency::LatencyTracker`] since both ports use the same
+//! fixed-window-plus-nearest-rank percentile implementation. See the
+//! `scheduler::adaptive` module for how the two wire together.
+
+use std::collections::VecDeque;
+
+/// Rolling mean-fill-ratio tracker.
+///
+/// Ported from `sie_server/core/adaptive_batching.py::BatchEfficiencyTracker`.
+///
+/// A fill ratio near 1.0 means the GPU is fully saturated — batches
+/// are consistently hitting the cost cap. Near 0 means the batcher
+/// is flushing tiny batches; the adaptive cost knob should stay
+/// conservative.
+#[derive(Debug, Clone)]
+pub struct BatchEfficiencyTracker {
+ window_size: usize,
+ ratios: VecDeque<f64>,
+}
+
+impl BatchEfficiencyTracker {
+ /// Construct with an explicit window size. Python's default is 50;
+ /// callers that want parity with the Python defaults should use
+ /// [`Self::default`].
+ #[must_use]
+ pub fn new(window_size: usize) -> Self {
+ Self {
+ window_size,
+ ratios: VecDeque::with_capacity(window_size),
+ }
+ }
+
+ /// Record a batch fill ratio. `actual_cost` may be any cost unit;
+ /// the ratio is taken against `max_cost`. Zero or negative
+ /// `max_cost` is silently dropped (matches Python's guard) —
+ /// adapters that haven't populated the cap yet shouldn't poison
+ /// the mean.
+ pub fn record(&mut self, actual_cost: u64, max_cost: u64) {
+ if max_cost == 0 {
+ return;
+ }
+ if self.ratios.len() == self.window_size {
+ self.ratios.pop_front();
+ }
+ let ratio = actual_cost as f64 / max_cost as f64;
+ self.ratios.push_back(ratio);
+ }
+
+ /// Mean of the current window, or `None` when nothing's been
+ /// recorded yet. Matches Python's `mean_fill_ratio`.
+ #[must_use]
+ pub fn mean_fill_ratio(&self) -> Option<f64> {
+ if self.ratios.is_empty() {
+ return None;
+ }
+ let sum: f64 = self.ratios.iter().sum();
+ Some(sum / self.ratios.len() as f64)
+ }
+
+ /// Number of samples currently in the window.
+ #[must_use]
+ pub fn sample_count(&self) -> usize {
+ self.ratios.len()
+ }
+
+ /// Clear all samples. Used by the controller on starvation
+ /// recovery and on `reset()`.
+ pub fn reset(&mut self) {
+ self.ratios.clear();
+ }
+}
+
+impl Default for BatchEfficiencyTracker {
+ /// Default window of 50, matching Python.
+ fn default() -> Self {
+ Self::new(50)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn empty_tracker_reports_none() {
+ let t = BatchEfficiencyTracker::default();
+ assert_eq!(t.mean_fill_ratio(), None);
+ assert_eq!(t.sample_count(), 0);
+ }
+
+ #[test]
+ fn zero_max_cost_is_ignored() {
+ let mut t = BatchEfficiencyTracker::default();
+ t.record(10, 0);
+ assert_eq!(t.sample_count(), 0);
+ }
+
+ #[test]
+ fn mean_is_arithmetic_average() {
+ let mut t = BatchEfficiencyTracker::default();
+ t.record(1, 4); // 0.25
+ t.record(3, 4); // 0.75
+ let m = t.mean_fill_ratio().unwrap();
+ assert!((m - 0.5).abs() < f64::EPSILON);
+ }
+
+ #[test]
+ fn window_drops_oldest_past_capacity() {
+ let mut t = BatchEfficiencyTracker::new(2);
+ t.record(0, 10); // 0.0
+ t.record(10, 10); // 1.0
+ t.record(5, 10); // 0.5 — evicts 0.0
+ assert_eq!(t.sample_count(), 2);
+ let m = t.mean_fill_ratio().unwrap();
+ // Mean of (1.0 + 0.5) / 2 = 0.75
+ assert!((m - 0.75).abs() < f64::EPSILON);
+ }
+
+ #[test]
+ fn reset_clears_window() {
+ let mut t = BatchEfficiencyTracker::default();
+ t.record(1, 2);
+ t.reset();
+ assert_eq!(t.sample_count(), 0);
+ assert_eq!(t.mean_fill_ratio(), None);
+ }
+}
diff --git a/packages/sie_server_sidecar/src/shutdown.rs b/packages/sie_server_sidecar/src/shutdown.rs
new file mode 100644
index 000000000..1e1d8f87c
--- /dev/null
+++ b/packages/sie_server_sidecar/src/shutdown.rs
@@ -0,0 +1,187 @@
+//! Graceful shutdown utilities.
+//!
+//! One `Shutdown` broadcast channel signals every long-running task to
+//! stop. `install_signal_handlers` registers SIGTERM (pod preemption) and
+//! SIGINT (Ctrl-C) to trip it. Consumers either call `wait()` or use it
+//! directly in `tokio::select!`.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+
+use tokio::sync::Notify;
+use tracing::info;
+
+/// Latched broadcast signal. Tripped by `fire()` exactly once (idempotent);
+/// every subsequent `wait()` — including those registered *after* `fire()` —
+/// returns immediately.
+///
+/// Previous implementation used a bare `tokio::sync::Notify` whose
+/// `notify_waiters()` only wakes *currently parked* futures. A late waiter
+/// (e.g. a task that finishes its current `select!` branch after SIGTERM and
+/// only then hits the `shutdown.wait()` branch) would block forever. The
+/// `AtomicBool` latch closes that hole: the fast path checks `fired` first
+/// and bails out synchronously; the slow path subscribes to the `Notify`
+/// *then* re-checks the flag to close the register-between-fire race.
+pub struct Shutdown {
+ fired: AtomicBool,
+ notify: Notify,
+}
+
+impl Shutdown {
+ pub fn new() -> Self {
+ Self {
+ fired: AtomicBool::new(false),
+ notify: Notify::new(),
+ }
+ }
+
+ /// Trip the shutdown signal. Idempotent — once tripped, subsequent
+ /// `wait()` callers return immediately. Safe to call from any thread.
+ pub fn fire(&self) {
+ // Release ordering pairs with the Acquire load in `wait`/`is_fired`
+ // so a waiter that observes `fired=true` is guaranteed to see every
+ // memory write ordered-before the `fire()` call.
+ self.fired.store(true, Ordering::Release);
+ self.notify.notify_waiters();
+ }
+
+ /// Returns true if `fire()` has already been called.
+ pub fn is_fired(&self) -> bool {
+ self.fired.load(Ordering::Acquire)
+ }
+
+ /// Wait until `fire()` has been called. Multiple callers may wait
+ /// concurrently; each wakes when `fire()` runs. Callers that register
+ /// *after* `fire()` return immediately.
+ pub async fn wait(&self) {
+ // Fast path: already fired.
+ if self.is_fired() {
+ return;
+ }
+ // Slow path: subscribe, then re-check. The re-check closes the window
+ // where `fire()` runs between our first load and the `notified()`
+ // registration (Notify would lose that notification).
+ let notified = self.notify.notified();
+ tokio::pin!(notified);
+ if self.is_fired() {
+ return;
+ }
+ notified.await;
+ }
+}
+
+impl Default for Shutdown {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Install SIGTERM + SIGINT handlers that trip the given `Shutdown`.
+///
+/// On non-unix targets (only here to keep `cargo check --all-targets`
+/// happy on CI images lacking `libc::SIGTERM`), this does nothing.
+pub fn install_signal_handlers(shutdown: Arc<Shutdown>) {
+ #[cfg(unix)]
+ {
+ tokio::spawn(async move {
+ use tokio::signal::unix::{signal, SignalKind};
+ let mut term = match signal(SignalKind::terminate()) {
+ Ok(s) => s,
+ Err(e) => {
+ tracing::warn!(error = %e, "failed to install SIGTERM handler");
+ return;
+ }
+ };
+ let mut int_ = match signal(SignalKind::interrupt()) {
+ Ok(s) => s,
+ Err(e) => {
+ tracing::warn!(error = %e, "failed to install SIGINT handler");
+ return;
+ }
+ };
+ tokio::select! {
+ _ = term.recv() => info!("received SIGTERM"),
+ _ = int_.recv() => info!("received SIGINT"),
+ }
+ shutdown.fire();
+ });
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = shutdown;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::Duration;
+
+ #[tokio::test]
+ async fn fire_wakes_all_waiters() {
+ let shutdown = Arc::new(Shutdown::new());
+ let a = Arc::clone(&shutdown);
+ let b = Arc::clone(&shutdown);
+ let task_a = tokio::spawn(async move { a.wait().await });
+ let task_b = tokio::spawn(async move { b.wait().await });
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ shutdown.fire();
+
+ tokio::time::timeout(Duration::from_millis(100), task_a)
+ .await
+ .unwrap()
+ .unwrap();
+ tokio::time::timeout(Duration::from_millis(100), task_b)
+ .await
+ .unwrap()
+ .unwrap();
+ }
+
+ #[tokio::test]
+ async fn wait_after_fire_returns_immediately() {
+ // Regression: the old implementation used bare `Notify::notify_waiters`
+ // which is edge-triggered — a waiter that registered *after* fire()
+ // would block forever until a second fire(). With the latched
+ // AtomicBool + Notify design, `wait()` is level-triggered: once fired,
+ // every subsequent waiter returns immediately.
+ let shutdown = Arc::new(Shutdown::new());
+ shutdown.fire();
+
+ tokio::time::timeout(Duration::from_millis(100), shutdown.wait())
+ .await
+ .expect("wait() must return immediately after fire()");
+ }
+
+ #[tokio::test]
+ async fn race_fire_between_subscribe_and_await() {
+ // The classic missed-wakeup: we call `wait()` on a thread that is
+ // currently in the middle of `Notify::notified()` registration when
+ // `fire()` runs on another thread. The re-check after subscribe
+ // closes that window.
+ for _ in 0..200 {
+ let shutdown = Arc::new(Shutdown::new());
+ let waiter = {
+ let s = Arc::clone(&shutdown);
+ tokio::spawn(async move { s.wait().await })
+ };
+ // Yield to give the waiter a chance to park.
+ tokio::task::yield_now().await;
+ shutdown.fire();
+ tokio::time::timeout(Duration::from_millis(50), waiter)
+ .await
+ .expect("waiter must not block after fire()")
+ .unwrap();
+ }
+ }
+
+ #[tokio::test]
+ async fn is_fired_reflects_state() {
+ let shutdown = Shutdown::new();
+ assert!(!shutdown.is_fired());
+ shutdown.fire();
+ assert!(shutdown.is_fired());
+ shutdown.fire();
+ assert!(shutdown.is_fired());
+ }
+}
diff --git a/packages/sie_server_sidecar/src/subject.rs b/packages/sie_server_sidecar/src/subject.rs
new file mode 100644
index 000000000..2d23906fb
--- /dev/null
+++ b/packages/sie_server_sidecar/src/subject.rs
@@ -0,0 +1,180 @@
+//! NATS subject helpers — model-id normalisation + extraction.
+//!
+//! Work subject format: `sie.work.{normalized_model_id}.{pool_name}`.
+
+/// Subject token index of the normalized model id (`sie.work.<MODEL>.pool`).
+const MODEL_TOKEN_INDEX: usize = 2;
+
+/// Minimum number of dot-delimited tokens a valid work subject must have.
+const MIN_SUBJECT_PARTS: usize = 4;
+
+/// Inverse of [`normalize_model_id`]. Best-effort: `__` → `/`, `_dot_` → `.`.
+pub fn denormalize_model_id(normalized: &str) -> String {
+ normalized.replace("__", "/").replace("_dot_", ".")
+}
+
+/// Make a model id safe to embed in a NATS subject token.
+pub fn normalize_model_id(model_id: &str) -> String {
+ model_id
+ .replace('/', "__")
+ .replace('.', "_dot_")
+ .replace(['*', '>', ' '], "_")
+}
+
+/// Extract and denormalise the model id from a work subject.
+/// Returns `None` for malformed subjects (fewer than 4 tokens).
+pub fn extract_model_id(subject: &str) -> Option<String> {
+ let parts: Vec<&str> = subject.split('.').collect();
+ if parts.len() < MIN_SUBJECT_PARTS {
+ return None;
+ }
+ Some(denormalize_model_id(parts[MODEL_TOKEN_INDEX]))
+}
+
+/// True iff the two NATS subject filters share at least one concrete
+/// subject — i.e. NATS would reject creating two WorkQueue consumers
+/// with these filters on the same stream.
+///
+/// Wildcard semantics:
+/// - `*` matches exactly one token
+/// - `>` matches one or more trailing tokens (only legal as the last
+/// token; anything else is treated as a literal here, which still
+/// gives a sound — if conservative — answer)
+///
+/// This is the predicate behind the worker's stale-durable self-heal
+/// in `nats_consumer::ensure_stream_and_consumer`: we treat any
+/// existing consumer whose filter overlaps ours (and whose name is not
+/// ours) as a leftover from a prior bundle/engine deploy, and delete
+/// it. Without this, flipping bundles on the same pool wedges
+/// JetStream with `consumer filter overlaps` and the worker
+/// CrashLoops.
+pub fn subjects_overlap(a: &str, b: &str) -> bool {
+ let at: Vec<&str> = a.split('.').collect();
+ let bt: Vec<&str> = b.split('.').collect();
+ if at.is_empty() || bt.is_empty() {
+ return false;
+ }
+
+ let a_has_gt = at.last() == Some(&">");
+ let b_has_gt = bt.last() == Some(&">");
+ let a_fixed = if a_has_gt { at.len() - 1 } else { at.len() };
+ let b_fixed = if b_has_gt { bt.len() - 1 } else { bt.len() };
+
+ let common = a_fixed.min(b_fixed);
+ for i in 0..common {
+ let ta = at[i];
+ let tb = bt[i];
+ if ta != "*" && tb != "*" && ta != tb {
+ return false;
+ }
+ }
+
+ // After matching the fixed prefix, decide whether the trailing
+ // tokens (if any) can also align under `>` semantics. `>` requires
+ // at least one trailing token on the other side.
+ match (a_has_gt, b_has_gt) {
+ (false, false) => at.len() == bt.len(),
+ (true, false) => bt.len() >= at.len(),
+ (false, true) => at.len() >= bt.len(),
+ (true, true) => true,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn normalize_handles_slashes_and_dots() {
+ assert_eq!(normalize_model_id("BAAI/bge-m3"), "BAAI__bge-m3");
+ assert_eq!(normalize_model_id("a.b"), "a_dot_b");
+ assert_eq!(normalize_model_id("a/b.c"), "a__b_dot_c");
+ }
+
+ #[test]
+ fn denormalize_is_inverse_of_normalize_for_safe_ids() {
+ for id in ["BAAI/bge-m3", "openai/text-embedding-3-small", "x.y"] {
+ assert_eq!(denormalize_model_id(&normalize_model_id(id)), id);
+ }
+ }
+
+ #[test]
+ fn extract_from_valid_subject() {
+ assert_eq!(
+ extract_model_id("sie.work.BAAI__bge-m3.l4"),
+ Some("BAAI/bge-m3".to_string())
+ );
+ assert_eq!(
+ extract_model_id("sie.work.a_dot_b.default"),
+ Some("a.b".to_string())
+ );
+ }
+
+ #[test]
+ fn extract_returns_none_on_malformed() {
+ assert_eq!(extract_model_id(""), None);
+ assert_eq!(extract_model_id("sie.work"), None);
+ assert_eq!(extract_model_id("sie.work.model"), None);
+ }
+
+ // ----- subjects_overlap ---------------------------------------------------
+
+ #[test]
+ fn overlap_identical_filters_with_wildcard_overlap() {
+ // The exact case that wedged the GKE worker on bundle flips:
+ // two consumers (e.g. `default_l4` from a new deploy and a
+ // stale durable left behind by a previous bundle) both
+ // filtered on this string.
+ assert!(subjects_overlap("sie.work.*.l4", "sie.work.*.l4"));
+ }
+
+ #[test]
+ fn overlap_wildcard_vs_literal_in_same_slot() {
+ assert!(subjects_overlap(
+ "sie.work.*.l4",
+ "sie.work.BAAI__bge-m3.l4"
+ ));
+ assert!(subjects_overlap(
+ "sie.work.BAAI__bge-m3.l4",
+ "sie.work.*.l4"
+ ));
+ }
+
+ #[test]
+ fn overlap_disjoint_pools_do_not_overlap() {
+ // Different pools → distinct streams in practice, but the
+ // predicate must still report no overlap so it's safe to call
+ // even on cross-stream listings.
+ assert!(!subjects_overlap("sie.work.*.l4", "sie.work.*.h100"));
+ assert!(!subjects_overlap("sie.work.foo.l4", "sie.work.foo.eval-l4"));
+ }
+
+ #[test]
+ fn overlap_different_lengths_without_gt_do_not_overlap() {
+ assert!(!subjects_overlap("sie.work.*.l4", "sie.work.*.l4.extra"));
+ assert!(!subjects_overlap("sie.work.*", "sie.work.*.l4"));
+ }
+
+ #[test]
+ fn overlap_gt_swallows_trailing_tokens() {
+ // `>` must match AT LEAST one trailing token, so it overlaps
+ // with longer filters but not with one of equal length.
+ assert!(subjects_overlap("sie.work.>", "sie.work.foo.l4"));
+ assert!(subjects_overlap("sie.work.foo.l4", "sie.work.>"));
+ assert!(subjects_overlap("sie.>", "sie.work.*.l4"));
+ assert!(!subjects_overlap("sie.work.>", "sie.work"));
+ assert!(!subjects_overlap("sie.>", "nats.work.*.l4"));
+ }
+
+ #[test]
+ fn overlap_two_gt_filters_that_share_a_prefix() {
+ assert!(subjects_overlap("sie.work.>", "sie.>"));
+ assert!(!subjects_overlap("sie.>", "nats.>"));
+ }
+
+ #[test]
+ fn overlap_empty_inputs_are_safe() {
+ assert!(!subjects_overlap("", "sie.work.*.l4"));
+ assert!(!subjects_overlap("sie.work.*.l4", ""));
+ }
+}
diff --git a/packages/sie_server_sidecar/src/tokenize/mod.rs b/packages/sie_server_sidecar/src/tokenize/mod.rs
new file mode 100644
index 000000000..00f416432
--- /dev/null
+++ b/packages/sie_server_sidecar/src/tokenize/mod.rs
@@ -0,0 +1,292 @@
+//! Rust-side tokenisation for the Python-IPC backend path.
+//!
+//! The sidecar tokenises text for models whose adapter has declared a
+//! tokeniser on the `EnsureModelReady` handshake (see
+//! [`registry::TokenizerRegistry::register_from_descriptor`]) and
+//! attaches the result as [`crate::ipc_types::PreparedTokens`] on
+//! `EncodeBatchItem` / `ScoreBatchItem`. The Python adapter checks the
+//! `tokenizer_id` hash; on match it uses the tokens directly, on
+//! mismatch / absence it falls back to its own HF `AutoTokenizer`
+//! call — bit-for-bit the same wire contract as today.
+//!
+//! # Parity with Python
+//!
+//! The Python adapters that currently tokenise inline
+//! (`RoPEFlashAdapter`, `XLMRobertaFlashAdapter`, `ModernBertFlashAdapter`,
+//! `NomicFlashAdapter`, ...) all call the HF fast tokenizer with the
+//! same kwargs:
+//!
+//! ```python
+//! tokenizer(texts, max_length=N, truncation=True, padding=False)
+//! ```
+//!
+//! Ragged per-item `input_ids` — no batch padding. The packed flash
+//! path handles cross-sequence layout itself via `cu_seqlens`. The
+//! Rust side mirrors that policy in [`tokenize_no_pad`]: it loads the
+//! same `tokenizer.json` via the HF `tokenizers` crate, forces
+//! truncation to `max_seq_len`, and disables padding. `input_ids`
+//! vectors therefore have their natural per-item lengths and match
+//! Python's output byte-for-byte (see the byte-identity unit test).
+//!
+//! # What this module DOESN'T do (v1 scope)
+//!
+//! - No query / doc template application (`"query: {text}"` etc). If
+//! the model has a template configured, the dispatcher elides
+//! `prepared_tokens` for that request and Python tokenises as
+//! today. Template support is an additive v2 extension.
+//! - No sentence-pair tokenisation (cross-encoder score). Those
+//! models fall back to Python tokenise for v1.
+//! - No image / audio / multimodal preprocessing.
+//!
+//! Anything not covered above stays on the Python path — v1 is
+//! strictly additive and non-destructive.
+
+pub mod registry;
+
+use tokenizers::{PaddingParams, PaddingStrategy, Tokenizer, TruncationParams, TruncationStrategy};
+
+pub use registry::{TokenizerEntry, TokenizerRegistry};
+
+/// Per-item ragged token output, matching Python's
+/// `tokenizer(texts, max_length, truncation=True, padding=False)`.
+///
+/// Each inner `Vec<u32>` is the `input_ids` for the corresponding
+/// text; `attention_mask[i]` has the same length as `input_ids[i]`
+/// (all-ones for single-sequence text, since there is no padding);
+/// `token_type_ids[i]` is present when the tokenizer produces
+/// segments (zero-filled for most BERT-family encoders), otherwise
+/// the vector is empty and the caller treats it as "not emitted".
+#[derive(Debug, Clone, Default)]
+pub struct RaggedTokens {
+ pub input_ids: Vec<Vec<u32>>,
+ pub attention_mask: Vec<Vec<u32>>,
+ pub token_type_ids: Vec<Vec<u32>>,
+}
+
+impl RaggedTokens {
+ pub fn is_empty(&self) -> bool {
+ self.input_ids.is_empty()
+ }
+
+ pub fn len(&self) -> usize {
+ self.input_ids.len()
+ }
+
+ /// True iff every `token_type_ids[i]` is all-zeros. BERT-family
+ /// tokenizers emit a zero-filled segment vector even when the
+ /// model doesn't use segments; the dispatcher uses this to skip
+ /// emitting the field over the wire and save bytes.
+ pub fn token_type_ids_all_zero(&self) -> bool {
+ self.token_type_ids
+ .iter()
+ .all(|row| row.iter().all(|&t| t == 0))
+ }
+}
+
+/// Load a HF fast-tokenizer from `tokenizer.json` configured for the
+/// IPC-path policy: **no padding, truncate to `max_seq_len`**.
+///
+/// This is the only HF tokenizer loader in the workspace — the
+/// flash-attn adapters on the Python side explicitly require ragged
+/// input, so we never pad on the sidecar; Python pads ad-hoc when a
+/// model needs it.
+///
+/// # Padding preservation
+///
+/// Do NOT clobber `pad_id` / `pad_token` on an existing
+/// `PaddingParams` block in `tokenizer.json` (XLM-R's `pad_id=1`
+/// would regress to `0` otherwise). Mutate in place if present,
+/// install defaults only when absent. Strategy is explicitly set to
+/// `PaddingStrategy::Fixed(0)` in the "absent" case so batch-time
+/// padding never silently re-activates.
+pub fn load_no_pad_tokenizer(
+ path: &std::path::Path,
+ max_seq_len: usize,
+) -> Result<Tokenizer, String> {
+ let mut tok = Tokenizer::from_file(path).map_err(|e| format!("load tokenizer: {e}"))?;
+
+ // Disable padding. The existing `PaddingParams` (if any) still
+ // carries `pad_id` / `pad_token` that the adapter might need at
+ // pad time; we just set the strategy to `Fixed(0)` so the
+ // encode_batch call itself emits no padding.
+ if let Some(existing) = tok.get_padding_mut() {
+ existing.strategy = PaddingStrategy::Fixed(0);
+ } else {
+ tok.with_padding(Some(PaddingParams {
+ strategy: PaddingStrategy::Fixed(0),
+ ..Default::default()
+ }));
+ }
+
+ tok.with_truncation(Some(TruncationParams {
+ max_length: max_seq_len,
+ strategy: TruncationStrategy::LongestFirst,
+ ..Default::default()
+ }))
+ .map_err(|e| format!("set truncation: {e}"))?;
+
+ Ok(tok)
+}
+
+/// Batch-tokenise `texts` into ragged per-item `input_ids` +
+/// `attention_mask` + `token_type_ids`, with no padding.
+///
+/// Mirrors Python's
+/// ```python
+/// tokenizer(texts, max_length=N, truncation=True, padding=False)
+/// ```
+///
+/// Returns a default (empty) [`RaggedTokens`] when `texts` is empty.
+pub fn tokenize_no_pad(tok: &Tokenizer, texts: &[&str]) -> Result<RaggedTokens, String> {
+ if texts.is_empty() {
+ return Ok(RaggedTokens::default());
+ }
+ let encodings = tok
+ .encode_batch(texts.to_vec(), true)
+ .map_err(|e| format!("tokenize batch: {e}"))?;
+
+ let mut input_ids = Vec::with_capacity(encodings.len());
+ let mut attention_mask = Vec::with_capacity(encodings.len());
+ let mut token_type_ids = Vec::with_capacity(encodings.len());
+ for enc in encodings {
+ input_ids.push(enc.get_ids().to_vec());
+ attention_mask.push(enc.get_attention_mask().to_vec());
+ token_type_ids.push(enc.get_type_ids().to_vec());
+ }
+
+ Ok(RaggedTokens {
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ })
+}
+
+/// Compute the stable, cross-language content hash of a loaded
+/// tokenizer.
+///
+/// The hash is taken over the tokenizer's canonical JSON
+/// serialisation (`Tokenizer::to_string(false)`), **not** the raw
+/// bytes of the `tokenizer.json` file. Two reasons:
+///
+/// 1. The Python side can reproduce it exactly: HF's `tokenizers`
+/// crate is the same library wrapped by the Python package, so
+/// `tokenizer.backend_tokenizer.to_str(pretty=False).encode()`
+/// yields byte-identical input to BLAKE3.
+/// 2. The raw on-disk file can vary in insignificant ways (trailing
+/// whitespace, key ordering after some HF hub round-trips)
+/// without the actual tokenizer configuration changing. Hashing
+/// the parsed form avoids false drift alarms.
+///
+/// Uses BLAKE3 truncated to 32 hex chars (128 bits) — overkill for
+/// accidental-drift detection, fits comfortably in the wire budget,
+/// and is trivially reproducible on the Python side via the
+/// `blake3` PyPI package.
+///
+/// Callers should hash the tokenizer **before** applying any
+/// IPC-specific padding / truncation config (the
+/// `load_no_pad_tokenizer` call), so the id is determined by the
+/// tokenizer's own declared settings, not by our runtime overrides.
+/// The registry does this correctly.
+pub fn tokenizer_content_hash(tok: &Tokenizer) -> String {
+ // `to_string(false)` → compact, non-pretty JSON. The Python
+ // `tokenizers` binding exposes the same method as
+ // `.to_str(pretty=False)`; both wrap `Tokenizer::to_string` in
+ // the underlying Rust crate.
+ let canonical = tok
+ .to_string(false)
+ .expect("tokenizer.json round-trip serialisation must not fail");
+ let digest = blake3::hash(canonical.as_bytes());
+ digest.to_hex().as_str()[..32].to_string()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn ragged_empty_by_default() {
+ let r = RaggedTokens::default();
+ assert!(r.is_empty());
+ assert_eq!(r.len(), 0);
+ }
+
+ #[test]
+ fn tokenizer_content_hash_is_deterministic_and_short() {
+ // Tiny WordLevel tokenizer used throughout the registry
+ // tests; re-inlined here so this unit doesn't depend on the
+ // registry's test-only constant.
+ const TINY: &str = r#"{
+ "version": "1.0",
+ "truncation": null,
+ "padding": null,
+ "added_tokens": [],
+ "normalizer": null,
+ "pre_tokenizer": {"type": "Whitespace"},
+ "post_processor": null,
+ "decoder": null,
+ "model": {
+ "type": "WordLevel",
+ "vocab": {"[UNK]": 0, "hello": 1, "world": 2},
+ "unk_token": "[UNK]"
+ }
+ }"#;
+ let dir = tempfile::TempDir::new().unwrap();
+ let path = dir.path().join("tokenizer.json");
+ std::fs::write(&path, TINY).unwrap();
+
+ let tok_a = Tokenizer::from_file(&path).unwrap();
+ let tok_b = Tokenizer::from_file(&path).unwrap();
+ let a = tokenizer_content_hash(&tok_a);
+ let b = tokenizer_content_hash(&tok_b);
+ assert_eq!(a, b, "hash must be deterministic for the same input");
+ assert_eq!(a.len(), 32, "hash must be exactly 32 hex chars (128 bits)");
+
+ // Sanity: mutating the tokenizer (different vocab) changes
+ // the canonical serialisation and therefore the hash.
+ const TINY2: &str = r#"{
+ "version": "1.0",
+ "truncation": null,
+ "padding": null,
+ "added_tokens": [],
+ "normalizer": null,
+ "pre_tokenizer": {"type": "Whitespace"},
+ "post_processor": null,
+ "decoder": null,
+ "model": {
+ "type": "WordLevel",
+ "vocab": {"[UNK]": 0, "hello": 1, "there": 2},
+ "unk_token": "[UNK]"
+ }
+ }"#;
+ let path2 = dir.path().join("tokenizer2.json");
+ std::fs::write(&path2, TINY2).unwrap();
+ let tok_c = Tokenizer::from_file(&path2).unwrap();
+ assert_ne!(a, tokenizer_content_hash(&tok_c));
+ }
+
+ #[test]
+ fn token_type_ids_all_zero_detects_bert_style_segments() {
+ let empty = RaggedTokens::default();
+ assert!(
+ empty.token_type_ids_all_zero(),
+ "empty counts as all-zero (no rows to violate)"
+ );
+
+ let bert_like = RaggedTokens {
+ input_ids: vec![vec![1, 2, 3], vec![4, 5]],
+ attention_mask: vec![vec![1, 1, 1], vec![1, 1]],
+ token_type_ids: vec![vec![0, 0, 0], vec![0, 0]],
+ };
+ assert!(bert_like.token_type_ids_all_zero());
+
+ let pair_like = RaggedTokens {
+ input_ids: vec![vec![1, 2, 3]],
+ attention_mask: vec![vec![1, 1, 1]],
+ token_type_ids: vec![vec![0, 1, 1]],
+ };
+ assert!(
+ !pair_like.token_type_ids_all_zero(),
+ "sentence-pair segment ids must not be collapsed"
+ );
+ }
+}
diff --git a/packages/sie_server_sidecar/src/tokenize/registry.rs b/packages/sie_server_sidecar/src/tokenize/registry.rs
new file mode 100644
index 000000000..6607c9c8b
--- /dev/null
+++ b/packages/sie_server_sidecar/src/tokenize/registry.rs
@@ -0,0 +1,500 @@
+//! Per-model tokenizer registry, lazily populated from
+//! `EnsureModelReady` handshake descriptors.
+//!
+//! # How tokenisers get into the registry
+//!
+//! The registry is **adapter-driven**: the
+//! Python (or future native) adapter declares its tokeniser path,
+//! content hash, and max-seq-len on the first
+//! `EnsureModelReady(model_id)` for that model, and the dispatcher
+//! calls [`TokenizerRegistry::register_from_descriptor`] to ingest
+//! the entry. There is no sidecar-local model list that gates this path.
+//!
+//! # Concurrency
+//!
+//! Entries are stored behind an `RwLock` so the dispatcher's
+//! per-batch lookup ([`TokenizerRegistry::get`]) is wait-free under
+//! contention from the rare ingest path. `TokenizerEntry` is `Clone`
+//! (the underlying `Tokenizer` is wrapped in [`Arc`]), so the read
+//! path returns an owned snapshot and the lock is released before
+//! tokenisation runs.
+
+use std::collections::HashMap;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, RwLock};
+
+use tokenizers::Tokenizer;
+use tracing::{info, warn};
+
+use super::{load_no_pad_tokenizer, tokenize_no_pad, tokenizer_content_hash, RaggedTokens};
+use crate::ipc_types::ModelDescriptor;
+
+/// Fallback max sequence length when an entry doesn't carry one.
+/// Matches the historical `max_seq_len` default used across adapters
+/// so operators see consistent behaviour.
+pub const DEFAULT_MAX_SEQ_LEN: usize = 512;
+
+/// Loaded per-model tokenizer.
+#[derive(Clone)]
+pub struct TokenizerEntry {
+ /// Underlying HF fast-tokenizer, configured with no padding +
+ /// truncate-to-`max_seq_len`. Shared across worker threads via
+ /// [`Arc`]; `tokenizers::Tokenizer::encode_batch` is itself
+ /// thread-safe (immutable borrow).
+ tokenizer: Arc<Tokenizer>,
+ /// Per-model truncation bound. Already baked into `tokenizer`'s
+ /// truncation config; kept here for logging / metrics.
+ max_seq_len: usize,
+ /// Stable content hash of the `tokenizer.json` bytes used to
+ /// construct this entry. Emitted over the wire so Python can
+ /// verify it matches the tokenizer its adapter loaded.
+ tokenizer_id: String,
+ /// Model-default `query_template`, sourced from the adapter's
+ /// `EnsureModelReady` descriptor. Selected when an item arrives
+ /// with `is_query=true` and its `options.query_template` is
+ /// absent. `None` keeps today's behaviour (no template
+ /// application on the Rust side for this model).
+ default_query_template: Option<String>,
+ /// Model-default `doc_template` (selected when `is_query=false`).
+ /// Same wire contract as [`Self::default_query_template`].
+ default_doc_template: Option<String>,
+}
+
+impl TokenizerEntry {
+ pub fn tokenizer_id(&self) -> &str {
+ &self.tokenizer_id
+ }
+
+ pub fn max_seq_len(&self) -> usize {
+ self.max_seq_len
+ }
+
+ /// Model-default `query_template` from the adapter handshake.
+ pub fn default_query_template(&self) -> Option<&str> {
+ self.default_query_template.as_deref()
+ }
+
+ /// Model-default `doc_template` from the adapter handshake.
+ pub fn default_doc_template(&self) -> Option<&str> {
+ self.default_doc_template.as_deref()
+ }
+
+ /// Tokenise a batch of texts with this entry's tokenizer. Ragged
+ /// output (no padding), truncated at `max_seq_len`. See
+ /// [`tokenize_no_pad`].
+ pub fn tokenize(&self, texts: &[&str]) -> Result<RaggedTokens, String> {
+ tokenize_no_pad(self.tokenizer.as_ref(), texts)
+ }
+}
+
+impl std::fmt::Debug for TokenizerEntry {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("TokenizerEntry")
+ .field("max_seq_len", &self.max_seq_len)
+ .field("tokenizer_id", &self.tokenizer_id)
+ .field("default_query_template", &self.default_query_template)
+ .field("default_doc_template", &self.default_doc_template)
+ .finish()
+ }
+}
+
+/// Per-model tokenizer lookup. Always exists — empty registry
+/// just means "no model has registered a tokeniser yet" and every
+/// [`TokenizerRegistry::get`] returns `None`. Wrapped in an [`Arc`]
+/// so the dispatcher and any future callers share a single mutable
+/// table.
+#[derive(Debug)]
+pub struct TokenizerRegistry {
+ entries: RwLock<HashMap<String, TokenizerEntry>>,
+}
+
+impl TokenizerRegistry {
+ /// Build an empty registry. Tokenisers are added later via
+ /// [`Self::register_from_descriptor`] during the IPC handshake.
+ pub fn empty() -> Arc<Self> {
+ Arc::new(Self {
+ entries: RwLock::new(HashMap::new()),
+ })
+ }
+
+ /// Look up the tokenizer for a model id. Returns an owned (cloned)
+ /// entry so the caller can drop the read lock before running
+ /// `encode_batch`. `Arc<Tokenizer>` makes the clone cheap.
+ /// Absent → caller must fall back to the Python tokenise path
+ /// (no `prepared_tokens` on the wire).
+ pub fn get(&self, model_id: &str) -> Option<TokenizerEntry> {
+ self.entries
+ .read()
+ .expect("tokenizer registry RwLock poisoned")
+ .get(model_id)
+ .cloned()
+ }
+
+ /// True iff a tokeniser is registered for `model_id`.
+ pub fn contains(&self, model_id: &str) -> bool {
+ self.entries
+ .read()
+ .expect("tokenizer registry RwLock poisoned")
+ .contains_key(model_id)
+ }
+
+ pub fn len(&self) -> usize {
+ self.entries
+ .read()
+ .expect("tokenizer registry RwLock poisoned")
+ .len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ /// Sorted list of model ids — used for startup log output and
+ /// operator introspection.
+ pub fn model_ids(&self) -> Vec<String> {
+ let guard = self
+ .entries
+ .read()
+ .expect("tokenizer registry RwLock poisoned");
+ let mut ids: Vec<String> = guard.keys().cloned().collect();
+ ids.sort_unstable();
+ ids
+ }
+
+ /// Ingest a tokeniser declared by an adapter on the
+ /// `EnsureModelReady` handshake.
+ ///
+ /// Returns:
+ ///
+ /// * `Ok(true)` — entry was newly inserted (first time we've
+ /// seen this `model_id` with a tokenizer_path).
+ /// * `Ok(false)` — entry already present, descriptor has no
+ /// `tokenizer_path`, or the descriptor's tokenizer hash matches
+ /// the cached one (idempotent re-handshake).
+ /// * `Err(_)` — descriptor named a path that fails to load
+ /// (file missing, bad JSON, ...). The caller should log and
+ /// continue: the model just falls back to Python tokenisation.
+ ///
+ /// If the existing entry has a different `tokenizer_id` than the
+ /// descriptor, we replace it — the adapter is the source of
+ /// truth, and a hot-reload of the model's tokeniser must be
+ /// reflected here.
+ pub fn register_from_descriptor(
+ &self,
+ model_id: &str,
+ descriptor: &ModelDescriptor,
+ ) -> Result<bool, String> {
+ let Some(path_str) = descriptor.tokenizer_path.as_deref() else {
+ return Ok(false);
+ };
+ if path_str.is_empty() {
+ return Ok(false);
+ }
+
+ // Idempotent: if we already loaded a tokeniser for this model
+ // and the declared id + templates match, do nothing. Saves the
+ // cost of re-reading + re-hashing on every batch's
+ // ensure_ready call. Templates are part of the equality check
+ // so a YAML-driven template edit hot-reloads on the next
+ // handshake without restarting the sidecar.
+ if let Some(existing) = self.get(model_id) {
+ if let Some(decl_id) = descriptor.tokenizer_id.as_deref() {
+ let templates_match = existing.default_query_template.as_deref()
+ == descriptor.default_query_template.as_deref()
+ && existing.default_doc_template.as_deref()
+ == descriptor.default_doc_template.as_deref();
+ if existing.tokenizer_id() == decl_id && templates_match {
+ return Ok(false);
+ }
+ } else {
+ return Ok(false);
+ }
+ }
+
+ let max_seq_len = descriptor
+ .max_seq_len
+ .map(|v| v as usize)
+ .filter(|&v| v > 0)
+ .unwrap_or(DEFAULT_MAX_SEQ_LEN);
+
+ let path = PathBuf::from(path_str);
+ let entry = load_entry_with_templates(
+ &path,
+ max_seq_len,
+ descriptor.default_query_template.clone(),
+ descriptor.default_doc_template.clone(),
+ )?;
+
+ // Defence in depth: if the adapter declared a `tokenizer_id`
+ // and our locally-computed hash disagrees, refuse to register
+ // rather than enabling a fast path that the Python side will
+ // immediately reject. The mismatch is loud at `warn` so an
+ // operator notices the path/version drift.
+ if let Some(decl_id) = descriptor.tokenizer_id.as_deref() {
+ if entry.tokenizer_id != decl_id {
+ warn!(
+ model = %model_id,
+ declared_id = %decl_id,
+ loaded_id = %entry.tokenizer_id,
+ path = %path.display(),
+ "tokenize: descriptor tokenizer_id disagrees with loaded file; \
+ skipping registration — Python will tokenise this model"
+ );
+ return Ok(false);
+ }
+ }
+
+ let mut guard = self
+ .entries
+ .write()
+ .expect("tokenizer registry RwLock poisoned");
+ let newly_inserted = !guard.contains_key(model_id);
+ info!(
+ model = %model_id,
+ max_seq_len = entry.max_seq_len,
+ tokenizer_id = %entry.tokenizer_id,
+ path = %path.display(),
+ replaced = !newly_inserted,
+ "tokenize: registered tokeniser from EnsureModelReady descriptor"
+ );
+ guard.insert(model_id.to_string(), entry);
+ Ok(newly_inserted)
+ }
+}
+
+impl Default for TokenizerRegistry {
+ fn default() -> Self {
+ Self {
+ entries: RwLock::new(HashMap::new()),
+ }
+ }
+}
+
+fn load_entry_with_templates(
+ path: &Path,
+ max_seq_len: usize,
+ default_query_template: Option<String>,
+ default_doc_template: Option<String>,
+) -> Result<TokenizerEntry, String> {
+ if !path.is_file() {
+ return Err(format!("tokenizer.json not found: {}", path.display()));
+ }
+ // Hash BEFORE applying our IPC-specific padding/truncation overrides
+ // so the id identifies the *adapter's* tokeniser, not our runtime
+ // configuration. See `tokenizer_content_hash` for the rationale.
+ let hash_source =
+ Tokenizer::from_file(path).map_err(|e| format!("load tokenizer for hash: {e}"))?;
+ let tokenizer_id = tokenizer_content_hash(&hash_source);
+ drop(hash_source);
+
+ let tokenizer = load_no_pad_tokenizer(path, max_seq_len)?;
+ Ok(TokenizerEntry {
+ tokenizer: Arc::new(tokenizer),
+ max_seq_len,
+ tokenizer_id,
+ default_query_template,
+ default_doc_template,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::Write;
+ use tempfile::TempDir;
+
+ /// Minimal `tokenizer.json` blob for a WordLevel tokenizer. The
+ /// byte-identity integration test uses a real HF model; here we
+ /// just need a JSON the `tokenizers` crate will accept so the
+ /// registry-loading path is exercised end-to-end without a
+ /// network fetch.
+ const TINY_TOKENIZER_JSON: &str = r#"{
+ "version": "1.0",
+ "truncation": null,
+ "padding": null,
+ "added_tokens": [],
+ "normalizer": null,
+ "pre_tokenizer": { "type": "Whitespace" },
+ "post_processor": null,
+ "decoder": null,
+ "model": {
+ "type": "WordLevel",
+ "vocab": { "[UNK]": 0, "hello": 1, "world": 2 },
+ "unk_token": "[UNK]"
+ }
+}"#;
+
+ fn write_tiny_tokenizer(dir: &TempDir) -> PathBuf {
+ let path = dir.path().join("tokenizer.json");
+ let mut f = std::fs::File::create(&path).unwrap();
+ f.write_all(TINY_TOKENIZER_JSON.as_bytes()).unwrap();
+ path
+ }
+
+ #[test]
+ fn empty_registry_is_zero_cost() {
+ let reg = TokenizerRegistry::empty();
+ assert!(reg.is_empty());
+ assert_eq!(reg.len(), 0);
+ assert!(reg.get("any-model").is_none());
+ assert!(!reg.contains("any-model"));
+ }
+
+ // -- Handshake path ----------------------------------------------------
+
+ #[test]
+ fn register_from_descriptor_loads_tokenizer_and_returns_true() {
+ let dir = TempDir::new().unwrap();
+ let path = write_tiny_tokenizer(&dir);
+ let reg = TokenizerRegistry::empty();
+
+ let descriptor = ModelDescriptor {
+ tokenizer_path: Some(path.display().to_string()),
+ tokenizer_id: None,
+ max_seq_len: Some(64),
+ output_types: vec!["dense".into()],
+ supports_run_batch: true,
+ ..Default::default()
+ };
+
+ let inserted = reg
+ .register_from_descriptor("test-model", &descriptor)
+ .expect("descriptor load should succeed");
+ assert!(inserted);
+ assert_eq!(reg.len(), 1);
+
+ let entry = reg.get("test-model").unwrap();
+ assert_eq!(entry.max_seq_len(), 64);
+ assert_eq!(entry.tokenizer_id().len(), 32);
+
+ // Tokenisation works through the descriptor-loaded entry.
+ let out = entry.tokenize(&["hello world"]).unwrap();
+ assert_eq!(out.input_ids[0], vec![1, 2]);
+ }
+
+ #[test]
+ fn register_from_descriptor_is_idempotent_on_matching_hash() {
+ let dir = TempDir::new().unwrap();
+ let path = write_tiny_tokenizer(&dir);
+ let reg = TokenizerRegistry::empty();
+
+ let mut descriptor = ModelDescriptor {
+ tokenizer_path: Some(path.display().to_string()),
+ tokenizer_id: None,
+ max_seq_len: Some(64),
+ ..Default::default()
+ };
+ // First call: insert. Capture the loaded tokenizer_id.
+ assert!(reg
+ .register_from_descriptor("test-model", &descriptor)
+ .unwrap());
+ let loaded_id = reg.get("test-model").unwrap().tokenizer_id().to_string();
+
+ // Second call with declared_id == loaded_id: no-op.
+ descriptor.tokenizer_id = Some(loaded_id);
+ assert!(!reg
+ .register_from_descriptor("test-model", &descriptor)
+ .unwrap());
+ }
+
+ #[test]
+ fn register_from_descriptor_skips_when_tokenizer_id_mismatches() {
+ let dir = TempDir::new().unwrap();
+ let path = write_tiny_tokenizer(&dir);
+ let reg = TokenizerRegistry::empty();
+
+ // Declared id deliberately wrong → registry refuses to register
+ // rather than enabling a fast path the Python side will reject.
+ let descriptor = ModelDescriptor {
+ tokenizer_path: Some(path.display().to_string()),
+ tokenizer_id: Some("deadbeef".repeat(4)),
+ max_seq_len: Some(64),
+ ..Default::default()
+ };
+ let inserted = reg
+ .register_from_descriptor("test-model", &descriptor)
+ .unwrap();
+ assert!(!inserted);
+ assert!(reg.is_empty());
+ }
+
+ #[test]
+ fn register_from_descriptor_returns_false_when_path_absent() {
+ let reg = TokenizerRegistry::empty();
+ let descriptor = ModelDescriptor::default();
+ assert!(!reg
+ .register_from_descriptor("test-model", &descriptor)
+ .unwrap());
+ assert!(reg.is_empty());
+ }
+
+ #[test]
+ fn register_from_descriptor_stores_default_templates() {
+ let dir = TempDir::new().unwrap();
+ let path = write_tiny_tokenizer(&dir);
+ let reg = TokenizerRegistry::empty();
+ let descriptor = ModelDescriptor {
+ tokenizer_path: Some(path.display().to_string()),
+ tokenizer_id: None,
+ max_seq_len: Some(64),
+ default_query_template: Some("query: {text}".into()),
+ default_doc_template: Some("passage: {text}".into()),
+ ..Default::default()
+ };
+ assert!(reg
+ .register_from_descriptor("test-model", &descriptor)
+ .unwrap());
+ let entry = reg.get("test-model").unwrap();
+ assert_eq!(entry.default_query_template(), Some("query: {text}"));
+ assert_eq!(entry.default_doc_template(), Some("passage: {text}"));
+ }
+
+ #[test]
+ fn register_from_descriptor_replaces_entry_when_templates_change() {
+ // A YAML edit to a template should hot-reload on the next
+ // EnsureModelReady — the registry must not stick with the
+ // old templates just because the tokenizer hash hasn't moved.
+ let dir = TempDir::new().unwrap();
+ let path = write_tiny_tokenizer(&dir);
+ let reg = TokenizerRegistry::empty();
+
+ let mut descriptor = ModelDescriptor {
+ tokenizer_path: Some(path.display().to_string()),
+ tokenizer_id: None,
+ max_seq_len: Some(64),
+ default_query_template: Some("v1-query: {text}".into()),
+ default_doc_template: Some("v1-doc: {text}".into()),
+ ..Default::default()
+ };
+ assert!(reg
+ .register_from_descriptor("test-model", &descriptor)
+ .unwrap());
+ let loaded_id = reg.get("test-model").unwrap().tokenizer_id().to_string();
+
+ // Same tokenizer hash + new templates: must replace, not skip.
+ descriptor.tokenizer_id = Some(loaded_id);
+ descriptor.default_query_template = Some("v2-query: {text}".into());
+ // Re-registration returns `false` (entry already existed for
+ // this model id) but the stored templates must reflect v2.
+ let _ = reg
+ .register_from_descriptor("test-model", &descriptor)
+ .unwrap();
+ let entry = reg.get("test-model").unwrap();
+ assert_eq!(entry.default_query_template(), Some("v2-query: {text}"));
+ assert_eq!(entry.default_doc_template(), Some("v1-doc: {text}"));
+ }
+
+ #[test]
+ fn register_from_descriptor_errors_on_missing_file() {
+ let reg = TokenizerRegistry::empty();
+ let descriptor = ModelDescriptor {
+ tokenizer_path: Some("/definitely/not/a/tokenizer.json".into()),
+ ..Default::default()
+ };
+ let err = reg
+ .register_from_descriptor("test-model", &descriptor)
+ .unwrap_err();
+ assert!(err.contains("not found"), "got {err:?}");
+ assert!(reg.is_empty());
+ }
+}
diff --git a/packages/sie_server_sidecar/src/work_types.rs b/packages/sie_server_sidecar/src/work_types.rs
new file mode 100644
index 000000000..44e2fc3d8
--- /dev/null
+++ b/packages/sie_server_sidecar/src/work_types.rs
@@ -0,0 +1,207 @@
+//! NATS wire types — these MUST stay in lockstep with
+//! `packages/sie_gateway/src/queue/publisher.rs` (the publisher). All
+//! fields use `#[serde(default)]` so a forward-compatible producer can
+//! add fields without breaking us.
+//!
+//! Wire format is msgpack **named** (`rmp_serde::to_vec_named` / decoded
+//! from a msgpack map into the named struct).
+
+use serde::{Deserialize, Serialize};
+
+/// Work item pulled from JetStream. Must stay wire-compatible with the
+/// gateway publisher.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WorkItem {
+ pub work_item_id: String,
+ pub request_id: String,
+ pub item_index: u32,
+ pub total_items: u32,
+ pub operation: String,
+ pub model_id: String,
+ #[serde(default)]
+ pub profile_id: String,
+ /// Mirror of `WorkItem.engine` from the gateway publisher. The
+ /// gateway started populating this in the engine-routing follow-up
+ /// (today only `pytorch` is in use); older gateway builds omit it
+ /// and we decode them as the empty string. Workers can use it for
+ /// an optional sanity check (e.g. WARN if the dispatched engine
+ /// doesn't match the worker's configured backend) — for the
+ /// pre-engine fleet behaviour is unchanged.
+ #[serde(default)]
+ pub engine: String,
+ pub pool_name: String,
+ pub machine_profile: String,
+ #[serde(default)]
+ pub item: Option<serde_json::Value>,
+ #[serde(default)]
+ pub payload_ref: Option<String>,
+ #[serde(default)]
+ pub output_types: Option<Vec<String>>,
+ #[serde(default)]
+ pub instruction: Option<String>,
+ #[serde(default)]
+ pub is_query: bool,
+ #[serde(default)]
+ pub options: Option<serde_json::Value>,
+ #[serde(default)]
+ pub query_item: Option<serde_json::Value>,
+ #[serde(default)]
+ pub query_payload_ref: Option<String>,
+ #[serde(default)]
+ pub score_items: Option<Vec<serde_json::Value>>,
+ #[serde(default)]
+ pub labels: Option<Vec<String>>,
+ #[serde(default)]
+ pub output_schema: Option<serde_json::Value>,
+ #[serde(default)]
+ pub generate: Option<serde_json::Value>,
+ #[serde(default)]
+ pub routing_key: Option<String>,
+ #[serde(default)]
+ pub prompt_cache_key: Option<String>,
+ #[serde(default)]
+ pub bundle_config_hash: String,
+ #[serde(default)]
+ pub router_id: String,
+ pub reply_subject: String,
+ #[serde(default)]
+ pub traceparent: Option<String>,
+ #[serde(default)]
+ pub tracestate: Option<String>,
+ #[serde(default)]
+ pub timestamp: f64,
+}
+
+/// Per-item result published back to the gateway's inbox.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WorkResult {
+ #[serde(default)]
+ pub work_item_id: String,
+ pub request_id: String,
+ #[serde(default)]
+ pub item_index: u32,
+ #[serde(default)]
+ pub success: bool,
+ #[serde(default, with = "serde_bytes")]
+ pub result_msgpack: Vec<u8>,
+ #[serde(default)]
+ pub error: Option<String>,
+ #[serde(default)]
+ pub error_code: Option<String>,
+ #[serde(default)]
+ pub inference_ms: Option<f64>,
+ #[serde(default)]
+ pub queue_ms: Option<f64>,
+ #[serde(default)]
+ pub processing_ms: Option<f64>,
+ #[serde(default)]
+ pub worker_id: Option<String>,
+ #[serde(default)]
+ pub tokenization_ms: Option<f64>,
+ #[serde(default)]
+ pub postprocessing_ms: Option<f64>,
+ #[serde(default)]
+ pub payload_fetch_ms: Option<f64>,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn sample_work_item() -> WorkItem {
+ WorkItem {
+ work_item_id: "req-1.0".into(),
+ request_id: "req-1".into(),
+ item_index: 0,
+ total_items: 1,
+ operation: "encode".into(),
+ model_id: "BAAI/bge-m3".into(),
+ profile_id: String::new(),
+ engine: String::new(),
+ pool_name: "l4".into(),
+ machine_profile: "l4-spot".into(),
+ item: Some(serde_json::json!({"text": "hello"})),
+ 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: "abc".into(),
+ router_id: "r1".into(),
+ reply_subject: "_INBOX.r1.req-1".into(),
+ traceparent: None,
+ tracestate: None,
+ timestamp: 1_700_000_000.0,
+ }
+ }
+
+ #[test]
+ fn work_item_msgpack_named_roundtrip() {
+ let item = sample_work_item();
+ let bytes = rmp_serde::to_vec_named(&item).unwrap();
+ let back: WorkItem = rmp_serde::from_slice(&bytes).unwrap();
+ assert_eq!(back.request_id, "req-1");
+ assert_eq!(back.item_index, 0);
+ assert_eq!(back.total_items, 1);
+ assert_eq!(back.operation, "encode");
+ assert_eq!(back.model_id, "BAAI/bge-m3");
+ assert_eq!(back.output_types, Some(vec!["dense".to_string()]));
+ assert_eq!(back.item, Some(serde_json::json!({"text": "hello"})));
+ }
+
+ #[test]
+ fn work_item_forward_compatible_extra_field_ignored() {
+ // Producer adds a new field we don't know about — we must still decode.
+ let mut map = serde_json::to_value(sample_work_item()).unwrap();
+ map["unknown_future_field"] = serde_json::json!(42);
+ let bytes = rmp_serde::to_vec_named(&map).unwrap();
+ let back: WorkItem = rmp_serde::from_slice(&bytes).unwrap();
+ assert_eq!(back.request_id, "req-1");
+ }
+
+ #[test]
+ fn work_item_with_payload_ref_has_no_item() {
+ let mut item = sample_work_item();
+ item.item = None;
+ item.payload_ref = Some("req-1_0.bin".into());
+ let bytes = rmp_serde::to_vec_named(&item).unwrap();
+ let back: WorkItem = rmp_serde::from_slice(&bytes).unwrap();
+ assert!(back.item.is_none());
+ assert_eq!(back.payload_ref, Some("req-1_0.bin".into()));
+ }
+
+ #[test]
+ fn work_result_roundtrip_named() {
+ let result = WorkResult {
+ work_item_id: "req-1.2".into(),
+ request_id: "req-1".into(),
+ item_index: 2,
+ success: true,
+ result_msgpack: vec![0x81, 0xa5, b'h', b'e', b'l', b'l', b'o', 0x05],
+ error: None,
+ error_code: None,
+ inference_ms: Some(12.5),
+ queue_ms: None,
+ processing_ms: Some(14.0),
+ worker_id: Some("w-1".into()),
+ tokenization_ms: None,
+ postprocessing_ms: None,
+ payload_fetch_ms: None,
+ };
+ let bytes = rmp_serde::to_vec_named(&result).unwrap();
+ let back: WorkResult = rmp_serde::from_slice(&bytes).unwrap();
+ assert!(back.success);
+ assert_eq!(back.request_id, "req-1");
+ assert_eq!(back.item_index, 2);
+ assert_eq!(back.result_msgpack.len(), 8);
+ assert_eq!(back.inference_ms, Some(12.5));
+ }
+}
diff --git a/packages/sie_server_sidecar/tests/byte_identity.rs b/packages/sie_server_sidecar/tests/byte_identity.rs
new file mode 100644
index 000000000..970b3e3fc
--- /dev/null
+++ b/packages/sie_server_sidecar/tests/byte_identity.rs
@@ -0,0 +1,173 @@
+//! Rust ↔ Python AutoTokenizer byte-identity harness.
+//!
+//! The goal of this test is to prove that
+//! [`sie_server_sidecar::tokenize::tokenize_no_pad`] produces byte-for-byte
+//! identical `input_ids`, `attention_mask`, and `token_type_ids` to
+//! Python's `transformers.AutoTokenizer(..., padding=False,
+//! truncation=True, max_length=N)` for a given real-world tokenizer
+//! (in practice: `Alibaba-NLP/gte-multilingual-base`).
+//!
+//! Running cost and offline constraints mean we do **not** ship the
+//! real tokenizer weights in this repo. Instead the test is driven
+//! by a fixture JSON file generated by the companion helper script
+//! `packages/sie_server/scripts/generate_tokenize_fixture.py`, which
+//! uses the real `transformers` library to produce ground-truth
+//! token ids for a curated list of test cases.
+//!
+//! Usage:
+//!
+//! ```bash
+//! # one-off: generate the fixture against the real HF tokenizer
+//! uv run --with transformers --with huggingface_hub \
+//! packages/sie_server/scripts/generate_tokenize_fixture.py \
+//! --model Alibaba-NLP/gte-multilingual-base \
+//! --max-seq-len 512 \
+//! --out /tmp/gte_fixture.json
+//!
+//! # run the parity check
+//! SIE_BYTE_IDENTITY_FIXTURE=/tmp/gte_fixture.json \
+//! cargo test --test byte_identity -- --nocapture
+//! ```
+//!
+//! When `SIE_BYTE_IDENTITY_FIXTURE` is unset (the CI default) the
+//! test is skipped with an informative log line so `cargo test`
+//! stays green on developer machines that don't have the model
+//! cached.
+
+use std::path::PathBuf;
+
+use serde::Deserialize;
+use sie_server_sidecar::tokenize::{load_no_pad_tokenizer, tokenize_no_pad};
+
+#[derive(Debug, Deserialize)]
+struct Fixture {
+ /// Human-readable identifier, e.g. "Alibaba-NLP/gte-multilingual-base".
+ /// Not used by the test logic; purely for diagnostics.
+ #[serde(default)]
+ model_id: String,
+ /// Absolute path to the `tokenizer.json` file used to produce
+ /// the expected ids. The Rust side loads the same file.
+ tokenizer_path: String,
+ max_seq_len: usize,
+ cases: Vec<Case>,
+}
+
+#[derive(Debug, Deserialize)]
+struct Case {
+ text: String,
+ /// Token ids produced by `transformers.AutoTokenizer(...,
+ /// padding=False, truncation=True, max_length=N)`.
+ input_ids: Vec<u32>,
+ /// Attention mask as returned by the Python tokenizer. For the
+ /// `padding=False` path this is always all-ones of length
+ /// `input_ids.len()`, but we compare it verbatim anyway so a
+ /// future change (e.g. bucket padding) would fail loudly.
+ attention_mask: Vec<u32>,
+ /// `token_type_ids` as returned by the Python tokenizer. Some
+ /// tokenizers (e.g. XLM-R / gte-multilingual-base) don't emit
+ /// these, and the Python `transformers` helper omits the field;
+ /// the fixture generator represents that as an empty list.
+ #[serde(default)]
+ token_type_ids: Vec<u32>,
+}
+
+fn load_fixture() -> Option<Fixture> {
+ let path = std::env::var("SIE_BYTE_IDENTITY_FIXTURE").ok()?;
+ let bytes = std::fs::read(&path)
+ .unwrap_or_else(|e| panic!("SIE_BYTE_IDENTITY_FIXTURE={path} not readable: {e}"));
+ let fixture: Fixture = serde_json::from_slice(&bytes).unwrap_or_else(|e| {
+ panic!("SIE_BYTE_IDENTITY_FIXTURE={path} is not valid fixture JSON: {e}")
+ });
+ Some(fixture)
+}
+
+#[test]
+fn rust_tokenize_matches_python_autotokenizer_byte_for_byte() {
+ let Some(fixture) = load_fixture() else {
+ eprintln!(
+ "skipping byte-identity test: set SIE_BYTE_IDENTITY_FIXTURE=/path/to/fixture.json \
+ (see tests/byte_identity.rs for how to generate one)"
+ );
+ return;
+ };
+
+ let tok_path = PathBuf::from(&fixture.tokenizer_path);
+ assert!(
+ tok_path.exists(),
+ "fixture's tokenizer_path does not exist on disk: {}",
+ tok_path.display()
+ );
+
+ let tokenizer = load_no_pad_tokenizer(&tok_path, fixture.max_seq_len)
+ .expect("failed to load tokenizer.json on the Rust side");
+
+ // Tokenise each case individually. We deliberately do NOT batch
+ // them through one `encode_batch` call: the fixture generator
+ // calls the Python tokenizer per-text as well, and we want to
+ // preserve that semantics (no cross-sequence pair encoding).
+ let mut mismatches: Vec<String> = Vec::new();
+
+ for (i, case) in fixture.cases.iter().enumerate() {
+ let got = tokenize_no_pad(&tokenizer, &[&case.text])
+ .expect("tokenize_no_pad should not fail on well-formed input");
+ assert_eq!(
+ got.len(),
+ 1,
+ "expected exactly one encoded sequence per call"
+ );
+
+ let got_ids = &got.input_ids[0];
+ let got_mask = &got.attention_mask[0];
+ let got_types = &got.token_type_ids[0];
+
+ if *got_ids != case.input_ids {
+ mismatches.push(format!(
+ "case #{i} input_ids mismatch\n text = {:?}\n python = {:?}\n rust = {:?}",
+ case.text, case.input_ids, got_ids
+ ));
+ continue;
+ }
+
+ if *got_mask != case.attention_mask {
+ mismatches.push(format!(
+ "case #{i} attention_mask mismatch\n text = {:?}\n python = {:?}\n rust = {:?}",
+ case.text, case.attention_mask, got_mask
+ ));
+ continue;
+ }
+
+ // token_type_ids: some tokenizers (XLM-R family) don't emit
+ // segment ids. The fixture encodes "not emitted" as an empty
+ // list; in that case Rust's vector of zeros must also be all
+ // zero (length match against input_ids is already implied by
+ // the tokenizers crate contract).
+ if case.token_type_ids.is_empty() {
+ if got_types.iter().any(|&x| x != 0) {
+ mismatches.push(format!(
+ "case #{i} token_type_ids: python emitted none but rust has non-zero segment ids\n text = {:?}\n rust = {:?}",
+ case.text, got_types
+ ));
+ }
+ } else if *got_types != case.token_type_ids {
+ mismatches.push(format!(
+ "case #{i} token_type_ids mismatch\n text = {:?}\n python = {:?}\n rust = {:?}",
+ case.text, case.token_type_ids, got_types
+ ));
+ }
+ }
+
+ assert!(
+ mismatches.is_empty(),
+ "{} / {} case(s) differ from Python AutoTokenizer (model={}):\n\n{}",
+ mismatches.len(),
+ fixture.cases.len(),
+ fixture.model_id,
+ mismatches.join("\n\n")
+ );
+
+ eprintln!(
+ "byte-identity: {} case(s) matched Python AutoTokenizer for {}",
+ fixture.cases.len(),
+ fixture.model_id
+ );
+}
diff --git a/packages/sie_server_sidecar/tests/integration_smoke.rs b/packages/sie_server_sidecar/tests/integration_smoke.rs
new file mode 100644
index 000000000..9ead74539
--- /dev/null
+++ b/packages/sie_server_sidecar/tests/integration_smoke.rs
@@ -0,0 +1,2503 @@
+//! End-to-end smoke test for the worker-sidecar.
+//!
+//! What this proves:
+//! * The Rust `sie-server-sidecar` binary compiles and starts.
+//! * It can reach a real NATS JetStream server and create the expected
+//! pool stream + durable pull consumer.
+//! * It can open the UDS to the Python `IpcServer` and exchange
+//! msgpack-framed RPCs (Ping, EnsureModelReady, ProcessEncodeBatch).
+//! * It can direct-dispatch generation work to `ProcessGenerate`, stream
+//! generation events back over IPC, publish the raw response, and ACK.
+//! * It publishes a `WorkResult` to the reply subject whose shape matches
+//! what `sie_gateway` expects.
+//!
+//! What it does **not** prove:
+//! * Real inference. The Python side runs a stub executor
+//! (`sie_server._ipc_test_harness`) that returns a canned
+//! `result_msgpack` without loading any model.
+//! * Anything about the gateway publisher / collector.
+//! * Production configuration of S3, metrics scraping, etc.
+//!
+//! External deps required: `nats-server` on `$PATH` and `uv` (for the
+//! Python harness). If either is missing the test is skipped so clean
+//! dev machines / CI without these tools still `cargo test` green.
+
+use std::net::TcpStream;
+use std::path::PathBuf;
+use std::process::Stdio;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, OnceLock};
+use std::time::{Duration, Instant};
+
+use futures_util::StreamExt;
+use sie_server_sidecar::subject::normalize_model_id;
+use sie_server_sidecar::work_types::{WorkItem, WorkResult};
+use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
+use tokio::net::TcpListener;
+use tokio::process::{Child, Command};
+use tokio::sync::{OwnedSemaphorePermit, Semaphore};
+use tokio::time::{sleep, timeout};
+
+static SMOKE_TEST_SEMAPHORE: OnceLock<Arc<Semaphore>> = OnceLock::new();
+
+async fn smoke_test_guard() -> OwnedSemaphorePermit {
+ SMOKE_TEST_SEMAPHORE
+ .get_or_init(|| Arc::new(Semaphore::new(1)))
+ .clone()
+ .acquire_owned()
+ .await
+ .expect("smoke test semaphore is open")
+}
+
+// ---------------------------------------------------------------------------
+// Skip helpers — keep the test happy on bare-bones dev machines
+// ---------------------------------------------------------------------------
+
+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 {
+ let mut missing = vec![];
+ if which("nats-server").is_none() {
+ missing.push("nats-server");
+ }
+ if which("mise").is_none() && which("uv").is_none() {
+ missing.push("mise/uv");
+ }
+ if !missing.is_empty() {
+ eprintln!(
+ "integration_smoke: skipping — missing tools on $PATH: {}",
+ missing.join(", ")
+ );
+ return true;
+ }
+ false
+}
+
+// ---------------------------------------------------------------------------
+// NATS harness
+// ---------------------------------------------------------------------------
+
+fn find_free_tcp_port() -> u16 {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
+ listener.local_addr().unwrap().port()
+}
+
+struct NatsHarness {
+ child: Child,
+ url: String,
+ port: u16,
+}
+
+impl NatsHarness {
+ async fn start() -> Self {
+ let port = find_free_tcp_port();
+ let store_dir = tempfile::tempdir().expect("jetstream dir");
+ let child = Command::new("nats-server")
+ .arg("-p")
+ .arg(port.to_string())
+ .arg("-js")
+ .arg("-sd")
+ .arg(store_dir.path())
+ .arg("-m")
+ .arg("0")
+ .stdout(Stdio::null())
+ .stderr(Stdio::null())
+ .kill_on_drop(true)
+ .spawn()
+ .expect("spawn nats-server");
+
+ // Keep the temp dir alive for the server's lifetime.
+ std::mem::forget(store_dir);
+
+ let url = format!("nats://127.0.0.1:{port}");
+ wait_for_tcp(port, Duration::from_secs(10))
+ .await
+ .expect("nats-server ready");
+
+ Self { child, url, port }
+ }
+}
+
+async fn wait_for_tcp(port: u16, budget: Duration) -> Result<(), String> {
+ let deadline = Instant::now() + budget;
+ while Instant::now() < deadline {
+ if TcpStream::connect(("127.0.0.1", port)).is_ok() {
+ return Ok(());
+ }
+ sleep(Duration::from_millis(50)).await;
+ }
+ Err(format!("timeout waiting for 127.0.0.1:{port}"))
+}
+
+/// Raw HTTP/1.1 GET /metrics against the worker's Prometheus endpoint.
+/// A hand-rolled client avoids pulling reqwest into dev-deps for this
+/// single assertion.
+fn scrape_metrics(port: u16) -> std::io::Result<String> {
+ use std::io::{Read, Write};
+ let mut sock = TcpStream::connect(("127.0.0.1", port))?;
+ sock.set_read_timeout(Some(Duration::from_secs(5)))?;
+ sock.set_write_timeout(Some(Duration::from_secs(5)))?;
+ sock.write_all(b"GET /metrics HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")?;
+ let mut raw = String::new();
+ sock.read_to_string(&mut raw)?;
+ // Strip HTTP headers — body starts after the first blank line.
+ match raw.find("\r\n\r\n") {
+ Some(idx) => Ok(raw[idx + 4..].to_string()),
+ None => Ok(raw),
+ }
+}
+
+impl Drop for NatsHarness {
+ fn drop(&mut self) {
+ let _ = self.child.start_kill();
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Gateway pool-status harness
+// ---------------------------------------------------------------------------
+
+struct GatewayPoolHarness {
+ url: String,
+ assigned: Arc<AtomicBool>,
+ handle: tokio::task::JoinHandle<()>,
+}
+
+impl GatewayPoolHarness {
+ async fn start(
+ pool: &'static str,
+ worker_id: &'static str,
+ machine_profile: &'static str,
+ ) -> Self {
+ let listener = TcpListener::bind(("127.0.0.1", 0))
+ .await
+ .expect("bind fake gateway");
+ let addr = listener.local_addr().expect("fake gateway local addr");
+ let assigned = Arc::new(AtomicBool::new(false));
+ let assigned_for_task = Arc::clone(&assigned);
+ let handle = tokio::spawn(async move {
+ loop {
+ let Ok((mut socket, _)) = listener.accept().await else {
+ return;
+ };
+ let assigned = Arc::clone(&assigned_for_task);
+ tokio::spawn(async move {
+ let mut buf = vec![0u8; 2048];
+ let Ok(n) = socket.read(&mut buf).await else {
+ return;
+ };
+ let request = String::from_utf8_lossy(&buf[..n]);
+ let expected_path = format!("/v1/pools/{pool}");
+ let ok_path = request.lines().next().is_some_and(|line| {
+ line.starts_with("GET ") && line.contains(&expected_path)
+ });
+ let (status, body) = if ok_path {
+ let assigned_workers = if assigned.load(Ordering::Acquire) {
+ format!(
+ r#"[{{"name":"{worker_id}","url":"http://{worker_id}","gpu":"{machine_profile}"}}]"#
+ )
+ } else {
+ "[]".to_string()
+ };
+ (
+ "200 OK",
+ format!(
+ r#"{{"spec":{{"gpu_caps":{{"{machine_profile}":1}}}},"status":{{"state":"active","assigned_workers":{assigned_workers}}}}}"#
+ ),
+ )
+ } else {
+ ("404 Not Found", "{}".to_string())
+ };
+ let response = format!(
+ "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = socket.write_all(response.as_bytes()).await;
+ });
+ }
+ });
+
+ Self {
+ url: format!("http://{addr}"),
+ assigned,
+ handle,
+ }
+ }
+
+ fn set_assigned(&self, value: bool) {
+ self.assigned.store(value, Ordering::Release);
+ }
+}
+
+impl Drop for GatewayPoolHarness {
+ fn drop(&mut self) {
+ self.handle.abort();
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Python IPC harness
+// ---------------------------------------------------------------------------
+
+struct PythonHarness {
+ child: Child,
+ socket_path: PathBuf,
+}
+
+impl PythonHarness {
+ async fn start(socket_path: PathBuf) -> Self {
+ Self::start_with_extra_args(socket_path, 0, Vec::new()).await
+ }
+
+ /// Like [`Self::start`] but injects a fixed `per_request_delay_ms`
+ /// into every `process_*_batch` RPC on the Python side. Tests use
+ /// this to make concurrent in-flight RPCs observable on the
+ /// Prometheus `sie_worker_ipc_pool_inflight` gauge.
+ async fn start_with_delay_ms(socket_path: PathBuf, per_request_delay_ms: u64) -> Self {
+ Self::start_with_extra_args(socket_path, per_request_delay_ms, Vec::new()).await
+ }
+
+ async fn start_with_descriptor(
+ socket_path: PathBuf,
+ tokenizer_path: &std::path::Path,
+ max_seq_len: u32,
+ ) -> Self {
+ Self::start_with_extra_args(
+ socket_path,
+ 0,
+ vec![
+ "--tokenizer-path".to_string(),
+ tokenizer_path.display().to_string(),
+ "--max-seq-len".to_string(),
+ max_seq_len.to_string(),
+ ],
+ )
+ .await
+ }
+
+ async fn start_with_fake_generate(socket_path: PathBuf, model_id: &str) -> Self {
+ Self::start_with_extra_args(
+ socket_path,
+ 0,
+ vec!["--fake-generate-model".to_string(), model_id.to_string()],
+ )
+ .await
+ }
+
+ async fn start_with_fake_generate_after_capability_polls(
+ socket_path: PathBuf,
+ model_id: &str,
+ hidden_polls: u32,
+ ) -> Self {
+ Self::start_with_extra_args(
+ socket_path,
+ 0,
+ vec![
+ "--fake-generate-model".to_string(),
+ model_id.to_string(),
+ "--fake-generate-hidden-polls".to_string(),
+ hidden_polls.to_string(),
+ ],
+ )
+ .await
+ }
+
+ async fn start_with_extra_args(
+ socket_path: PathBuf,
+ per_request_delay_ms: u64,
+ extra_args: Vec<String>,
+ ) -> Self {
+ let (program, base_args) = 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()])
+ };
+
+ let workspace = workspace_root();
+ let delay_str = per_request_delay_ms.to_string();
+ let mut harness_args = vec![
+ "python".to_string(),
+ "-m".to_string(),
+ "sie_server._ipc_test_harness".to_string(),
+ "--socket".to_string(),
+ socket_path.to_str().unwrap().to_string(),
+ "--worker-id".to_string(),
+ "smoke-harness".to_string(),
+ "--log-level".to_string(),
+ "INFO".to_string(),
+ "--per-request-delay-ms".to_string(),
+ delay_str,
+ ];
+ harness_args.extend(extra_args);
+
+ let mut cmd = Command::new(program);
+ cmd.current_dir(&workspace)
+ .args(&base_args)
+ .args(&harness_args)
+ .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:?}");
+ }
+ }
+ }
+ }
+ if !ready {
+ panic!(
+ "python harness never printed HARNESS_READY within 45s (socket={})",
+ socket_path.display()
+ );
+ }
+
+ // Drain remaining stdout in background so the pipe doesn't fill up.
+ tokio::spawn(async move {
+ while let Ok(Some(line)) = reader.next_line().await {
+ eprintln!("[python-harness] {line}");
+ }
+ });
+
+ // Drain stderr too.
+ 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);
+ }
+}
+
+fn workspace_root() -> PathBuf {
+ // tests/ → package root; package root → workspace root is two levels up
+ // (packages/sie_server_sidecar).
+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("..")
+ .join("..")
+ .canonicalize()
+ .expect("canonicalize workspace root")
+}
+
+// ---------------------------------------------------------------------------
+// sie-server-sidecar binary harness
+// ---------------------------------------------------------------------------
+
+struct WorkerHarness {
+ child: Child,
+}
+
+impl WorkerHarness {
+ fn spawn(
+ nats_url: &str,
+ ipc_socket: &std::path::Path,
+ pool: &str,
+ bundle: &str,
+ metrics_port: u16,
+ payload_store_url: Option<&str>,
+ ) -> Self {
+ Self::spawn_with_env(
+ nats_url,
+ ipc_socket,
+ pool,
+ bundle,
+ metrics_port,
+ payload_store_url,
+ &[],
+ )
+ }
+
+ /// Same as [`Self::spawn`] but allows injecting additional env vars
+ /// (used e.g. to set `SIE_IPC_POOL_SIZE` for pool integration tests).
+ fn spawn_with_env(
+ nats_url: &str,
+ ipc_socket: &std::path::Path,
+ pool: &str,
+ bundle: &str,
+ metrics_port: u16,
+ payload_store_url: Option<&str>,
+ extra_env: &[(&str, &str)],
+ ) -> Self {
+ let exe = env!("CARGO_BIN_EXE_sie-server-sidecar");
+ let mut cmd = Command::new(exe);
+ cmd.env("SIE_NATS_URL", nats_url)
+ .env("SIE_POOL", pool)
+ .env("SIE_BUNDLE", bundle)
+ .env("SIE_IPC_SOCKET_PATH", ipc_socket)
+ .env("SIE_WORKER_METRICS_PORT", metrics_port.to_string())
+ .env("SIE_WORKER_ID", "smoke-worker")
+ .env("SIE_WORKER_PING_INTERVAL_MS", "500")
+ .env("RUST_LOG", "info,sie_server_sidecar=debug,async_nats=warn")
+ .stdout(Stdio::inherit())
+ .stderr(Stdio::inherit())
+ .kill_on_drop(true);
+ if let Some(url) = payload_store_url {
+ cmd.env("SIE_PAYLOAD_STORE_URL", url);
+ }
+ for (k, v) in extra_env {
+ cmd.env(k, v);
+ }
+ let child = cmd.spawn().expect("spawn sie-server-sidecar");
+ Self { child }
+ }
+}
+
+impl Drop for WorkerHarness {
+ fn drop(&mut self) {
+ let _ = self.child.start_kill();
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Short-socket helper — macOS AF_UNIX has a ~104-char limit on paths, and the
+// `$TMPDIR` on this platform is ~50 chars. We create a dir under /tmp (short)
+// instead.
+// ---------------------------------------------------------------------------
+
+struct ShortSocket {
+ path: PathBuf,
+ _dir: tempfile::TempDir,
+}
+
+impl ShortSocket {
+ fn new(name: &str) -> Self {
+ let dir = tempfile::Builder::new()
+ .prefix("siews-")
+ .tempdir_in("/tmp")
+ .expect("create short socket dir");
+ let path = dir.path().join(name);
+ Self { path, _dir: dir }
+ }
+}
+
+// ---------------------------------------------------------------------------
+// The test
+// ---------------------------------------------------------------------------
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn smoke_encode_request_round_trips_through_rust_worker() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ // 1. Start NATS.
+ let nats = NatsHarness::start().await;
+ eprintln!("nats: {} (port {})", nats.url, nats.port);
+
+ // 2. Start Python IPC harness.
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start(sock.path.clone()).await;
+ eprintln!("python harness: socket={}", python.socket_path.display());
+
+ // 3. Start the worker-sidecar.
+ let pool = "smoke";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn(&nats.url, &sock.path, pool, bundle, metrics_port, None);
+
+ // Wait until the worker metrics endpoint responds; this proves the binary
+ // started the NATS, IPC, and metrics stack.
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+
+ // Let the worker create the consumer before publishing. Without this the
+ // publish could arrive before the stream exists.
+ sleep(Duration::from_millis(500)).await;
+
+ // Connect our own NATS client for publish/subscribe.
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+
+ let reply_subject = format!("_INBOX.smoke.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+
+ // 6. Publish a synthetic encode WorkItem on the pool subject.
+ let model_id = "BAAI/bge-m3";
+ let normalized = "BAAI__bge-m3";
+ let subject = format!("sie.work.{}.{}", normalized, pool);
+ let request_id = "smoke-req-1";
+
+ // Stamp `timestamp` at `now - 0.25s` so the worker sees a realistic
+ // queue latency (Python computes `(time.time() - wi.timestamp) * 1000`).
+ let now_s = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64();
+ let work_item = WorkItem {
+ work_item_id: format!("{request_id}.0"),
+ request_id: request_id.into(),
+ item_index: 0,
+ total_items: 1,
+ operation: "encode".into(),
+ model_id: model_id.into(),
+ profile_id: String::new(),
+ engine: String::new(),
+ pool_name: pool.into(),
+ machine_profile: "cpu".into(),
+ item: Some(serde_json::json!({"text": "hello rust worker"})),
+ 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: "smoke-gw".into(),
+ reply_subject: reply_subject.clone(),
+ traceparent: None,
+ tracestate: None,
+ timestamp: now_s - 0.25,
+ };
+ let payload = rmp_serde::to_vec_named(&work_item).expect("encode WorkItem");
+
+ // JetStream publish so the stream actually captures the message.
+ let js = async_nats::jetstream::new(client.clone());
+ let (stream, sequence) = publish_jetstream_with_retry(&js, &subject, payload).await;
+ eprintln!("published WorkItem, stream={} seq={}", stream, sequence);
+
+ // 7. Wait for the reply.
+ let reply = timeout(Duration::from_secs(30), sub.next())
+ .await
+ .expect("timed out waiting for WorkResult")
+ .expect("reply stream closed");
+
+ let result: WorkResult = rmp_serde::from_slice(&reply.payload).expect("decode WorkResult");
+ eprintln!("got WorkResult: {result:?}");
+
+ assert!(
+ result.success,
+ "expected success, got error={:?}",
+ result.error
+ );
+ assert_eq!(result.request_id, request_id);
+ assert_eq!(result.work_item_id, format!("{request_id}.0"));
+ assert_eq!(result.item_index, 0);
+ assert!(!result.result_msgpack.is_empty(), "result_msgpack is empty");
+
+ // Decode the canned payload from the stub executor.
+ let canned: serde_json::Value =
+ rmp_serde::from_slice(&result.result_msgpack).expect("decode canned");
+ assert_eq!(canned["smoke"], "ok");
+ assert_eq!(canned["source"], "ipc_test_harness");
+
+ // worker_id must be set by publisher::build_work_result.
+ assert_eq!(result.worker_id.as_deref(), Some("smoke-worker"));
+
+ // Parity #1: Rust-computed timing fields must be populated on the
+ // success/ack path.
+ //
+ // - `queue_ms` comes from `(now - WorkItem.timestamp) * 1000`; we
+ // stamp `timestamp = now() - 0.25s` so we expect ~250ms + scheduling.
+ // - `processing_ms` is set to 0.0 to match Python's placeholder.
+ // - `payload_fetch_ms` is omitted because the WorkItem has an inline
+ // `item` (no payload_ref resolution).
+ let queue_ms = result.queue_ms.expect("queue_ms should be populated");
+ assert!(
+ (100.0..5_000.0).contains(&queue_ms),
+ "queue_ms out of expected range: {queue_ms}",
+ );
+ assert_eq!(
+ result.processing_ms,
+ Some(0.0),
+ "processing_ms should match Python placeholder",
+ );
+ assert!(
+ result.payload_fetch_ms.is_none(),
+ "payload_fetch_ms should be None for inline items, got {:?}",
+ result.payload_fetch_ms,
+ );
+
+ // Parity #2: the worker must expose Prometheus metrics that mirror
+ // Python's `sie_pull_loop_*` surface, so existing dashboards keep
+ // working. We just confirm the names show up after a successful
+ // encode cycle — exact counts live in the lib-side unit tests.
+ let body = scrape_metrics(metrics_port).expect("scrape /metrics");
+ for expected in [
+ "sie_pull_loop_items_fetched",
+ "sie_pull_loop_batch_process_seconds",
+ "sie_worker_messages_received_total",
+ "sie_worker_messages_acked_total",
+ ] {
+ assert!(
+ body.contains(expected),
+ "/metrics body missing expected metric {expected}:\n{body}"
+ );
+ }
+
+ // Drop everything in reverse order (workers/python/nats) via Drop impls.
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ // Keep sock alive just a tick so the drain has a moment.
+ let _ = sock;
+
+ // Brief courtesy wait so kill-on-drop children get reaped before the
+ // test harness returns — avoids noisy zombie warnings.
+ sleep(Duration::from_millis(200)).await;
+
+ // Silence unused warning on Arc in case the compiler complains.
+ let _ = Arc::new(());
+}
+
+/// End-to-end smoke test for generation direct-dispatch through the
+/// sidecar. The Python harness exposes one fake generation model and
+/// answers `ProcessGenerate` with the same event sequence a real
+/// StreamingProcessor would use: progress ACK, raw publish, final ACK.
+///
+/// This is intentionally below the full Tilt/SGLang layer. It proves
+/// the sidecar-only contract that endpoint tests cannot isolate:
+/// worker-specific stream creation, direct generation subject routing,
+/// streaming IPC frames, raw NATS publish, and JetStream settlement.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn smoke_generate_direct_dispatch_round_trips_through_rust_worker() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ let nats = NatsHarness::start().await;
+ eprintln!("nats: {} (port {})", nats.url, nats.port);
+
+ let model_id = "Qwen/Qwen3-0.6B";
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start_with_fake_generate(sock.path.clone(), model_id).await;
+ eprintln!("python harness: socket={}", python.socket_path.display());
+
+ let pool = "smoke-gen";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn(&nats.url, &sock.path, pool, bundle, metrics_port, None);
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+ sleep(Duration::from_millis(500)).await;
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let reply_subject = format!("_INBOX.smoke-gen.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+
+ let request_id = "smoke-generate-1";
+ let subject = format!(
+ "sie.work.{}.{}.{}",
+ normalize_model_id(model_id),
+ pool,
+ normalize_model_id("smoke-worker"),
+ );
+ let now_s = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64();
+ let work_item = WorkItem {
+ work_item_id: format!("{request_id}.0"),
+ request_id: request_id.into(),
+ item_index: 0,
+ total_items: 1,
+ operation: "generate".into(),
+ model_id: model_id.into(),
+ profile_id: String::new(),
+ engine: String::new(),
+ pool_name: pool.into(),
+ machine_profile: "cpu".into(),
+ item: None,
+ payload_ref: None,
+ output_types: None,
+ instruction: None,
+ is_query: false,
+ options: None,
+ query_item: None,
+ query_payload_ref: None,
+ score_items: None,
+ labels: None,
+ output_schema: None,
+ generate: Some(serde_json::json!({
+ "prompt": "hello",
+ "max_new_tokens": 4,
+ "temperature": 0.0,
+ "top_p": 1.0,
+ })),
+ routing_key: None,
+ prompt_cache_key: None,
+ bundle_config_hash: String::new(),
+ router_id: "smoke-gw".into(),
+ reply_subject: reply_subject.clone(),
+ traceparent: None,
+ tracestate: None,
+ timestamp: now_s - 0.25,
+ };
+ let payload = rmp_serde::to_vec_named(&work_item).expect("encode generate WorkItem");
+ let js = async_nats::jetstream::new(client.clone());
+ let (stream, sequence) = publish_jetstream_with_retry(&js, &subject, payload).await;
+ eprintln!(
+ "published generate WorkItem, stream={} seq={}",
+ stream, sequence
+ );
+
+ let reply = timeout(Duration::from_secs(30), sub.next())
+ .await
+ .expect("timed out waiting for raw generate reply")
+ .expect("reply stream closed");
+ let body: serde_json::Value =
+ rmp_serde::from_slice(&reply.payload).expect("decode raw generate payload");
+ eprintln!("got raw generate payload: {body}");
+
+ assert_eq!(body["smoke"], "generate");
+ assert_eq!(body["source"], "ipc_test_harness");
+ assert_eq!(body["model_id"], model_id);
+ assert_eq!(body["request_id"], request_id);
+ assert_eq!(body["work_item_id"], format!("{request_id}.0"));
+
+ let mut acked = 0.0;
+ let deadline = Instant::now() + Duration::from_secs(3);
+ while Instant::now() < deadline {
+ let metrics = scrape_metrics(metrics_port).expect("scrape /metrics");
+ acked = scrape_scalar(&metrics, "sie_worker_messages_acked_total").unwrap_or(0.0);
+ if acked >= 1.0 {
+ break;
+ }
+ sleep(Duration::from_millis(100)).await;
+ }
+ assert!(
+ acked >= 1.0,
+ "generate ProcessGenerate ACK event did not settle the JetStream message",
+ );
+
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ sleep(Duration::from_millis(200)).await;
+}
+
+/// Generation direct-dispatch must also come up after a live config change.
+/// The harness hides its generation capability from the startup
+/// WorkerCapabilities probe, then exposes it on the next probe. This exercises
+/// the sidecar's capability reconciler without needing a full sie-config
+/// process in the smoke test.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn smoke_generation_direct_dispatch_activates_after_capability_reconcile() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ let nats = NatsHarness::start().await;
+ eprintln!("nats: {} (port {})", nats.url, nats.port);
+
+ let model_id = "Qwen/Qwen3-0.6B";
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start_with_fake_generate_after_capability_polls(
+ sock.path.clone(),
+ model_id,
+ 1,
+ )
+ .await;
+ eprintln!("python harness: socket={}", python.socket_path.display());
+
+ let pool = "smoke-gen-hot-add";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn_with_env(
+ &nats.url,
+ &sock.path,
+ pool,
+ bundle,
+ metrics_port,
+ None,
+ &[("SIE_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS", "1000")],
+ );
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+
+ // The binary clamps the reconcile interval to 5s so production cannot
+ // accidentally create a tight IPC polling loop.
+ sleep(Duration::from_millis(6_500)).await;
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let reply_subject = format!("_INBOX.smoke-gen-hot-add.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+
+ let request_id = "smoke-generate-hot-add-1";
+ let subject = format!(
+ "sie.work.{}.{}.{}",
+ normalize_model_id(model_id),
+ pool,
+ normalize_model_id("smoke-worker"),
+ );
+ let now_s = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64();
+ let work_item = WorkItem {
+ work_item_id: format!("{request_id}.0"),
+ request_id: request_id.into(),
+ item_index: 0,
+ total_items: 1,
+ operation: "generate".into(),
+ model_id: model_id.into(),
+ profile_id: String::new(),
+ engine: String::new(),
+ pool_name: pool.into(),
+ machine_profile: "cpu".into(),
+ item: None,
+ payload_ref: None,
+ output_types: None,
+ instruction: None,
+ is_query: false,
+ options: None,
+ query_item: None,
+ query_payload_ref: None,
+ score_items: None,
+ labels: None,
+ output_schema: None,
+ generate: Some(serde_json::json!({
+ "prompt": "hello after config",
+ "max_new_tokens": 4,
+ "temperature": 0.0,
+ "top_p": 1.0,
+ })),
+ routing_key: None,
+ prompt_cache_key: None,
+ bundle_config_hash: String::new(),
+ router_id: "smoke-gw".into(),
+ reply_subject: reply_subject.clone(),
+ traceparent: None,
+ tracestate: None,
+ timestamp: now_s,
+ };
+ let payload = rmp_serde::to_vec_named(&work_item).expect("encode generate WorkItem");
+ let js = async_nats::jetstream::new(client.clone());
+ let (stream, sequence) = publish_jetstream_with_retry(&js, &subject, payload).await;
+ eprintln!(
+ "published hot-add generate WorkItem, stream={} seq={}",
+ stream, sequence
+ );
+
+ let reply = timeout(Duration::from_secs(30), sub.next())
+ .await
+ .expect("timed out waiting for raw generate reply")
+ .expect("reply stream closed");
+ let body: serde_json::Value =
+ rmp_serde::from_slice(&reply.payload).expect("decode raw generate payload");
+ assert_eq!(body["smoke"], "generate");
+ assert_eq!(body["model_id"], model_id);
+ assert_eq!(body["request_id"], request_id);
+
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ sleep(Duration::from_millis(200)).await;
+}
+
+/// End-to-end smoke test for the payload-store offload path.
+///
+/// The gateway normally offloads large item payloads to a
+/// `LocalPayloadStore` (which writes to a shared volume) and stamps the
+/// resulting absolute path on the WorkItem as `payload_ref` with `item =
+/// None`. The worker is expected to pull the bytes back, decode them
+/// from msgpack, and only then dispatch the batch to Python.
+///
+/// What this proves on top of the inline-item test:
+/// * The worker-sidecar honors `SIE_PAYLOAD_STORE_URL`.
+/// * `LocalPayloadStore::get` resolves the absolute path and returns
+/// the bytes the gateway wrote.
+/// * The dispatcher feeds the decoded item into `ProcessEncodeBatch`
+/// and gets a successful outcome back.
+/// * `payload_fetch_ms` is populated (> 0) on the success path.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn smoke_payload_ref_request_round_trips_through_rust_worker() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ // 1. NATS.
+ let nats = NatsHarness::start().await;
+ eprintln!("nats: {} (port {})", nats.url, nats.port);
+
+ // 2. Python IPC harness.
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start(sock.path.clone()).await;
+ eprintln!("python harness: socket={}", python.socket_path.display());
+
+ // 3. A shared "payload store" directory — stand-in for the gateway's
+ // LocalPayloadStore base_dir. We use /tmp for short paths.
+ let payload_dir = tempfile::Builder::new()
+ .prefix("siews-payloads-")
+ .tempdir_in("/tmp")
+ .expect("create payload dir");
+ let payload_store_url = payload_dir
+ .path()
+ .to_str()
+ .expect("payload dir utf-8")
+ .to_string();
+
+ // Mimic the gateway's offload protocol: msgpack-encode the item and
+ // persist it as `{request_id}_{item_index}.bin`. The `payload_ref`
+ // is the absolute path, which is what `LocalPayloadStore::put`
+ // returns in production.
+ let request_id = "smoke-payload-ref-1";
+ let item_key = format!("{request_id}_0.bin");
+ let item_path = payload_dir.path().join(&item_key);
+ let item_body = serde_json::json!({"text": "hello from payload store"});
+ let item_bytes = rmp_serde::to_vec_named(&item_body).expect("msgpack encode item");
+ tokio::fs::write(&item_path, &item_bytes)
+ .await
+ .expect("write payload");
+ let payload_ref = item_path.to_str().expect("payload path utf-8").to_string();
+ eprintln!("wrote payload: {payload_ref} ({} bytes)", item_bytes.len());
+
+ // 4. worker-sidecar wired to the payload store.
+ let pool = "smoke";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn(
+ &nats.url,
+ &sock.path,
+ pool,
+ bundle,
+ metrics_port,
+ Some(&payload_store_url),
+ );
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+ sleep(Duration::from_millis(500)).await;
+
+ // 5. Publish a WorkItem with item=None and payload_ref set.
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let reply_subject = format!("_INBOX.smoke.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+
+ let model_id = "BAAI/bge-m3";
+ let normalized = "BAAI__bge-m3";
+ let subject = format!("sie.work.{}.{}", normalized, pool);
+ let now_s = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64();
+ let work_item = WorkItem {
+ work_item_id: format!("{request_id}.0"),
+ request_id: request_id.into(),
+ item_index: 0,
+ total_items: 1,
+ operation: "encode".into(),
+ model_id: model_id.into(),
+ profile_id: String::new(),
+ engine: String::new(),
+ pool_name: pool.into(),
+ machine_profile: "cpu".into(),
+ item: None,
+ payload_ref: Some(payload_ref.clone()),
+ 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: "smoke-gw".into(),
+ reply_subject: reply_subject.clone(),
+ traceparent: None,
+ tracestate: None,
+ timestamp: now_s,
+ };
+ let payload = rmp_serde::to_vec_named(&work_item).expect("encode WorkItem");
+
+ let js = async_nats::jetstream::new(client.clone());
+ let (stream, sequence) = publish_jetstream_with_retry(&js, &subject, payload).await;
+ eprintln!(
+ "published payload-ref WorkItem, stream={} seq={}",
+ stream, sequence
+ );
+
+ // 6. Reply must arrive, decode, and reflect a successful publish_and_ack.
+ let reply = timeout(Duration::from_secs(30), sub.next())
+ .await
+ .expect("timed out waiting for WorkResult")
+ .expect("reply stream closed");
+ let result: WorkResult = rmp_serde::from_slice(&reply.payload).expect("decode WorkResult");
+ eprintln!("got WorkResult: {result:?}");
+
+ assert!(
+ result.success,
+ "expected success, got error={:?}",
+ result.error
+ );
+ assert_eq!(result.request_id, request_id);
+ assert_eq!(result.work_item_id, format!("{request_id}.0"));
+ assert_eq!(result.item_index, 0);
+
+ // The canned stub payload must still round-trip.
+ let canned: serde_json::Value =
+ rmp_serde::from_slice(&result.result_msgpack).expect("decode canned");
+ assert_eq!(canned["smoke"], "ok");
+ assert_eq!(canned["source"], "ipc_test_harness");
+
+ // Parity: payload_fetch_ms is populated for the offloaded path.
+ // The read is from local tmpfs so the duration is tiny — just
+ // assert it exists and is non-negative. A hard upper bound would
+ // flake under CI load.
+ let fetch_ms = result
+ .payload_fetch_ms
+ .expect("payload_fetch_ms should be populated when item is offloaded");
+ assert!(
+ (0.0..5_000.0).contains(&fetch_ms),
+ "payload_fetch_ms out of expected range: {fetch_ms}"
+ );
+
+ // Drop in reverse startup order.
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ let _ = payload_dir;
+
+ sleep(Duration::from_millis(200)).await;
+}
+
+// ---------------------------------------------------------------------------
+// Concurrent / stress scenarios for the pull loop
+//
+// These exist because we regressed from "N concurrent requests all succeed
+// in ~tens of ms" to "1 succeeds in ~30 ms, N-1 hit 30 s gateway timeout" by
+// recreating the async-nats pull stream every iteration with a 1-20 ms
+// expiry. Under concurrency any message the server had routed to the
+// dropped stream became `ack_pending` until `ack_wait=30s` elapsed.
+//
+// The floor the tests defend is:
+//
+// * a **burst** of N concurrent publishes resolves end-to-end in a wall
+// clock comfortably below `ack_wait` (30 s), with **no redelivery
+// count > 1** on any message (i.e. we never hit the stream-drop path);
+// * the `sie_worker_nats_redelivery_total` counter stays at zero.
+//
+// Both assertions were false before the long-lived-stream fix and are
+// true after it. This is effectively the cheapest stress test that would
+// have caught the production regression without the whole helm stack.
+// ---------------------------------------------------------------------------
+
+/// Scrape `sie_worker_nats_redelivery_total` from the worker's /metrics
+/// body. The counter is present unconditionally (emitted even at 0) by
+/// [`MetricsRegistry::new`], so a missing line is a test failure rather
+/// than "not enough load yet".
+fn redelivery_total(metrics_body: &str) -> u64 {
+ for line in metrics_body.lines() {
+ let line = line.trim();
+ if line.starts_with('#') {
+ continue;
+ }
+ if let Some(rest) = line.strip_prefix("sie_worker_nats_redelivery_total") {
+ let rest = rest.trim_start();
+ let val = rest.split_whitespace().next().unwrap_or("0");
+ return val.parse::<f64>().unwrap_or(0.0) as u64;
+ }
+ }
+ panic!("sie_worker_nats_redelivery_total missing from /metrics body:\n{metrics_body}");
+}
+
+async fn publish_jetstream_with_retry(
+ js: &async_nats::jetstream::Context,
+ subject: &str,
+ payload: Vec<u8>,
+) -> (String, u64) {
+ let mut last_error = String::new();
+ for attempt in 0..50 {
+ let ack = js
+ .publish(subject.to_string(), payload.clone().into())
+ .await
+ .expect("jetstream publish");
+ match ack.await {
+ Ok(ack) => return (ack.stream, ack.sequence),
+ Err(e) => {
+ last_error = format!("{e:?}");
+ if !last_error.contains("StreamNotFound") {
+ panic!("await publish ack: {last_error}");
+ }
+ eprintln!(
+ "publish ack stream not ready yet (attempt={attempt}, subject={subject})"
+ );
+ sleep(Duration::from_millis(100)).await;
+ }
+ }
+ }
+ panic!("stream was never ready for {subject}: {last_error}");
+}
+
+async fn publish_work_item(
+ js: &async_nats::jetstream::Context,
+ subject: &str,
+ request_id: &str,
+ model_id: &str,
+ normalized: &str,
+ pool: &str,
+ reply_subject: &str,
+) {
+ let _ = normalized; // subject is pre-built by caller
+ let now_s = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64();
+ let work_item = WorkItem {
+ work_item_id: format!("{request_id}.0"),
+ request_id: request_id.into(),
+ item_index: 0,
+ total_items: 1,
+ operation: "encode".into(),
+ model_id: model_id.into(),
+ profile_id: String::new(),
+ engine: String::new(),
+ pool_name: pool.into(),
+ machine_profile: "cpu".into(),
+ item: Some(serde_json::json!({"text": format!("concurrent-{request_id}")})),
+ 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: "stress-gw".into(),
+ reply_subject: reply_subject.into(),
+ traceparent: None,
+ tracestate: None,
+ timestamp: now_s,
+ };
+ let payload = rmp_serde::to_vec_named(&work_item).expect("encode WorkItem");
+ let _ = publish_jetstream_with_retry(js, subject, payload).await;
+}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn pool_admission_pauses_until_gateway_assigns_worker() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ let pool = "gated";
+ let worker_id = "smoke-worker";
+ let gateway = GatewayPoolHarness::start(pool, worker_id, pool).await;
+
+ let nats = NatsHarness::start().await;
+ let sock = ShortSocket::new("ipc.sock");
+ let _python = PythonHarness::start(sock.path.clone()).await;
+
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn_with_env(
+ &nats.url,
+ &sock.path,
+ pool,
+ bundle,
+ metrics_port,
+ None,
+ &[
+ ("SIE_GATEWAY_URL", gateway.url.as_str()),
+ ("SIE_POOL_ADMISSION_CHECK_INTERVAL_S", "1"),
+ ("SIE_POOL_ADMISSION_PAUSE_S", "0.1"),
+ ("SIE_POOL_ADMISSION_STALE_AFTER_S", "0"),
+ ],
+ );
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+ sleep(Duration::from_millis(500)).await;
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let js = async_nats::jetstream::new(client.clone());
+
+ let reply_subject = format!("_INBOX.gated.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+
+ let model_id = "BAAI/bge-m3";
+ let normalized = "BAAI__bge-m3";
+ let subject = format!("sie.work.{}.{}", normalized, pool);
+ publish_work_item(
+ &js,
+ &subject,
+ "gated-req-1",
+ model_id,
+ normalized,
+ pool,
+ &reply_subject,
+ )
+ .await;
+
+ match timeout(Duration::from_millis(700), sub.next()).await {
+ Err(_) => {}
+ Ok(Some(msg)) => panic!(
+ "worker pulled while not assigned; payload bytes={}",
+ msg.payload.len()
+ ),
+ Ok(None) => panic!("reply subscription closed while worker was not assigned"),
+ }
+
+ gateway.set_assigned(true);
+ let reply = timeout(Duration::from_secs(5), sub.next())
+ .await
+ .expect("timed out waiting for WorkResult after assignment")
+ .expect("reply stream closed after assignment");
+ let result: WorkResult = rmp_serde::from_slice(&reply.payload).expect("decode WorkResult");
+ assert!(
+ result.success,
+ "expected success after assignment, got error={:?}",
+ result.error
+ );
+ assert_eq!(result.request_id, "gated-req-1");
+}
+
+/// Fire N concurrent publishes on distinct reply subjects and assert that
+/// **every one** gets a reply within a budget well short of `ack_wait`.
+///
+/// Regression guard: the pre-fix code reliably failed this at N >= 2 with
+/// 1 reply arriving fast and the rest timing out after 30 s. Anything
+/// near that pattern re-appearing should trip this test.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn stress_concurrent_requests_do_not_stall_on_ack_wait() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ const CONCURRENCY: usize = 16;
+ // Budget must be comfortably below `ack_wait=30s`. The pre-fix code
+ // took ~30.002 s to service the N-1 stragglers; 10 s gives us a 20 s
+ // margin while being forgiving of CI noise.
+ const REPLY_BUDGET: Duration = Duration::from_secs(10);
+
+ let nats = NatsHarness::start().await;
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start(sock.path.clone()).await;
+
+ let pool = "stress";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn(&nats.url, &sock.path, pool, bundle, metrics_port, None);
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+ sleep(Duration::from_millis(500)).await;
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let js = async_nats::jetstream::new(client.clone());
+
+ let model_id = "BAAI/bge-m3";
+ let normalized = "BAAI__bge-m3";
+ let subject = format!("sie.work.{}.{}", normalized, pool);
+
+ // One subscription per request on a unique inbox; collect all N in a
+ // concurrent `JoinSet` so the publishes are temporally clustered.
+ let mut join = tokio::task::JoinSet::new();
+ let start = Instant::now();
+ for i in 0..CONCURRENCY {
+ let reply_subject = format!("_INBOX.stress.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+ let subject = subject.clone();
+ let model_id = model_id.to_string();
+ let normalized = normalized.to_string();
+ let pool = pool.to_string();
+ let js = js.clone();
+ join.spawn(async move {
+ let request_id = format!("stress-req-{i}");
+ publish_work_item(
+ &js,
+ &subject,
+ &request_id,
+ &model_id,
+ &normalized,
+ &pool,
+ &reply_subject,
+ )
+ .await;
+ let msg = timeout(REPLY_BUDGET, sub.next())
+ .await
+ .unwrap_or_else(|_| {
+ panic!(
+ "request {request_id} did not receive a WorkResult within {:?} \
+ (pre-fix regression would stall here at ~30s)",
+ REPLY_BUDGET,
+ )
+ })
+ .expect("reply stream closed");
+ let result: WorkResult =
+ rmp_serde::from_slice(&msg.payload).expect("decode WorkResult");
+ assert!(
+ result.success,
+ "request {} got success=false: {:?}",
+ request_id, result.error,
+ );
+ assert_eq!(result.request_id, request_id);
+ result
+ });
+ }
+
+ let mut seen = 0usize;
+ while let Some(res) = join.join_next().await {
+ res.expect("stress task panicked");
+ seen += 1;
+ }
+ assert_eq!(seen, CONCURRENCY, "missing replies");
+
+ let elapsed = start.elapsed();
+ // Global wall-clock guard. Even with 1 ms per request serially this
+ // should finish fast; 10 s is the ack_wait safety rail.
+ assert!(
+ elapsed < Duration::from_secs(15),
+ "concurrent burst took {:?} (pre-fix would be ~30s)",
+ elapsed,
+ );
+
+ // Metrics check: redelivery_total must stay at 0 because we never let
+ // messages sit past ack_wait.
+ let metrics = scrape_metrics(metrics_port).expect("scrape /metrics");
+ let redelivered = redelivery_total(&metrics);
+ assert_eq!(
+ redelivered, 0,
+ "sie_worker_nats_redelivery_total = {redelivered}, expected 0 \
+ (a non-zero value means the pull loop is letting messages sit \
+ past ack_wait, which is the regression we're guarding against)"
+ );
+
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ sleep(Duration::from_millis(200)).await;
+}
+
+/// Sustained-load variant: many publishes spread over a few seconds (so
+/// the adaptive quantum controller actually warms up). Guards against a
+/// regression where the quantum grows without bound and steady-state
+/// throughput collapses.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn stress_sustained_load_finishes_within_budget() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ const TOTAL: usize = 200;
+ const INTER_PUBLISH_MS: u64 = 10; // 100 req/s offered load
+ const BUDGET: Duration = Duration::from_secs(15);
+
+ let nats = NatsHarness::start().await;
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start(sock.path.clone()).await;
+
+ let pool = "stress-sustained";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn(&nats.url, &sock.path, pool, bundle, metrics_port, None);
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+ sleep(Duration::from_millis(500)).await;
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let js = async_nats::jetstream::new(client.clone());
+
+ let model_id = "BAAI/bge-m3";
+ let normalized = "BAAI__bge-m3";
+ let subject = format!("sie.work.{}.{}", normalized, pool);
+
+ let mut join = tokio::task::JoinSet::new();
+ let start = Instant::now();
+ for i in 0..TOTAL {
+ let reply_subject = format!("_INBOX.stress-sus.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+ let subject = subject.clone();
+ let model_id = model_id.to_string();
+ let normalized = normalized.to_string();
+ let pool = pool.to_string();
+ let js = js.clone();
+ join.spawn(async move {
+ let request_id = format!("sustained-{i}");
+ publish_work_item(
+ &js,
+ &subject,
+ &request_id,
+ &model_id,
+ &normalized,
+ &pool,
+ &reply_subject,
+ )
+ .await;
+ let msg = timeout(Duration::from_secs(10), sub.next())
+ .await
+ .unwrap_or_else(|_| panic!("sustained request {request_id} timed out"))
+ .expect("reply stream closed");
+ let result: WorkResult =
+ rmp_serde::from_slice(&msg.payload).expect("decode WorkResult");
+ assert!(
+ result.success,
+ "request {request_id} failed: {:?}",
+ result.error
+ );
+ });
+ sleep(Duration::from_millis(INTER_PUBLISH_MS)).await;
+ }
+
+ let mut seen = 0usize;
+ while let Some(res) = join.join_next().await {
+ res.expect("sustained task panicked");
+ seen += 1;
+ }
+ assert_eq!(seen, TOTAL, "missing replies under sustained load");
+
+ let elapsed = start.elapsed();
+ assert!(
+ elapsed < BUDGET,
+ "sustained load of {TOTAL} req took {:?}, budget {:?}",
+ elapsed,
+ BUDGET,
+ );
+
+ let metrics = scrape_metrics(metrics_port).expect("scrape /metrics");
+ let redelivered = redelivery_total(&metrics);
+ // Under sustained load with a healthy worker we expect zero
+ // redeliveries; allow 1% headroom for scheduler noise.
+ assert!(
+ redelivered <= (TOTAL / 100) as u64,
+ "sie_worker_nats_redelivery_total = {redelivered}, over 1% of offered load",
+ );
+
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ sleep(Duration::from_millis(200)).await;
+}
+
+/// Scrape a single-series Prometheus gauge / counter value by metric name.
+/// Returns `None` if the line isn't present (e.g. label-variant unseen
+/// yet), in which case callers typically treat it as "zero observed".
+fn scrape_scalar(metrics_body: &str, name: &str) -> Option<f64> {
+ for line in metrics_body.lines() {
+ let line = line.trim();
+ if line.starts_with('#') || line.is_empty() {
+ continue;
+ }
+ let rest = match line.strip_prefix(name) {
+ Some(r) => r,
+ None => continue,
+ };
+ // Word-boundary guard — `foo` must not match `foo_extended`.
+ match rest.chars().next() {
+ Some(c) if c.is_whitespace() || c == '{' => {}
+ _ => continue,
+ }
+ let val = rest.split_whitespace().next_back().unwrap_or("nan");
+ return val.parse::<f64>().ok();
+ }
+ None
+}
+
+/// Scrape the total sample count of a Prometheus Histogram. Used to
+/// confirm that the pool-acquire path was actually exercised.
+fn histogram_count(metrics_body: &str, name: &str) -> u64 {
+ let needle = format!("{name}_count");
+ scrape_scalar(metrics_body, &needle).unwrap_or(0.0) as u64
+}
+
+/// Pool integration test. Drives a burst of requests across **multiple
+/// distinct model IDs** with Python artificially slowed to 150ms/RPC,
+/// and asserts the IPC pool is what enables concurrency between model
+/// groups.
+///
+/// Design notes:
+/// - The Rust dispatcher intentionally **batches requests targeting
+/// the same model into a single IPC call** (that's the whole point
+/// of the adaptive batcher). A naive "fire 8 requests to the same
+/// model" test would therefore observe `inflight=1` even with a
+/// 4-slot pool, because there's only one ProcessEncodeBatch RPC to
+/// issue for that group. The test used to fail for exactly that
+/// reason.
+/// - To actually exercise the pool we need ≥ 2 **distinct model
+/// groups** running concurrently through the dispatcher. With N
+/// models, the dispatcher's `ensure_model_ready` + `process_encode_batch`
+/// for each group become independent RPCs that the pool should run
+/// in parallel.
+/// - Python-side delay (via `--per-request-delay-ms`) stretches each
+/// RPC long enough for Prometheus scrapes to catch a non-zero
+/// `sie_worker_ipc_pool_inflight` gauge mid-burst.
+///
+/// Assertions:
+/// 1. `sie_worker_ipc_pool_size` matches the configured pool size.
+/// 2. All requests succeed.
+/// 3. The peak observed `sie_worker_ipc_pool_inflight` during the
+/// burst is `>= 2` — the regression guard for the single-mutex era.
+/// 4. End-to-end latency is under a budget that only holds if the
+/// model groups ran in parallel (vs. serialized).
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn pool_enables_concurrent_in_flight_ipc() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ const POOL_SIZE: usize = 4;
+ // Four distinct models → four independent dispatcher model groups
+ // → at least four parallel IPC calls if the pool works.
+ const MODELS: &[(&str, &str)] = &[
+ ("BAAI/bge-m3", "BAAI__bge-m3"),
+ ("BAAI/bge-small-en", "BAAI__bge-small-en"),
+ (
+ "sentence-transformers/all-MiniLM-L6-v2",
+ "sentence-transformers__all-MiniLM-L6-v2",
+ ),
+ ("intfloat/e5-base-v2", "intfloat__e5-base-v2"),
+ ];
+ const PYTHON_DELAY_MS: u64 = 150;
+ // Serialized floor: MODELS.len() groups × (ensure_model_ready +
+ // process_encode_batch) × PYTHON_DELAY_MS ≈ 4 × 2 × 150ms = 1.2s
+ // minimum if everything ran on one socket.
+ // Parallel floor with 4-slot pool: ~2 × 150ms (ensure then process)
+ // for each group running in parallel + dispatcher/NATS overhead,
+ // comfortably under 1.5s in practice.
+ const BUDGET: Duration = Duration::from_millis(1500);
+
+ let nats = NatsHarness::start().await;
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start_with_delay_ms(sock.path.clone(), PYTHON_DELAY_MS).await;
+
+ let pool = "pool-integ";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let pool_size_str = POOL_SIZE.to_string();
+ let _worker = WorkerHarness::spawn_with_env(
+ &nats.url,
+ &sock.path,
+ pool,
+ bundle,
+ metrics_port,
+ None,
+ &[
+ ("SIE_IPC_POOL_SIZE", pool_size_str.as_str()),
+ ("SIE_MAX_CONCURRENT_BATCHES", pool_size_str.as_str()),
+ ],
+ );
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+ sleep(Duration::from_millis(500)).await;
+
+ let pre = scrape_metrics(metrics_port).expect("initial scrape");
+ let observed_size = scrape_scalar(&pre, "sie_worker_ipc_pool_size")
+ .expect("sie_worker_ipc_pool_size gauge missing");
+ assert_eq!(
+ observed_size as usize, POOL_SIZE,
+ "configured SIE_IPC_POOL_SIZE did not propagate to the pool metric"
+ );
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let js = async_nats::jetstream::new(client.clone());
+
+ // Poller: scrape the /metrics endpoint as fast as we reasonably
+ // can (10ms cadence) while the burst is in flight, tracking the
+ // peak inflight value seen.
+ use std::sync::atomic::{AtomicBool, AtomicI64, Ordering as AtomicOrdering};
+ let peak_inflight = Arc::new(AtomicI64::new(0));
+ let stop_poller = Arc::new(AtomicBool::new(false));
+ let peak_clone = Arc::clone(&peak_inflight);
+ let stop_clone = Arc::clone(&stop_poller);
+ let poller = tokio::spawn(async move {
+ while !stop_clone.load(AtomicOrdering::Relaxed) {
+ if let Ok(body) = scrape_metrics(metrics_port) {
+ if let Some(v) = scrape_scalar(&body, "sie_worker_ipc_pool_inflight") {
+ let v = v as i64;
+ let mut cur = peak_clone.load(AtomicOrdering::Relaxed);
+ while v > cur
+ && peak_clone
+ .compare_exchange(
+ cur,
+ v,
+ AtomicOrdering::Relaxed,
+ AtomicOrdering::Relaxed,
+ )
+ .is_err()
+ {
+ cur = peak_clone.load(AtomicOrdering::Relaxed);
+ }
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ });
+
+ // Fire 2 requests per model = 8 total requests across 4 groups.
+ let mut join = tokio::task::JoinSet::new();
+ let start = Instant::now();
+ for (idx, (model_id, normalized)) in MODELS.iter().enumerate() {
+ for rep in 0..2 {
+ let reply_subject = format!("_INBOX.pool.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+ let subject = format!("sie.work.{}.{}", normalized, pool);
+ let model_id = (*model_id).to_string();
+ let normalized = (*normalized).to_string();
+ let pool = pool.to_string();
+ let js = js.clone();
+ let request_id = format!("pool-req-{idx}-{rep}");
+ join.spawn(async move {
+ publish_work_item(
+ &js,
+ &subject,
+ &request_id,
+ &model_id,
+ &normalized,
+ &pool,
+ &reply_subject,
+ )
+ .await;
+ let msg = timeout(Duration::from_secs(10), sub.next())
+ .await
+ .unwrap_or_else(|_| panic!("pool request {request_id} timed out"))
+ .expect("reply stream closed");
+ let result: WorkResult =
+ rmp_serde::from_slice(&msg.payload).expect("decode WorkResult");
+ assert!(
+ result.success,
+ "request {request_id} failed: {:?}",
+ result.error
+ );
+ });
+ }
+ }
+ let total = MODELS.len() * 2;
+ let mut seen = 0usize;
+ while let Some(res) = join.join_next().await {
+ res.expect("pool task panicked");
+ seen += 1;
+ }
+ let elapsed = start.elapsed();
+ assert_eq!(seen, total);
+
+ stop_poller.store(true, AtomicOrdering::Relaxed);
+ let _ = poller.await;
+
+ // --- Assertion 1: peak inflight observed > 1.
+ let peak = peak_inflight.load(AtomicOrdering::Relaxed);
+ assert!(
+ peak >= 2,
+ "peak sie_worker_ipc_pool_inflight = {peak}; expected >= 2 with \
+ {} distinct model groups in flight. inflight=1 throughout means \
+ the pool regressed to single-connection serialization.",
+ MODELS.len(),
+ );
+
+ // --- Assertion 2: latency budget — only meetable with parallel IPC.
+ assert!(
+ elapsed < BUDGET,
+ "concurrent burst across {} model groups took {:?}; budget {:?}. \
+ Serialized (pool=1) would take ≥ {} × 2 × {}ms = {:?} in Python \
+ delay alone. A budget miss here means the IPC pool regressed.",
+ MODELS.len(),
+ elapsed,
+ BUDGET,
+ MODELS.len(),
+ PYTHON_DELAY_MS,
+ Duration::from_millis((MODELS.len() as u64) * 2 * PYTHON_DELAY_MS),
+ );
+
+ // --- Assertion 3: the acquire histogram recorded samples.
+ let post = scrape_metrics(metrics_port).expect("post scrape");
+ let acquire_count = histogram_count(&post, "sie_worker_ipc_pool_acquire_wait_seconds");
+ assert!(
+ acquire_count >= MODELS.len() as u64,
+ "sie_worker_ipc_pool_acquire_wait_seconds_count = {acquire_count}; \
+ expected >= {} (one per model group's process_encode_batch RPC)",
+ MODELS.len(),
+ );
+
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ sleep(Duration::from_millis(200)).await;
+}
+
+// ---------------------------------------------------------------------------
+// Rust-side prepared_tokens round-trip
+// ---------------------------------------------------------------------------
+
+/// End-to-end smoke test for the Rust-side `prepared_tokens` hand-off.
+///
+/// What this proves on top of the baseline encode test:
+/// * The Python `EnsureModelReady` descriptor is honored by the worker:
+/// the named model's `tokenizer.json` is loaded and registered.
+/// * For a plain-text encode request with no instruction/template and
+/// `is_query = false`, the dispatcher pre-tokenizes the text in Rust
+/// and attaches a `PreparedTokens` payload to the outgoing
+/// `ProcessEncodeBatch` IPC call.
+/// * The Python IPC stub (`_ipc_test_harness`) receives
+/// `prepared_tokens` on the `EncodeBatchItem`, and echoes back the
+/// tokenizer id, the first `input_ids` sequence, and the configured
+/// `max_seq_len` so we can assert on it here.
+///
+/// What it does **not** prove:
+/// * That the Python fast-path actually accepts the hand-off and skips
+/// its own tokenizer — that's covered in Python unit tests. The
+/// harness runs no real adapter, so we just verify the Rust side
+/// populated the wire field end-to-end.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn smoke_prepared_tokens_round_trip_through_rust_worker() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ // 1. Materialise a tiny WordLevel tokenizer on disk. The vocab is
+ // chosen so "hello world" tokenizes deterministically to [1, 2].
+ const TINY_TOKENIZER_JSON: &str = r#"{
+ "version": "1.0",
+ "truncation": null,
+ "padding": null,
+ "added_tokens": [],
+ "normalizer": null,
+ "pre_tokenizer": { "type": "Whitespace" },
+ "post_processor": null,
+ "decoder": null,
+ "model": {
+ "type": "WordLevel",
+ "vocab": { "[UNK]": 0, "hello": 1, "world": 2 },
+ "unk_token": "[UNK]"
+ }
+}"#;
+ let tok_dir = tempfile::Builder::new()
+ .prefix("siews-tok-")
+ .tempdir_in("/tmp")
+ .expect("tokenizer tempdir");
+ let tok_path = tok_dir.path().join("tokenizer.json");
+ std::fs::write(&tok_path, TINY_TOKENIZER_JSON).expect("write tokenizer.json");
+
+ // 2. NATS + Python IPC harness.
+ let nats = NatsHarness::start().await;
+ eprintln!("nats: {} (port {})", nats.url, nats.port);
+
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start_with_descriptor(sock.path.clone(), &tok_path, 64).await;
+ eprintln!("python harness: socket={}", python.socket_path.display());
+
+ // 3. Start the worker-sidecar. The Python harness returns a
+ // ModelDescriptor pointing at our tiny tokenizer. Pick a custom
+ // max_seq_len (64) so we can assert it round-trips through
+ // PreparedTokens.max_seq_len.
+ let model_id = "tiny-prepared-tokens";
+ let normalized = "tiny-prepared-tokens"; // no slash to normalize
+ let pool = "smoke-pt";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+
+ let _worker = WorkerHarness::spawn(&nats.url, &sock.path, pool, bundle, metrics_port, None);
+
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+ sleep(Duration::from_millis(500)).await;
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let reply_subject = format!("_INBOX.smoke-pt.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+
+ // 4. Publish a plain-text encode WorkItem that satisfies the
+ // Rust-tokenisation safety rules (text-only, no instruction,
+ // is_query = false) so the dispatcher actually pre-tokenizes.
+ let subject = format!("sie.work.{}.{}", normalized, pool);
+ let request_id = "smoke-pt-req-1";
+ let now_s = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64();
+ let work_item = WorkItem {
+ work_item_id: format!("{request_id}.0"),
+ request_id: request_id.into(),
+ item_index: 0,
+ total_items: 1,
+ operation: "encode".into(),
+ model_id: model_id.into(),
+ profile_id: String::new(),
+ engine: String::new(),
+ pool_name: pool.into(),
+ machine_profile: "cpu".into(),
+ item: Some(serde_json::json!({"text": "hello world"})),
+ 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: "smoke-gw".into(),
+ reply_subject: reply_subject.clone(),
+ traceparent: None,
+ tracestate: None,
+ timestamp: now_s - 0.25,
+ };
+ let payload = rmp_serde::to_vec_named(&work_item).expect("encode WorkItem");
+ let js = async_nats::jetstream::new(client.clone());
+ let _ = publish_jetstream_with_retry(&js, &subject, payload).await;
+
+ // 5. Collect the reply and decode the canned echo from the harness.
+ let reply = timeout(Duration::from_secs(30), sub.next())
+ .await
+ .expect("timed out waiting for WorkResult")
+ .expect("reply stream closed");
+ let result: WorkResult = rmp_serde::from_slice(&reply.payload).expect("decode WorkResult");
+ assert!(
+ result.success,
+ "expected success, got error={:?}",
+ result.error
+ );
+ assert_eq!(result.request_id, request_id);
+ assert!(!result.result_msgpack.is_empty(), "result_msgpack is empty");
+
+ let canned: serde_json::Value =
+ rmp_serde::from_slice(&result.result_msgpack).expect("decode canned");
+ eprintln!("canned echo: {canned}");
+
+ // 6. Assertions on the echoed prepared_tokens block — this is the
+ // evidence that the Rust dispatcher actually populated
+ // `prepared_tokens` on the IPC request and that the Python stub
+ // deserialised it back into an `EncodeBatchItem`.
+ let pt = canned
+ .get("prepared_tokens")
+ .expect("canned payload missing `prepared_tokens`");
+ assert_eq!(
+ pt.get("present").and_then(|v| v.as_bool()),
+ Some(true),
+ "Rust dispatcher did not attach prepared_tokens for a plain-text encode. \
+ Check ModelDescriptor ingestion or the safety gates in \
+ Dispatcher::maybe_prepare_encode_tokens. Full echo: {canned}",
+ );
+
+ let tokenizer_id = pt
+ .get("tokenizer_id")
+ .and_then(|v| v.as_str())
+ .expect("tokenizer_id should be a string when prepared_tokens is present");
+ assert_eq!(
+ tokenizer_id.len(),
+ 32,
+ "tokenizer_id should be a 32-char blake3 prefix, got {tokenizer_id:?}",
+ );
+ assert!(
+ tokenizer_id.chars().all(|c| c.is_ascii_hexdigit()),
+ "tokenizer_id should be hex-only, got {tokenizer_id:?}",
+ );
+
+ assert_eq!(
+ pt.get("max_seq_len").and_then(|v| v.as_u64()),
+ Some(64),
+ "max_seq_len did not round-trip from ModelDescriptor. echo: {canned}",
+ );
+
+ // "hello world" against the tiny vocab = [1, 2]. The WordLevel model
+ // has no special tokens / post-processor, so this is exact.
+ let ids = pt
+ .get("input_ids_first_seq")
+ .and_then(|v| v.as_array())
+ .expect("input_ids_first_seq should be a list");
+ let ids: Vec<u64> = ids
+ .iter()
+ .map(|v| v.as_u64().expect("input id is a non-negative int"))
+ .collect();
+ assert_eq!(
+ ids,
+ vec![1u64, 2u64],
+ "tokenized ids for `hello world` should be [1, 2] against the tiny \
+ vocab (hello=1, world=2). Got {ids:?} — tokenizer loading or \
+ tokenize_no_pad semantics regressed.",
+ );
+
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ let _ = tok_dir;
+ sleep(Duration::from_millis(200)).await;
+}
+
+// ---------------------------------------------------------------------------
+// Rust scheduler smoke tests.
+//
+// Since the scheduler is always-on now (no `SIE_RUST_SCHEDULER_MODELS`
+// gate), every request routes through batch formation → `RunBatch` IPC →
+// the Python stub's `process_*_batch` handler. The tests below cover the
+// surface the original encode smoke test doesn't exercise:
+//
+// * the score path (which forces `LoraKey::base` regardless of
+// `options["lora"]`),
+// * the extract path (ExtractBatchItem shape is distinct),
+// * concurrent-item coalescing into a single RunBatch (the whole
+// reason the scheduler exists).
+//
+// We also scrape `/metrics` to assert the dispatcher's
+// `sie_worker_scheduler_enqueued_items_total{op=..}` counter actually
+// increments — that's the direct evidence the request went through the
+// scheduler path, not the legacy `process_*_batch` fallback.
+// ---------------------------------------------------------------------------
+
+/// Scrape a Prometheus counter value by metric name + exact label suffix.
+/// Returns 0.0 when the series isn't present (useful for before/after
+/// deltas where the first scrape may show the counter uninitialised).
+fn scrape_counter(body: &str, metric: &str, label_suffix: &str) -> f64 {
+ for line in body.lines() {
+ let line = line.trim();
+ if line.starts_with('#') {
+ continue;
+ }
+ let Some(rest) = line.strip_prefix(metric) else {
+ continue;
+ };
+ if !rest.starts_with(label_suffix) {
+ continue;
+ }
+ // After `metric{..labels..}` there's a space then the value.
+ let after_labels = match rest.find('}') {
+ Some(i) => &rest[i + 1..],
+ None => rest,
+ };
+ let val = after_labels.split_whitespace().next().unwrap_or("0");
+ return val.parse::<f64>().unwrap_or(0.0);
+ }
+ 0.0
+}
+
+/// Publish a score WorkItem that carries an inline query + one score
+/// item (no payload_ref indirection). Mirrors `publish_work_item` but
+/// for the score shape.
+async fn publish_score_work_item(
+ js: &async_nats::jetstream::Context,
+ subject: &str,
+ request_id: &str,
+ model_id: &str,
+ pool: &str,
+ reply_subject: &str,
+) {
+ let now_s = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64();
+ let work_item = WorkItem {
+ work_item_id: format!("{request_id}.0"),
+ request_id: request_id.into(),
+ item_index: 0,
+ total_items: 1,
+ operation: "score".into(),
+ model_id: model_id.into(),
+ profile_id: String::new(),
+ engine: String::new(),
+ pool_name: pool.into(),
+ machine_profile: "cpu".into(),
+ item: None,
+ payload_ref: None,
+ output_types: None,
+ instruction: None,
+ is_query: false,
+ options: None,
+ query_item: Some(serde_json::json!({"text": "what is the capital of France?"})),
+ query_payload_ref: None,
+ score_items: Some(vec![serde_json::json!({"text": "Paris is the capital."})]),
+ labels: None,
+ output_schema: None,
+ generate: None,
+ routing_key: None,
+ prompt_cache_key: None,
+ bundle_config_hash: String::new(),
+ router_id: "scheduler-smoke-gw".into(),
+ reply_subject: reply_subject.into(),
+ traceparent: None,
+ tracestate: None,
+ timestamp: now_s,
+ };
+ let payload = rmp_serde::to_vec_named(&work_item).expect("encode score WorkItem");
+ let _ = publish_jetstream_with_retry(js, subject, payload).await;
+}
+
+/// Publish an extract WorkItem. Uses `output_schema` + `labels` so the
+/// ExtractBatchItem shape exercises more fields than the minimal path.
+async fn publish_extract_work_item(
+ js: &async_nats::jetstream::Context,
+ subject: &str,
+ request_id: &str,
+ model_id: &str,
+ pool: &str,
+ reply_subject: &str,
+) {
+ let now_s = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64();
+ let work_item = WorkItem {
+ work_item_id: format!("{request_id}.0"),
+ request_id: request_id.into(),
+ item_index: 0,
+ total_items: 1,
+ operation: "extract".into(),
+ model_id: model_id.into(),
+ profile_id: String::new(),
+ engine: String::new(),
+ pool_name: pool.into(),
+ machine_profile: "cpu".into(),
+ item: Some(serde_json::json!({"text": "Barack Obama was born in Hawaii."})),
+ payload_ref: None,
+ output_types: None,
+ instruction: None,
+ is_query: false,
+ options: None,
+ query_item: None,
+ query_payload_ref: None,
+ score_items: None,
+ labels: Some(vec!["PERSON".into(), "LOCATION".into()]),
+ output_schema: Some(serde_json::json!({"type": "entities"})),
+ generate: None,
+ routing_key: None,
+ prompt_cache_key: None,
+ bundle_config_hash: String::new(),
+ router_id: "scheduler-smoke-gw".into(),
+ reply_subject: reply_subject.into(),
+ traceparent: None,
+ tracestate: None,
+ timestamp: now_s,
+ };
+ let payload = rmp_serde::to_vec_named(&work_item).expect("encode extract WorkItem");
+ let _ = publish_jetstream_with_retry(js, subject, payload).await;
+}
+
+/// Score: publish a score WorkItem, expect a reply, and assert the
+/// `sie_worker_scheduler_enqueued_items_total{op="score"}` counter
+/// stepped from 0 → 1. That's direct evidence the request went
+/// through `Dispatcher::enqueue_score_into_scheduler` (not the legacy
+/// `handle_score` path) and that the drain loop shipped the batch
+/// over `RunBatch`.
+///
+/// Regression guard: if anyone rewires the dispatcher so score bypasses
+/// the scheduler (or silently falls back to `process_score_batch`), the
+/// scheduler metric stays at 0 and this test fails loudly.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn smoke_scheduler_routes_score_request_end_to_end() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ let nats = NatsHarness::start().await;
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start(sock.path.clone()).await;
+
+ let pool = "sched-score";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn(&nats.url, &sock.path, pool, bundle, metrics_port, None);
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+ sleep(Duration::from_millis(500)).await;
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let js = async_nats::jetstream::new(client.clone());
+
+ let model_id = "BAAI/bge-m3";
+ let normalized = "BAAI__bge-m3";
+ let subject = format!("sie.work.{}.{}", normalized, pool);
+
+ let reply_subject = format!("_INBOX.sched-score.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+
+ let request_id = "sched-score-1";
+ publish_score_work_item(&js, &subject, request_id, model_id, pool, &reply_subject).await;
+
+ let reply = timeout(Duration::from_secs(30), sub.next())
+ .await
+ .expect("timed out waiting for score WorkResult")
+ .expect("reply stream closed");
+ let result: WorkResult = rmp_serde::from_slice(&reply.payload).expect("decode WorkResult");
+ assert!(
+ result.success,
+ "score via scheduler returned error: {:?}",
+ result.error
+ );
+ assert_eq!(result.request_id, request_id);
+
+ // The scheduler counter is labelled `{model, op}`. The model label
+ // is the dispatcher's `model_label(model_id)` which for an
+ // unconfigured model collapses to the raw id.
+ let body = scrape_metrics(metrics_port).expect("scrape /metrics");
+ let enqueued = scrape_counter(
+ &body,
+ "sie_worker_scheduler_enqueued_items_total",
+ &format!("{{model=\"{model_id}\",operation=\"score\"}}"),
+ );
+ assert!(
+ enqueued >= 1.0,
+ "sie_worker_scheduler_enqueued_items_total for score must be >= 1 \
+ (actual: {enqueued}). A zero means score bypassed the Rust \
+ scheduler — check Dispatcher::enqueue_score_into_scheduler."
+ );
+
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ sleep(Duration::from_millis(200)).await;
+}
+
+/// Extract: same shape as the score test but for the extract path.
+/// Covers the third SchedulerItem variant and its ExtractBatchItem
+/// wire shape.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn smoke_scheduler_routes_extract_request_end_to_end() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ let nats = NatsHarness::start().await;
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start(sock.path.clone()).await;
+
+ let pool = "sched-extract";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn(&nats.url, &sock.path, pool, bundle, metrics_port, None);
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+ sleep(Duration::from_millis(500)).await;
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let js = async_nats::jetstream::new(client.clone());
+
+ let model_id = "BAAI/bge-m3";
+ let normalized = "BAAI__bge-m3";
+ let subject = format!("sie.work.{}.{}", normalized, pool);
+
+ let reply_subject = format!("_INBOX.sched-extract.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+
+ let request_id = "sched-extract-1";
+ publish_extract_work_item(&js, &subject, request_id, model_id, pool, &reply_subject).await;
+
+ let reply = timeout(Duration::from_secs(30), sub.next())
+ .await
+ .expect("timed out waiting for extract WorkResult")
+ .expect("reply stream closed");
+ let result: WorkResult = rmp_serde::from_slice(&reply.payload).expect("decode WorkResult");
+ assert!(
+ result.success,
+ "extract via scheduler returned error: {:?}",
+ result.error
+ );
+ assert_eq!(result.request_id, request_id);
+
+ let body = scrape_metrics(metrics_port).expect("scrape /metrics");
+ let enqueued = scrape_counter(
+ &body,
+ "sie_worker_scheduler_enqueued_items_total",
+ &format!("{{model=\"{model_id}\",operation=\"extract\"}}"),
+ );
+ assert!(
+ enqueued >= 1.0,
+ "sie_worker_scheduler_enqueued_items_total for extract must be >= 1 \
+ (actual: {enqueued}). A zero means extract bypassed the Rust \
+ scheduler — check Dispatcher::enqueue_extract_into_scheduler."
+ );
+
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ sleep(Duration::from_millis(200)).await;
+}
+
+/// Concurrent encodes: publish N items fast enough that several land in
+/// the scheduler's 15 ms coalesce window, then verify (a) every reply
+/// comes back successfully and (b) the scheduler counter records all
+/// N items. We can't cleanly assert "these were in a single RunBatch"
+/// from the outside without instrumenting Python, but the enqueue
+/// counter at least proves the items went through the scheduler and
+/// didn't fall through to the legacy per-op path.
+///
+/// Also scrapes `sie_pull_loop_batch_process_seconds{op="encode"}_count`
+/// — under the scheduler each drain-loop tick contributes one
+/// observation, so this stays > 0 after the test just like on the
+/// legacy path. Dashboards keyed off that histogram continue working.
+#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+async fn smoke_scheduler_coalesces_concurrent_encodes() {
+ if skip_unless_tools_available() {
+ return;
+ }
+ let _guard = smoke_test_guard().await;
+
+ const CONCURRENCY: usize = 8;
+ const REPLY_BUDGET: Duration = Duration::from_secs(15);
+
+ let nats = NatsHarness::start().await;
+ let sock = ShortSocket::new("ipc.sock");
+ let python = PythonHarness::start(sock.path.clone()).await;
+
+ let pool = "sched-burst";
+ let bundle = "default";
+ let metrics_port = find_free_tcp_port();
+ let _worker = WorkerHarness::spawn(&nats.url, &sock.path, pool, bundle, metrics_port, None);
+ wait_for_tcp(metrics_port, Duration::from_secs(30))
+ .await
+ .expect("worker metrics port");
+ sleep(Duration::from_millis(500)).await;
+
+ let client = async_nats::connect(&nats.url)
+ .await
+ .expect("client connect");
+ let js = async_nats::jetstream::new(client.clone());
+
+ let model_id = "BAAI/bge-m3";
+ let normalized = "BAAI__bge-m3";
+ let subject = format!("sie.work.{}.{}", normalized, pool);
+
+ let mut join = tokio::task::JoinSet::new();
+ for i in 0..CONCURRENCY {
+ let reply_subject = format!("_INBOX.sched-burst.{}", uuid::Uuid::new_v4());
+ let mut sub = client
+ .subscribe(reply_subject.clone())
+ .await
+ .expect("subscribe reply");
+ let subject = subject.clone();
+ let model_id = model_id.to_string();
+ let normalized = normalized.to_string();
+ let pool = pool.to_string();
+ let js = js.clone();
+ join.spawn(async move {
+ let request_id = format!("sched-burst-{i}");
+ publish_work_item(
+ &js,
+ &subject,
+ &request_id,
+ &model_id,
+ &normalized,
+ &pool,
+ &reply_subject,
+ )
+ .await;
+ let msg = timeout(REPLY_BUDGET, sub.next())
+ .await
+ .unwrap_or_else(|_| panic!("sched-burst {request_id} timed out"))
+ .expect("reply stream closed");
+ let result: WorkResult =
+ rmp_serde::from_slice(&msg.payload).expect("decode WorkResult");
+ assert!(
+ result.success,
+ "sched-burst {request_id} got success=false: {:?}",
+ result.error
+ );
+ });
+ }
+
+ let mut seen = 0usize;
+ while let Some(res) = join.join_next().await {
+ res.expect("sched-burst task panicked");
+ seen += 1;
+ }
+ assert_eq!(seen, CONCURRENCY, "missing replies");
+
+ // The enqueue counter must reflect every item we submitted. It's
+ // incremented inside `enqueue_encode_into_scheduler` at enqueue
+ // time (not after the drain completes), so this runs no race
+ // against the drain loop finishing.
+ let body = scrape_metrics(metrics_port).expect("scrape /metrics");
+ let enqueued = scrape_counter(
+ &body,
+ "sie_worker_scheduler_enqueued_items_total",
+ &format!("{{model=\"{model_id}\",operation=\"encode\"}}"),
+ );
+ assert!(
+ enqueued >= CONCURRENCY as f64,
+ "sie_worker_scheduler_enqueued_items_total for encode should be \
+ >= {CONCURRENCY} (actual: {enqueued}). Missing samples mean \
+ items bypassed the Rust scheduler path.",
+ );
+
+ // `batch_items` is a histogram; the `_count` series tracks the
+ // number of observations. Each flushed batch is one observation,
+ // so at minimum we need a single sample (possibly more if the
+ // items landed across multiple 15 ms coalesce windows). The
+ // corresponding `_sum` must then be ≥ CONCURRENCY since every
+ // item contributes one to the size sum.
+ //
+ // Label order matters: the `prometheus` crate emits labels in
+ // alphabetical order (lora < model < operation), not in the
+ // registration order. Dashboards that hard-code label order
+ // against the registration tuple break; our scrape assertions
+ // need to match the on-the-wire order exactly.
+ let batch_items_count = scrape_counter(
+ &body,
+ "sie_worker_scheduler_batch_items_count",
+ &format!("{{lora=\"base\",model=\"{model_id}\",operation=\"encode\"}}"),
+ );
+ assert!(
+ batch_items_count >= 1.0,
+ "sie_worker_scheduler_batch_items_count must be >= 1 \
+ (actual: {batch_items_count}). A zero means the drain \
+ loop never ran or the histogram isn't being observed.",
+ );
+ let batch_items_sum = scrape_counter(
+ &body,
+ "sie_worker_scheduler_batch_items_sum",
+ &format!("{{lora=\"base\",model=\"{model_id}\",operation=\"encode\"}}"),
+ );
+ assert!(
+ batch_items_sum >= CONCURRENCY as f64,
+ "sie_worker_scheduler_batch_items_sum should be >= {CONCURRENCY} \
+ (actual: {batch_items_sum}). Every submitted item contributes \
+ 1 to the histogram sum; smaller means items were dropped.",
+ );
+
+ // Live models_total gauge: after touching exactly one model, it
+ // should have incremented to at least 1. We don't assert
+ // equality because other scheduler tests running in the same
+ // harness do not share this worker (each test spawns its
+ // own), but we defensively use `>= 1` so the gauge isn't racy
+ // against any parallel test reuse.
+ let models_total = scrape_counter(&body, "sie_worker_scheduler_models_total", "");
+ assert!(
+ models_total >= 1.0,
+ "sie_worker_scheduler_models_total must be >= 1 (actual: {models_total}). \
+ The gauge should tick up on first-traffic scheduler creation.",
+ );
+
+ drop(_worker);
+ drop(python);
+ drop(nats);
+ let _ = sock;
+ sleep(Duration::from_millis(200)).await;
+}
diff --git a/packages/sie_server_sidecar/tests/readyz_http.rs b/packages/sie_server_sidecar/tests/readyz_http.rs
new file mode 100644
index 000000000..d46bb985d
--- /dev/null
+++ b/packages/sie_server_sidecar/tests/readyz_http.rs
@@ -0,0 +1,165 @@
+//! End-to-end HTTP coverage for the sidecar metrics server's probe routes.
+//!
+//! This test stands up only the metrics HTTP plane and shared readiness
+//! state. It does not require NATS or the Python IPC harness.
+
+use std::io::{Read, Write};
+use std::net::{TcpListener, TcpStream};
+use std::sync::Arc;
+use std::time::Duration;
+
+use sie_server_sidecar::metrics::{spawn_metrics_server, MetricsRegistry};
+use sie_server_sidecar::readiness::Readiness;
+use sie_server_sidecar::shutdown::Shutdown;
+
+fn pick_free_port() -> u16 {
+ let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
+ let port = listener.local_addr().unwrap().port();
+ drop(listener);
+ port
+}
+
+fn http_get(port: u16, path: &str) -> std::io::Result<(String, String)> {
+ let mut sock = TcpStream::connect(("127.0.0.1", port))?;
+ sock.set_read_timeout(Some(Duration::from_secs(5)))?;
+ sock.set_write_timeout(Some(Duration::from_secs(5)))?;
+ let request = format!("GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n");
+ sock.write_all(request.as_bytes())?;
+
+ let mut raw = String::new();
+ sock.read_to_string(&mut raw)?;
+ let status_line = raw.lines().next().unwrap_or("").to_owned();
+ let body = match raw.find("\r\n\r\n") {
+ Some(idx) => raw[idx + 4..].to_owned(),
+ None => String::new(),
+ };
+ Ok((status_line, body))
+}
+
+async fn start_server(readiness: Arc<Readiness>) -> u16 {
+ let port = pick_free_port();
+ let metrics = Arc::new(MetricsRegistry::new().unwrap());
+ let shutdown = Arc::new(Shutdown::new());
+ let _handle = spawn_metrics_server(port, metrics, readiness, shutdown).expect("spawn server");
+
+ let deadline = std::time::Instant::now() + Duration::from_secs(2);
+ while std::time::Instant::now() < deadline {
+ if tokio::net::TcpStream::connect(("127.0.0.1", port))
+ .await
+ .is_ok()
+ {
+ return port;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ panic!("metrics server did not bind on port {port} within budget");
+}
+
+async fn http_get_async(port: u16, path: &str) -> std::io::Result<(String, String)> {
+ let path = path.to_owned();
+ tokio::task::spawn_blocking(move || http_get(port, &path))
+ .await
+ .expect("blocking task did not panic")
+}
+
+#[tokio::test]
+async fn readyz_handshake_pending_returns_503() {
+ let readiness = Arc::new(Readiness::new(2_000, 3));
+ let port = start_server(Arc::clone(&readiness)).await;
+
+ let (status, body) = http_get_async(port, "/readyz").await.unwrap();
+ assert!(
+ status.starts_with("HTTP/1.1 503"),
+ "expected 503 status line, got {status:?}"
+ );
+ assert!(
+ body.contains("handshake pending"),
+ "body should mention handshake pending, got {body:?}"
+ );
+}
+
+#[tokio::test]
+async fn readyz_after_ping_returns_200() {
+ let readiness = Arc::new(Readiness::new(2_000, 3));
+ readiness.record_ping_success();
+ let port = start_server(Arc::clone(&readiness)).await;
+
+ let (status, body) = http_get_async(port, "/readyz").await.unwrap();
+ assert!(
+ status.starts_with("HTTP/1.1 200"),
+ "expected 200 status line, got {status:?}"
+ );
+ assert_eq!(body, "ok");
+}
+
+#[tokio::test]
+async fn readyz_after_drain_returns_503_draining() {
+ let readiness = Arc::new(Readiness::new(2_000, 3));
+ readiness.record_ping_success();
+ let port = start_server(Arc::clone(&readiness)).await;
+
+ let (status_before, _) = http_get_async(port, "/readyz").await.unwrap();
+ assert!(status_before.starts_with("HTTP/1.1 200"));
+
+ readiness.mark_draining();
+
+ let (status_after, body_after) = http_get_async(port, "/readyz").await.unwrap();
+ assert!(
+ status_after.starts_with("HTTP/1.1 503"),
+ "expected 503 after drain, got {status_after:?}"
+ );
+ assert!(
+ body_after.contains("draining"),
+ "body should mention draining, got {body_after:?}"
+ );
+}
+
+#[tokio::test]
+async fn readyz_after_stale_heartbeat_returns_503() {
+ let readiness = Arc::new(Readiness::new(50, 1));
+ readiness.record_ping_success();
+ let port = start_server(Arc::clone(&readiness)).await;
+
+ tokio::time::sleep(Duration::from_millis(150)).await;
+
+ let (status, body) = http_get_async(port, "/readyz").await.unwrap();
+ assert!(
+ status.starts_with("HTTP/1.1 503"),
+ "expected 503 after staleness, got {status:?}"
+ );
+ assert!(
+ body.contains("heartbeat stale"),
+ "body should mention staleness, got {body:?}"
+ );
+ assert!(
+ body.contains("threshold 50 ms"),
+ "body should surface the threshold, got {body:?}"
+ );
+}
+
+#[tokio::test]
+async fn healthz_remains_200_regardless_of_readiness() {
+ let readiness = Arc::new(Readiness::new(2_000, 3));
+ readiness.mark_draining();
+ let port = start_server(Arc::clone(&readiness)).await;
+
+ let (status, body) = http_get_async(port, "/healthz").await.unwrap();
+ assert!(
+ status.starts_with("HTTP/1.1 200"),
+ "/healthz must stay green, got {status:?}"
+ );
+ assert_eq!(body, "ok");
+}
+
+#[tokio::test]
+async fn unknown_path_returns_404() {
+ let readiness = Arc::new(Readiness::new(2_000, 3));
+ let port = start_server(Arc::clone(&readiness)).await;
+
+ let (status, body) = http_get_async(port, "/does-not-exist").await.unwrap();
+ assert!(
+ status.starts_with("HTTP/1.1 404"),
+ "expected 404 for unknown path, got {status:?}"
+ );
+ assert_eq!(body, "not found");
+}
diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.json
index be3f02c90..f8960c79d 100644
--- a/packages/sie_ts_sdk/package.json
+++ b/packages/sie_ts_sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@superlinked/sie-sdk",
- "version": "0.4.1",
+ "version": "0.4.2",
"description": "Official TypeScript SDK for SIE (Search Inference Engine)",
"type": "module",
"main": "./dist/index.cjs",
@@ -67,14 +67,23 @@
"access": "public"
},
"dependencies": {
- "@msgpack/msgpack": "^3.0.0"
+ "@msgpack/msgpack": "^3.1.3"
},
"devDependencies": {
"@biomejs/biome": "^1.9.4",
- "@playwright/test": "^1.57.0",
- "@types/node": "^22.0.0",
- "tsup": "^8.3.5",
- "typescript": "^5.7.2",
- "vitest": "^2.1.8"
+ "@playwright/test": "^1.60.0",
+ "@types/node": "^22.19.19",
+ "tsup": "^8.5.1",
+ "typescript": "^5.9.3",
+ "vitest": "^2.1.9"
+ },
+ "pnpm": {
+ "overrides": {
+ "esbuild": ">=0.25.0",
+ "picomatch": ">=4.0.4",
+ "postcss": ">=8.5.10",
+ "rollup": ">=4.59.0",
+ "vite": "^6.4.2"
+ }
}
}
diff --git a/packages/sie_ts_sdk/pnpm-lock.yaml b/packages/sie_ts_sdk/pnpm-lock.yaml
index 74448ce73..6518ff6e4 100644
--- a/packages/sie_ts_sdk/pnpm-lock.yaml
+++ b/packages/sie_ts_sdk/pnpm-lock.yaml
@@ -4,39 +4,42 @@ settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
+overrides:
+ esbuild: '>=0.25.0'
+ picomatch: '>=4.0.4'
+ postcss: '>=8.5.10'
+ rollup: '>=4.59.0'
+ vite: ^6.4.2
+
importers:
.:
dependencies:
'@msgpack/msgpack':
- specifier: ^3.0.0
+ specifier: ^3.1.3
version: 3.1.3
devDependencies:
'@biomejs/biome':
specifier: ^1.9.4
version: 1.9.4
- '@changesets/cli':
- specifier: ^2.27.10
- version: 2.29.8(@types/[email protected])
+ '@playwright/test':
+ specifier: ^1.60.0
+ version: 1.60.0
'@types/node':
- specifier: ^22.0.0
- version: 22.19.3
+ specifier: ^22.19.19
+ version: 22.19.19
tsup:
- specifier: ^8.3.5
+ specifier: ^8.5.1
typescript:
- specifier: ^5.7.2
+ specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.8
- version: 2.1.9(@types/[email protected])
+ specifier: ^2.1.9
+ version: 2.1.9(@types/[email protected])([email protected])
packages:
- '@babel/[email protected]':
- resolution: {integrity: sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==}
- engines: {node: '>=6.9.0'}
-
'@biomejs/[email protected]':
resolution: {integrity: sha512-1rkd7G70+o9KkTn5KLmDYXihGoTaIGO9PIIN2ZB7UJxFrWw04CZHPYiMRjYsaDvVV7hP1dYNRLxSANLaBFGpog==}
engines: {node: '>=14.21.3'}
@@ -90,259 +93,102 @@ packages:
cpu: [x64]
os: [win32]
- '@changesets/[email protected]':
- resolution: {integrity: sha512-ddBvf9PHdy2YY0OUiEl3TV78mH9sckndJR14QAt87KLEbIov81XO0q0QAmvooBxXlqRRP8I9B7XOzZwQG7JkWA==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-tPgeeqCHIwNo8sypKlS3gOPmsS3wP0zHt67JDuL20P4QcXiw/O4Hl7oXiuLnP9yg+rXLQ2sScdV1Kkzde61iSQ==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-x/xEleCFLH28c3bQeQIyeZf8lFXyDFVn1SgcBiR2Tw/r4IAWlk1fzxCEZ6NxQAjF2Nwtczoen3OA2qR+UawQ8Q==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-1weuGZpP63YWUYjay/E84qqwcnt5yJMM0tep10Up7Q5cS/DGe2IZ0Uj3HNMxGhCINZuR7aO9WBMdKnPit5ZDPA==}
- hasBin: true
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-CYiRhA4bWKemdYi/uwImjPxqWNpqGPNbEBdX1BdONALFIDK7MCUj6FPkzD+z9gJcvDFUQJn9aDVf4UG7OT6Kog==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-6BLOQUscTpZeGljvyQXlWOItQyU71kCdGz7Pi8H8zdw6BI0g3m43iL4xKUVPWtG+qrrL9DTjpdn8eYuCQSRpow==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-gphr+v0mv2I3Oxt19VdWRRUxq3sseyUpX9DaHpTUmLj92Y10AGy+XOtV+kbM6L/fDcpx7/ISDFK6T8A/P3lOdQ==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-yjZMHpUHgl4Xl5gRlolVuxDkm4HgSJqT93Ri1Uz8kGrQb+5iJ8dkXJ20M2j/Y4iV5QzS2c5SeTxVSKX+2eMI0g==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-hwawtob9DryoGTpixy1D3ZXbGgJu1Rhr+ySH2PvTLHvkZuQ7sRT4oQwMh0hbqZH1weAooedEjRsbrWcGLCeyVQ==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-BXANzRFkX+XcC1q/d27NKvlJ1yf7PSAgi8JG6dt8EfbHFHi4neau7mufcSca5zRhwOL8j9s6EqsxmT+s+/E6Sw==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-OQtR36ZlnuTxKqoW4Sv6x5YIhOmClRd5pWsjZsddYxpWs517R0HkyiefQPIytCVh4ZcC5x9XaG8KTdd5iRQUfg==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-Uo5MC5mfg4OM0jU3up66fmSn6/NE9INK+8/Vn/7sMVcdWg46zfbvvUSjD9EMonVqPi9fbrJH9SXHn48Tr1f2yA==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-HaL/gEyFVvkf9KFg6484wR9s0qjAXlZ8qWPDkTyKF6+zqjBe/I2mygg3MbpZ++hdi0ToqNUF8cjj7fBy0dg8Ug==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-P5QaN9hJSQQKJShzzpBT13FzOSPyHbqdoIBUd2DJdgvnECCyO6LmAOWSV+O8se2TaZJVwSXjL+v9yhb+a9JeJg==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-qAK/WrqWLNCP22UDdBTMPH5f41elVDlsNyat180A33dWxuUDyNpg6fPi/FyTZwRriVjg0L8gnjJn2F9XAoF0qw==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-LDQvVDv5Kb50ny2s25Fhm3d9QSZimsoUGBsUioj6MC3qbMUCuC8GPIvk/M6IvXx3lYhAs0lwWUQLb+VIEUCECw==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-rKQcJ+o1nKNgeoYRHKOS07tAMNd3YSN0uHaJOZYjBAgxfV7TUE7JE+z4BzZdQwb5hKaYbayKN5KrYV7ODb2rAA==}
-
- '@changesets/[email protected]':
- resolution: {integrity: sha512-CdTLvIOPiCNuH71pyDu3rA+Q0n65cmAbXnwWH84rKGiFumFzkmHNT8KHTMEchcxN+Kl8I54xGUhJ7l3E7X396Q==}
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==}
- engines: {node: '>=12'}
- cpu: [ppc64]
- os: [aix]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [aix]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [android]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==}
engines: {node: '>=18'}
cpu: [arm64]
os: [android]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==}
- engines: {node: '>=12'}
- cpu: [arm]
- os: [android]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==}
engines: {node: '>=18'}
cpu: [arm]
os: [android]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [android]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==}
engines: {node: '>=18'}
cpu: [x64]
os: [android]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [darwin]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==}
engines: {node: '>=18'}
cpu: [arm64]
os: [darwin]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [darwin]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==}
engines: {node: '>=18'}
cpu: [x64]
os: [darwin]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [freebsd]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==}
engines: {node: '>=18'}
cpu: [arm64]
os: [freebsd]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [freebsd]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==}
engines: {node: '>=18'}
cpu: [x64]
os: [freebsd]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [linux]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==}
- engines: {node: '>=12'}
- cpu: [arm]
- os: [linux]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==}
engines: {node: '>=18'}
cpu: [arm]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==}
- engines: {node: '>=12'}
- cpu: [ia32]
- os: [linux]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==}
engines: {node: '>=18'}
cpu: [ia32]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==}
- engines: {node: '>=12'}
- cpu: [loong64]
- os: [linux]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==}
engines: {node: '>=18'}
cpu: [loong64]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==}
- engines: {node: '>=12'}
- cpu: [mips64el]
- os: [linux]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==}
engines: {node: '>=18'}
cpu: [mips64el]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==}
- engines: {node: '>=12'}
- cpu: [ppc64]
- os: [linux]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==}
- engines: {node: '>=12'}
- cpu: [riscv64]
- os: [linux]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==}
engines: {node: '>=18'}
cpu: [riscv64]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==}
- engines: {node: '>=12'}
- cpu: [s390x]
- os: [linux]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==}
engines: {node: '>=18'}
cpu: [s390x]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [linux]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==}
engines: {node: '>=18'}
@@ -355,12 +201,6 @@ packages:
cpu: [arm64]
os: [netbsd]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [netbsd]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==}
engines: {node: '>=18'}
@@ -373,12 +213,6 @@ packages:
cpu: [arm64]
os: [openbsd]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [openbsd]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==}
engines: {node: '>=18'}
@@ -391,63 +225,30 @@ packages:
cpu: [arm64]
os: [openharmony]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [sunos]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==}
engines: {node: '>=18'}
cpu: [x64]
os: [sunos]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [win32]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==}
engines: {node: '>=18'}
cpu: [arm64]
os: [win32]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==}
- engines: {node: '>=12'}
- cpu: [ia32]
- os: [win32]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==}
engines: {node: '>=18'}
cpu: [ia32]
os: [win32]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [win32]
-
'@esbuild/[email protected]':
resolution: {integrity: sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [win32]
- '@inquirer/[email protected]':
- resolution: {integrity: sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA==}
- engines: {node: '>=18'}
- peerDependencies:
- '@types/node': '>=18'
- peerDependenciesMeta:
- '@types/node':
- optional: true
-
'@jridgewell/[email protected]':
resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}
@@ -461,146 +262,145 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
- '@manypkg/[email protected]':
- resolution: {integrity: sha512-mki5uBvhHzO8kYYix/WRy2WX8S3B5wdVSc9D6KcU5lQNglP2yt58/VfLuAK49glRXChosY8ap2oJ1qgma3GUVA==}
-
- '@manypkg/[email protected]':
- resolution: {integrity: sha512-fo+QhuU3qE/2TQMQmbVMqaQ6EWbMhi4ABWP+O4AM1NqPBuy0OrApV5LO6BrrgnhtAHS2NH6RrVk9OL181tTi8A==}
-
'@msgpack/[email protected]':
resolution: {integrity: sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==}
engines: {node: '>= 18'}
- '@nodelib/[email protected]':
- resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
- engines: {node: '>= 8'}
-
- '@nodelib/[email protected]':
- resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==}
- engines: {node: '>= 8'}
-
- '@nodelib/[email protected]':
- resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==}
- engines: {node: '>= 8'}
+ '@playwright/[email protected]':
+ resolution: {integrity: sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==}
+ engines: {node: '>=18'}
+ hasBin: true
- '@rollup/[email protected]':
- resolution: {integrity: sha512-OywsdRHrFvCdvsewAInDKCNyR3laPA2mc9bRYJ6LBp5IyvF3fvXbbNR0bSzHlZVFtn6E0xw2oZlyjg4rKCVcng==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-F5QXMSiFebS9hKZj02XhWLLnRpJ3B3AROP0tWbFBSj+6kCbg5m9j5JoHKd4mmSVy5mS/IMQloYgYxCuJC0fxEQ==}
cpu: [arm]
os: [android]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-Skx39Uv+u7H224Af+bDgNinitlmHyQX1K/atIA32JP3JQw6hVODX5tkbi2zof/E69M1qH2UoN3Xdxgs90mmNYw==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-GxxTKApUpzRhof7poWvCJHRF51C67u1R7D6DiluBE8wKU1u5GWE8t+v81JvJYtbawoBFX1hLv5Ei4eVjkWokaw==}
cpu: [arm64]
os: [android]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-k43D4qta/+6Fq+nCDhhv9yP2HdeKeP56QrUUTW7E6PhZP1US6NDqpJj4MY0jBHlJivVJD5P8NxrjuobZBJTCRw==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-tua0TaJxMOB1R0V0RS1jFZ/RpURFDJIOR2A6jWwQeawuFyS4gBW+rntLRaQd0EQ4bd6Vp44Z2rXW+YYDBsj6IA==}
cpu: [arm64]
os: [darwin]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-cOo7biqwkpawslEfox5Vs8/qj83M/aZCSSNIWpVzfU2CYHa2G3P1UN5WF01RdTHSgCkri7XOlTdtk17BezlV3A==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-CSKq7MsP+5PFIcydhAiR1K0UhEI1A2jWXVKHPCBZ151yOutENwvnPocgVHkivu2kviURtCEB6zUQw0vs8RrhMg==}
cpu: [x64]
os: [darwin]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-miSvuFkmvFbgJ1BevMa4CPCFt5MPGw094knM64W9I0giUIMMmRYcGW/JWZDriaw/k1kOBtsWh1z6nIFV1vPNtA==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-+O8OkVdyvXMtJEciu2wS/pzm1IxntEEQx3z5TAVy4l32G0etZn+RsA48ARRrFm6Ri8fvqPQfgrvNxSjKAbnd3g==}
cpu: [arm64]
os: [freebsd]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-KGXIs55+b/ZfZsq9aR026tmr/+7tq6VG6MsnrvF4H8VhwflTIuYh+LFUlIsRdQSgrgmtM3fVATzEAj4hBQlaqQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-Iw3oMskH3AfNuhU0MSN7vNbdi4me/NiYo2azqPz/Le16zHSa+3RRmliCMWWQmh4lcndccU40xcJuTYJZxNo/lw==}
cpu: [x64]
os: [freebsd]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-EHMUcDwhtdRGlXZsGSIuXSYwD5kOT9NVnx9sqzYiwAc91wfYOE1g1djOEDseZJKKqtHAHGwnGPQu3kytmfaXLQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-EIPRXTVQpHyF8WOo219AD2yEltPehLTcTMz2fn6JsatLYSzQf00hj3rulF+yauOlF9/FtM2WpkT/hJh/KJFGhA==}
cpu: [arm]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-+pBrqEjaakN2ySv5RVrj/qLytYhPKEUwk+e3SFU5jTLHIcAtqh2rLrd/OkbNuHJpsBgxsD8ccJt5ga/SeG0JmA==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-J3Yh9PzzF1Ovah2At+lHiGQdsYgArxBbXv/zHfSyaiFQEqvNv7DcW98pCrmdjCZBrqBiKrKKe2V+aaSGWuBe/w==}
cpu: [arm]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-NSqc7rE9wuUaRBsBp5ckQ5CVz5aIRKCwsoa6WMF7G01sX3/qHUw/z4pv+D+ahL1EIKy6Enpcnz1RY8pf7bjwng==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-BFDEZMYfUvLn37ONE1yMBojPxnMlTFsdyNoqncT0qFq1mAfllL+ATMMJd8TeuVMiX84s1KbcxcZbXInmcO2mRg==}
cpu: [arm64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-gr5vDbg3Bakga5kbdpqx81m2n9IX8M6gIMlQQIXiLTNeQW6CucvuInJ91EuCJ/JYvc+rcLLsDFcfAD1K7fMofg==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-pc9EYOSlOgdQ2uPl1o9PF6/kLSgaUosia7gOuS8mB69IxJvlclko1MECXysjs5ryez1/5zjYqx3+xYU0TU6R1A==}
cpu: [arm64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-gsrtB1NA3ZYj2vq0Rzkylo9ylCtW/PhpLEivlgWe0bpgtX5+9j9EZa0wtZiCjgu6zmSeZWyI/e2YRX1URozpIw==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-NxnomyxYerDh5n4iLrNa+sH+Z+U4BMEE46V2PgQ/hoB909i8gV1M5wPojWg9fk1jWpO3IQnOs20K4wyZuFLEFQ==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-nbJnQ8a3z1mtmrwImCYhc6BGpThAyYVRQxw9uKSKG4wR6aAYno9sVjJ0zaZcW9BPJX1GbrDPf+SvdWjgTuDmnw==}
cpu: [loong64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-y3qNOfTBStmFNq+t4s7Tmc9hW2ENtPg8FeUD/VShI7rKxNW7O4fFeaYbMsd3tpFlIg1Q8IapFgy7Q9i2BqeBvA==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-2EU6acNrQLd8tYvo/LXW535wupT3m6fo7HKo6lr7ktQoItxTyOL1ZCR/GfGCuXl2vR+zmfI6eRXkSemafv+iVg==}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-WeBtoMuaMxiiIrO2IYP3xs6GMWkJP2C0EoT8beTLkUPmzV1i/UcOSVw1d5r9KBODtHKilG5yFxsGRnBbK3wJ4A==}
cpu: [ppc64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-89sepv7h2lIVPsFma8iwmccN7Yjjtgz0Rj/Ou6fEqg3HDhpCa+Et+YSufy27i6b0Wav69Qv4WBNl3Rs6pwhebQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-FJHFfqpKUI3A10WrWKiFbBZ7yVbGT4q4B5o1qKFFojqpaYoh9LrQgqWCmmcxQzVSXYtyB5bzkXrYzlHTs21MYA==}
cpu: [riscv64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-ZcU77ieh0M2Q8Ur7D5X7KvK+UxbXeDHwiOt/CPSBTI1fBmeDMivW0dPkdqkT4rOgDjrDDBUed9x4EgraIKoR2A==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-mcEl6CUT5IAUmQf1m9FYSmVqCJlpQ8r8eyftFUHG8i9OhY7BkBXSUdnLH5DOf0wCOjcP9v/QO93zpmF1SptCCw==}
cpu: [riscv64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-2AdWy5RdDF5+4YfG/YesGDDtbyJlC9LHmL6rZw6FurBJ5n4vFGupsOBGfwMRjBYH7qRQowT8D/U4LoSvVwOhSQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-ynt3JxVd2w2buzoKDWIyiV1pJW93xlQic1THVLXilz429oijRpSHivZAgp65KBu+cMcgf1eVVjdnTLvPxgCuoQ==}
cpu: [s390x]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-WGt5J8Ij/rvyqpFexxk3ffKqqbLf9AqrTBbWDk7ApGUzaIs6V+s2s84kAxklFwmMF/vBNGrVdYgbblCOFFezMQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-Boiz5+MsaROEWDf+GGEwF8VMHGhlUoQMtIPjOgA5fv4osupqTVnJteQNKJwUcnUog2G55jYXH7KZFFiJe0TEzQ==}
cpu: [x64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-JzQmb38ATzHjxlPHuTH6tE7ojnMKM2kYNzt44LO/jJi8BpceEC8QuXYA908n8r3CNuG/B3BV8VR3Hi1rYtmPiw==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-+qfSY27qIrFfI/Hom04KYFw3GKZSGU4lXus51wsb5EuySfFlWRwjkKWoE9emgRw/ukoT4Udsj4W/+xxG8VbPKg==}
cpu: [x64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-huT3fd0iC7jigGh7n3q/+lfPcXxBi+om/Rs3yiFxjvSxbSB6aohDFXbWvlspaqjeOh+hx7DDHS+5Es5qRkWkZg==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-VpTfOPHgVXEBeeR8hZ2O0F3aSso+JDWqTWmTmzcQKted54IAdUVbxE+j/MVxUsKa8L20HJhv3vUezVPoquqWjA==}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-IPOsh5aRYuLv/nkU51X10Bf75Bsf6+gZdx1X+QP5QM6lIJFHHqbHLG0uJn/hWthzo13UAc2umiUorqZy3axoZg==}
cpu: [arm64]
os: [openharmony]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-c2V0W1bsKIKfbLMBu/WGBz6Yci8nJ/ZJdheE0EwB73N3MvHYKiKGs3mVilX4Gs70eGeDaMqEob25Tw2Gb9Nqyw==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-4QzE9E81OohJ/HKzHhsqU+zcYYojVOXlFMs1DdyMT6qXl/niOH7AVElmmEdUNHHS/oRkc++d5k6Vy85zFs0DEw==}
cpu: [arm64]
os: [win32]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-woEHgqQqDCkAzrDhvDipnSirm5vxUXtSKDYTVpZG3nUdW/VVB5VdCYA2iReSj/u3yCZzXID4kuKG7OynPnB3WQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-zTPgT1YuHHcd+Tmx7h8aml0FWFVelV5N54oHow9SLj+GfoDy/huQ+UV396N/C7KpMDMiPspRktzM1/0r1usYEA==}
cpu: [ia32]
os: [win32]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-dzAc53LOuFvHwbCEOS0rPbXp6SIhAf2txMP5p6mGyOXXw5mWY8NGGbPMPrs4P1WItkfApDathBj/NzMLUZ9rtQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-DRS4G7mi9lJxqEDezIkKCaUIKCrLUUDCUaCsTPCi/rtqaC6D/jjwslMQyiDU50Ka0JKpeXeRBFBAXwArY52vBw==}
cpu: [x64]
os: [win32]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-hYT5d3YNdSh3mbCU1gwQyPgQd3T2ne0A3KG8KSBdav5TiBg6eInVmV+TeR5uHufiIgSFg0XsOWGW5/RhNcSvPg==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-QVTUovf40zgTqlFVrKA1uXMVvU2QWEFWfAH8Wdc48IxLvrJMQVMBRjuQyUpzZCDkakImib9eVazbWlC6ksWtJw==}
cpu: [x64]
os: [win32]
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
- '@types/[email protected]':
- resolution: {integrity: sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ==}
-
- '@types/[email protected]':
- resolution: {integrity: sha512-1N9SBnWYOJTrNZCdh/yJE+t910Y128BoyY+zBLWhL3r0TYzlTmFdXrPwHL9DyFZmlEXNQQolTZh3KHV31QDhyA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==}
'@vitest/[email protected]':
resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==}
@@ -609,7 +409,7 @@ packages:
resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==}
peerDependencies:
msw: ^2.4.9
- vite: ^5.0.0
+ vite: ^6.4.2
peerDependenciesMeta:
msw:
optional: true
@@ -636,44 +436,18 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
- resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==}
- engines: {node: '>=6'}
-
- resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==}
- resolution: {integrity: sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==}
-
- resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
-
- resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-pbnl5XzGBdrFU/wT4jqmJVPn2B6UHPBOhzMQkY/SPUPB6QtUXtmBHBIwCbXJol93mOpGMnQyP/+BB19q04xj7g==}
- engines: {node: '>=4'}
-
- resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
peerDependencies:
- esbuild: '>=0.18'
+ esbuild: '>=0.25.0'
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
@@ -683,9 +457,6 @@ packages:
resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ==}
-
resolution: {integrity: sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==}
engines: {node: '>= 16'}
@@ -694,10 +465,6 @@ packages:
resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==}
engines: {node: '>= 14.16.0'}
- resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==}
engines: {node: '>= 6'}
@@ -709,10 +476,6 @@ packages:
resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==}
engines: {node: ^14.18.0 || >=16.10.0}
- resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
- engines: {node: '>= 8'}
-
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
engines: {node: '>=6.0'}
@@ -726,36 +489,18 @@ packages:
resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==}
+ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==}
- engines: {node: '>=8.6'}
-
resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
- resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==}
- engines: {node: '>=12'}
- hasBin: true
-
resolution: {integrity: sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==}
engines: {node: '>=18'}
hasBin: true
- resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==}
- engines: {node: '>=4'}
- hasBin: true
-
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
@@ -763,109 +508,101 @@ packages:
resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==}
engines: {node: '>=12.0.0'}
- resolution: {integrity: sha512-UOiS2in6/Q0FK0R0q6UY9vYpQ21mr/Qn1KOnte7vsACuNJf514WvCCUHSRCPcgjPT2bAhNIJdlE6bVap1GKmeg==}
-
- resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}
- engines: {node: '>=8.6.0'}
-
- resolution: {integrity: sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==}
-
resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}
engines: {node: '>=12.0.0'}
peerDependencies:
- picomatch: ^3 || ^4
+ picomatch: '>=4.0.4'
peerDependenciesMeta:
picomatch:
optional: true
- resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==}
- resolution: {integrity: sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==}
- engines: {node: '>=6 <7 || >=8'}
-
- resolution: {integrity: sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==}
- engines: {node: '>=6 <7 || >=8'}
+ resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+ os: [darwin]
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
- resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==}
- engines: {node: '>= 6'}
-
- resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==}
+ resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
-
- resolution: {integrity: sha512-tsYlhAYpjCKa//8rXZ9DqKEawhPoSytweBC2eNvcaDK+57RZLHGqNs3PZTQO6yekLFSuvA6AlnAfrw1uBvtb+Q==}
- hasBin: true
-
- resolution: {integrity: sha512-2Tth85cXwGFHfvRgZWszZSvdo+0Xsqmw8k8ZwxScfcBneNUraK+dxRxRm24nszx80Y0TVio8kKLt5sLE7ZCLlw==}
- engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [android]
- resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
- engines: {node: '>= 4'}
+ resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [darwin]
- resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}
- engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [darwin]
- resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}
- engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [freebsd]
- resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==}
- engines: {node: '>=0.12.0'}
+ resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm]
+ os: [linux]
- resolution: {integrity: sha512-2AT6j+gXe/1ueqbW6fLZJiIw3F8iXGJtt0yDrZaBhAZEG1raiTxKWU+IPqMCzQAXOUCKdA4UDMgacKH25XG2Cw==}
- engines: {node: '>=4'}
+ resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
- resolution: {integrity: sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==}
- engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
- resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
+ resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
- resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}
- engines: {node: '>=10'}
+ resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
- resolution: {integrity: sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==}
- hasBin: true
+ resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [win32]
- resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==}
- hasBin: true
+ resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [win32]
- resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==}
+ resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}
+ engines: {node: '>= 12.0.0'}
resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==}
@@ -878,42 +615,23 @@ packages:
resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
- resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg==}
-
resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
- resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==}
- engines: {node: '>= 8'}
-
- resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==}
- engines: {node: '>=8.6'}
-
resolution: {integrity: sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==}
- resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==}
- engines: {node: '>=4'}
-
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}
- resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
+ resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
@@ -921,44 +639,6 @@ packages:
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-/jHxFIzoMXdqPzTaCpFzAAWhpkSjZPF4Vsn6jAfNpmbH/ymsmd7Qc6VE9BGn0L6YMj6uwpQLxCECpus4ukKS9Q==}
-
- resolution: {integrity: sha512-ZBxxZ5sL2HghephhpGAQdoskxplTwr7ICaehZwLIlfL6acuVgZPm8yBNuRAFBGEqtD/hmUeq9eqLg2ys9Xr/yw==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==}
- engines: {node: '>=6'}
-
- resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw==}
- engines: {node: '>=6'}
-
- resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==}
- engines: {node: '>=6'}
-
- resolution: {integrity: sha512-BEnLolu+yuz22S56CU1SUKq3XC3PkwD5wv4ikR4MfGvnRVcmzXR9DwSlW2fEamyTPyXHomBJRzgapeuBvRNzJQ==}
-
- resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==}
@@ -972,18 +652,10 @@ packages:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
- resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==}
- engines: {node: '>=8.6'}
-
- resolution: {integrity: sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==}
+ resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==}
- engines: {node: '>=6'}
-
resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}
engines: {node: '>= 6'}
@@ -991,12 +663,22 @@ packages:
resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==}
+ resolution: {integrity: sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==}
+ engines: {node: '>=18'}
+ hasBin: true
+
+ resolution: {integrity: sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==}
+ engines: {node: '>=18'}
+ hasBin: true
+
resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==}
engines: {node: '>= 18'}
peerDependencies:
jiti: '>=1.21.0'
- postcss: '>=8.0.9'
+ postcss: '>=8.5.10'
tsx: ^4.8.1
yaml: ^2.4.2
peerDependenciesMeta:
@@ -1009,25 +691,10 @@ packages:
yaml:
optional: true
- resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==}
+ resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==}
engines: {node: ^10 || ^12 || >=14}
- resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==}
- engines: {node: '>=10.13.0'}
- hasBin: true
-
- resolution: {integrity: sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==}
-
- resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
-
- resolution: {integrity: sha512-VIMnQi/Z4HT2Fxuwg5KrY174U1VdUIASQVWXXyqtNRtxSr9IYkn1rsI6Tb6HsrHCmB7gVpNwX6JxPTHcH6IoTA==}
- engines: {node: '>=6'}
-
resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==}
engines: {node: '>= 14.18.0'}
@@ -1036,45 +703,14 @@ packages:
resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
- engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
-
- resolution: {integrity: sha512-3nk8Y3a9Ea8szgKhinMlGMhGMw89mqule3KWczxhIzqudyHdCIOHw8WJlj/r329fACjKLEh13ZSk7oE22kyeIw==}
+ resolution: {integrity: sha512-WHeFSbZYsPu3+bLoNRUuAO+wavNlocOPf3wSHTP7hcFKVnJeWsYlCDbr3mTS14FCizf9ccIxXA8sGL8zKeQN3g==}
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
hasBin: true
- resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}
-
- resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
-
- resolution: {integrity: sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==}
- engines: {node: '>=10'}
- hasBin: true
-
- resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
- resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
- engines: {node: '>=14'}
-
- resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
@@ -1083,35 +719,17 @@ packages:
resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}
engines: {node: '>= 12'}
- resolution: {integrity: sha512-MmnduQUuHCoFckZoWnXsTg7JaiLBJrKFj9UI2MbRPGaJeVpsLcVBu6P/IGZovziM/YBsellCmsprgNA+w0CzVg==}
-
- resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==}
-
resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}
resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
- resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==}
- engines: {node: '>=4'}
-
resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}
engines: {node: '>=16 || 14 >=14.17'}
hasBin: true
- resolution: {integrity: sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==}
engines: {node: '>=0.8'}
@@ -1129,6 +747,10 @@ packages:
resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==}
engines: {node: '>=12.0.0'}
+ resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==}
+ engines: {node: '>=12.0.0'}
+
resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}
engines: {node: ^18.0.0 || >=20.0.0}
@@ -1141,10 +763,6 @@ packages:
resolution: {integrity: sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==}
engines: {node: '>=14.0.0'}
- resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==}
- engines: {node: '>=8.0'}
-
resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==}
hasBin: true
@@ -1159,7 +777,7 @@ packages:
peerDependencies:
'@microsoft/api-extractor': ^7.36.0
'@swc/core': ^1
- postcss: ^8.4.12
+ postcss: '>=8.5.10'
typescript: '>=4.5.0'
peerDependenciesMeta:
'@microsoft/api-extractor':
@@ -1182,31 +800,32 @@ packages:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
- resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==}
- engines: {node: '>= 4.0.0'}
-
resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==}
engines: {node: ^18.0.0 || >=20.0.0}
hasBin: true
- resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==}
- engines: {node: ^18.0.0 || >=20.0.0}
+ resolution: {integrity: sha512-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ==}
+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
hasBin: true
peerDependencies:
- '@types/node': ^18.0.0 || >=20.0.0
+ '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0
+ jiti: '>=1.21.0'
less: '*'
lightningcss: ^1.21.0
sass: '*'
sass-embedded: '*'
stylus: '*'
sugarss: '*'
- terser: ^5.4.0
+ terser: ^5.16.0
+ tsx: ^4.8.1
+ yaml: ^2.4.2
peerDependenciesMeta:
'@types/node':
optional: true
+ jiti:
+ optional: true
less:
optional: true
lightningcss:
@@ -1221,6 +840,10 @@ packages:
optional: true
terser:
optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==}
@@ -1247,11 +870,6 @@ packages:
jsdom:
optional: true
- resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}
- engines: {node: '>= 8'}
- hasBin: true
-
resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}
engines: {node: '>=8'}
@@ -1259,8 +877,6 @@ packages:
snapshots:
- '@babel/[email protected]': {}
-
'@biomejs/[email protected]':
optionalDependencies:
'@biomejs/cli-darwin-arm64': 1.9.4
@@ -1296,304 +912,84 @@ snapshots:
'@biomejs/[email protected]':
optional: true
- '@changesets/[email protected]':
- dependencies:
- '@changesets/config': 3.1.2
- '@changesets/get-version-range-type': 0.4.0
- '@changesets/git': 3.0.4
- '@changesets/should-skip-package': 0.1.2
- '@changesets/types': 6.1.0
- '@manypkg/get-packages': 1.1.3
- detect-indent: 6.1.0
- fs-extra: 7.0.1
- lodash.startcase: 4.4.0
- outdent: 0.5.0
- prettier: 2.8.8
- resolve-from: 5.0.0
- semver: 7.7.3
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/errors': 0.2.0
- '@changesets/get-dependents-graph': 2.1.3
- '@changesets/should-skip-package': 0.1.2
- '@changesets/types': 6.1.0
- '@manypkg/get-packages': 1.1.3
- semver: 7.7.3
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/types': 6.1.0
-
- '@changesets/[email protected](@types/[email protected])':
- dependencies:
- '@changesets/apply-release-plan': 7.0.14
- '@changesets/assemble-release-plan': 6.0.9
- '@changesets/changelog-git': 0.2.1
- '@changesets/config': 3.1.2
- '@changesets/errors': 0.2.0
- '@changesets/get-dependents-graph': 2.1.3
- '@changesets/get-release-plan': 4.0.14
- '@changesets/git': 3.0.4
- '@changesets/logger': 0.1.1
- '@changesets/pre': 2.0.2
- '@changesets/read': 0.6.6
- '@changesets/should-skip-package': 0.1.2
- '@changesets/types': 6.1.0
- '@changesets/write': 0.4.0
- '@inquirer/external-editor': 1.0.3(@types/[email protected])
- '@manypkg/get-packages': 1.1.3
- ansi-colors: 4.1.3
- ci-info: 3.9.0
- enquirer: 2.4.1
- fs-extra: 7.0.1
- mri: 1.2.0
- p-limit: 2.3.0
- package-manager-detector: 0.2.11
- picocolors: 1.1.1
- resolve-from: 5.0.0
- semver: 7.7.3
- spawndamnit: 3.0.1
- term-size: 2.2.1
- transitivePeerDependencies:
- - '@types/node'
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/errors': 0.2.0
- '@changesets/get-dependents-graph': 2.1.3
- '@changesets/logger': 0.1.1
- '@changesets/types': 6.1.0
- '@manypkg/get-packages': 1.1.3
- fs-extra: 7.0.1
- micromatch: 4.0.8
-
- '@changesets/[email protected]':
- dependencies:
- extendable-error: 0.1.7
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/types': 6.1.0
- '@manypkg/get-packages': 1.1.3
- picocolors: 1.1.1
- semver: 7.7.3
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/assemble-release-plan': 6.0.9
- '@changesets/config': 3.1.2
- '@changesets/pre': 2.0.2
- '@changesets/read': 0.6.6
- '@changesets/types': 6.1.0
- '@manypkg/get-packages': 1.1.3
-
- '@changesets/[email protected]': {}
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/errors': 0.2.0
- '@manypkg/get-packages': 1.1.3
- is-subdir: 1.2.0
- micromatch: 4.0.8
- spawndamnit: 3.0.1
-
- '@changesets/[email protected]':
- dependencies:
- picocolors: 1.1.1
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/types': 6.1.0
- js-yaml: 4.1.1
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/errors': 0.2.0
- '@changesets/types': 6.1.0
- '@manypkg/get-packages': 1.1.3
- fs-extra: 7.0.1
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/git': 3.0.4
- '@changesets/logger': 0.1.1
- '@changesets/parse': 0.4.2
- '@changesets/types': 6.1.0
- fs-extra: 7.0.1
- p-filter: 2.1.0
- picocolors: 1.1.1
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/types': 6.1.0
- '@manypkg/get-packages': 1.1.3
-
- '@changesets/[email protected]': {}
-
- '@changesets/[email protected]': {}
-
- '@changesets/[email protected]':
- dependencies:
- '@changesets/types': 6.1.0
- fs-extra: 7.0.1
- human-id: 4.1.3
- prettier: 2.8.8
-
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
- optional: true
-
'@esbuild/[email protected]':
optional: true
- '@inquirer/[email protected](@types/[email protected])':
- dependencies:
- chardet: 2.1.1
- iconv-lite: 0.7.1
- optionalDependencies:
- '@types/node': 22.19.3
-
'@jridgewell/[email protected]':
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -1608,107 +1004,90 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5
- '@manypkg/[email protected]':
- dependencies:
- '@babel/runtime': 7.28.4
- '@types/node': 12.20.55
- find-up: 4.1.0
- fs-extra: 8.1.0
-
- '@manypkg/[email protected]':
- dependencies:
- '@babel/runtime': 7.28.4
- '@changesets/types': 4.1.0
- '@manypkg/find-root': 1.1.0
- fs-extra: 8.1.0
- globby: 11.1.0
- read-yaml-file: 1.1.0
-
'@msgpack/[email protected]': {}
- '@nodelib/[email protected]':
+ '@playwright/[email protected]':
dependencies:
- '@nodelib/fs.stat': 2.0.5
- run-parallel: 1.2.0
+ playwright: 1.60.0
- '@nodelib/[email protected]': {}
+ '@rollup/[email protected]':
+ optional: true
- '@nodelib/[email protected]':
- dependencies:
- '@nodelib/fs.scandir': 2.1.5
- fastq: 1.20.1
+ '@rollup/[email protected]':
+ optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@types/[email protected]': {}
+ '@rollup/[email protected]':
+ optional: true
- '@types/[email protected]': {}
+ '@types/[email protected]': {}
- '@types/[email protected]':
+ '@types/[email protected]':
dependencies:
undici-types: 6.21.0
@@ -1719,13 +1098,13 @@ snapshots:
chai: 5.3.3
tinyrainbow: 1.2.0
dependencies:
'@vitest/spy': 2.1.9
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- vite: 5.4.21(@types/[email protected])
+ vite: 6.4.2(@types/[email protected])([email protected])
'@vitest/[email protected]':
dependencies:
@@ -1754,30 +1133,10 @@ snapshots:
-
-
- dependencies:
- sprintf-js: 1.0.3
-
-
-
- dependencies:
- is-windows: 1.0.2
-
- dependencies:
- fill-range: 7.1.1
-
dependencies:
esbuild: 0.27.2
@@ -1793,73 +1152,29 @@ snapshots:
loupe: 3.2.1
pathval: 2.0.1
-
dependencies:
readdirp: 4.1.2
-
- dependencies:
- path-key: 3.1.1
- shebang-command: 2.0.0
- which: 2.0.2
-
dependencies:
ms: 2.1.3
-
- dependencies:
- path-type: 4.0.0
-
- dependencies:
- ansi-colors: 4.1.3
- strip-ansi: 6.0.1
+ optional: true
- optionalDependencies:
- '@esbuild/aix-ppc64': 0.21.5
- '@esbuild/android-arm': 0.21.5
- '@esbuild/android-arm64': 0.21.5
- '@esbuild/android-x64': 0.21.5
- '@esbuild/darwin-arm64': 0.21.5
- '@esbuild/darwin-x64': 0.21.5
- '@esbuild/freebsd-arm64': 0.21.5
- '@esbuild/freebsd-x64': 0.21.5
- '@esbuild/linux-arm': 0.21.5
- '@esbuild/linux-arm64': 0.21.5
- '@esbuild/linux-ia32': 0.21.5
- '@esbuild/linux-loong64': 0.21.5
- '@esbuild/linux-mips64el': 0.21.5
- '@esbuild/linux-ppc64': 0.21.5
- '@esbuild/linux-riscv64': 0.21.5
- '@esbuild/linux-s390x': 0.21.5
- '@esbuild/linux-x64': 0.21.5
- '@esbuild/netbsd-x64': 0.21.5
- '@esbuild/openbsd-x64': 0.21.5
- '@esbuild/sunos-x64': 0.21.5
- '@esbuild/win32-arm64': 0.21.5
- '@esbuild/win32-ia32': 0.21.5
- '@esbuild/win32-x64': 0.21.5
-
optionalDependencies:
'@esbuild/aix-ppc64': 0.27.2
@@ -1889,115 +1204,79 @@ snapshots:
'@esbuild/win32-ia32': 0.27.2
'@esbuild/win32-x64': 0.27.2
-
dependencies:
'@types/estree': 1.0.8
-
- dependencies:
- '@nodelib/fs.stat': 2.0.5
- '@nodelib/fs.walk': 1.2.8
- glob-parent: 5.1.2
- merge2: 1.4.1
- micromatch: 4.0.8
-
- dependencies:
- reusify: 1.1.0
-
optionalDependencies:
- picomatch: 4.0.3
-
- dependencies:
- to-regex-range: 5.0.1
-
- dependencies:
- locate-path: 5.0.0
- path-exists: 4.0.0
+ picomatch: 4.0.4
dependencies:
magic-string: 0.30.21
mlly: 1.8.0
- rollup: 4.54.0
-
- dependencies:
- graceful-fs: 4.2.11
- jsonfile: 4.0.0
- universalify: 0.1.2
+ rollup: 4.60.4
- dependencies:
- graceful-fs: 4.2.11
- jsonfile: 4.0.0
- universalify: 0.1.2
+ optional: true
optional: true
- dependencies:
- is-glob: 4.0.3
-
- dependencies:
- array-union: 2.1.0
- dir-glob: 3.0.1
- fast-glob: 3.3.3
- ignore: 5.3.2
- merge2: 1.4.1
- slash: 3.0.0
-
+ optional: true
- dependencies:
- safer-buffer: 2.1.2
+ optional: true
+ optional: true
+ optional: true
- dependencies:
- is-extglob: 2.1.1
+ optional: true
+ optional: true
- dependencies:
- better-path-resolve: 1.0.0
+ optional: true
+ optional: true
+ optional: true
+ optional: true
- dependencies:
- argparse: 1.0.10
- esprima: 4.0.1
+ optional: true
dependencies:
- argparse: 2.0.1
-
+ detect-libc: 2.1.2
optionalDependencies:
- graceful-fs: 4.2.11
+ lightningcss-android-arm64: 1.32.0
+ lightningcss-darwin-arm64: 1.32.0
+ lightningcss-darwin-x64: 1.32.0
+ lightningcss-freebsd-x64: 1.32.0
+ lightningcss-linux-arm-gnueabihf: 1.32.0
+ lightningcss-linux-arm64-gnu: 1.32.0
+ lightningcss-linux-arm64-musl: 1.32.0
+ lightningcss-linux-x64-gnu: 1.32.0
+ lightningcss-linux-x64-musl: 1.32.0
+ lightningcss-win32-arm64-msvc: 1.32.0
+ lightningcss-win32-x64-msvc: 1.32.0
+ optional: true
@@ -2005,25 +1284,12 @@ snapshots:
- dependencies:
- p-locate: 4.1.0
-
-
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
-
- dependencies:
- braces: 3.0.3
- picomatch: 2.3.1
-
dependencies:
acorn: 8.15.0
@@ -2031,8 +1297,6 @@ snapshots:
pkg-types: 1.3.1
ufo: 1.6.1
-
@@ -2041,38 +1305,10 @@ snapshots:
object-assign: 4.1.1
thenify-all: 1.6.0
-
- dependencies:
- p-map: 2.1.0
-
- dependencies:
- p-try: 2.2.0
-
- dependencies:
- p-limit: 2.3.0
-
-
-
- dependencies:
- quansync: 0.2.11
-
-
-
-
@@ -2081,11 +1317,7 @@ snapshots:
-
-
@@ -2095,106 +1327,71 @@ snapshots:
mlly: 1.8.0
pathe: 2.0.3
+
+ dependencies:
+ playwright-core: 1.60.0
+ optionalDependencies:
+ fsevents: 2.3.2
+
dependencies:
lilconfig: 3.1.3
optionalDependencies:
- postcss: 8.5.6
+ postcss: 8.5.15
dependencies:
- nanoid: 3.3.11
+ nanoid: 3.3.12
picocolors: 1.1.1
source-map-js: 1.2.1
-
-
-
- dependencies:
- graceful-fs: 4.2.11
- js-yaml: 3.14.2
- pify: 4.0.1
- strip-bom: 3.0.0
-
-
dependencies:
'@types/estree': 1.0.8
optionalDependencies:
- '@rollup/rollup-android-arm-eabi': 4.54.0
- '@rollup/rollup-android-arm64': 4.54.0
- '@rollup/rollup-darwin-arm64': 4.54.0
- '@rollup/rollup-darwin-x64': 4.54.0
- '@rollup/rollup-freebsd-arm64': 4.54.0
- '@rollup/rollup-freebsd-x64': 4.54.0
- '@rollup/rollup-linux-arm-gnueabihf': 4.54.0
- '@rollup/rollup-linux-arm-musleabihf': 4.54.0
- '@rollup/rollup-linux-arm64-gnu': 4.54.0
- '@rollup/rollup-linux-arm64-musl': 4.54.0
- '@rollup/rollup-linux-loong64-gnu': 4.54.0
- '@rollup/rollup-linux-ppc64-gnu': 4.54.0
- '@rollup/rollup-linux-riscv64-gnu': 4.54.0
- '@rollup/rollup-linux-riscv64-musl': 4.54.0
- '@rollup/rollup-linux-s390x-gnu': 4.54.0
- '@rollup/rollup-linux-x64-gnu': 4.54.0
- '@rollup/rollup-linux-x64-musl': 4.54.0
- '@rollup/rollup-openharmony-arm64': 4.54.0
- '@rollup/rollup-win32-arm64-msvc': 4.54.0
- '@rollup/rollup-win32-ia32-msvc': 4.54.0
- '@rollup/rollup-win32-x64-gnu': 4.54.0
- '@rollup/rollup-win32-x64-msvc': 4.54.0
+ '@rollup/rollup-android-arm-eabi': 4.60.4
+ '@rollup/rollup-android-arm64': 4.60.4
+ '@rollup/rollup-darwin-arm64': 4.60.4
+ '@rollup/rollup-darwin-x64': 4.60.4
+ '@rollup/rollup-freebsd-arm64': 4.60.4
+ '@rollup/rollup-freebsd-x64': 4.60.4
+ '@rollup/rollup-linux-arm-gnueabihf': 4.60.4
+ '@rollup/rollup-linux-arm-musleabihf': 4.60.4
+ '@rollup/rollup-linux-arm64-gnu': 4.60.4
+ '@rollup/rollup-linux-arm64-musl': 4.60.4
+ '@rollup/rollup-linux-loong64-gnu': 4.60.4
+ '@rollup/rollup-linux-loong64-musl': 4.60.4
+ '@rollup/rollup-linux-ppc64-gnu': 4.60.4
+ '@rollup/rollup-linux-ppc64-musl': 4.60.4
+ '@rollup/rollup-linux-riscv64-gnu': 4.60.4
+ '@rollup/rollup-linux-riscv64-musl': 4.60.4
+ '@rollup/rollup-linux-s390x-gnu': 4.60.4
+ '@rollup/rollup-linux-x64-gnu': 4.60.4
+ '@rollup/rollup-linux-x64-musl': 4.60.4
+ '@rollup/rollup-openbsd-x64': 4.60.4
+ '@rollup/rollup-openharmony-arm64': 4.60.4
+ '@rollup/rollup-win32-arm64-msvc': 4.60.4
+ '@rollup/rollup-win32-ia32-msvc': 4.60.4
+ '@rollup/rollup-win32-x64-gnu': 4.60.4
+ '@rollup/rollup-win32-x64-msvc': 4.60.4
fsevents: 2.3.3
- dependencies:
- queue-microtask: 1.2.3
-
-
-
- dependencies:
- shebang-regex: 3.0.0
-
-
-
-
- dependencies:
- cross-spawn: 7.0.6
- signal-exit: 4.1.0
-
-
- dependencies:
- ansi-regex: 5.0.1
-
-
dependencies:
'@jridgewell/gen-mapping': 0.3.13
@@ -2205,8 +1402,6 @@ snapshots:
tinyglobby: 0.2.15
ts-interface-checker: 0.1.13
-
dependencies:
thenify: 3.3.1
@@ -2221,8 +1416,13 @@ snapshots:
dependencies:
- fdir: 6.5.0([email protected])
- picomatch: 4.0.3
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.4
+
+ dependencies:
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.4
@@ -2230,15 +1430,11 @@ snapshots:
- dependencies:
- is-number: 7.0.0
-
dependencies:
bundle-require: 5.1.0([email protected])
cac: 6.7.14
@@ -2249,16 +1445,16 @@ snapshots:
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
picocolors: 1.1.1
- postcss-load-config: 6.0.1([email protected])
+ postcss-load-config: 6.0.1([email protected])
resolve-from: 5.0.0
- rollup: 4.54.0
+ rollup: 4.60.4
source-map: 0.7.6
sucrase: 3.35.1
tinyexec: 0.3.2
tinyglobby: 0.2.15
tree-kill: 1.2.2
optionalDependencies:
- postcss: 8.5.6
+ postcss: 8.5.15
typescript: 5.9.3
transitivePeerDependencies:
- jiti
@@ -2272,17 +1468,16 @@ snapshots:
-
dependencies:
cac: 6.7.14
debug: 4.4.3
es-module-lexer: 1.7.0
pathe: 1.1.2
- vite: 5.4.21(@types/[email protected])
+ vite: 6.4.2(@types/[email protected])([email protected])
transitivePeerDependencies:
- '@types/node'
+ - jiti
- less
- lightningcss
- sass
@@ -2291,20 +1486,26 @@ snapshots:
- sugarss
- supports-color
- terser
+ - tsx
+ - yaml
dependencies:
- esbuild: 0.21.5
- postcss: 8.5.6
- rollup: 4.54.0
+ esbuild: 0.27.2
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.4
+ postcss: 8.5.15
+ rollup: 4.60.4
+ tinyglobby: 0.2.16
optionalDependencies:
- '@types/node': 22.19.3
+ '@types/node': 22.19.19
fsevents: 2.3.3
+ lightningcss: 1.32.0
dependencies:
'@vitest/expect': 2.1.9
- '@vitest/mocker': 2.1.9([email protected](@types/[email protected]))
+ '@vitest/mocker': 2.1.9([email protected](@types/[email protected])([email protected]))
'@vitest/pretty-format': 2.1.9
'@vitest/runner': 2.1.9
'@vitest/snapshot': 2.1.9
@@ -2320,12 +1521,13 @@ snapshots:
tinyexec: 0.3.2
tinypool: 1.1.1
tinyrainbow: 1.2.0
- vite: 5.4.21(@types/[email protected])
- vite-node: 2.1.9(@types/[email protected])
+ vite: 6.4.2(@types/[email protected])([email protected])
+ vite-node: 2.1.9(@types/[email protected])([email protected])
why-is-node-running: 2.3.0
optionalDependencies:
- '@types/node': 22.19.3
+ '@types/node': 22.19.19
transitivePeerDependencies:
+ - jiti
- less
- lightningcss
- msw
@@ -2335,10 +1537,8 @@ snapshots:
- sugarss
- supports-color
- terser
-
- dependencies:
- isexe: 2.0.0
+ - tsx
+ - yaml
dependencies:
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index bb8407262..518912a08 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -1838,14 +1838,17 @@ export class SIEClient {
: undefined;
try {
- if (headers) {
- return new (
- WebSocket as unknown as {
- new (u: string, p?: string[], o?: { headers: Record<string, string> }): WebSocket;
- }
- )(url, [], { headers });
+ if (!headers) {
+ return new WebSocket(url);
}
- return new WebSocket(url);
+ // In Node, `WebSocket` resolves to the `ws` package which accepts
+ // a third `{ headers }` options argument. In browsers, the native
+ // WebSocket only takes `(url, protocols)` and the third arg is
+ // silently dropped. Use `Reflect.construct` with a runtime args
+ // array so the call site doesn't statically appear to pass
+ // superfluous trailing arguments to the lib.dom WebSocket type.
+ const args: unknown[] = [url, [], { headers }];
+ return Reflect.construct(WebSocket, args) as WebSocket;
} catch (error) {
if (headers) {
throw new SIEConnectionError(
diff --git a/packages/sie_ts_sdk/src/images.ts b/packages/sie_ts_sdk/src/images.ts
index 21838e2bb..1e94817f7 100644
--- a/packages/sie_ts_sdk/src/images.ts
+++ b/packages/sie_ts_sdk/src/images.ts
@@ -1,7 +1,7 @@
/**
* Image handling utilities for the SIE TypeScript SDK.
*
- * Per design.md Section 4.3, images are serialized as bytes for transport.
+ * Images are serialized as bytes for transport.
* This module handles conversion from various input formats to Uint8Array.
*
* Supported input formats:
@@ -33,7 +33,6 @@ export type ImageInput = Uint8Array | ArrayBuffer | Blob | string;
/**
* Wire format for images sent to the server.
- * Per design.md Section 4.3.
*/
export interface ImageWireFormat {
data: Uint8Array;
@@ -114,7 +113,7 @@ function base64ToBytes(base64: string): Uint8Array {
/**
* Convert image bytes to wire format for transport.
*
- * Per design.md Section 4.3, images are sent as:
+ * Images are sent as:
* `{ data: <bytes>, format: "jpeg" | "png" | "webp" }`
*
* @param input - Image data in any supported format
diff --git a/packages/sie_ts_sdk/src/msgpack.ts b/packages/sie_ts_sdk/src/msgpack.ts
index 2b0b5542f..298adbe6e 100644
--- a/packages/sie_ts_sdk/src/msgpack.ts
+++ b/packages/sie_ts_sdk/src/msgpack.ts
@@ -205,7 +205,8 @@ export function packMessage(data: unknown): Uint8Array {
function isNumpyArrayMap(
obj: unknown,
): obj is { nd: boolean; type: string; shape: number[]; data: Uint8Array } {
- if (typeof obj !== "object" || obj === null) {
+ // Check `obj === null` first: `typeof null` is also `"object"` in JS.
+ if (obj === null || typeof obj !== "object") {
return false;
}
const map = obj as Record<string, unknown>;
diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.ts
index 8cdaff0b9..aefb2ecd6 100644
--- a/packages/sie_ts_sdk/src/version.ts
+++ b/packages/sie_ts_sdk/src/version.ts
@@ -1 +1 @@
-export const SDK_VERSION = "0.4.1"; // x-release-please-version
+export const SDK_VERSION = "0.4.2"; // x-release-please-version
diff --git a/packages/sie_ts_sdk/tests/browser/index.html b/packages/sie_ts_sdk/tests/browser/index.html
index da7fdabc4..3bbe5862e 100644
--- a/packages/sie_ts_sdk/tests/browser/index.html
+++ b/packages/sie_ts_sdk/tests/browser/index.html
@@ -61,7 +61,7 @@
// Check that we can instantiate the client
const client = new SIEClient('http://localhost:8080');
- addLog('Client instantiated: ' + (client !== null));
+ addLog('Client instantiated: ' + (client instanceof SIEClient));
addLog('Client has encode method: ' + (typeof client.encode === 'function'));
addLog('Client has score method: ' + (typeof client.score === 'function'));
addLog('Client has extract method: ' + (typeof client.extract === 'function'));
diff --git a/packages/sie_ts_sdk/tests/internal.test.ts b/packages/sie_ts_sdk/tests/internal.test.ts
index be997217f..f7a95be16 100644
--- a/packages/sie_ts_sdk/tests/internal.test.ts
+++ b/packages/sie_ts_sdk/tests/internal.test.ts
@@ -313,8 +313,8 @@ describe("handleError (gateway / FastAPI bodies)", () => {
});
});
- // roadmap §3 item 1.4: /v1/embeddings returns the OpenAI {error:{message,
- // type,param,code}} envelope on every error path. A SIE SDK user hitting
+ // /v1/embeddings returns the OpenAI {error:{message,type,param,code}}
+ // envelope on every error path. A SIE SDK user hitting
// it directly must still get a typed error with the parsed `code`.
it("reads OpenAI {error:{type,param,code}} envelope (embeddings 4xx)", async () => {
const res = new Response(
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 83e16e95a..267b644e3 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -4,12 +4,23 @@ settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
+overrides:
+ esbuild: '>=0.25.0'
+ form-data: '>=4.0.4'
+ langsmith: '>=0.6.0'
+ protobufjs: '>=7.5.8'
+ qs: '>=6.15.2'
+ tar: '>=7.5.11'
+ uuid: '>=11.1.1'
+ vite: ^6.4.2
+ ws: '>=8.20.1'
+
importers:
.:
devDependencies:
typescript:
- specifier: ^5.7.2
+ specifier: ^5.9.3
version: 5.9.3
integrations/sie_ts_chroma:
@@ -22,17 +33,17 @@ importers:
specifier: ^1.9.4
version: 1.9.4
chromadb:
- specifier: ^1.9.0
+ specifier: ^1.10.5
tsup:
- specifier: ^8.3.5
+ specifier: ^8.5.1
typescript:
- specifier: ^5.7.2
+ specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.8
- version: 2.1.9(@types/[email protected])
+ specifier: ^2.1.9
+ version: 2.1.9(@types/[email protected])([email protected])
integrations/sie_ts_lancedb:
dependencies:
@@ -47,17 +58,17 @@ importers:
specifier: ^0.17.0
version: 0.17.0([email protected])
apache-arrow:
- specifier: ^18.0.0
+ specifier: ^18.1.0
version: 18.1.0
tsup:
- specifier: ^8.3.5
+ specifier: ^8.5.1
typescript:
- specifier: ^5.7.2
+ specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.8
- version: 2.1.9(@types/[email protected])
+ specifier: ^2.1.9
+ version: 2.1.9(@types/[email protected])([email protected])
integrations/sie_ts_langchain:
dependencies:
@@ -69,17 +80,17 @@ importers:
specifier: ^1.9.4
version: 1.9.4
'@langchain/core':
- specifier: ^0.3.0
+ specifier: ^0.3.80
tsup:
- specifier: ^8.3.5
+ specifier: ^8.5.1
typescript:
- specifier: ^5.7.2
+ specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.8
- version: 2.1.9(@types/[email protected])
+ specifier: ^2.1.9
+ version: 2.1.9(@types/[email protected])([email protected])
integrations/sie_ts_llamaindex:
dependencies:
@@ -91,42 +102,42 @@ importers:
specifier: ^1.9.4
version: 1.9.4
llamaindex:
- specifier: ^0.8.0
+ specifier: ^0.8.37
tsup:
- specifier: ^8.3.5
+ specifier: ^8.5.1
typescript:
- specifier: ^5.7.2
+ specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.8
- version: 2.1.9(@types/[email protected])
+ specifier: ^2.1.9
+ version: 2.1.9(@types/[email protected])([email protected])
packages/sie_ts_sdk:
dependencies:
'@msgpack/msgpack':
- specifier: ^3.0.0
+ specifier: ^3.1.3
version: 3.1.3
devDependencies:
'@biomejs/biome':
specifier: ^1.9.4
version: 1.9.4
'@playwright/test':
- specifier: ^1.57.0
- version: 1.57.0
+ specifier: ^1.60.0
+ version: 1.60.0
'@types/node':
- specifier: ^22.0.0
- version: 22.19.3
+ specifier: ^22.19.19
+ version: 22.19.19
tsup:
- specifier: ^8.3.5
+ specifier: ^8.5.1
typescript:
- specifier: ^5.7.2
+ specifier: ^5.9.3
version: 5.9.3
vitest:
- specifier: ^2.1.8
- version: 2.1.9(@types/[email protected])
+ specifier: ^2.1.9
+ version: 2.1.9(@types/[email protected])([email protected])
packages:
@@ -136,6 +147,16 @@ packages:
'@aws-crypto/[email protected]':
resolution: {integrity: sha512-IzSgsrxUcsrejQbPVilIKy16kAT52EwB6zSaI+M3xxIhKh5+aldEyvI+z6erM7TCLB2BJsFrtHjp6/4/sr+3dA==}
+ '@aws-crypto/[email protected]':
+ resolution: {integrity: sha512-nLbCWqQNgUiwwtFsen1AdzAtvuLRsQS8rYgMuxCrdKf9kOssamGLuPwyTY9wyYblNr9+1XM8v6zoDTPPSIeANg==}
+ engines: {node: '>=16.0.0'}
+
+ '@aws-crypto/[email protected]':
+ resolution: {integrity: sha512-+iWb8qaHLYKrNvGRbiYRHSdKRWhto5XlZUEBwDjYNf+ly5SVYG6zEoYIdxvf5R3zyeP16w4PLBn3rH1xc74Rag==}
+
+ '@aws-crypto/[email protected]':
+ resolution: {integrity: sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg==}
+
'@aws-crypto/[email protected]':
resolution: {integrity: sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==}
@@ -152,137 +173,133 @@ packages:
'@aws-crypto/[email protected]':
resolution: {integrity: sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-Sj+r1e1Hqn9/2Z3FYiOL1C7thHht3ZihEB2/yInY1hxA5WJtdWL+OKMd0m+rJy9ZzRWPYSDPFLql+NGtaMKNKQ==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-xYmNlcyqiBjUo5gcoKt73weZkHHAxcDYcHLAEJkPxJQFxr0lBSAefQLQv7wCKRCKQe9rxuMRnve7U7XSoVWCcg==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-N65uuvmLS1RGehAMOfyVtwYJ0Txk7GOyivnhNKPPB45adI15maZVFtKM5PzeKTODAZjseaVV9nG8s03baQeyCQ==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-FxVwuw86c2Mw4p+0tOtoE+1sDTk+eOBZD/NwwK+wwx1gHkdO/EYSv231O9A1YM8HPjUrI0vZ/hP/szckBxHW0A==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-6qNCIeaMzKzfqasy2nNRuYnMuaMebCcCPP4J2CVGkA8QYMbIVKPlkn9bpB20Vxe6H/r3jtCCLQaOJjVTx/6dXg==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-c6GoTcswgT8rO3Z6Vv3O7j958CVw+i56udpd6mkE8zlOwme9bN7uejo9T/05F3pg66BK5SQMc7O67VGpdKAMNg==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-DrZgDnF1lQZv75a52nFWs6MExihJF2GZB6ETZRqr6jMwhrk2kbJPUtvgbifwcL7AYmVqHQDJBrR/MqkwwFCpiw==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-ppamm04uoj3hhNO5IlQSs5D6rWX1fWkzcn6a4pZrojk8Y6ObY9wzLDdT/Eq3gv6O9hOebi9tYTNB8b8fQj9XJw==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-O+j43kTMoh0jIgXU5C68aA+KWqYCpQ4MiYMIW6WahHGiKOBfk/N1EEifZkY/BIYMNTipItyFI4RROQhZhT/TxA==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-P+QGozmXn2mZZI7sDgk+aUm+RTI61MPSFB+Ir2vjEjEbEsE4e7hYtzrDvAUxZy9ko81h53e11+F/GYlvwDkaOQ==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-475mkhGaWCr+Z52fOOVb/q2VHuNvqEDixlYIkeaO6xJ6t9qR0wpLt4hOQaR6zR1wfZV0SlE7d8RErdYq/PByog==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-f8ZRPoATqSVS1LW19KwiWn2/BSTdylXPznAjDI2r7d3+RT880/yRT9uBQhPE+Ba986LiMRvg1AhmFYDwNLk/0A==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-8dS55QHRxXgJlHkEYaCGZIhieCs9NU1HU1BcqQ4RfUdSsfRdxxktqUKgCnBnOOn0oD3PPA8cQOCAVgIyRb3Rfw==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-jjT0p0Y7KZtcvExYiPCLJnqM9lkXDV1KBEg/13OE2DXv/9batzlyJHVKUEnRNJccY0O2Sul17E1su38CgdBhGQ==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-u7twvZa1/6GWmPBZs6DbjlegCoNzNjBsMS/6fvh5quByYrcJr/uLd8YEr7S3UIq4kR/gSnHqcae7y2nL2bqZdg==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-+3fsKtWybe5BjKEUA3/07oh7Ayfd82IED2+gyyaVfS/4PU78E3TaOQxSGOJ1t7Imefoidw/ne9QA7apX8wEnJg==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-sDwtDnBSszUIbzbOORGh5gmXGl9aK25+BHb4gb1aVlqB+nNL2+IUEJA62+CE55lXSH8qXF90paivjK8tOHTwPA==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-gZFw5wBefCIPg9vpT+gV5FdhfNKhYTVDZa1IsZCcn3SRoYUOJ/E05vwIogkJoonqBL0ttBGi5vhthX7xceekRg==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-vdoZbNG2dt66I7EpN3fKCzi6fp9xjIiwEA/vVVgqO4wXCGw8rKPIdDUus4e13VvTr330uQs2W0UNg/7AgtquEQ==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-QqEGHfQeZgUDqh7zpqHufrZ8T644ELEWvB+4gUdewLyRw4IRF+6CJqeQuRWqucZdQzoQeMh7fNAD9BWxFAdNig==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-/KIz9kadwbeLy6SKvT79W81Y+hb/8LMDyeloA2zhouE28hmne+hLn0wNCQXAAupFFlYOAtZR2NTBs7HBAReJlg==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-3YCv52ExXIRz3LAVNysevd+s7akSpg9dl39v9LJ7dOQH+s5rHi3jMZYQyxwMmglxQGMuzYRfQ0o1VSP2UOlIRw==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-CBYHJ5ufp8HC4q+o7IJejCUctJXWaksgpmoFpXerbjAso7/Fg7LLUu9inXVOxlHKLlvYekDXjIUBXDJS2WYdgg==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-cXaozlgJCOwmE6D7x4npcPdyk7kiFZdrGjN3D6tXXtItJJMNGPafDfAJn4YQmciMooG/X+b0Y6RTqdVVMx26jg==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-dgnvwjMq5Y66WozzUzxNkCFap+umHUtqMMKlr8z/vl9NYMLem/WUbWNpFFOVFWquXikc+ewtpBMR4KEDXfZ+KA==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-YePoj5kQuPmE0MHnyftXCfsO8ZSBd2kDr50XEIUrdejSbGFlayYvUuCohdb8drhGhPm6b65o7H1eC26EZhwUvA==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-HSyfH4f3uG63enBz2KOg25lcEUNPffUVIWcjQCBMIntsojBAOOHcGjuwiKvhwL5tt4nqTAoTXTMZ+drKYM5IAg==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-Ys/JJe++8Z2Y5meR1taMBaVcrGBA0/XsVTQR+qOKZbdNyg+8Jlv5rYZSwh8SqEHY00goSOZy7PHzZ2rLNQxDLg==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-BBgKawVyfQZglEkNTuBBdC3azlyqNXsvvN4jPkWAiNYcY0x1BasaJFl+7u/HisfULstryweJq/dAvIZIxzlZaA==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-WWTJnV7eCKNi9PMJuKs2kMybOcJ1gi+xA8XLzbUTr0Dm1RKMnAxmtOpaU8FIve3tZ8LUssBCEscaNxudu3ZlMg==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-w1qfKrSKHf9b5a8O76yQ1t69u6NWuBjr5kBX+jRWFx/5mu6RLpqERXRpVJxfosbep7k3B+DSB5tZMZ82GKcJtQ==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-FhasMTBDBmMN7EEa1hUeHwo5p5Mv3Dm8w0VEbdXX/6ola/uyhRuJt8zGkH09mLTmab20USTzEpPqyqEoe1MqNg==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-D2H/WoxhAZNYX+IjkKTdOhOkWQaK0jjJrDBj56hKjU5c9ltQiaX/1PqJ4dfjHntEshJfu0w+E6XJ+/6A6ILBBA==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-sHiqIFg8o2ipT7t40B89Vj0ubSUtY6OSt/+Ee/OXhHch5K4+81zP2+QX8Lkc/nJ2QSmCySxOke7TEbmX69fe2g==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-50vcHu96XakQnIvlKJ1UoltrFODjsq2KvtTgHiPFteUS884lQnK5VC/8xd1Msz/1ONpLMzdCVproCQqhDTtMPQ==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-ot1kZ1JGHUxcXPOARhej/n/+Odfx9VPt60pNrUq8Lf/U2blIF3+uj5v56gw76VD70dZvrfeLNo9jKz6pQJfOlA==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-/KuCcS8b5TpQXkYOrPLYytrgxBhv81+5pChkOlhegbeHttjM69pyUpQVJqyfDM/A7wPLnDrzCAnk4zaAOkY0Nw==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-hkfspNUP4criAH6ton6BGKgnm5dZx+7bUOy1YqlTfejDeUPAM23D81q/IX+hdlS3KUsfwGz5ADTqZWKBEUpf4A==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-CBmixMY36JdAdt9ALgm7yVlvOXGUCHt9Z2kn5p9XVO5StO6HCH+cayV7YYV1CDLsXvVyebaXgBmif9wHoxCeNA==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-7PQvGNhtveKlvVqNahqWx5yrwxP7ecwAoB1dYBf8eKwfo2tzzCbNnW+q2nO3N066ktQaB4iBQbDRWtizm+amoQ==}
+ engines: {node: '>=20.0.0'}
+
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-Js2VYaCM269feB0cs0cGmlIhdOgT9aMqzdBx68lCy6kVCYfzr0T36ovUFDvfUmatkuBeyBJhCwaLBh7P8meH5Q==}
+ engines: {node: '>=20.0.0'}
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-9WpRUbINdGroV3HiZZIBoJvL2ndoWk39OfwxWs2otxByppJZNN14bg/lvCx5e8ggHUti7IBk5rb0nqQZ4m05pg==}
engines: {node: '>=14.0.0'}
deprecated: This package has moved to @smithy/protocol-http
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-V8iY3blh8l2iaOqXWW88HbkY5jDoWjH56jonprG/cpyqqCnprvpMUZWPWYJoI8rHRf2bqzZeql1slxG6EnKI7A==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-Few9FoQqOt/0KSvZYP+qdW0dfOhfQ9N+gl2UUDvCPW6mkPKHli9LMbKxWj+wZ5zKPaOoqxuR3Hhy3OTpndkfSw==}
+ engines: {node: '>=20.0.0'}
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-2xLJvSdzcZZAg0lsDLUAuSQuihzK0dcxIK7WmfuJeF7DGKJFmp9czQmz5f3qiDz6IDQzvgK1M9vtJSVCslJbyQ==}
engines: {node: '>=14.0.0'}
deprecated: This package has moved to @smithy/signature-v4
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-UCj7lQXODduD1myNJQkV+LYcGYJ9iiMggR8ow8Hva1g3A/Na5imNXzz6O67k7DAee0TYpy+gkNw+SizC6min8Q==}
- engines: {node: '>=18.0.0'}
-
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-wzWC2Nrt859ABk6UCAVY/WYEbAd7FjkdrQL6m24+tfmWYDNRByTJ9uOgU/kw9zqLCAwb//CPvrJdhqjTznWXAg==}
- engines: {node: '>=18.0.0'}
-
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-xwF9K24mZSxcxKS3UKQFeX/dPYkEps9wF1b+MGON7EvnbcucrJGyQyK1v1xFPn1aqXkBTFi+SZaMRx5E5YCVFw==}
- engines: {node: '>=18.0.0'}
-
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-nhmgKHnNV9K+i9daumaIz8JTLsIIML9PE/HUks5liyrjUzenjW/aHoc7WJ9/Td/gPZtayxFnXQSJRb/fDlBuJw==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-hG9YKApmZOw+drJ9Nuoaf/OvC8e5W1+3eoLeN5p2uVCZRWsv27teIS0b4kiH6Sfv3WMmamqYJxmE2WMwyp/L/A==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-exueuwxef0lUJRnGaVkNSC674eAiWU07ORhxBnevFFZEKisln+09Qrtw823iyv5I1N8T+wKfh95xvtWQrNKNQw==}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-kuBfgQVdcz5Bmapc4A13YbpVw/pXkesfhetcFYwbntqas8sF41OHyd4o28+/TG2ZQdHBsv90Lsu5y6oitvYCdg==}
+ engines: {node: '>=20.0.0'}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-ycbYCwqXk4gJGp0Oxkzf2KBeeGBdTxz559D41NJP8FlzSej1Gh7Rk40Zo6AyTfsNWkrl/kVi1t937OIzC5t+9Q==}
- engines: {node: '>=18.0.0'}
- peerDependencies:
- aws-crt: '>=1.0.0'
- peerDependenciesMeta:
- aws-crt:
- optional: true
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-WhlJNNINQB+9qtLtZJcpQdgZw3SCDCpXdUJP7cToGwHbCWCnRckGlc6Bx/OhWwIYFNAn+FIydY8SZ0QmVu3xTQ==}
+ engines: {node: '>=20.0.0'}
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-UvFa/vR+e19XookZF8RzFZBrw2EUkQWxiBW0yYQAhvk3C+QVGl0H3ouca8LDBlBfQKXwmW3huo/59H8rwb1wJw==}
- '@aws-sdk/[email protected]':
- resolution: {integrity: sha512-Ai5iiQqS8kJ5PjzMhWcLKN0G2yasAkvpnPlq2EnqlIMdB48HsizElt62qcktdxp4neRMyGkFq4NzgmDbXnhRiA==}
- engines: {node: '>=18.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-cDbrqvDS73whl6YAPSPq0U6whzG6UWI9PuWh0wrUuGoZexhWEqhdunbukV7iBoaWnFV1AODutM5hOD6rtn439g==}
+ engines: {node: '>=20.0.0'}
- resolution: {integrity: sha512-C0NBLsIqzDIae8HFw9YIrIBsbc0xTiOtt7fAukGPnqQ/+zZNaq+4jhuccltK0QuWHBnNm/a6kLIRA6GFiM10eg==}
+ resolution: {integrity: sha512-iY8yvjE0y651BixKNPgmv1WrQc+GZ142sb0z4gYnChDDY2YqI4P/jsSopBWrKfAt7LOJAkOXt7rC/hms+WclQQ==}
engines: {node: '>=18.0.0'}
- '@azure-rest/[email protected]':
- resolution: {integrity: sha512-EHaOXW0RYDKS5CFffnixdyRPak5ytiCtU7uXDcP/uiY+A6jFRwNGzzJBiznkCzvi5EYpY+YWinieqHb0oY916A==}
+ '@azure-rest/[email protected]':
+ resolution: {integrity: sha512-iuFKDm8XPzNxPfRjhyU5/xKZmcRDzSuEghXDHHk4MjBV/wFL34GmYVBZnn9wmuoLBeS1qAw9ceMdaeJBPcB1QQ==}
engines: {node: '>=20.0.0'}
@@ -297,9 +314,12 @@ packages:
resolution: {integrity: sha512-Nh5PhEOeY6PrnxNPsEHRr9eimxLwgLlpmguQaHKBinFYA/RU9+kOYVOQqOrTsCL+KSxrLLl1gD8Dk5BFW/7l/w==}
engines: {node: '>=20.0.0'}
- '@azure/[email protected]':
- resolution: {integrity: sha512-az9BkXND3/d5VgdRRQVkiJb2gOmDU8Qcq4GvjtBmDICNiQ9udFmDk4ZpSB5Qq1OmtDJGlQAfBaS4palFsazQ5g==}
+ '@azure/[email protected]':
+ resolution: {integrity: sha512-f1P96IB399YiN2ARYHP7EpZi3Bf3wH4SN2lGzrw7JVwm7bbsVYtf2iKSBwTywD2P62NOPZGHFSZi+6jjb75JuA==}
engines: {node: '>=20.0.0'}
+ peerDependencies:
+ '@azure/core-client': ^1.10.0
+ '@azure/core-rest-pipeline': ^1.22.0
resolution: {integrity: sha512-0YIpccoX8m/k00O7mDDMdJpbr6mf1yWo2dfmxt5A8XVZVVMz2SSKaEbMCeJRvgQ0IaSlqhjT47p4hVIRRy90xw==}
@@ -309,8 +329,8 @@ packages:
resolution: {integrity: sha512-YKWi9YuCU04B55h25cnOYZHxXYtEvQEbKST5vqRga7hWY9ydd3FZHdeQF8pyh+acWZvppw13M/LMGx0LABUVMA==}
engines: {node: '>=18.0.0'}
- '@azure/[email protected]':
- resolution: {integrity: sha512-MzHym+wOi8CLUlKCQu12de0nwcq9k9Kuv43j4Wa++CsCpJwps2eeBQwD2Bu8snkxTtDKDx4GwjuR9E8yC8LNrg==}
+ '@azure/[email protected]':
+ resolution: {integrity: sha512-Evs1INHo+jUjwHi1T6SG6Ua/LHOQBCLuKEEE6efIpt4ZOoNonaT1kP32GoOcdNDbfqsD2445CPri3MubBy5DEQ==}
engines: {node: '>=20.0.0'}
@@ -321,17 +341,17 @@ packages:
resolution: {integrity: sha512-XPArKLzsvl0Hf0CaGyKHUyVgF7oDnhKoP85Xv6M4StF/1AhfORhZudHtOyf2s+FcbuQ9dPRAjB8J2KvRRMUK2A==}
engines: {node: '>=20.0.0'}
- '@azure/[email protected]':
- resolution: {integrity: sha512-3LzLibuVgbhWEv6B9Hz7bMn0KAKKlr3Rn9xPulZ6Xx69GuwgWmQ4qmkrfYBBBFCJDQXoVAvVGBYkt9VlW8hmOg==}
+ '@azure/[email protected]':
+ resolution: {integrity: sha512-AWRj+yhw1lybutNcsHJ8syxWXnTLvc3CPwwdCwG1I0I71f25ZcBkxneTeoaB3X57+xl1nO+zJKUqfm0RhpGUFA==}
engines: {node: '>=20.0.0'}
- '@azure/[email protected]':
- resolution: {integrity: sha512-uWC0fssc+hs1TGGVkkghiaFkkS7NkTxfnCH+Hdg+yTehTpMcehpok4PgUKKdyCH+9ldu6FhiHRv84Ntqj1vVcw==}
+ '@azure/[email protected]':
+ resolution: {integrity: sha512-5C/2WD5Vb1lHnZS16dNQRPMjN6oV/Upba+C9nBIs15PmOi6A3ZGs4Lr2u60zw4S04gi+u3cEXiqTVP7M4Pz3kw==}
engines: {node: '>=20.0.0'}
- '@azure/[email protected]':
- resolution: {integrity: sha512-wRLVaroQtOqfg60cxkzUkGKrKMsCP6uYXAOomOIysSMyt1/YM0eUn9LqieAWM8DLcU4+07Fio2YGpPeqUbpP9w==}
- engines: {node: '>=18.0.0'}
+ '@azure/[email protected]':
+ resolution: {integrity: sha512-aCDidWuKY06LWQ4x7/8TIXK6iRqTaRWRL3t7T+LC+j1b07HtoIsOxP/tU90G4jCSBn5TAyUTCtA4MS/y5Hudaw==}
+ engines: {node: '>=20.0.0'}
resolution: {integrity: sha512-eDT7iXoBTRZ2n3fLiftuGJFD+yjkiB1GNqzU2KbY1TLYeXeSPVTVgn2eJ5vmRTZ11978jy2Kg2wI7xa9Tyr8ag==}
@@ -341,17 +361,17 @@ packages:
resolution: {integrity: sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA==}
engines: {node: '>=20.0.0'}
- '@azure/[email protected]':
- resolution: {integrity: sha512-bZ8Pta6YAbdd0o0PEaL1/geBsPrLEnyY/RDWqvF1PP9RUH8EMLvUMGoZFYS6jSlUan6KZ9IMTLCnwpWWpQRK/w==}
+ '@azure/[email protected]':
+ resolution: {integrity: sha512-zkGNYS3TwY8lUpPIafAmsFCYZbgFixY9y/LZB9GUg0IILoHTqpN26j5OrkL1AQThh/YdZsawe4iWXfp85lFVxg==}
engines: {node: '>=0.8.0'}
- '@azure/[email protected]':
- resolution: {integrity: sha512-shSDU7Ioecya+Aob5xliW9IGq1Ui8y4EVSdWGyI1Gbm4Vg61WpP95LuzcY214/wEjSn6w4PZYD4/iVldErHayQ==}
+ '@azure/[email protected]':
+ resolution: {integrity: sha512-hQjjsekAjB00cM1EmatWJlzhEoK2Qhz7Rj5gvM6tYf8iL7RM3tkxlpU9fG0+ofkulzg9AEEA6dIEnSmDr5ZqUA==}
engines: {node: '>=0.8.0'}
- '@azure/[email protected]':
- resolution: {integrity: sha512-lvuAwsDpPDE/jSuVQOBMpLbXuVuLsPNRwWCyK3/6bPlBk0fGWegqoZ0qjZclMWyQ2JNvIY3vHY7hoFmFmFQcOw==}
- engines: {node: '>=16'}
+ '@azure/[email protected]':
+ resolution: {integrity: sha512-toS+2AePxqyzb0YOKttDOOiSl3jrkK9aiqIvpurpis0O34QcIS5gToqrgT39p04Dpxw3YoUU0lxJKTpSFFfA6Q==}
+ engines: {node: '>=20'}
resolution: {integrity: sha512-4+Qw+qaGqnkdUCq/vEFzk/bkROogTvdbPb1fmI8poxNfDDN1q2WHxBmhI7CYwesrBj1yXC4i5E0aISBxZqZi0g==}
@@ -424,12 +444,15 @@ packages:
resolution: {integrity: sha512-Z9pEVyyHfglh8XAKrIASxdvORdei4pLUKDDGarqYvBkA9B9rKdqqdN+4I42Dz8paU5uscu8FwM5mc+Ly/U6jfA==}
engines: {node: '>=14.0.0'}
+ '@datastructures-js/[email protected]':
+ resolution: {integrity: sha512-PSBhJ2/SmeRPRHuBv7i/fHWIdSC3JTyq56qb+Rq0wjOagi0/fdV5/B/3Md5zFZus/W6OkSPMaxMKKMNMrSmubg==}
+
'@discordjs/[email protected]':
resolution: {integrity: sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==}
engines: {node: '>=18'}
- '@discordjs/[email protected]':
- resolution: {integrity: sha512-RDYrhmpB7mTvmCKcpj+pc5k7POKszS4E2O9TYc+U+Y4iaCP+r910QdO43qmpOja8LRr1RJ0b3U+CqVsnPqzf4w==}
+ '@discordjs/[email protected]':
+ resolution: {integrity: sha512-wwQdgjeaoYFiaG+atbqx6aJDpqW7JHAo0HrQkBTbYzM3/PJ3GweQIpgElNcGZ26DCUOXMyawYd0YF7vtr+fZXg==}
engines: {node: '>=18'}
'@discordjs/[email protected]':
@@ -440,299 +463,165 @@ packages:
resolution: {integrity: sha512-4B4OijXeVNOPZlYA2oEwWOTkzyltLao+xbotHQeqN++Rv27Y6s818+n2Qkp8q+Fxhn0t/5lA5X1Mxktud8eayQ==}
engines: {node: '>=14.17.0'}
- '@emnapi/[email protected]':
- resolution: {integrity: sha512-PVtJr5CmLwYAU9PZDMITZoR5iAOShYREoR45EyyLrbntV50mdePTgUn4AmOw90Ifcj+x2kRjdzr1HP3RrNiHGA==}
+ resolution: {integrity: sha512-3DkkN3FKJ++BQy8PE3LONoVSVBONG7hld9D+VqBp1Dcfw2PGSnWyg20NET5cJkiygWK2y2H1ra8GWk3yixzuuA==}
+ engines: {node: '>=18.18.2'}
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==}
- engines: {node: '>=12'}
- cpu: [ppc64]
- os: [aix]
+ '@emnapi/[email protected]':
+ resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==}
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [aix]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [android]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==}
engines: {node: '>=18'}
cpu: [arm64]
os: [android]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==}
- engines: {node: '>=12'}
- cpu: [arm]
- os: [android]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==}
engines: {node: '>=18'}
cpu: [arm]
os: [android]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [android]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==}
engines: {node: '>=18'}
cpu: [x64]
os: [android]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [darwin]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [darwin]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [darwin]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [darwin]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [freebsd]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==}
engines: {node: '>=18'}
cpu: [arm64]
os: [freebsd]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [freebsd]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==}
engines: {node: '>=18'}
cpu: [x64]
os: [freebsd]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [linux]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==}
engines: {node: '>=18'}
cpu: [arm64]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==}
- engines: {node: '>=12'}
- cpu: [arm]
- os: [linux]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==}
engines: {node: '>=18'}
cpu: [arm]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==}
- engines: {node: '>=12'}
- cpu: [ia32]
- os: [linux]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==}
engines: {node: '>=18'}
cpu: [ia32]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==}
- engines: {node: '>=12'}
- cpu: [loong64]
- os: [linux]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==}
engines: {node: '>=18'}
cpu: [loong64]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==}
- engines: {node: '>=12'}
- cpu: [mips64el]
- os: [linux]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==}
engines: {node: '>=18'}
cpu: [mips64el]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==}
- engines: {node: '>=12'}
- cpu: [ppc64]
- os: [linux]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==}
engines: {node: '>=18'}
cpu: [ppc64]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==}
- engines: {node: '>=12'}
- cpu: [riscv64]
- os: [linux]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==}
engines: {node: '>=18'}
cpu: [riscv64]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==}
- engines: {node: '>=12'}
- cpu: [s390x]
- os: [linux]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==}
engines: {node: '>=18'}
cpu: [s390x]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [linux]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==}
engines: {node: '>=18'}
cpu: [x64]
os: [linux]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==}
engines: {node: '>=18'}
cpu: [arm64]
os: [netbsd]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [netbsd]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==}
engines: {node: '>=18'}
cpu: [x64]
os: [netbsd]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openbsd]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [openbsd]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==}
engines: {node: '>=18'}
cpu: [x64]
os: [openbsd]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==}
engines: {node: '>=18'}
cpu: [arm64]
os: [openharmony]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [sunos]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==}
engines: {node: '>=18'}
cpu: [x64]
os: [sunos]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==}
- engines: {node: '>=12'}
- cpu: [arm64]
- os: [win32]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==}
engines: {node: '>=18'}
cpu: [arm64]
os: [win32]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==}
- engines: {node: '>=12'}
- cpu: [ia32]
- os: [win32]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==}
engines: {node: '>=18'}
cpu: [ia32]
os: [win32]
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==}
- engines: {node: '>=12'}
- cpu: [x64]
- os: [win32]
-
- '@esbuild/[email protected]':
- resolution: {integrity: sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==}
+ '@esbuild/[email protected]':
+ resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==}
engines: {node: '>=18'}
cpu: [x64]
os: [win32]
@@ -750,21 +639,12 @@ packages:
peerDependencies:
graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0
- resolution: {integrity: sha512-Iq8QQQ/7X3Sac15oB6p0FmUg/klxQvXLeileoqrTRGJYLV+/9tubbr9ipz0GKHjmXVsgFPo/+W+2cA8eNcR+XA==}
+ resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==}
engines: {node: '>=12.10.0'}
- resolution: {integrity: sha512-H9l79u4kJ2PVSxUNA08HMYAnUBLj9v6KjYQ7SQ71hOZcEXhShE/y5iQCesP8+6/Ik/7i2O0a10bPquIcYfufog==}
- engines: {node: ^8.13.0 || >=10.10.0}
-
- resolution: {integrity: sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==}
- engines: {node: '>=6'}
- hasBin: true
-
- resolution: {integrity: sha512-rc1hOQtjIWGxcxpb9aHAfLpIctjEnsDehj0DAiVfBlmT84uvR0uUtN2hEi/ecvWVjXUGf5qPF4qEgiLOx1YIMQ==}
+ resolution: {integrity: sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg==}
engines: {node: '>=6'}
hasBin: true
@@ -776,8 +656,8 @@ packages:
resolution: {integrity: sha512-9KsiorsdIK8+7VmlamAT7Uh90zxAhC/SeKaKc80v58JhtPYuwaJpmR/ST7XAUxrHAFqHTCoTH5aJnJDwSL6xIQ==}
engines: {node: '>=18'}
- '@huggingface/[email protected]':
- resolution: {integrity: sha512-asqfZ4GQS0hD876Uw4qiUb7Tr/V5Q+JZuo2L+BtdrD4U40QU58nIRq3ZSgAzJgT874VLjhGVacaYfrdpXtEvtA==}
+ '@huggingface/[email protected]':
+ resolution: {integrity: sha512-uWTG+l3VJRsl7EXxYizuL3P+cCPoc3cRqbWWRcQN0FhejRfbdq0RNhCmbY/YDtnTcz9icdLYuLDjsnz4d8JMuw==}
engines: {node: '>=18'}
'@huggingface/[email protected]':
@@ -786,8 +666,8 @@ packages:
'@huggingface/[email protected]':
resolution: {integrity: sha512-tsTk4zVjImqdqjS8/AOZg2yNLd1z9S5v+7oUPpXaasDRwEDhB+xnglK1k5cad26lL5/ZIaeREgWWy0bs9y9pPA==}
- resolution: {integrity: sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==}
+ resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
engines: {node: '>=18'}
@@ -994,7 +874,6 @@ packages:
'@lancedb/[email protected]':
resolution: {integrity: sha512-AgQ4dqHBjoEpVdND5tmzhy0OJxwP4gJnEjOz3jVh7ip+8EYhR44wO6XbEhpxvvGfXyyepDrulo3bpL1323eNSg==}
engines: {node: '>= 18'}
- cpu: [x64, arm64]
os: [darwin, linux, win32]
peerDependencies:
apache-arrow: '>=15.0.0 <=18.1.0'
@@ -1135,26 +1014,29 @@ packages:
resolution: {integrity: sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==}
hasBin: true
- '@mistralai/[email protected]':
- resolution: {integrity: sha512-6/BVj2mcaggYbpMzNSxtqtM2Tv/Jb5845XFd2CMYFO+O5VBkX70iLjtkBBTI4JFhh1l9vTCIMYXBVOjLoBVHGQ==}
+ '@mistralai/[email protected]':
+ resolution: {integrity: sha512-fb995eiz3r0KsBGtRjFV+/iLbX+UpfalxpF+YitT3R6ukrPD4PN+FGwwmYcRFhNAzVzDUtTVxQYnjQWEnwV5nw==}
'@mixedbread-ai/[email protected]':
resolution: {integrity: sha512-NJiY6BVPR+s/DTzUPQS1Pv418trOmII/8hftmIqxXlYaKbIrgJimQfwCW9M6Y21YPcMA8zTQGYZHm4IWlMjIQw==}
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
- '@mongodb-js/[email protected]':
- resolution: {integrity: sha512-p7X/ytJDIdwUfFL/CLOhKgdfJe1Fa8uw9seJYvdOmnP9JBWGWHW69HkOixXS6Wy9yvGf1MbhcS6lVmrhy4jm2g==}
+ '@mongodb-js/[email protected]':
+ resolution: {integrity: sha512-o9rAHc0IpIjuPSxRutWpE1F62x7n+4mVS4rCNHkzhIUMQcc18bb6xEq5wd2NdN0WjepIyXIppRshYI2kQDOZVA==}
'@msgpack/[email protected]':
resolution: {integrity: sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==}
engines: {node: '>= 18'}
+ '@nodable/[email protected]':
+ resolution: {integrity: sha512-Pig3HxDIoMgjdEH8OCf/dkcTmLFjJRjWuq8jSnklu284/TKOPibSRERmOykiwmyXTtv61mP+44f3GMx0tLAyjg==}
+
'@notionhq/[email protected]':
resolution: {integrity: sha512-repLjfvmiwZ/oKAULpudXZ67VnXaGpr+AbzRXOntO89v8kslVlUfZX/VLgKRzQ0gRWGBabtFp+5YoTRuhQp6jA==}
engines: {node: '>=18'}
- '@opentelemetry/[email protected]':
- resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==}
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==}
engines: {node: '>=8.0.0'}
'@petamoriken/[email protected]':
@@ -1164,8 +1046,8 @@ packages:
resolution: {integrity: sha512-WoVsbvmCgvZfjm/nCasJXuQ/tw0es5BpedLHvRScAm6xJ/nL07s3B0TrsM8m8rACTiUgbdYsdLY1W6cEBhS9xA==}
engines: {node: '>=18.0.0'}
- '@playwright/[email protected]':
- resolution: {integrity: sha512-6TyEnHgd6SArQO8UO2OMTxshln3QMWBtPGrOCgs3wVEmQmwyuNtB10IZMfmYDE0riwNR1cu4q+pPcxMVtaG3TA==}
+ '@playwright/[email protected]':
+ resolution: {integrity: sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==}
engines: {node: '>=18'}
hasBin: true
@@ -1175,20 +1057,20 @@ packages:
'@protobufjs/[email protected]':
resolution: {integrity: sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==}
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==}
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==}
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==}
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==}
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==}
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==}
'@protobufjs/[email protected]':
resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==}
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==}
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-pa0vFRuws4wkvaXKK1uXZMAwAX4/t8ANaJo45iw/oQHNQ9q5xUzwgFmVJGXiga2BeN+zpX7Vf9vmsiIa2J+MUw==}
'@protobufjs/[email protected]':
resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==}
@@ -1196,11 +1078,11 @@ packages:
'@protobufjs/[email protected]':
resolution: {integrity: sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==}
- '@protobufjs/[email protected]':
- resolution: {integrity: sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==}
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==}
- '@qdrant/[email protected]':
- resolution: {integrity: sha512-Zm4wEZURrZ24a+Hmm4l1QQYjiz975Ep3vF0yzWR7ICGcxittNz47YK2iBOk8kb8qseCu8pg7WmO1HOIsO8alvw==}
+ '@qdrant/[email protected]':
+ resolution: {integrity: sha512-/0dqX5uV9chC1DnYSnU4gNMrDqse/pt6hHg3Rqqpl5isH7xl1xSNvffjzBoxycDD79luWn7Ho6Rh/61sOs5DNw==}
engines: {node: '>=18.17.0', pnpm: '>=8'}
peerDependencies:
typescript: '>=4.7'
@@ -1209,113 +1091,128 @@ packages:
resolution: {integrity: sha512-oQG/FejNpItrxRHoyctYvT3rwGZOnK4jr3JdppO/c78ktDvkWiPXPHNsrDf33K9sZdRb6PR7gi4noIapu5q4HA==}
engines: {node: '>=18.0.0', pnpm: '>=8'}
- '@rollup/[email protected]':
- resolution: {integrity: sha512-OywsdRHrFvCdvsewAInDKCNyR3laPA2mc9bRYJ6LBp5IyvF3fvXbbNR0bSzHlZVFtn6E0xw2oZlyjg4rKCVcng==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-F5QXMSiFebS9hKZj02XhWLLnRpJ3B3AROP0tWbFBSj+6kCbg5m9j5JoHKd4mmSVy5mS/IMQloYgYxCuJC0fxEQ==}
cpu: [arm]
os: [android]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-Skx39Uv+u7H224Af+bDgNinitlmHyQX1K/atIA32JP3JQw6hVODX5tkbi2zof/E69M1qH2UoN3Xdxgs90mmNYw==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-GxxTKApUpzRhof7poWvCJHRF51C67u1R7D6DiluBE8wKU1u5GWE8t+v81JvJYtbawoBFX1hLv5Ei4eVjkWokaw==}
cpu: [arm64]
os: [android]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-k43D4qta/+6Fq+nCDhhv9yP2HdeKeP56QrUUTW7E6PhZP1US6NDqpJj4MY0jBHlJivVJD5P8NxrjuobZBJTCRw==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-tua0TaJxMOB1R0V0RS1jFZ/RpURFDJIOR2A6jWwQeawuFyS4gBW+rntLRaQd0EQ4bd6Vp44Z2rXW+YYDBsj6IA==}
cpu: [arm64]
os: [darwin]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-cOo7biqwkpawslEfox5Vs8/qj83M/aZCSSNIWpVzfU2CYHa2G3P1UN5WF01RdTHSgCkri7XOlTdtk17BezlV3A==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-CSKq7MsP+5PFIcydhAiR1K0UhEI1A2jWXVKHPCBZ151yOutENwvnPocgVHkivu2kviURtCEB6zUQw0vs8RrhMg==}
cpu: [x64]
os: [darwin]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-miSvuFkmvFbgJ1BevMa4CPCFt5MPGw094knM64W9I0giUIMMmRYcGW/JWZDriaw/k1kOBtsWh1z6nIFV1vPNtA==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-+O8OkVdyvXMtJEciu2wS/pzm1IxntEEQx3z5TAVy4l32G0etZn+RsA48ARRrFm6Ri8fvqPQfgrvNxSjKAbnd3g==}
cpu: [arm64]
os: [freebsd]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-KGXIs55+b/ZfZsq9aR026tmr/+7tq6VG6MsnrvF4H8VhwflTIuYh+LFUlIsRdQSgrgmtM3fVATzEAj4hBQlaqQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-Iw3oMskH3AfNuhU0MSN7vNbdi4me/NiYo2azqPz/Le16zHSa+3RRmliCMWWQmh4lcndccU40xcJuTYJZxNo/lw==}
cpu: [x64]
os: [freebsd]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-EHMUcDwhtdRGlXZsGSIuXSYwD5kOT9NVnx9sqzYiwAc91wfYOE1g1djOEDseZJKKqtHAHGwnGPQu3kytmfaXLQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-EIPRXTVQpHyF8WOo219AD2yEltPehLTcTMz2fn6JsatLYSzQf00hj3rulF+yauOlF9/FtM2WpkT/hJh/KJFGhA==}
cpu: [arm]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-+pBrqEjaakN2ySv5RVrj/qLytYhPKEUwk+e3SFU5jTLHIcAtqh2rLrd/OkbNuHJpsBgxsD8ccJt5ga/SeG0JmA==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-J3Yh9PzzF1Ovah2At+lHiGQdsYgArxBbXv/zHfSyaiFQEqvNv7DcW98pCrmdjCZBrqBiKrKKe2V+aaSGWuBe/w==}
cpu: [arm]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-NSqc7rE9wuUaRBsBp5ckQ5CVz5aIRKCwsoa6WMF7G01sX3/qHUw/z4pv+D+ahL1EIKy6Enpcnz1RY8pf7bjwng==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-BFDEZMYfUvLn37ONE1yMBojPxnMlTFsdyNoqncT0qFq1mAfllL+ATMMJd8TeuVMiX84s1KbcxcZbXInmcO2mRg==}
cpu: [arm64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-gr5vDbg3Bakga5kbdpqx81m2n9IX8M6gIMlQQIXiLTNeQW6CucvuInJ91EuCJ/JYvc+rcLLsDFcfAD1K7fMofg==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-pc9EYOSlOgdQ2uPl1o9PF6/kLSgaUosia7gOuS8mB69IxJvlclko1MECXysjs5ryez1/5zjYqx3+xYU0TU6R1A==}
cpu: [arm64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-gsrtB1NA3ZYj2vq0Rzkylo9ylCtW/PhpLEivlgWe0bpgtX5+9j9EZa0wtZiCjgu6zmSeZWyI/e2YRX1URozpIw==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-NxnomyxYerDh5n4iLrNa+sH+Z+U4BMEE46V2PgQ/hoB909i8gV1M5wPojWg9fk1jWpO3IQnOs20K4wyZuFLEFQ==}
+ cpu: [loong64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-nbJnQ8a3z1mtmrwImCYhc6BGpThAyYVRQxw9uKSKG4wR6aAYno9sVjJ0zaZcW9BPJX1GbrDPf+SvdWjgTuDmnw==}
cpu: [loong64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-y3qNOfTBStmFNq+t4s7Tmc9hW2ENtPg8FeUD/VShI7rKxNW7O4fFeaYbMsd3tpFlIg1Q8IapFgy7Q9i2BqeBvA==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-2EU6acNrQLd8tYvo/LXW535wupT3m6fo7HKo6lr7ktQoItxTyOL1ZCR/GfGCuXl2vR+zmfI6eRXkSemafv+iVg==}
cpu: [ppc64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-89sepv7h2lIVPsFma8iwmccN7Yjjtgz0Rj/Ou6fEqg3HDhpCa+Et+YSufy27i6b0Wav69Qv4WBNl3Rs6pwhebQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-WeBtoMuaMxiiIrO2IYP3xs6GMWkJP2C0EoT8beTLkUPmzV1i/UcOSVw1d5r9KBODtHKilG5yFxsGRnBbK3wJ4A==}
+ cpu: [ppc64]
+ os: [linux]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-FJHFfqpKUI3A10WrWKiFbBZ7yVbGT4q4B5o1qKFFojqpaYoh9LrQgqWCmmcxQzVSXYtyB5bzkXrYzlHTs21MYA==}
cpu: [riscv64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-ZcU77ieh0M2Q8Ur7D5X7KvK+UxbXeDHwiOt/CPSBTI1fBmeDMivW0dPkdqkT4rOgDjrDDBUed9x4EgraIKoR2A==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-mcEl6CUT5IAUmQf1m9FYSmVqCJlpQ8r8eyftFUHG8i9OhY7BkBXSUdnLH5DOf0wCOjcP9v/QO93zpmF1SptCCw==}
cpu: [riscv64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-2AdWy5RdDF5+4YfG/YesGDDtbyJlC9LHmL6rZw6FurBJ5n4vFGupsOBGfwMRjBYH7qRQowT8D/U4LoSvVwOhSQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-ynt3JxVd2w2buzoKDWIyiV1pJW93xlQic1THVLXilz429oijRpSHivZAgp65KBu+cMcgf1eVVjdnTLvPxgCuoQ==}
cpu: [s390x]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-WGt5J8Ij/rvyqpFexxk3ffKqqbLf9AqrTBbWDk7ApGUzaIs6V+s2s84kAxklFwmMF/vBNGrVdYgbblCOFFezMQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-Boiz5+MsaROEWDf+GGEwF8VMHGhlUoQMtIPjOgA5fv4osupqTVnJteQNKJwUcnUog2G55jYXH7KZFFiJe0TEzQ==}
cpu: [x64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-JzQmb38ATzHjxlPHuTH6tE7ojnMKM2kYNzt44LO/jJi8BpceEC8QuXYA908n8r3CNuG/B3BV8VR3Hi1rYtmPiw==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-+qfSY27qIrFfI/Hom04KYFw3GKZSGU4lXus51wsb5EuySfFlWRwjkKWoE9emgRw/ukoT4Udsj4W/+xxG8VbPKg==}
cpu: [x64]
os: [linux]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-huT3fd0iC7jigGh7n3q/+lfPcXxBi+om/Rs3yiFxjvSxbSB6aohDFXbWvlspaqjeOh+hx7DDHS+5Es5qRkWkZg==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-VpTfOPHgVXEBeeR8hZ2O0F3aSso+JDWqTWmTmzcQKted54IAdUVbxE+j/MVxUsKa8L20HJhv3vUezVPoquqWjA==}
+ cpu: [x64]
+ os: [openbsd]
+
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-IPOsh5aRYuLv/nkU51X10Bf75Bsf6+gZdx1X+QP5QM6lIJFHHqbHLG0uJn/hWthzo13UAc2umiUorqZy3axoZg==}
cpu: [arm64]
os: [openharmony]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-c2V0W1bsKIKfbLMBu/WGBz6Yci8nJ/ZJdheE0EwB73N3MvHYKiKGs3mVilX4Gs70eGeDaMqEob25Tw2Gb9Nqyw==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-4QzE9E81OohJ/HKzHhsqU+zcYYojVOXlFMs1DdyMT6qXl/niOH7AVElmmEdUNHHS/oRkc++d5k6Vy85zFs0DEw==}
cpu: [arm64]
os: [win32]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-woEHgqQqDCkAzrDhvDipnSirm5vxUXtSKDYTVpZG3nUdW/VVB5VdCYA2iReSj/u3yCZzXID4kuKG7OynPnB3WQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-zTPgT1YuHHcd+Tmx7h8aml0FWFVelV5N54oHow9SLj+GfoDy/huQ+UV396N/C7KpMDMiPspRktzM1/0r1usYEA==}
cpu: [ia32]
os: [win32]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-dzAc53LOuFvHwbCEOS0rPbXp6SIhAf2txMP5p6mGyOXXw5mWY8NGGbPMPrs4P1WItkfApDathBj/NzMLUZ9rtQ==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-DRS4G7mi9lJxqEDezIkKCaUIKCrLUUDCUaCsTPCi/rtqaC6D/jjwslMQyiDU50Ka0JKpeXeRBFBAXwArY52vBw==}
cpu: [x64]
os: [win32]
- '@rollup/[email protected]':
- resolution: {integrity: sha512-hYT5d3YNdSh3mbCU1gwQyPgQd3T2ne0A3KG8KSBdav5TiBg6eInVmV+TeR5uHufiIgSFg0XsOWGW5/RhNcSvPg==}
+ '@rollup/[email protected]':
+ resolution: {integrity: sha512-QVTUovf40zgTqlFVrKA1uXMVvU2QWEFWfAH8Wdc48IxLvrJMQVMBRjuQyUpzZCDkakImib9eVazbWlC6ksWtJw==}
cpu: [x64]
os: [win32]
@@ -1330,35 +1227,19 @@ packages:
'@selderee/[email protected]':
resolution: {integrity: sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ==}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-rzMY6CaKx2qxrbYbqjXWS0plqEy7LOdKHS0bg4ixJ6aoGDPNUcLWk/FRNuCILh7GKLG9TFUXYYeQQldMBBwuyw==}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-Kt8phUg45M15EjhYAbZ+fFikYneijLu9Liugz8ZsYz2i8j0hzGv27LWKpEHYRfvj+LyCOSijpcR/2i8RouV+cA==}
engines: {node: '>=18.0.0'}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-HAGoUAFYsUkoSckuKbCPayECeMim8pOu+yLy1zOxt1sifzEbrsRpYa+mKcMdiHKMeiqOibyPG0sFJnmaV/OGEg==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-WsSHCPq/neD5G/MkK4csLI5Y5Pkd9c1NMfpYEKeghSGaD4Ja1qLIohRQf2D5c1Uy5aXp76DeKHkzWZ9KAlHroQ==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-CmduWdCiILCRNbQWFR0OcZlUPVtyE49Sr8yYL0rZQ4D/wKxiNzBNS/YHemvnbkIWj623fplgkexUd/c9CAKdoA==}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-yiF8xHpdkaTfzLVqFzsP6WvNghEK+qZzLYWFD13L2SsFhbXwBGlxdocKF95qjr7s5lE5NRage+EJFK4mAsx88Q==}
engines: {node: '>=18.0.0'}
'@smithy/[email protected]':
resolution: {integrity: sha512-3tEbUb8t8an226jKB6V/Q2XU/J53lCwCzULuBPEaF4JjSh+FlCMp7TmogE/Aij5J9DwlsZ4VAD/IRDuQ/0ZtMw==}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-h/Fi+o7mti4n8wx1SR6UHWLaakwHRx29sizvp8OOm7iqwKGFneT06GCSFhml6Bha5BT6ot5pj3CYZnCHhGC2Rg==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-PU/JWLTBCV1c8FtB8tEFnY4eV1tSfBc7bDBADHfn1K+uRbPgSJ9jnJp0hyjiFN2PMdPzxsf1Fdu0eo9fJ760Xw==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-ncvgCr9a15nPlkhIUx3CU4d7E7WEuVJOV7fS7nnK2hLtPK9tYRBkMHQbhXU1VvvKeBm/O0x26OEoBq+ngFpOEQ==}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-SK3VMeH0fibgdTg2QeB+O4p7Yy/2E5HBOHJeC58FshkDdeuX8lOgO7PfjYfLyPLP1ch55j91cQqKBzDS0mRjSQ==}
engines: {node: '>=18.0.0'}
'@smithy/[email protected]':
@@ -1369,100 +1250,28 @@ packages:
resolution: {integrity: sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==}
engines: {node: '>=14.0.0'}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-GszfBfCcvt7kIbJ41LuNa5f0wvQCHhnGx/aDaZJCCT05Ld6x6U2s0xsc/0mBFONBZjQJp2U/0uSJ178OXOwbhg==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-gpLspUAoe6f1M6H0u4cVuFzxZBrsGZmjx2O9SigurTx4PbntYa4AJ+o0G0oGm1L2oSX6oBhcGHwrfJHup2JnJg==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-MqbXK6Y9uq17h+4r0ogu/sBT6V/rdV+5NvYL7ZV444BKfQygYe8wAhDrVXagVebN6w2RE0Fm245l69mOsPGZzg==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-8rDGYen5m5+NV9eHv9ry0sqm2gI6W7mc1VSFMtn6Igo25S507/HaOX9LTHAS2/J32VXD0xSzrY0H5FJtOMS4/w==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-bsOT0rJ+HHlZd9crHoS37mt8qRRN/h9jRve1SXUhVbkRzu0QaNYZp1i1jha4n098tsvROjcwfLlfvcFuJSXEsw==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-7r58wq8sdOcrwWe+klL9y3bc4GW1gnlfnFOuL7CXa7UzfhzhxKuzNdtqgzmTV+53lEp9NXh5hY/S4UgjLOzPfw==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-NELpdmBOO6EpZtWgQiHjoShs1kmweaiNuETUpuup+cmm/xJYjT4eUjfhrXRP4jCOaAsS3c3yPsP3B+K+/fyPCQ==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-jmNYKe9MGGPoSl/D7JDDs1C8b3dC8f/w78LbaVfoTtWy4xAd5dfjaFG9c9PWPihY4ggMQNQSMtzU77CNgAJwmA==}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-3dA9TQ+ybRSZ/m0wnbZhiBy4Dezjgq1Ib/ZZrYTpJDBgpoLLU/SDzZc/g0x0MNAdOJe1wPcM+x2PBRmoOur+Sw==}
engines: {node: '>=18.0.0'}
'@smithy/[email protected]':
resolution: {integrity: sha512-GfGfruksi3nXdFok5RhgtOnWe5f6BndzYfmEXISD+5gAGdayFGpjWu5pIqIweTudMtse20bGbc+7MFZXT1Tb8Q==}
engines: {node: '>=14.0.0'}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-1r07pb994I20dD/c2seaZhoCuNYm0rWrvBxhCQ70brNh11M5Ml2ew6qJVo0lclB3jMIXirD4s2XRXRe7QEi0xA==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-eKONSywHZxK4tBxe2lXEysh8wbBdvDWiA+RIuaxZSgCMmA0zMgoDpGLJhnyj+c0leOQprVnXOmcB4m+W9Rw7sg==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-3X5ZvzUHmlSTHAXFlswrS6EGt8fMSIxX/c3Rm1Pni3+wYWB6cjGocmRIoqcQF9nU5OgGmL0u7l9m44tSUpfj9w==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-YB7oCbukqEb2Dlh3340/8g8vNGbs/QsNNRms+gv3N2AtZz9/1vSBx6/6tpwQpZMEJFs7Uq8h4mmOn48ZZ72MkA==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-M7iUUff/KwfNunmrgtqBfvZSzh3bmFgv/j/t1Y1dQ+8dNo34br1cqVEqy6v0mYEgi0DkGO7Xig0AnuOaEGVlcg==}
- engines: {node: '>=18.0.0'}
-
'@smithy/[email protected]':
resolution: {integrity: sha512-fDo3m7YqXBs7neciOePPd/X9LPm5QLlDMdIC4m1H6dgNLnXfLMFNIxEfPyohGA8VW9Wn4X8lygnPSGxDZSmp0Q==}
engines: {node: '>=14.0.0'}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-9oNUlqBlFZFOSdxgImA6X5GFuzE7V2H7VG/7E70cdLhidFbdtvxxt81EHgykGK5vq5D3FafH//X+Oy31j3CKOg==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-D5z79xQWpgrGpAHb054Fn2CCTQZpog7JELbVQ6XAvXs5MNKWf28U9gzSBlJkOyMl9LA1TZEjRtwvGXfP0Sl90g==}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-QBJKWGqIknH0dc9LWpfH1mkdokAx6iXYN3UcQ3eY6uIEyScuoQAhfl94ge7ozUy9WgFUdE8xsvwBjaYBbWmPNA==}
engines: {node: '>=18.0.0'}
'@smithy/[email protected]':
resolution: {integrity: sha512-z1r00TvBqF3dh4aHhya7nz1HhvCg4TRmw51fjMrh5do3h+ngSstt/yKlNbHeb9QxJmFbmN8KEVSWgb1bRvfEoA==}
engines: {node: '>=14.0.0'}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-mlrmL0DRDVe3mNrjTcVcZEgkFmufITfUAPBEA+AHYiIeYyJebso/He1qLbP3PssRe22KUzLRpQSdBPbXdgZ2VA==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-/RLtVsRV4uY3qPWhBDsjwahAtt3x2IsMGnP5W1b2VZIe+qgCqkLxI1UOHDZp1Q1QSOrdOR32MF3Ph2JfWT1VHg==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-GkXZ59JfyxsIwNTWFnjmFEI8kZpRNIBfxKjv09+nkAWPt/4aGaEWMM04m4sxgNVWkbt2MdSvE3KF/PfX4nFedQ==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-Fkoh/I76szMKJnBXWPdFkQJl2r9SjPt3cMzLdOB6eJ4Pnpas8hVoWPYemX/peO0yrrvldgCUVJqOAjUrOLjbxg==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-h53dz/pISVrVrfxV1iqXlx5pRg3V2YWFcSQyPyXZRrZoZj4R4DeWRDo1a7dd3CPTcFi3kE+98tuNyD2axyZReA==}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-P+otAxbV4CqBybp7EkcJCrig63yE2E7PuNVOmilVMRcx/O+QDzGULTrKsq4DV13gSfak9ObPrWaHl/9bL5YcWw==}
engines: {node: '>=18.0.0'}
'@smithy/[email protected]':
@@ -1473,58 +1282,18 @@ packages:
resolution: {integrity: sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==}
engines: {node: '>=14.0.0'}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-YEjpl6XJ36FTKmD+kRJJWYvrHeUvm5ykaUS5xK+6oXffQPHeEM4/nXlZPe+Wu0lsgRUcNZiliYNh/y7q9c2y6Q==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-/eiSP3mzY3TsvUOYMeL4EqUX6fgUOj2eUOU4rMMgVbq67TiRLyxT7Xsjxq0bW3OwuzK009qOwF0L2OgJqperAQ==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-3a4+4mhf6VycEJyHIQLypRbiwG6aJvbQAeRAVXydMmfweEPnLLabRbdyo/Pjw8Rew9vjsh5WCdhmDaHkQnhhhA==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-s4ILhyAvVqhMDYREeTS68R43B1V5aenV5q/V1QpRQJkCXib5BPRo4s7uNdzGtIKxaPHCfU/8YkvPAEvTpxgspg==}
- engines: {node: '>=18.0.0'}
-
'@smithy/[email protected]':
resolution: {integrity: sha512-7UtIE9eH0u41zpB60Jzr0oNCQ3hMJUabMcKRUVjmyHTXiWDE4vjSqN6qlih7rCNeKGbioS7f/y2Jgym4QZcKFg==}
engines: {node: '>=14.0.0'}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==}
- engines: {node: '>=18.0.0'}
-
'@smithy/[email protected]':
resolution: {integrity: sha512-6hhckcBqVgjWAqLy2vqlPZ3rfxLDhFWEmM7oLh2POGvsi7j0tHkbN7w4DFhuBExVJAbJ/qqxqZdRY6Fu7/OezQ==}
engines: {node: '>=14.0.0'}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-i1IkpbOae6NvIKsEeLLM9/2q4X+M90KV3oCFgWQI4q0Qz+yUZvsr+gZPdAEAtFhWQhAHpTsJO8DRJPuwVyln+w==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-SvDdsQyF5CIASa4EYVT02LukPHVzAgUA4kMAuZ97QJc2BpAqZfA4PINB8/KOoCXEw9tsuv/jQjMeaHFvxdLNGg==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-ZnnBhTapjM0YPGUSmOs0Mcg/Gg87k503qG4zU2v/+Js2Gu+daKOJMeqcQns8ajepY8tgzzfYxl6kQyZKml6O2w==}
- engines: {node: '>=18.0.0'}
-
'@smithy/[email protected]':
resolution: {integrity: sha512-/jL/V1xdVRt5XppwiaEU8Etp5WHZj609n0xMTuehmCqdoOFbId1M+aEeDWZsQ+8JbEB/BJ6ynY2SlYmOaKtt8w==}
engines: {node: '>=14.0.0'}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-igZpCKV9+E/Mzrpq6YacdTQ0qTiLm85gD6N/IrmyDvQFA4UnU3d5g3m8tMT/6zG/vVkWSU+VxeUyGonL62DuxA==}
- engines: {node: '>=18.0.0'}
-
'@smithy/[email protected]':
resolution: {integrity: sha512-p/MYV+JmqmPyjdgyN2UxAeYDj9cBqCjp0C/NsTWnnjoZUVqoeZ6IrW915L9CAKWVECgv9lVQGc4u/yz26/bI1A==}
engines: {node: '>=14.0.0'}
@@ -1533,23 +1302,11 @@ packages:
resolution: {integrity: sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==}
engines: {node: '>=14.0.0'}
- '@smithy/[email protected]':
- resolution: {integrity: sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-vHJFXi9b7kUEpHWUCY3Twl+9NPOZvQ0SAi+Ewtn48mbiJk4JY9MZmKQjGB4SCvVb9WPiSphZJYY6RIbs+grrzw==}
- engines: {node: '>=18.0.0'}
-
- '@smithy/[email protected]':
- resolution: {integrity: sha512-4aUIteuyxtBUhVdiQqcDhKFitwfd9hqoSDYY2KRXiWtgoWJ9Bmise+KfEPDiVHWeJepvF8xJO9/9+WDIciMFFw==}
- engines: {node: '>=18.0.0'}
-
'@so-ric/[email protected]':
resolution: {integrity: sha512-/KiKkpHNOBgkFJwu9sh48LkHSMYGyuTcSFK/qMBdnOAlrRJzRSXAOFB5qwzaVQuDl8wAvHVMkaASQDReTahxuw==}
- resolution: {integrity: sha512-jI/VAmtdjB/RnI8GTnokyX7Ug8c+g+ffD6QRLa6XQewtnGyukKkKSk3wLTM3b5cjt1jNh9x0jfVlagdN2gDKQg==}
+ resolution: {integrity: sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw==}
resolution: {integrity: sha512-uv0aG6R0Y8WHZLTamZwtfsDLVRnOa+n+n5rEvFWL5Na5gZ8V2Teab/duDPFzIIIhs9qizDpcavCusCLJZu62Kw==}
@@ -1560,48 +1317,54 @@ packages:
resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==}
- '@types/[email protected]':
- resolution: {integrity: sha512-FOvQ0YPD5NOfPgMzJihoT+Za5pdkDJWcbpuj1DjaKZIr/gxodQjY/uWEFlTNqW2ugXHUiL8lRQgw63dzKHZdeQ==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}
- '@types/[email protected]':
- resolution: {integrity: sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-gIW7lQLZbue7lRSWEFql49QJJWThrTFFeIMJdp3eH4tKoxm1OvEPg02rm4wCCSHS0cL3/Fizimb35b7k8atwsQ==}
resolution: {integrity: sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-xf/JsSlnXQ+mzvc0IpXemcrO4BrCfpgNpMco+GLcXkFk01k/gW9lGJu+Vof0ZSvHK6DsHJDPSbjFPs36QkWXqw==}
+
resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==}
- '@types/[email protected]':
- resolution: {integrity: sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ECymXOukMnOoVkC2bb1Vc/w/836DXncOg5m8Xj1RH7xSHZJWNYY6Zh7EH477vcnD5egKNNfy2RpNOmuChhFPgQ==}
+
+ '@types/[email protected]':
+ resolution: {integrity: sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==}
- '@types/[email protected]':
- resolution: {integrity: sha512-1N9SBnWYOJTrNZCdh/yJE+t910Y128BoyY+zBLWhL3r0TYzlTmFdXrPwHL9DyFZmlEXNQQolTZh3KHV31QDhyA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-hroOstUScF6zhIi+5+x0dzqrHA1EJi+Irri6b1fxolMTqqHIV/Cg77EtnQcZqZCu8hR3mX2BzIxN4/GzI68Kfw==}
resolution: {integrity: sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-bDX6d5a5ZDWC81tgDv224n/3PKNYfIQJTPHzlbk4vBWJrYXF6Tg1ncaVmP/c3JbGN2AK9p7zmHorJC2D6oejGQ==}
+
resolution: {integrity: sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA==}
resolution: {integrity: sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==}
-
resolution: {integrity: sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==}
resolution: {integrity: sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==}
- '@typespec/[email protected]':
- resolution: {integrity: sha512-IlqQ/Gv22xUC1r/WQm4StLkYQmaaTsXAhUVsNE0+xiyf0yRFiH5++q78U3bw6bLKDCTmh0uqKB9eG9+Bt75Dkg==}
+ '@typespec/[email protected]':
+ resolution: {integrity: sha512-yURCknZhvywvQItHMMmFSo+fq5arCUIyz/CVk7jD89MSai7dkaX8ufjCWp3NttLojoTVbcE72ri+be/TnEbMHw==}
engines: {node: '>=20.0.0'}
- '@upstash/[email protected]':
- resolution: {integrity: sha512-ptQ9xnxtKqmpNK52PCcHCszlPOLxIBfjsv7ty8RoF95pkjctS9rSjTQ3Pl9bx5VFbpDj+0dMXw88WLt6swDkgQ==}
+ '@upstash/[email protected]':
+ resolution: {integrity: sha512-yXsWKeuHNYyH72BcSZd3bV5ZD5MybAoTvKxkMaeV2UzuGfNzbHBVh5eO+ysTWTFAf8I9XcOueF4tZfAGjCa4Iw==}
'@vitest/[email protected]':
resolution: {integrity: sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==}
@@ -1610,7 +1373,7 @@ packages:
resolution: {integrity: sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==}
peerDependencies:
msw: ^2.4.9
- vite: ^5.0.0
+ vite: ^6.4.2
peerDependenciesMeta:
msw:
optional: true
@@ -1636,19 +1399,24 @@ packages:
resolution: {integrity: sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==}
engines: {node: '>=v14.0.0', npm: '>=7.0.0'}
- '@xmldom/[email protected]':
- resolution: {integrity: sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw==}
+ '@xmldom/[email protected]':
+ resolution: {integrity: sha512-KRYzxepc14G/CEpEGc3Yn+JKaAeT63smlDr+vjB8jRfgTBBI9wRj/nkQEO+ucV8p8I9bfKLWp37uHgFrbntPvw==}
engines: {node: '>=10.0.0'}
- '@zilliz/[email protected]':
- resolution: {integrity: sha512-qOaVIpQ3E4w6Dp4lp9QIIuGedpE5dWRhK9SRX+y9WXcq4EXYvcdfR2aG/Vb5tWBPQwcMrGb5z8gRfFy7/gRbIw==}
+ '@xterm/[email protected]':
+ resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==}
+
+ '@zenfs/[email protected]':
+ resolution: {integrity: sha512-jFihhedKitw1X9rlImtaca4KTs1Xk9awo4GxUemqt2ucE1jLi10lyRfFFbiYXZsFDkuCWGHwEQwv7BeDIEXMbQ==}
+ engines: {node: '>= 18'}
+ hasBin: true
+
+ '@zilliz/[email protected]':
+ resolution: {integrity: sha512-osxYMzOhmoUjkx42fAMT2lsjYKXvGp0C92bjtcUTv3iDXPWoZP5GsiUJqohvCjxlKs3n7C7SXAKV/H6FL2AUsw==}
resolution: {integrity: sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==}
- resolution: {integrity: sha512-VtUwTNU8fpMwvWGn4xE93ywbogTYsuT+AUxAXOeelbXuQVIwNmC5YLeho9sH4vZ4ITW8414TTAOG1nW6uIVHCA==}
-
resolution: {integrity: sha512-yTt9CI0x+nRfX6BFMenEGP8ooPvErGH6AbFz20C2IeOLIlDsrw/VHpgne3GsCEuTA410IiFiaLVFKmgM4bKEPQ==}
@@ -1656,8 +1424,8 @@ packages:
resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==}
engines: {node: '>=6.5'}
- resolution: {integrity: sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==}
+ resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==}
engines: {node: '>=0.4.0'}
hasBin: true
@@ -1673,8 +1441,8 @@ packages:
resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==}
engines: {node: '>= 8.0.0'}
- resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==}
+ resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}
resolution: {integrity: sha512-qk6RIVMS/R1yTvBzfIL1T76PsIL7DIVCINoLuFw2YXKLpLtsTobqdChMs8m3OhuPS3CEE3+Ra5ibYiqdyogbsQ==}
@@ -1717,8 +1485,8 @@ packages:
resolution: {integrity: sha512-SGDvmg6QTYiTxCBkYVmThcoa67uLl35pyzRHdpCGBOcqFy6BtwnphoFPk7LhJshD+Yk1Kt35WGWeZPTgwR4Fhw==}
engines: {node: '>=12.17'}
- resolution: {integrity: sha512-7IZuOxwxTWs3U+JjH8aBxhA6RM3tOFjEDKgxhvnNpHLjVIKEaxl4hqFd+g0eSNtz7QnHUZJQffaz7JCariC0MQ==}
+ resolution: {integrity: sha512-KLu/lUAZEYz17zWMV6kk9nJyzzO1kItpZ5vruW5WpNjTpbgye58V1PKUOCWNndyxBn099lEBg3V5CbxKq1plAw==}
engines: {node: '>=18'}
@@ -1735,8 +1503,8 @@ packages:
resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
- resolution: {integrity: sha512-5Q2mfq2WfGuFp3uS//0s6baOJLMoVduPYVeNmDYxu5OUA1/cBfvr2RIS7vi62LdNj/urk1hfmj867I3qt6uZ7Q==}
+ resolution: {integrity: sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==}
peerDependencies:
react-native-b4a: '*'
peerDependenciesMeta:
@@ -1746,16 +1514,16 @@ packages:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
- resolution: {integrity: sha512-riJjyv1/mHLIPX4RwiK+oW9/4c3TEUeORHKefKAKnZ5kyslbN+HXowtbaVEqt4IMUB7OXlfixcs6gsFeo/jhiQ==}
+ resolution: {integrity: sha512-HdUm8EMQBLaJvGUdidNNbqpA1kYkwNcb+MYxkxCLAPJGQzlv9J0C24h8V65Z4c5GLd/JEALDvpFCQgpLJqc0zw==}
peerDependencies:
bare-abort-controller: '*'
peerDependenciesMeta:
bare-abort-controller:
optional: true
- resolution: {integrity: sha512-veTnRzkb6aPHOvSKIOy60KzURfBdUflr5VReI+NSaPL6xf+XLdONQgZgpYvUuZLVQ8dCqxpBAudaOM1+KpAUxw==}
+ resolution: {integrity: sha512-WDRsyVN52eAx/lBamKD6uyw8H4228h/x0sGGGegOamM2cd7Pag88GfMQalobXI+HaEUxpCkbKQUDOQqt9wawRw==}
engines: {bare: '>=1.16.0'}
peerDependencies:
bare-buffer: '*'
@@ -1763,26 +1531,29 @@ packages:
bare-buffer:
optional: true
- resolution: {integrity: sha512-T+V1+1srU2qYNBmJCXZkUY5vQ0B4FSlL3QDROnKQYOqeiQR8UbjNHlPa+TIbM4cuidiN9GaTaOZgSEgsvPbh5A==}
+ resolution: {integrity: sha512-6M5XjcnsygQNPMCMPXSK379xrJFiZ/AEMNBmFEmQW8d/789VQATvriyi5r0HYTL9TkQ26rn3kgdTG3aisbrXkQ==}
engines: {bare: '>=1.14.0'}
resolution: {integrity: sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==}
- resolution: {integrity: sha512-oyXQNicV1y8nc2aKffH+BUHFRXmx6VrPzlnaEvMhram0nPBrKcEdcyBg5r08D0i8VxngHFAiVyn1QKXpSG0B8A==}
+ resolution: {integrity: sha512-Vp0cnjYyrEC4whYTymQ+YZi6pBpfiICZO3cfRG8sy67ZNWe951urv1x4eW1BKNngw3U+3fPYb5JQvHbCtxH7Ow==}
peerDependencies:
+ bare-abort-controller: '*'
bare-buffer: '*'
bare-events: '*'
peerDependenciesMeta:
+ bare-abort-controller:
+ optional: true
bare-buffer:
optional: true
bare-events:
optional: true
- resolution: {integrity: sha512-ZMq4gd9ngV5aTMa5p9+UfY0b3skwhHELaDkhEHetMdX0LRkW9kzaym4oo/Eh+Ghm0CCDuMTsRIGM/ytUc1ZYmw==}
+ resolution: {integrity: sha512-Kccpc7ACfXaxfeInfqKcZtW4pT5YBn1mesc4sCsun6sRwtbJ4h+sNOaksUpYEJUKfN65YWC6Bw2OJEFiKxq8nQ==}
resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}
@@ -1800,11 +1571,22 @@ packages:
resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==}
deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.
- resolution: {integrity: sha512-OHawaAbjwx6rqICCKgSG0SAnT05bzd7ppyKLVUITZpANBaaMFBAsaNkto3LoQ31tyFP5kNujE8Cdx85G9VzOkw==}
+ resolution: {integrity: sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==}
+
+ resolution: {integrity: sha512-EwOCDEex4quD37XhqM3omwtMoJjr//isUZz1JopUNWms+4Z2ViyM/k1YIRePpoVNnQhENnxtFjLaxNHrT7xIUg==}
+
+ resolution: {integrity: sha512-U3K72/JAi3jITpdhZBqzSUq+DUY697tLxOuFXB+FpAE/Ug+5C3VZrv4uA674EUZHxNAuQ9wETXNqQkxZD6oL4A==}
+ engines: {node: '>=v18.0.0'}
- resolution: {integrity: sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==}
+ resolution: {integrity: sha512-0F2z/VSnLbmEeBcUrSuDH5l0HxTXdQQzLjkmBR4cYfvg1zJrKSlmIZFqyFR8oX0NrwPhy3c3HQ6i3OxMbew4Tg==}
+
+ resolution: {integrity: sha512-MTxGsqgYTwfshYWTRdmZRC+M7FnG1b4y7RO7p2k3X24Wq0yv1m77Wsj0BzlPzd/IowgESfsruQCUToa7vbOpPQ==}
+ engines: {node: '>=16.20.1'}
resolution: {integrity: sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==}
@@ -1827,7 +1609,7 @@ packages:
resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==}
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
peerDependencies:
- esbuild: '>=0.18'
+ esbuild: '>=0.25.0'
resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}
@@ -1864,8 +1646,8 @@ packages:
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-OAlb+T7V4Op9OwdkjmguYRqncdlx5JiofwOAUkmTF+jNdHwzTaTs4sRAGpzLF3oOz5xAyDGrPgeIDFQmDOTiJw==}
+ resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}
engines: {node: '>= 16'}
@@ -1875,10 +1657,6 @@ packages:
resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==}
- resolution: {integrity: sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==}
engines: {node: '>=18'}
@@ -1904,6 +1682,27 @@ packages:
voyageai:
optional: true
+ resolution: {integrity: sha512-+IeTjjf44pKUY3vp1BacwO2tFAPcWCd64zxPZZm98dVj/kbSBeaHKB2D6eX7iRLHS1PTVASuqoR6mAJ+nrsTBg==}
+ engines: {node: '>=14.17.0'}
+ peerDependencies:
+ '@google/generative-ai': ^0.1.1
+ cohere-ai: ^5.0.0 || ^6.0.0 || ^7.0.0
+ ollama: ^0.5.0
+ openai: ^3.0.0 || ^4.0.0
+ voyageai: ^0.0.3-1
+ peerDependenciesMeta:
+ '@google/generative-ai':
+ optional: true
+ cohere-ai:
+ optional: true
+ ollama:
+ optional: true
+ openai:
+ optional: true
+ voyageai:
+ optional: true
+
resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}
engines: {node: '>=12'}
@@ -1974,9 +1773,6 @@ packages:
resolution: {integrity: sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==}
- resolution: {integrity: sha512-SrhBq4hYVjLCkBVOWaTzceJalvn5K1Zq5aQA6wXC/cYjI3frKWNPEMK3sZsJfNNQApvCQmgBcc13ZKmFj8qExw==}
-
resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}
@@ -1986,8 +1782,8 @@ packages:
resolution: {integrity: sha512-l3nz3euub2QMg5ouu5U09Ew9Wf6/wQ8I++ch1loQ0ljmzhmfZYrH9fflS22i/PQEvsPvxCwxgz5q7UB8K1JO4Q==}
- resolution: {integrity: sha512-t5EcLVS6QPBNqM2z8fakk/NKel+Xzshgt8FFKAn+qwlD1pzZWxh0nVCrvFK7ZDb6XucZeF9z8C7CBWTRIVApAw==}
+ resolution: {integrity: sha512-98IT+HOahAisibz/yjKbzuOBwYcjJ7BCLPzARyHiyEBmRz4fatF+KPJszEHXsGYjUG234aH/cOjW1wwTbKUZlA==}
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
@@ -2026,8 +1822,8 @@ packages:
resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-XDuvSq38Hr1MdN47EDvYtx3U0MTqpCEn+F6ft8z2vYDzMrvQhVp0ui9oQdqW3MvK3vqUETglt1tVGgjLuJ5izg==}
+ resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==}
engines: {node: '>=18'}
@@ -2062,8 +1858,8 @@ packages:
resolution: {integrity: sha512-7xpNK0EiWjjDFp2nAhHXezE4OUWm7s1zhc/UXXN6hnFFU8dfoPHgV0Hx0RPiCa3ILRpdeh152icc68DGCyXYIw==}
- resolution: {integrity: sha512-Cv47jzY1jkGkh5sv0bfHYqGgKOWO1peOrGMkDFM4UmaGMOTgOW8QSexhvixa9sVOiz8MnVOBryWYyw/CEVhj7w==}
+ resolution: {integrity: sha512-WFUE/2o0lBlLeCQonQ+Pu2RqHAqbytBJ2RlXR91gzk05InSS6k9ShzzLYoymrA4c2oRgRKGE7/VqQJNNdGWSxQ==}
resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
@@ -2112,8 +1908,8 @@ packages:
resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}
- resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==}
+ resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}
engines: {node: '>= 0.4'}
@@ -2123,13 +1919,8 @@ packages:
resolution: {integrity: sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==}
- resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==}
- engines: {node: '>=12'}
- hasBin: true
-
- resolution: {integrity: sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==}
+ resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==}
engines: {node: '>=18'}
hasBin: true
@@ -2151,6 +1942,9 @@ packages:
resolution: {integrity: sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==}
+ resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}
+
resolution: {integrity: sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==}
@@ -2178,11 +1972,14 @@ packages:
resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==}
- resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==}
+ resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==}
+
+ resolution: {integrity: sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==}
- resolution: {integrity: sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ==}
+ resolution: {integrity: sha512-C0AaNuC+mscy6vrAQKAc/rMq+zAPHodfHGZu4sGVehvAQt/JLG1O5zEcYcXSY5zSqr4YVgxsB+pHXTq0i7eDlg==}
hasBin: true
@@ -2227,10 +2024,6 @@ packages:
resolution: {integrity: sha512-G6NsmEW15s0Uw9XnCg+33H3ViYRyiM0hMrMhhqQOR8NFc5GhYrI+6I3u7OTw7b91J2g8rtvMBZJDbcGb2YUniw==}
engines: {node: '>= 18'}
- resolution: {integrity: sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==}
- engines: {node: '>= 6'}
-
resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==}
engines: {node: '>= 6'}
@@ -2246,10 +2039,6 @@ packages:
resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==}
- resolution: {integrity: sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==}
- engines: {node: '>= 8'}
-
resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==}
@@ -2304,7 +2093,7 @@ packages:
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
- deprecated: Glob versions prior to v9 are no longer supported
+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
resolution: {integrity: sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==}
@@ -2334,8 +2123,8 @@ packages:
peerDependencies:
graphql: 14 - 16
- resolution: {integrity: sha512-DKKrynuQRne0PNpEbzuEdHlYOMksHSUI8Zc9Unei5gTsMNA2/vMpoMz/yKba50pejK56qj98qM0SjYxAKi13gQ==}
+ resolution: {integrity: sha512-BBvQ/406p+4CZbTpCbVPSxfzrZrbnuWSP1ELYgyS6B+hNeKzgrdB4JczCa5VZUBQrDa9hUngm0KnexY6pJRN5Q==}
engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0}
@@ -2366,8 +2155,8 @@ packages:
resolution: {integrity: sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==}
- resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==}
+ resolution: {integrity: sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==}
engines: {node: '>= 0.4'}
@@ -2408,6 +2197,9 @@ packages:
resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==}
+ resolution: {integrity: sha512-u8BMiMa05OPBgd32CKTead0CVTsFVgwFk23nNXo1teKPF6Sxcu0lXxEzP//zTcaKzXbGgPDXGmj/woyv+I4C5w==}
+
resolution: {integrity: sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==}
@@ -2429,8 +2221,8 @@ packages:
resolution: {integrity: sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw==}
+ resolution: {integrity: sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==}
engines: {node: '>=16'}
@@ -2439,6 +2231,11 @@ packages:
resolution: {integrity: sha512-qvUtwJ3j6qwsF3jLxkZ72qCgjMysPzDfeV240JHiGZsANBYd+EEuu35v7dfrJ9Up0Ak07D7GGSkGhCHTqg/5wA==}
+ resolution: {integrity: sha512-BhBvN2MBpWTaSHdWRb/bwdZJ1WaehQ2L1KngkCkfLUGF0mAWAT1sQUQacEmQ0jXkFw/czDXPNQSL5u2/Krsz1w==}
+ peerDependencies:
+ ws: '>=8.20.1'
+
resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==}
engines: {node: '>=10'}
@@ -2478,13 +2275,14 @@ packages:
resolution: {integrity: sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==}
- resolution: {integrity: sha512-XXR1+9INH8YX96FKWc5tie0QixWz6tOqAsAKfcJyPkE0xPep+NDz0IQLR32q4bn10QK3LqD2HN6T3n6z1YLW7Q==}
+ resolution: {integrity: sha512-Gg+IeRGoF1/aStu80aEnIXJCu+N6+4NoV4tAVFS51ZPRBsRa2KG0LkS7K7/ryZ/yES7O9xdqah5QuuWMIeMjQw==}
peerDependencies:
'@opentelemetry/api': '*'
'@opentelemetry/exporter-trace-otlp-proto': '*'
'@opentelemetry/sdk-trace-base': '*'
openai: '*'
+ ws: '>=8.20.1'
peerDependenciesMeta:
'@opentelemetry/api':
optional: true
@@ -2494,6 +2292,8 @@ packages:
optional: true
openai:
optional: true
+ ws:
+ optional: true
resolution: {integrity: sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg==}
@@ -2501,6 +2301,76 @@ packages:
resolution: {integrity: sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==}
+ resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [android]
+
+ resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [darwin]
+
+ resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [freebsd]
+
+ resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm]
+ os: [linux]
+
+ resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+
+ resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [linux]
+
+ resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+
+ resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [linux]
+
+ resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [arm64]
+ os: [win32]
+
+ resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==}
+ engines: {node: '>= 12.0.0'}
+ cpu: [x64]
+ os: [win32]
+
+ resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}
+ engines: {node: '>= 12.0.0'}
+
resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==}
engines: {node: '>=14'}
@@ -2540,8 +2410,8 @@ packages:
resolution: {integrity: sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==}
- resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==}
+ resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}
resolution: {integrity: sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==}
@@ -2563,8 +2433,8 @@ packages:
resolution: {integrity: sha512-ERJq3FOzJTxBbFjZ7iDs+NiK4VI9Wz+RdrrAB8dio1oV+YvdPzUEE4QNiT2VD51DkIbCYRUUzCRkssXCHqSnKQ==}
engines: {node: 14 || >=16.14}
- resolution: {integrity: sha512-ThQLOhN86ZkJ7qemtVRGYM+gRgR8GEXNli9H/PMvpnZsE44Xfh3wx9kGJaldg314v85m+bFW6WBMaVHJc/c3zA==}
+ resolution: {integrity: sha512-afO2mnxW7GDTXMm5/AoN1WuOcdoKhtgXjIvHmobqTD1grNplhGdv3PFOyjCVmrnOZBIT/gD/koDKpYG+0mvHcg==}
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
@@ -2573,8 +2443,8 @@ packages:
resolution: {integrity: sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-BcEqqY/BOwIcI1iR5tqyVlqc3KIaMRa4egSoK83YAVrBf6+yqdAAbtUcFDCWX8Zef8/fgNZ6rl4VUv+vVX8ddQ==}
+ resolution: {integrity: sha512-cwnK1RIcRdDMi2HRx2EXGYlxqIEh0Oo3bLhorgnsVJi2UkbX1+jKxuBNR9PC5+JaX7EkmJxFPmo6mjLpqShI2w==}
engines: {node: '>=12.0.0'}
hasBin: true
@@ -2608,28 +2478,16 @@ packages:
resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==}
+ resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==}
resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}
- resolution: {integrity: sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==}
- engines: {node: '>=8'}
-
- resolution: {integrity: sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==}
+ resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}
engines: {node: '>=16 || 14 >=14.17'}
- resolution: {integrity: sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==}
- engines: {node: '>= 8'}
-
resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==}
engines: {node: '>= 18'}
@@ -2637,13 +2495,8 @@ packages:
resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==}
- resolution: {integrity: sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==}
- engines: {node: '>=10'}
- hasBin: true
-
- resolution: {integrity: sha512-l8D9ODSRWLe2KHJSifWGwBqpTZXIXTeo8mlKjY+E2HAakaTeNpqAyBZ8GSqLzHgw4XmHmC8whvpjJNMbFZN7/g==}
+ resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==}
resolution: {integrity: sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==}
@@ -2712,35 +2565,35 @@ packages:
resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}
- resolution: {integrity: sha512-Vpf9qnVW1RaDkoNKFUvfxqAbtI8ncb8OJlqZ9wwpXzWPEsvsB1nvdUi6oYrHIkQ1Y/tMDnr1h4nczS0VB9Xykg==}
+ resolution: {integrity: sha512-hC+0LidcL3XE4rp1C4H54KujgXKzbfyTngZTwBByQxsOxCEKZT0MPQ4hOKUH2jU1OYstqdDH4onyHPDzcV0XdQ==}
- resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
+ resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==}
- resolution: {integrity: sha512-Q9I/wm5lYkDTveKFirrTHBkBY137yavXZ4xQDXTPIycUp7aLXD8xPTHFhqtAFWUw05aS91uffZZRgdv3HS0y/g==}
+ resolution: {integrity: sha512-fXfNNdtjCQzc3O/w3WsK1AOU+xdE1V7FCm4FEQWS/UUVsV1616S2oryvWqsZAF8aOvuMir8lFtNmgH3DeP+PBg==}
- resolution: {integrity: sha512-7RNWbls5kAL1QVUOXvBsv1uO0wPQK3lHv+cY1gwkTzirnG1Nop4cBJZubpgziNbaVc/bl9QJcyvsf/NQxa3rjQ==}
+ resolution: {integrity: sha512-MEhnD3JMah0mgyivpb9hpRDbOBuXBxI/TVO+OK1h6rC97WM42HsPMR+zzRNQ0C5BqYJTw1nyWiQRD0DucO+pjQ==}
- resolution: {integrity: sha512-GK9pKNxlvnU5FAdaw7i2FFuR9CqBspcE+if2tqnKXBcE0R8525wj4BZvfcwj7FjvqbssqKxRHt2nwedalbJlww==}
+ resolution: {integrity: sha512-Cl3Pn00212Hl8/U6bpgMxmhZj5lyv3nWoJov4cd3FjWarktrMHP4DNvSjCnDwkMWYx4W1tyscEia4JX6Y4GVCQ==}
- resolution: {integrity: sha512-zsFhmbkAzwhTft6nd3VxcG0cvJsT70rL+BIGHWVq5fi6MwGrHwzqKaxXE+Hl2GmnGItnDKPPkO5/LQqjVkIdFg==}
+ resolution: {integrity: sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==}
engines: {node: '>=10'}
resolution: {integrity: sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==}
- resolution: {integrity: sha512-/bRZty2mXUIFY/xU5HLvveNHlswNJej+RnxBjOMkidWfwZzgTbPG1E3K5TOxRLOR+5hX7bSofy8yf1hZevMS8A==}
+ resolution: {integrity: sha512-c5Ko1fZJIJmzhFIkhRN76WTq+fC6tWnGy9CXA0fA+XygsWZmEwG8vmbkNqxMyoaa0Tin4djul49NzdVcJJcjeA==}
engines: {node: ^18 || ^20 || >= 21}
@@ -2761,6 +2614,9 @@ packages:
resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==}
hasBin: true
+ resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}
+
resolution: {integrity: sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==}
engines: {node: '>=6'}
@@ -2828,7 +2684,7 @@ packages:
resolution: {integrity: sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==}
hasBin: true
peerDependencies:
- ws: ^8.18.0
+ ws: '>=8.20.1'
zod: ^3.23.8
peerDependenciesMeta:
ws:
@@ -2864,6 +2720,10 @@ packages:
resolution: {integrity: sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw==}
+ resolution: {integrity: sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==}
+ engines: {node: '>=14.0.0'}
+
resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==}
engines: {node: '>=0.10.0'}
@@ -2881,14 +2741,14 @@ packages:
resolution: {integrity: sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ==}
- resolution: {integrity: sha512-YgCtzMH0ptvZJslLM1ffsY4EuGaU0cx4XSdXLRFae8bPP4dS5xL1tNB3k2o/N64cHJpwU7dxKli/nZ2lUa5fLg==}
+ resolution: {integrity: sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==}
- resolution: {integrity: sha512-nkc6NpDcvPVpZXxrreI/FOtX3XemeLl8E0qFr6F2Lrm/I8WOnaWNhIPK2Z7OHpw7gh5XJThi6j6ppgNoaT1w4w==}
+ resolution: {integrity: sha512-EMnU9E2fSULdsbErBbMaXJvFeD9B4+nPcM3f+4lsiCR0BHLPrLVjv3DbyM2hgQQviKJaTWIRRTjKjWlHg3p2ig==}
- resolution: {integrity: sha512-eHw63TsiGtFEfAd7tOTZ+TLy+i/2ePKS20H84qCQ+aQ60pve05Okon9tKMC+YN3j6XyeFoHnaim7Lt9WVafQsA==}
+ resolution: {integrity: sha512-HP/EbUafheaUOs7DxlG6tda/rhmsX2hCTJJJ+gCnhljGyNEs6pBHddbNuomlW3DqEhP3zYD+GqBWkYnJPIZ4tA==}
peerDependencies:
pg: ^8
@@ -2900,8 +2760,8 @@ packages:
resolution: {integrity: sha512-jO/oJOununpx8DzKgvSsWm61P8JjwXlaxSlbbfTBo1nvSWoo/+I6qZYaSN96jm/KDwa5d+JMQwPGgcP6HXDRow==}
engines: {node: '>=16.0.0'}
- resolution: {integrity: sha512-Tu8jMlcX+9d8+QVzKIvM/uJtp07PKr82IUOYEphaWcoBhIYkoHpLXN3qO59nAI11ripznDsEzEv8nUxBVWajGg==}
+ resolution: {integrity: sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==}
peerDependencies:
pg: '>=8.0'
@@ -2911,8 +2771,8 @@ packages:
peerDependencies:
pg-query-stream: 4.10.3
- resolution: {integrity: sha512-6DIBgBQaTKDJyxnXaLiLR8wBpQQcGWuAESkRBX/t6OwA8YsqP+iVSiond2EDy6Y/dsGk8rh/jtax3js5NeV7JQ==}
+ resolution: {integrity: sha512-n5taZ1kO3s9ngDTVxsEznOqCyToTgz0FLuPq0B33COy5pPpuWJpY3/2oRBVETuOgzdqRXfWpM9HIhp2LBBT1BA==}
resolution: {integrity: sha512-h2utrzpOIzeT9JfaqfvBbVuvCfBjH86jNfVrGGTbyepKAIOyTfDew0lAt8bbJjs9n/I5bGDl7S2sx6h5hPyJxw==}
@@ -2938,8 +2798,8 @@ packages:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
- resolution: {integrity: sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==}
+ resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}
engines: {node: '>=12'}
@@ -2952,13 +2812,13 @@ packages:
resolution: {integrity: sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==}
- resolution: {integrity: sha512-agTcKlMw/mjBWOnD6kFZttAAGHgi/Nw0CZ2o6JqWSbMlI219lAFLZZCyqByTsvVAJq5XA5H8cA6PrvBRpBWEuQ==}
+ resolution: {integrity: sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==}
engines: {node: '>=18'}
hasBin: true
- resolution: {integrity: sha512-ilYQj1s8sr2ppEJ2YVadYBN0Mb3mdo9J0wQ+UuDhzYqURwSoW4n1Xs5vs7ORwgDGmyEh33tRMeS8KhdkMoLXQw==}
+ resolution: {integrity: sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==}
engines: {node: '>=18'}
hasBin: true
@@ -2983,8 +2843,8 @@ packages:
yaml:
optional: true
- resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==}
+ resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==}
engines: {node: ^10 || ^12 || >=14}
@@ -3006,6 +2866,7 @@ packages:
resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==}
engines: {node: '>=10'}
+ deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available.
hasBin: true
@@ -3018,26 +2879,30 @@ packages:
resolution: {integrity: sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==}
engines: {node: '>= 0.6.0'}
- resolution: {integrity: sha512-5kQWPaJHi1WoCpjTGszzQ32PG2F4+wRY6BmAT4Vfw56Q2FZ4YZzK20xUYQH4YkfehY1e6QSICrJquM6xXZNcrw==}
- hasBin: true
-
- resolution: {integrity: sha512-CvexbZtbov6jW2eXAvLukXjXUW1TzFaivC46BpWc/3BpcCysb5Vffu+B3XHMm8lVEuy2Mm4XGex8hBSg1yapPg==}
+ resolution: {integrity: sha512-4K0myLaWL5EteuSAro91EGFgcfVgxb64Jx+7oDAY6GOkXD4M69yuSEljNcInGVCA5sOPxmZ/EqDLj2x0Q0+Ygg==}
engines: {node: '>=12.0.0'}
resolution: {integrity: sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==}
- resolution: {integrity: sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==}
+ resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==}
+ resolution: {integrity: sha512-kV/CThkXo6xyFEZUugw/+pIOywXcDbFYgSct5cT3gqlbkBE1SJdwy6UQoZvodiWF/ckQLZyDE/Bu1M6gVu5lVw==}
+ engines: {node: '>=0.6.0', teleport: '>=0.2.0'}
+ deprecated: |-
+ You or someone you depend on is using Q, the JavaScript Promise library that gave JavaScript developers strong feelings about promises. They can almost certainly migrate to the native JavaScript promise now. Thank you literally everyone for joining me in this bet against the odds. Be excellent to each other.
+
+ (For a CapTP with native promises, see @endo/eventual-send and @endo/captp)
+
+ resolution: {integrity: sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==}
engines: {node: '>=0.6'}
@@ -3065,8 +2930,9 @@ packages:
resolution: {integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==}
- resolution: {integrity: sha512-BZx9DsT4FAgXDTOdgJIc5eY6ECIXMwtlSPQoPglF20ycSWigttDDe88AozEsPPT4OWk5NujroGSBC1phw5uU+w==}
+ resolution: {integrity: sha512-wN6BXWua0t4o7vDamqc27J3VRxnokG9cDezsFN2nOnt2JD/IkJQHTYqM6UvmEctAZETAoviwEFQZJO3kZ4Ohew==}
+ engines: {node: '>=18.0.0'}
resolution: {integrity: sha512-1ufKejfUVz/azy+5TnzQP7U1+MHVWZ6psnQ06az8byUUnRhT+DZ/MvewzB1NQYBVMgNKR7xPDtTwlcP5nv/5+w==}
@@ -3100,8 +2966,8 @@ packages:
resolution: {integrity: sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==}
engines: {node: '>=8.0'}
- resolution: {integrity: sha512-3nk8Y3a9Ea8szgKhinMlGMhGMw89mqule3KWczxhIzqudyHdCIOHw8WJlj/r329fACjKLEh13ZSk7oE22kyeIw==}
+ resolution: {integrity: sha512-WHeFSbZYsPu3+bLoNRUuAO+wavNlocOPf3wSHTP7hcFKVnJeWsYlCDbr3mTS14FCizf9ccIxXA8sGL8zKeQN3g==}
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
hasBin: true
@@ -3136,8 +3002,8 @@ packages:
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
hasBin: true
- resolution: {integrity: sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==}
+ resolution: {integrity: sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg==}
engines: {node: '>=10'}
hasBin: true
@@ -3159,8 +3025,8 @@ packages:
resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==}
engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0}
- resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==}
+ resolution: {integrity: sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==}
engines: {node: '>= 0.4'}
@@ -3193,8 +3059,8 @@ packages:
resolution: {integrity: sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==}
- resolution: {integrity: sha512-j7piyCjAeTDSjzTSQ7DokZtMNwNlEAyxqSZeCS+CXH7fJ4jx3FuJ/mTW3mE+6JLs4VJBbcll0Kjn+KXI5t21Iw==}
+ resolution: {integrity: sha512-u5iEEXkMe2EInQio6Wv9LWHOQYRDbD2O9hzS27GpT/lwfIQhTCnHCTqedqHIHe9ZcvQo+9au6vngQayipz1NYw==}
resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
@@ -3230,8 +3096,8 @@ packages:
resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}
- resolution: {integrity: sha512-kn+e44esVfn2Fa/O0CPFcex27fjIL6MkVae0Mm6q+E6f0hWv578YCERbv+4m02cjxvDsPKLnmxral/rR6lBMAg==}
+ resolution: {integrity: sha512-VvNG1K72Po/xwJzxZFnZ++Tbrv4lwSptsbkFuzXCJAYZvCK5nnxsvXU6ajqkv7chyiI1Y0YXq2Jh8Iy8Y7NF/A==}
resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}
@@ -3251,8 +3117,8 @@ packages:
resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-l63NF9y/cLROq/yqKXSLtcMeeyOfnSQlfMSlzFt/K73oIaD8DGaQWd7Z34X9GPiKqP5rbSh84Hl4bOlLcjiSrQ==}
+ resolution: {integrity: sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q==}
resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}
@@ -3270,27 +3136,25 @@ packages:
resolution: {integrity: sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==}
- resolution: {integrity: sha512-LZA0oaPOc2fVo82Txf3gw+AkEd38szODlptMYejQUhndHMLQ9M059uXR+AfS7DNo0NpINvSqDsvyaCrBVkptWg==}
+ resolution: {integrity: sha512-QGxxTxxyleAdyM3kpFs14ymbYmNFrfY+pHj7Z8FgtbZ7w2//VAgLMac7sT6nRpIHjppXO2AwwEOg0bPFVRcmXw==}
resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ==}
+ resolution: {integrity: sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==}
- resolution: {integrity: sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==}
- engines: {node: '>=10'}
-
- resolution: {integrity: sha512-7NyxrTE4Anh8km8iEy7o0QYPs+0JKBTj5ZaqHg6B39erLg0qYXN3BijtShwbsNSvQ+LN75+KV+C4QR/f6Gwnpg==}
+ resolution: {integrity: sha512-dzGK0boVlC4W5QFuQN1EFSl3bIDYsk7Tj40U6eIBnK2k/8ml7TZ5agbI5j5+qnoVcAA+rNtBml8SEiLxZpNqRQ==}
engines: {node: '>=18'}
- deprecated: Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
- resolution: {integrity: sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA==}
+ resolution: {integrity: sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==}
+
+ resolution: {integrity: sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==}
resolution: {integrity: sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==}
@@ -3302,6 +3166,10 @@ packages:
resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==}
+ resolution: {integrity: sha512-AW8rwHYjeqXisS8B1iwko2gkNMFwSRJ+bO/W0xTGqRspTD3lGHwZx438+pHdOJ3GwpRAnK7TKbjqPOrHAa7ZwQ==}
+ engines: {node: '>= 10.18.0'}
+
resolution: {integrity: sha512-iOqSav00cVxEEICeD7TjLB1sueEL+81Wpzp2bY17uZjZN0pWZPuo4suZ/61VujxmqSGFfgOcNuTZ85QJwNZQpw==}
@@ -3311,8 +3179,8 @@ packages:
resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
- resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==}
+ resolution: {integrity: sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg==}
engines: {node: '>=12.0.0'}
@@ -3390,10 +3258,6 @@ packages:
resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==}
- engines: {node: '>=16'}
-
resolution: {integrity: sha512-g/KzbYKbH5C2vPkaXGu8DJlHrGKHLsM25Zg9WuC9pMGfuvT+X25tZQWo5fK1BjBm8+UrVE9LDCvaY0CQk+fXDA==}
@@ -3410,11 +3274,11 @@ packages:
resolution: {integrity: sha512-ya4mg/30vm+DOWfBg4YK3j2WD6TWtRkCbasOJr40CseYENzCUby/7rIvXA99JGsQHeNxLbnXdyLLxKSv3tauFw==}
engines: {node: '>=12.17'}
- resolution: {integrity: sha512-9a4/uxlTWJ4+a5i0ooc1rU7C7YOw3wT+UGqdeNNHWnOF9qcMBgLRS+4IYUqbczewFx4mLEig6gawh7X6mFlEkA==}
+ resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==}
- resolution: {integrity: sha512-GMXzWtsc57XAtguZgaQViUOzs0KTkk8ojr3/xAxXLITqf/3EMwxC0inyETfDFjH/Krbhuep0HNbbjI9i/q3F3g==}
+ resolution: {integrity: sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==}
resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==}
@@ -3422,12 +3286,12 @@ packages:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
- resolution: {integrity: sha512-gBLkYIlEnSp8pFbT64yFgGE6UIB9tAkhukC23PmMDCe5Nd+cRqKxSjw5y54MK2AZMgZfJWMaNE4nYUHgi1XEOw==}
+ resolution: {integrity: sha512-sC+b0tB1whOCzbtlx20fx3WgCXwkW627p4EA9uM+/tNNPkSS+eSEld6pAs9nDv7WbY1UUljBMYPtu9BCOrCWKA==}
engines: {node: '>=18.17'}
- resolution: {integrity: sha512-hU/10obOIu62MGYjdskASR3CUAiYaFTtC9Pa6vHyf//mAipSvSQg6od2CnJswq7fvzNS3zJhxoRkgNVaHurWKw==}
+ resolution: {integrity: sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A==}
engines: {node: '>=18.17'}
@@ -3446,43 +3310,46 @@ packages:
resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}
- resolution: {integrity: sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==}
- hasBin: true
-
- resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==}
- hasBin: true
+ resolution: {integrity: sha512-GQINDTb/ocyz4acQj3GXAe0wipYxws6L+9ouqaq10KlInTk9DGvW9TJd0pYa/Xu3cppNnZuB4T/sBuSXpcN2ng==}
- resolution: {integrity: sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==}
+ resolution: {integrity: sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg==}
hasBin: true
resolution: {integrity: sha512-zV3eW2NlXTsun/aJ7AixxZjH/byQcH/r3J99MI0dDEkU2cJIBJxhEWUHDTpOaLPRNhebPZoeHuykYREkI9HafA==}
hasBin: true
+ resolution: {integrity: sha512-cXEIW6cfr15lFv563k4GuVuW/fiwjknytD37jIOLSdSWuOI6WnO/oKwmP2FQTU2l01LP8/M5TSAJpzUaGe3uWg==}
+
resolution: {integrity: sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==}
engines: {node: ^18.0.0 || >=20.0.0}
hasBin: true
- resolution: {integrity: sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==}
- engines: {node: ^18.0.0 || >=20.0.0}
+ resolution: {integrity: sha512-2N/55r4JDJ4gdrCvGgINMy+HH3iRpNIz8K6SFwVsA+JbQScLiC+clmAxBgwiSPgcG9U15QmvqCGWzMbqda5zGQ==}
+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
hasBin: true
peerDependencies:
- '@types/node': ^18.0.0 || >=20.0.0
+ '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0
+ jiti: '>=1.21.0'
less: '*'
lightningcss: ^1.21.0
sass: '*'
sass-embedded: '*'
stylus: '*'
sugarss: '*'
- terser: ^5.4.0
+ terser: ^5.16.0
+ tsx: ^4.8.1
+ yaml: ^2.4.2
peerDependenciesMeta:
'@types/node':
optional: true
+ jiti:
+ optional: true
less:
optional: true
lightningcss:
@@ -3497,6 +3364,10 @@ packages:
optional: true
terser:
optional: true
+ tsx:
+ optional: true
+ yaml:
+ optional: true
resolution: {integrity: sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==}
@@ -3523,9 +3394,9 @@ packages:
jsdom:
optional: true
- resolution: {integrity: sha512-PB338DjIwUus1Mq1dxhCc6fEp+yA+aY4H4sSFDS0No/GguEufd6SDhHHVLOYMy2cPgX35dWgEx5jUbG5o3aPZA==}
- engines: {node: '>=20.0.0'}
+ resolution: {integrity: sha512-cimmwR8w8GnSKQsP7tyW3dT2fMxJA2Tj+WqGzaVVkTVOLH4bb4B4iY0SO3TJUM4L8bcHkL04+MY2RAWEWJpU6A==}
+ engines: {node: '>=22.0.0'}
resolution: {integrity: sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==}
@@ -3578,8 +3449,8 @@ packages:
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
- resolution: {integrity: sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==}
+ resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}
engines: {node: '>=10.0.0'}
peerDependencies:
bufferutil: ^4.0.1
@@ -3594,6 +3465,10 @@ packages:
resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==}
+ engines: {node: '>=16.0.0'}
+
resolution: {integrity: sha512-OyzrcFLL/nb6fMGHbiRDuPup9ljBycsdCypwuyg5AAHvyWzGfChJpCXMG88AGTIMFhGZ9RccFN1e6lhg3hkwKg==}
engines: {node: '>=4.0'}
@@ -3602,13 +3477,13 @@ packages:
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
engines: {node: '>=0.4'}
+ resolution: {integrity: sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==}
+
resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==}
-
resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==}
engines: {node: '>=18'}
@@ -3621,14 +3496,17 @@ packages:
resolution: {integrity: sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==}
engines: {node: '>=12'}
- resolution: {integrity: sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==}
+ resolution: {integrity: sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==}
peerDependencies:
- zod: ^3.25 || ^4
+ zod: ^3.25.28 || ^4
resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
+ resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
+
snapshots:
'@anthropic-ai/[email protected]':
@@ -3646,23 +3524,44 @@ snapshots:
'@aws-crypto/[email protected]':
dependencies:
'@aws-crypto/util': 3.0.0
- '@aws-sdk/types': 3.957.0
+ '@aws-sdk/types': 3.973.9
tslib: 1.14.1
+ '@aws-crypto/[email protected]':
+ dependencies:
+ '@aws-crypto/util': 5.2.0
+ '@aws-sdk/types': 3.973.9
+ tslib: 2.8.1
+
+ '@aws-crypto/[email protected]':
+ dependencies:
+ '@aws-crypto/util': 5.2.0
+ '@aws-sdk/types': 3.973.9
+ tslib: 2.8.1
+
+ '@aws-crypto/[email protected]':
+ dependencies:
+ '@aws-crypto/supports-web-crypto': 5.2.0
+ '@aws-crypto/util': 5.2.0
+ '@aws-sdk/types': 3.973.9
+ '@aws-sdk/util-locate-window': 3.965.5
+ '@smithy/util-utf8': 2.3.0
+ tslib: 2.8.1
+
'@aws-crypto/[email protected]':
dependencies:
'@aws-crypto/sha256-js': 5.2.0
'@aws-crypto/supports-web-crypto': 5.2.0
'@aws-crypto/util': 5.2.0
- '@aws-sdk/types': 3.957.0
- '@aws-sdk/util-locate-window': 3.957.0
+ '@aws-sdk/types': 3.973.9
+ '@aws-sdk/util-locate-window': 3.965.5
'@smithy/util-utf8': 2.3.0
tslib: 2.8.1
'@aws-crypto/[email protected]':
dependencies:
'@aws-crypto/util': 5.2.0
- '@aws-sdk/types': 3.957.0
+ '@aws-sdk/types': 3.973.9
tslib: 2.8.1
'@aws-crypto/[email protected]':
@@ -3671,458 +3570,306 @@ snapshots:
'@aws-crypto/[email protected]':
dependencies:
- '@aws-sdk/types': 3.957.0
+ '@aws-sdk/types': 3.973.9
'@aws-sdk/util-utf8-browser': 3.259.0
tslib: 1.14.1
'@aws-crypto/[email protected]':
dependencies:
- '@aws-sdk/types': 3.957.0
+ '@aws-sdk/types': 3.973.9
'@smithy/util-utf8': 2.3.0
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/credential-provider-node': 3.958.0
- '@aws-sdk/middleware-host-header': 3.957.0
- '@aws-sdk/middleware-logger': 3.957.0
- '@aws-sdk/middleware-recursion-detection': 3.957.0
- '@aws-sdk/middleware-user-agent': 3.957.0
- '@aws-sdk/region-config-resolver': 3.957.0
- '@aws-sdk/types': 3.957.0
- '@aws-sdk/util-endpoints': 3.957.0
- '@aws-sdk/util-user-agent-browser': 3.957.0
- '@aws-sdk/util-user-agent-node': 3.957.0
- '@smithy/config-resolver': 4.4.5
- '@smithy/core': 3.20.0
- '@smithy/fetch-http-handler': 5.3.8
- '@smithy/hash-node': 4.2.7
- '@smithy/invalid-dependency': 4.2.7
- '@smithy/middleware-content-length': 4.2.7
- '@smithy/middleware-endpoint': 4.4.1
- '@smithy/middleware-retry': 4.4.17
- '@smithy/middleware-serde': 4.2.8
- '@smithy/middleware-stack': 4.2.7
- '@smithy/node-config-provider': 4.3.7
- '@smithy/node-http-handler': 4.4.7
- '@smithy/protocol-http': 5.3.7
- '@smithy/smithy-client': 4.10.2
- '@smithy/types': 4.11.0
- '@smithy/url-parser': 4.2.7
- '@smithy/util-base64': 4.3.0
- '@smithy/util-body-length-browser': 4.2.0
- '@smithy/util-body-length-node': 4.2.1
- '@smithy/util-defaults-mode-browser': 4.3.16
- '@smithy/util-defaults-mode-node': 4.2.19
- '@smithy/util-endpoints': 3.2.7
- '@smithy/util-middleware': 4.2.7
- '@smithy/util-retry': 4.2.7
- '@smithy/util-utf8': 4.2.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/credential-provider-node': 3.972.45
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/fetch-http-handler': 5.4.5
+ '@smithy/node-http-handler': 4.7.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
+ '@aws-crypto/sha1-browser': 5.2.0
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/credential-provider-node': 3.958.0
- '@aws-sdk/middleware-host-header': 3.957.0
- '@aws-sdk/middleware-logger': 3.957.0
- '@aws-sdk/middleware-recursion-detection': 3.957.0
- '@aws-sdk/middleware-user-agent': 3.957.0
- '@aws-sdk/region-config-resolver': 3.957.0
- '@aws-sdk/types': 3.957.0
- '@aws-sdk/util-endpoints': 3.957.0
- '@aws-sdk/util-user-agent-browser': 3.957.0
- '@aws-sdk/util-user-agent-node': 3.957.0
- '@smithy/config-resolver': 4.4.5
- '@smithy/core': 3.20.0
- '@smithy/fetch-http-handler': 5.3.8
- '@smithy/hash-node': 4.2.7
- '@smithy/invalid-dependency': 4.2.7
- '@smithy/middleware-content-length': 4.2.7
- '@smithy/middleware-endpoint': 4.4.1
- '@smithy/middleware-retry': 4.4.17
- '@smithy/middleware-serde': 4.2.8
- '@smithy/middleware-stack': 4.2.7
- '@smithy/node-config-provider': 4.3.7
- '@smithy/node-http-handler': 4.4.7
- '@smithy/protocol-http': 5.3.7
- '@smithy/smithy-client': 4.10.2
- '@smithy/types': 4.11.0
- '@smithy/url-parser': 4.2.7
- '@smithy/util-base64': 4.3.0
- '@smithy/util-body-length-browser': 4.2.0
- '@smithy/util-body-length-node': 4.2.1
- '@smithy/util-defaults-mode-browser': 4.3.16
- '@smithy/util-defaults-mode-node': 4.2.19
- '@smithy/util-endpoints': 3.2.7
- '@smithy/util-middleware': 4.2.7
- '@smithy/util-retry': 4.2.7
- '@smithy/util-utf8': 4.2.0
- '@smithy/util-waiter': 4.2.7
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/credential-provider-node': 3.972.45
+ '@aws-sdk/middleware-bucket-endpoint': 3.972.16
+ '@aws-sdk/middleware-expect-continue': 3.972.13
+ '@aws-sdk/middleware-flexible-checksums': 3.974.22
+ '@aws-sdk/middleware-location-constraint': 3.972.11
+ '@aws-sdk/middleware-sdk-s3': 3.972.43
+ '@aws-sdk/middleware-ssec': 3.972.11
+ '@aws-sdk/signature-v4-multi-region': 3.996.29
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/fetch-http-handler': 5.4.5
+ '@smithy/node-http-handler': 4.7.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/middleware-host-header': 3.957.0
- '@aws-sdk/middleware-logger': 3.957.0
- '@aws-sdk/middleware-recursion-detection': 3.957.0
- '@aws-sdk/middleware-user-agent': 3.957.0
- '@aws-sdk/region-config-resolver': 3.957.0
- '@aws-sdk/types': 3.957.0
- '@aws-sdk/util-endpoints': 3.957.0
- '@aws-sdk/util-user-agent-browser': 3.957.0
- '@aws-sdk/util-user-agent-node': 3.957.0
- '@smithy/config-resolver': 4.4.5
- '@smithy/core': 3.20.0
- '@smithy/fetch-http-handler': 5.3.8
- '@smithy/hash-node': 4.2.7
- '@smithy/invalid-dependency': 4.2.7
- '@smithy/middleware-content-length': 4.2.7
- '@smithy/middleware-endpoint': 4.4.1
- '@smithy/middleware-retry': 4.4.17
- '@smithy/middleware-serde': 4.2.8
- '@smithy/middleware-stack': 4.2.7
- '@smithy/node-config-provider': 4.3.7
- '@smithy/node-http-handler': 4.4.7
- '@smithy/protocol-http': 5.3.7
- '@smithy/smithy-client': 4.10.2
- '@smithy/types': 4.11.0
- '@smithy/url-parser': 4.2.7
- '@smithy/util-base64': 4.3.0
- '@smithy/util-body-length-browser': 4.2.0
- '@smithy/util-body-length-node': 4.2.1
- '@smithy/util-defaults-mode-browser': 4.3.16
- '@smithy/util-defaults-mode-node': 4.2.19
- '@smithy/util-endpoints': 3.2.7
- '@smithy/util-middleware': 4.2.7
- '@smithy/util-retry': 4.2.7
- '@smithy/util-utf8': 4.2.0
- tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
-
- '@aws-sdk/[email protected]':
- dependencies:
- '@aws-sdk/types': 3.957.0
- '@aws-sdk/xml-builder': 3.957.0
- '@smithy/core': 3.20.0
- '@smithy/node-config-provider': 4.3.7
- '@smithy/property-provider': 4.2.7
- '@smithy/protocol-http': 5.3.7
- '@smithy/signature-v4': 5.3.7
- '@smithy/smithy-client': 4.10.2
- '@smithy/types': 4.11.0
- '@smithy/util-base64': 4.3.0
- '@smithy/util-middleware': 4.2.7
- '@smithy/util-utf8': 4.2.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/credential-provider-node': 3.972.45
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/fetch-http-handler': 5.4.5
+ '@smithy/node-http-handler': 4.7.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/client-cognito-identity': 3.958.0
- '@aws-sdk/types': 3.957.0
- '@smithy/property-provider': 4.2.7
- '@smithy/types': 4.11.0
+ '@aws-sdk/types': 3.973.9
+ '@aws-sdk/xml-builder': 3.972.26
+ '@aws/lambda-invoke-store': 0.2.4
+ '@smithy/core': 3.24.5
+ '@smithy/signature-v4': 5.4.5
+ '@smithy/types': 4.14.2
+ bowser: 2.14.1
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/types': 3.957.0
- '@smithy/property-provider': 4.2.7
- '@smithy/types': 4.11.0
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
- dependencies:
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/types': 3.957.0
- '@smithy/fetch-http-handler': 5.3.8
- '@smithy/node-http-handler': 4.4.7
- '@smithy/property-provider': 4.2.7
- '@smithy/protocol-http': 5.3.7
- '@smithy/smithy-client': 4.10.2
- '@smithy/types': 4.11.0
- '@smithy/util-stream': 4.5.8
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/nested-clients': 3.997.12
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
- dependencies:
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/credential-provider-env': 3.957.0
- '@aws-sdk/credential-provider-http': 3.957.0
- '@aws-sdk/credential-provider-login': 3.958.0
- '@aws-sdk/credential-provider-process': 3.957.0
- '@aws-sdk/credential-provider-sso': 3.958.0
- '@aws-sdk/credential-provider-web-identity': 3.958.0
- '@aws-sdk/nested-clients': 3.958.0
- '@aws-sdk/types': 3.957.0
- '@smithy/credential-provider-imds': 4.2.7
- '@smithy/property-provider': 4.2.7
- '@smithy/shared-ini-file-loader': 4.4.2
- '@smithy/types': 4.11.0
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/nested-clients': 3.958.0
- '@aws-sdk/types': 3.957.0
- '@smithy/property-provider': 4.2.7
- '@smithy/protocol-http': 5.3.7
- '@smithy/shared-ini-file-loader': 4.4.2
- '@smithy/types': 4.11.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/fetch-http-handler': 5.4.5
+ '@smithy/node-http-handler': 4.7.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
-
- '@aws-sdk/[email protected]':
- dependencies:
- '@aws-sdk/credential-provider-env': 3.957.0
- '@aws-sdk/credential-provider-http': 3.957.0
- '@aws-sdk/credential-provider-ini': 3.958.0
- '@aws-sdk/credential-provider-process': 3.957.0
- '@aws-sdk/credential-provider-sso': 3.958.0
- '@aws-sdk/credential-provider-web-identity': 3.958.0
- '@aws-sdk/types': 3.957.0
- '@smithy/credential-provider-imds': 4.2.7
- '@smithy/property-provider': 4.2.7
- '@smithy/shared-ini-file-loader': 4.4.2
- '@smithy/types': 4.11.0
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/credential-provider-env': 3.972.40
+ '@aws-sdk/credential-provider-http': 3.972.42
+ '@aws-sdk/credential-provider-login': 3.972.44
+ '@aws-sdk/credential-provider-process': 3.972.40
+ '@aws-sdk/credential-provider-sso': 3.972.44
+ '@aws-sdk/credential-provider-web-identity': 3.972.44
+ '@aws-sdk/nested-clients': 3.997.12
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/credential-provider-imds': 4.3.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/types': 3.957.0
- '@smithy/property-provider': 4.2.7
- '@smithy/shared-ini-file-loader': 4.4.2
- '@smithy/types': 4.11.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/nested-clients': 3.997.12
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
- dependencies:
- '@aws-sdk/client-sso': 3.958.0
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/token-providers': 3.958.0
- '@aws-sdk/types': 3.957.0
- '@smithy/property-provider': 4.2.7
- '@smithy/shared-ini-file-loader': 4.4.2
- '@smithy/types': 4.11.0
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/credential-provider-env': 3.972.40
+ '@aws-sdk/credential-provider-http': 3.972.42
+ '@aws-sdk/credential-provider-ini': 3.972.44
+ '@aws-sdk/credential-provider-process': 3.972.40
+ '@aws-sdk/credential-provider-sso': 3.972.44
+ '@aws-sdk/credential-provider-web-identity': 3.972.44
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/credential-provider-imds': 4.3.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/nested-clients': 3.958.0
- '@aws-sdk/types': 3.957.0
- '@smithy/property-provider': 4.2.7
- '@smithy/shared-ini-file-loader': 4.4.2
- '@smithy/types': 4.11.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
-
- '@aws-sdk/[email protected]':
- dependencies:
- '@aws-sdk/client-cognito-identity': 3.958.0
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/credential-provider-cognito-identity': 3.958.0
- '@aws-sdk/credential-provider-env': 3.957.0
- '@aws-sdk/credential-provider-http': 3.957.0
- '@aws-sdk/credential-provider-ini': 3.958.0
- '@aws-sdk/credential-provider-login': 3.958.0
- '@aws-sdk/credential-provider-node': 3.958.0
- '@aws-sdk/credential-provider-process': 3.957.0
- '@aws-sdk/credential-provider-sso': 3.958.0
- '@aws-sdk/credential-provider-web-identity': 3.958.0
- '@aws-sdk/nested-clients': 3.958.0
- '@aws-sdk/types': 3.957.0
- '@smithy/config-resolver': 4.4.5
- '@smithy/core': 3.20.0
- '@smithy/credential-provider-imds': 4.2.7
- '@smithy/node-config-provider': 4.3.7
- '@smithy/property-provider': 4.2.7
- '@smithy/types': 4.11.0
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/nested-clients': 3.997.12
+ '@aws-sdk/token-providers': 3.1054.0
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/types': 3.957.0
- '@smithy/protocol-http': 5.3.7
- '@smithy/types': 4.11.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/nested-clients': 3.997.12
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected]':
+ dependencies:
+ '@aws-sdk/client-cognito-identity': 3.1055.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/credential-provider-cognito-identity': 3.972.37
+ '@aws-sdk/credential-provider-env': 3.972.40
+ '@aws-sdk/credential-provider-http': 3.972.42
+ '@aws-sdk/credential-provider-ini': 3.972.44
+ '@aws-sdk/credential-provider-login': 3.972.44
+ '@aws-sdk/credential-provider-node': 3.972.45
+ '@aws-sdk/credential-provider-process': 3.972.40
+ '@aws-sdk/credential-provider-sso': 3.972.44
+ '@aws-sdk/credential-provider-web-identity': 3.972.44
+ '@aws-sdk/nested-clients': 3.997.12
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/credential-provider-imds': 4.3.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/types': 3.957.0
- '@smithy/types': 4.11.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/types': 3.957.0
- '@aws/lambda-invoke-store': 0.2.2
- '@smithy/protocol-http': 5.3.7
- '@smithy/types': 4.11.0
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/types': 3.957.0
- '@aws-sdk/util-endpoints': 3.957.0
- '@smithy/core': 3.20.0
- '@smithy/protocol-http': 5.3.7
- '@smithy/types': 4.11.0
+ '@aws-crypto/crc32': 5.2.0
+ '@aws-crypto/crc32c': 5.2.0
+ '@aws-crypto/util': 5.2.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/crc64-nvme': 3.972.9
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-crypto/sha256-browser': 5.2.0
- '@aws-crypto/sha256-js': 5.2.0
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/middleware-host-header': 3.957.0
- '@aws-sdk/middleware-logger': 3.957.0
- '@aws-sdk/middleware-recursion-detection': 3.957.0
- '@aws-sdk/middleware-user-agent': 3.957.0
- '@aws-sdk/region-config-resolver': 3.957.0
- '@aws-sdk/types': 3.957.0
- '@aws-sdk/util-endpoints': 3.957.0
- '@aws-sdk/util-user-agent-browser': 3.957.0
- '@aws-sdk/util-user-agent-node': 3.957.0
- '@smithy/config-resolver': 4.4.5
- '@smithy/core': 3.20.0
- '@smithy/fetch-http-handler': 5.3.8
- '@smithy/hash-node': 4.2.7
- '@smithy/invalid-dependency': 4.2.7
- '@smithy/middleware-content-length': 4.2.7
- '@smithy/middleware-endpoint': 4.4.1
- '@smithy/middleware-retry': 4.4.17
- '@smithy/middleware-serde': 4.2.8
- '@smithy/middleware-stack': 4.2.7
- '@smithy/node-config-provider': 4.3.7
- '@smithy/node-http-handler': 4.4.7
- '@smithy/protocol-http': 5.3.7
- '@smithy/smithy-client': 4.10.2
- '@smithy/types': 4.11.0
- '@smithy/url-parser': 4.2.7
- '@smithy/util-base64': 4.3.0
- '@smithy/util-body-length-browser': 4.2.0
- '@smithy/util-body-length-node': 4.2.1
- '@smithy/util-defaults-mode-browser': 4.3.16
- '@smithy/util-defaults-mode-node': 4.2.19
- '@smithy/util-endpoints': 3.2.7
- '@smithy/util-middleware': 4.2.7
- '@smithy/util-retry': 4.2.7
- '@smithy/util-utf8': 4.2.0
+ '@aws-sdk/types': 3.973.9
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@smithy/protocol-http': 1.2.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/signature-v4-multi-region': 3.996.29
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/types': 3.957.0
- '@smithy/config-resolver': 4.4.5
- '@smithy/node-config-provider': 4.3.7
- '@smithy/types': 4.11.0
+ '@aws-sdk/types': 3.973.9
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@smithy/signature-v4': 1.1.0
+ '@aws-crypto/sha256-browser': 5.2.0
+ '@aws-crypto/sha256-js': 5.2.0
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/signature-v4-multi-region': 3.996.29
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/fetch-http-handler': 5.4.5
+ '@smithy/node-http-handler': 4.7.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/core': 3.957.0
- '@aws-sdk/nested-clients': 3.958.0
- '@aws-sdk/types': 3.957.0
- '@smithy/property-provider': 4.2.7
- '@smithy/shared-ini-file-loader': 4.4.2
- '@smithy/types': 4.11.0
+ '@smithy/protocol-http': 1.2.0
tslib: 2.8.1
- transitivePeerDependencies:
- - aws-crt
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@smithy/types': 4.11.0
+ '@aws-sdk/types': 3.973.9
+ '@smithy/signature-v4': 5.4.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/types': 3.957.0
- '@smithy/types': 4.11.0
- '@smithy/url-parser': 4.2.7
- '@smithy/util-endpoints': 3.2.7
+ '@smithy/signature-v4': 1.1.0
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
+ '@aws-sdk/core': 3.974.14
+ '@aws-sdk/nested-clients': 3.997.12
+ '@aws-sdk/types': 3.973.9
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/types': 3.957.0
- '@smithy/types': 4.11.0
- bowser: 2.13.1
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@aws-sdk/middleware-user-agent': 3.957.0
- '@aws-sdk/types': 3.957.0
- '@smithy/node-config-provider': 4.3.7
- '@smithy/types': 4.11.0
tslib: 2.8.1
'@aws-sdk/[email protected]':
dependencies:
tslib: 2.8.1
- '@aws-sdk/[email protected]':
+ '@aws-sdk/[email protected]':
dependencies:
- '@smithy/types': 4.11.0
- fast-xml-parser: 5.2.5
+ '@smithy/types': 4.14.2
+ fast-xml-parser: 5.7.3
tslib: 2.8.1
- '@aws/[email protected]': {}
+ '@aws/[email protected]': {}
- '@azure-rest/[email protected]':
+ '@azure-rest/[email protected]':
dependencies:
'@azure/abort-controller': 2.1.2
'@azure/core-auth': 1.10.1
- '@azure/core-rest-pipeline': 1.22.2
+ '@azure/core-rest-pipeline': 1.23.0
'@azure/core-tracing': 1.3.1
- '@typespec/ts-http-runtime': 0.3.2
+ '@typespec/ts-http-runtime': 0.3.5
tslib: 2.8.1
transitivePeerDependencies:
- supports-color
@@ -4143,7 +3890,7 @@ snapshots:
dependencies:
'@azure/abort-controller': 2.1.2
'@azure/core-auth': 1.10.1
- '@azure/core-rest-pipeline': 1.22.2
+ '@azure/core-rest-pipeline': 1.23.0
'@azure/core-tracing': 1.3.1
'@azure/core-util': 1.13.1
'@azure/logger': 1.3.0
@@ -4151,13 +3898,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@azure/[email protected]':
dependencies:
'@azure/abort-controller': 2.1.2
'@azure/core-client': 1.10.1
- '@azure/core-rest-pipeline': 1.22.2
- transitivePeerDependencies:
- - supports-color
+ '@azure/core-rest-pipeline': 1.23.0
dependencies:
@@ -4172,14 +3917,14 @@ snapshots:
dependencies:
tslib: 2.8.1
- '@azure/[email protected]':
+ '@azure/[email protected]':
dependencies:
'@azure/abort-controller': 2.1.2
'@azure/core-auth': 1.10.1
'@azure/core-tracing': 1.3.1
'@azure/core-util': 1.13.1
'@azure/logger': 1.3.0
- '@typespec/ts-http-runtime': 0.3.2
+ '@typespec/ts-http-runtime': 0.3.5
tslib: 2.8.1
transitivePeerDependencies:
- supports-color
@@ -4191,49 +3936,50 @@ snapshots:
dependencies:
'@azure/abort-controller': 2.1.2
- '@typespec/ts-http-runtime': 0.3.2
+ '@typespec/ts-http-runtime': 0.3.5
tslib: 2.8.1
transitivePeerDependencies:
- supports-color
- '@azure/[email protected]':
dependencies:
'@azure/abort-controller': 2.1.2
'@azure/core-auth': 1.10.1
- '@azure/core-rest-pipeline': 1.22.2
+ '@azure/core-rest-pipeline': 1.23.0
'@azure/core-tracing': 1.3.1
'@azure/core-util': 1.13.1
- '@azure/keyvault-keys': 4.10.0
+ '@azure/keyvault-keys': 4.10.0(@azure/[email protected])
'@azure/logger': 1.3.0
fast-json-stable-stringify: 2.1.0
priorityqueuejs: 2.0.0
semaphore: 1.1.0
tslib: 2.8.1
transitivePeerDependencies:
+ - '@azure/core-client'
- supports-color
- '@azure/[email protected]':
+ '@azure/[email protected]':
dependencies:
'@azure/abort-controller': 2.1.2
'@azure/core-auth': 1.10.1
'@azure/core-client': 1.10.1
- '@azure/core-rest-pipeline': 1.22.2
+ '@azure/core-rest-pipeline': 1.23.0
'@azure/core-tracing': 1.3.1
'@azure/core-util': 1.13.1
'@azure/logger': 1.3.0
- '@azure/msal-browser': 4.27.0
- '@azure/msal-node': 3.8.4
+ '@azure/msal-browser': 5.11.0
+ '@azure/msal-node': 5.2.2
open: 10.2.0
tslib: 2.8.1
transitivePeerDependencies:
- supports-color
- '@azure/[email protected]':
+ '@azure/[email protected]':
dependencies:
+ '@azure-rest/core-client': 2.6.0
'@azure/abort-controller': 2.1.2
'@azure/core-auth': 1.10.1
- '@azure/core-client': 1.10.1
- '@azure/core-rest-pipeline': 1.22.2
+ '@azure/core-rest-pipeline': 1.23.0
'@azure/core-tracing': 1.3.1
'@azure/core-util': 1.13.1
'@azure/logger': 1.3.0
@@ -4241,49 +3987,49 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@azure/[email protected]':
dependencies:
- '@azure-rest/core-client': 2.5.1
+ '@azure-rest/core-client': 2.6.0
'@azure/abort-controller': 2.1.2
'@azure/core-auth': 1.10.1
- '@azure/core-http-compat': 2.3.1
+ '@azure/core-http-compat': 2.4.0(@azure/[email protected])(@azure/[email protected])
'@azure/core-lro': 2.7.2
'@azure/core-paging': 1.6.2
- '@azure/core-rest-pipeline': 1.22.2
+ '@azure/core-rest-pipeline': 1.23.0
'@azure/core-tracing': 1.3.1
'@azure/core-util': 1.13.1
- '@azure/keyvault-common': 2.0.0
+ '@azure/keyvault-common': 2.1.0
'@azure/logger': 1.3.0
tslib: 2.8.1
transitivePeerDependencies:
+ - '@azure/core-client'
- supports-color
dependencies:
- '@typespec/ts-http-runtime': 0.3.2
+ '@typespec/ts-http-runtime': 0.3.5
tslib: 2.8.1
transitivePeerDependencies:
- supports-color
- '@azure/[email protected]':
+ '@azure/[email protected]':
dependencies:
- '@azure/msal-common': 15.13.3
+ '@azure/msal-common': 16.6.2
- '@azure/[email protected]': {}
+ '@azure/[email protected]': {}
- '@azure/[email protected]':
+ '@azure/[email protected]':
dependencies:
- '@azure/msal-common': 15.13.3
+ '@azure/msal-common': 16.6.2
jsonwebtoken: 9.0.3
- uuid: 8.3.2
dependencies:
'@azure/core-auth': 1.10.1
'@azure/core-client': 1.10.1
- '@azure/core-http-compat': 2.3.1
+ '@azure/core-http-compat': 2.4.0(@azure/[email protected])(@azure/[email protected])
'@azure/core-paging': 1.6.2
- '@azure/core-rest-pipeline': 1.22.2
+ '@azure/core-rest-pipeline': 1.23.0
'@azure/core-tracing': 1.3.1
'@azure/core-util': 1.13.1
'@azure/logger': 1.3.0
@@ -4344,176 +4090,128 @@ snapshots:
typed-emitter: 2.1.0
uuidv7: 0.6.3
+ '@datastructures-js/[email protected]': {}
+
'@discordjs/[email protected]': {}
- '@discordjs/[email protected]':
+ '@discordjs/[email protected]':
dependencies:
'@discordjs/collection': 2.1.1
'@discordjs/util': 1.2.0
'@sapphire/async-queue': 1.5.5
'@sapphire/snowflake': 3.5.5
'@vladfrangu/async_event_emitter': 2.4.7
- discord-api-types: 0.38.37
- magic-bytes.js: 1.12.1
+ discord-api-types: 0.38.48
+ magic-bytes.js: 1.13.0
tslib: 2.8.1
- undici: 6.21.3
+ undici: 6.24.1
'@discordjs/[email protected]':
dependencies:
- discord-api-types: 0.38.37
+ discord-api-types: 0.38.48
'@discoveryjs/[email protected]': {}
- '@emnapi/[email protected]':
dependencies:
- tslib: 2.8.1
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
-
- '@esbuild/[email protected]':
- optional: true
+ '@aws-sdk/client-s3': 3.1055.0
+ '@types/node-int64': 0.4.32
+ '@types/thrift': 0.10.17
+ '@zenfs/core': 1.11.4
+ brotli-wasm: 3.0.1
+ bson: 6.10.3
+ int53: 1.0.0
+ long: 5.3.2
+ node-int64: 0.4.0
+ snappyjs: 0.7.0
+ thrift: 0.21.0
+ varint: 6.0.0
+ xxhash-wasm: 1.1.0
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
- '@esbuild/[email protected]':
+ '@emnapi/[email protected]':
+ dependencies:
+ tslib: 2.8.1
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
- '@esbuild/[email protected]':
+ '@esbuild/[email protected]':
optional: true
'@google-cloud/[email protected]':
@@ -4525,32 +4223,20 @@ snapshots:
'@google/[email protected]': {}
- '@graphql-typed-document-node/[email protected]([email protected])':
+ '@graphql-typed-document-node/[email protected]([email protected])':
dependencies:
- graphql: 16.12.0
+ graphql: 16.14.0
dependencies:
- '@grpc/proto-loader': 0.8.0
+ '@grpc/proto-loader': 0.8.1
'@js-sdsl/ordered-map': 4.4.2
- dependencies:
- '@grpc/proto-loader': 0.7.15
- '@types/node': 22.19.3
-
- dependencies:
- lodash.camelcase: 4.3.0
- long: 5.3.2
- protobufjs: 7.5.4
- yargs: 17.7.2
-
dependencies:
lodash.camelcase: 4.3.0
long: 5.3.2
- protobufjs: 7.5.4
+ protobufjs: 7.6.1
yargs: 17.7.2
'@huggingface/[email protected]':
@@ -4559,18 +4245,18 @@ snapshots:
'@huggingface/[email protected]': {}
- '@huggingface/[email protected]': {}
+ '@huggingface/[email protected]': {}
'@huggingface/[email protected]': {}
'@huggingface/[email protected]':
dependencies:
- '@huggingface/jinja': 0.5.3
+ '@huggingface/jinja': 0.5.9
onnxruntime-node: 1.21.0
onnxruntime-web: 1.22.0-dev.20250409-89f8206ba4
sharp: 0.34.5
- '@img/[email protected]': {}
+ '@img/[email protected]': {}
optionalDependencies:
@@ -4654,7 +4340,7 @@ snapshots:
dependencies:
- '@emnapi/runtime': 1.7.1
+ '@emnapi/runtime': 1.10.0
optional: true
@@ -4668,7 +4354,7 @@ snapshots:
'@isaacs/[email protected]':
dependencies:
- minipass: 7.1.2
+ minipass: 7.1.3
'@jridgewell/[email protected]':
dependencies:
@@ -4724,33 +4410,34 @@ snapshots:
'@lancedb/lancedb-win32-arm64-msvc': 0.17.0
'@lancedb/lancedb-win32-x64-msvc': 0.17.0
dependencies:
'@cfworker/json-schema': 4.1.1
ansi-styles: 5.2.0
camelcase: 6.3.0
decamelize: 1.2.0
js-tiktoken: 1.0.21
mustache: 4.2.0
p-queue: 6.6.2
p-retry: 4.6.2
- uuid: 10.0.0
+ uuid: 14.0.0
zod: 3.25.76
- zod-to-json-schema: 3.25.1([email protected])
+ zod-to-json-schema: 3.25.2([email protected])
transitivePeerDependencies:
- '@opentelemetry/api'
- '@opentelemetry/exporter-trace-otlp-proto'
- '@opentelemetry/sdk-trace-base'
- openai
+ - ws
dependencies:
'@anthropic-ai/sdk': 0.32.1
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- remeda: 2.32.0
- vitest: 2.1.9(@types/[email protected])
+ remeda: 2.37.0
+ vitest: 2.1.9(@types/[email protected])([email protected])
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@edge-runtime/vm'
@@ -4761,6 +4448,7 @@ snapshots:
- encoding
- gpt-tokenizer
- happy-dom
+ - jiti
- js-tiktoken
- jsdom
- less
@@ -4774,6 +4462,8 @@ snapshots:
- supports-color
- terser
- tiktoken
+ - tsx
+ - yaml
dependencies:
@@ -4788,17 +4478,18 @@ snapshots:
- pathe
- tiktoken
dependencies:
- '@azure/cosmos': 4.9.0
- '@azure/identity': 4.13.0
+ '@azure/cosmos': 4.9.3(@azure/[email protected])
+ '@azure/identity': 4.13.1
'@azure/search-documents': 12.2.0
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- mongodb: 6.21.0(@aws-sdk/[email protected])
+ mongodb: 6.21.0(@aws-sdk/[email protected])
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@aws-sdk/credential-providers'
+ - '@azure/core-client'
- '@huggingface/transformers'
- '@mongodb-js/zstd'
- gcp-metadata
@@ -4812,11 +4503,11 @@ snapshots:
- supports-color
- tiktoken
dependencies:
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
chromadb-default-embed: 2.14.0
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
@@ -4834,12 +4525,12 @@ snapshots:
- tiktoken
- voyageai
dependencies:
'@huggingface/transformers': 3.8.1
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- encoding
@@ -4863,7 +4554,6 @@ snapshots:
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
- - aws-crt
- encoding
- gpt-tokenizer
- js-tiktoken
@@ -4873,10 +4563,10 @@ snapshots:
dependencies:
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- '@types/node': 22.19.3
- magic-bytes.js: 1.12.1
+ '@types/node': 22.19.19
+ magic-bytes.js: 1.13.0
zod: 3.25.76
- zod-to-json-schema: 3.25.1([email protected])
+ zod-to-json-schema: 3.25.2([email protected])
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
@@ -4885,11 +4575,11 @@ snapshots:
- pathe
- tiktoken
dependencies:
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
@@ -4926,10 +4616,10 @@ snapshots:
- supports-color
- tiktoken
dependencies:
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
groq-sdk: 0.8.0
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
@@ -4942,13 +4632,13 @@ snapshots:
- ws
- zod
dependencies:
'@huggingface/inference': 2.8.1
'@huggingface/transformers': 3.8.1
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- encoding
@@ -4961,30 +4651,34 @@ snapshots:
dependencies:
- '@grpc/grpc-js': 1.14.3
+ '@grpc/grpc-js': 1.14.4
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- '@zilliz/milvus2-sdk-node': 2.6.9
+ '@zilliz/milvus2-sdk-node': 2.6.15
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
+ - bufferutil
- gpt-tokenizer
- js-tiktoken
- pathe
- tiktoken
+ - utf-8-validate
dependencies:
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- '@mistralai/mistralai': 1.11.0
+ '@mistralai/mistralai': 1.15.1
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
+ - bufferutil
- gpt-tokenizer
- js-tiktoken
- pathe
- tiktoken
+ - utf-8-validate
dependencies:
@@ -5000,11 +4694,11 @@ snapshots:
- pathe
- tiktoken
dependencies:
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- mongodb: 6.7.0(@aws-sdk/[email protected])
+ mongodb: 6.7.0(@aws-sdk/[email protected])
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@aws-sdk/credential-providers'
@@ -5033,7 +4727,7 @@ snapshots:
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
ollama: 0.5.18
- remeda: 2.32.0
+ remeda: 2.37.0
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
@@ -5042,11 +4736,11 @@ snapshots:
- pathe
- tiktoken
dependencies:
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
@@ -5076,7 +4770,7 @@ snapshots:
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
portkey-ai: 0.1.16
- remeda: 2.32.0
+ remeda: 2.37.0
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
@@ -5106,7 +4800,7 @@ snapshots:
dependencies:
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- '@qdrant/js-client-rest': 1.16.2([email protected])
+ '@qdrant/js-client-rest': 1.18.0([email protected])
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
@@ -5116,23 +4810,24 @@ snapshots:
- tiktoken
- typescript
dependencies:
- '@azure/cosmos': 4.9.0
- '@discordjs/rest': 2.6.0
+ '@azure/cosmos': 4.9.3(@azure/[email protected])
+ '@discordjs/rest': 2.6.1
'@discoveryjs/json-ext': 0.6.3
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- assemblyai: 4.22.1
+ assemblyai: 4.33.3
csv-parse: 5.6.0
discord-api-types: 0.37.120
- mammoth: 1.11.0
- mongodb: 6.21.0(@aws-sdk/[email protected])
+ mammoth: 1.12.0
+ mongodb: 6.21.0(@aws-sdk/[email protected])
notion-md-crawler: 1.0.2
papaparse: 5.5.3
unpdf: 0.12.2
transitivePeerDependencies:
- '@aws-sdk/credential-providers'
+ - '@azure/core-client'
- '@mongodb-js/zstd'
- bufferutil
- encoding
@@ -5161,7 +4856,7 @@ snapshots:
dependencies:
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- '@upstash/vector': 1.2.2
+ '@upstash/vector': 1.2.3
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
@@ -5170,9 +4865,9 @@ snapshots:
- pathe
- tiktoken
dependencies:
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
@@ -5188,7 +4883,7 @@ snapshots:
dependencies:
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- weaviate-client: 3.10.0
+ weaviate-client: 3.13.1
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@huggingface/transformers'
@@ -5207,315 +4902,209 @@ snapshots:
nopt: 5.0.0
npmlog: 5.0.1
rimraf: 3.0.2
- semver: 7.7.3
- tar: 6.2.1
+ semver: 7.8.1
+ tar: 7.5.15
transitivePeerDependencies:
- encoding
- supports-color
optional: true
- '@mistralai/[email protected]':
+ '@mistralai/[email protected]':
dependencies:
- zod: 3.25.76
- zod-to-json-schema: 3.25.1([email protected])
+ ws: 8.21.0
+ zod: 4.4.3
+ zod-to-json-schema: 3.25.2([email protected])
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
'@mixedbread-ai/[email protected]':
dependencies:
- form-data: 4.0.0
+ form-data: 4.0.5
formdata-node: 6.0.3
js-base64: 3.7.2
node-fetch: 2.7.0
- qs: 6.11.2
+ qs: 6.15.2
url-join: 4.0.1
transitivePeerDependencies:
- encoding
- '@mongodb-js/[email protected]':
+ '@mongodb-js/[email protected]':
dependencies:
sparse-bitfield: 3.0.3
'@msgpack/[email protected]': {}
+ '@nodable/[email protected]': {}
+
'@notionhq/[email protected]': {}
- '@opentelemetry/[email protected]': {}
+ '@opentelemetry/[email protected]': {}
'@petamoriken/[email protected]': {}
'@pinecone-database/[email protected]': {}
- '@playwright/[email protected]':
+ '@playwright/[email protected]':
dependencies:
- playwright: 1.57.0
+ playwright: 1.60.0
'@protobufjs/[email protected]': {}
'@protobufjs/[email protected]': {}
- '@protobufjs/[email protected]': {}
+ '@protobufjs/[email protected]': {}
- '@protobufjs/[email protected]': {}
+ '@protobufjs/[email protected]': {}
- '@protobufjs/[email protected]':
+ '@protobufjs/[email protected]':
dependencies:
'@protobufjs/aspromise': 1.1.2
- '@protobufjs/inquire': 1.1.0
'@protobufjs/[email protected]': {}
- '@protobufjs/[email protected]': {}
+ '@protobufjs/[email protected]': {}
'@protobufjs/[email protected]': {}
'@protobufjs/[email protected]': {}
- '@protobufjs/[email protected]': {}
+ '@protobufjs/[email protected]': {}
dependencies:
'@qdrant/openapi-typescript-fetch': 1.2.6
typescript: 5.9.3
- undici: 6.22.0
+ undici: 6.26.0
'@qdrant/[email protected]': {}
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
- optional: true
-
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@rollup/[email protected]':
+ '@rollup/[email protected]':
optional: true
- '@sapphire/[email protected]': {}
-
- '@sapphire/[email protected]': {}
-
- '@selderee/[email protected]':
- dependencies:
- domhandler: 5.0.3
- selderee: 0.11.0
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/types': 4.11.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/node-config-provider': 4.3.7
- '@smithy/types': 4.11.0
- '@smithy/util-config-provider': 4.2.0
- '@smithy/util-endpoints': 3.2.7
- '@smithy/util-middleware': 4.2.7
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/middleware-serde': 4.2.8
- '@smithy/protocol-http': 5.3.7
- '@smithy/types': 4.11.0
- '@smithy/util-base64': 4.3.0
- '@smithy/util-body-length-browser': 4.2.0
- '@smithy/util-middleware': 4.2.7
- '@smithy/util-stream': 4.5.8
- '@smithy/util-utf8': 4.2.0
- '@smithy/uuid': 1.1.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/node-config-provider': 4.3.7
- '@smithy/property-provider': 4.2.7
- '@smithy/types': 4.11.0
- '@smithy/url-parser': 4.2.7
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@aws-crypto/crc32': 3.0.0
- '@smithy/types': 1.2.0
- '@smithy/util-hex-encoding': 1.1.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/protocol-http': 5.3.7
- '@smithy/querystring-builder': 4.2.7
- '@smithy/types': 4.11.0
- '@smithy/util-base64': 4.3.0
- tslib: 2.8.1
+ '@rollup/[email protected]':
+ optional: true
- '@smithy/[email protected]':
- dependencies:
- '@smithy/types': 4.11.0
- '@smithy/util-buffer-from': 4.2.0
- '@smithy/util-utf8': 4.2.0
- tslib: 2.8.1
+ '@rollup/[email protected]':
+ optional: true
- '@smithy/[email protected]':
- dependencies:
- '@smithy/types': 4.11.0
- tslib: 2.8.1
+ '@rollup/[email protected]':
+ optional: true
- '@smithy/[email protected]':
- dependencies:
- tslib: 2.8.1
+ '@rollup/[email protected]':
+ optional: true
- '@smithy/[email protected]':
- dependencies:
- tslib: 2.8.1
+ '@rollup/[email protected]':
+ optional: true
- '@smithy/[email protected]':
- dependencies:
- tslib: 2.8.1
+ '@rollup/[email protected]':
+ optional: true
- '@smithy/[email protected]':
- dependencies:
- '@smithy/protocol-http': 5.3.7
- '@smithy/types': 4.11.0
- tslib: 2.8.1
+ '@rollup/[email protected]':
+ optional: true
- '@smithy/[email protected]':
- dependencies:
- '@smithy/core': 3.20.0
- '@smithy/middleware-serde': 4.2.8
- '@smithy/node-config-provider': 4.3.7
- '@smithy/shared-ini-file-loader': 4.4.2
- '@smithy/types': 4.11.0
- '@smithy/url-parser': 4.2.7
- '@smithy/util-middleware': 4.2.7
- tslib: 2.8.1
+ '@rollup/[email protected]':
+ optional: true
- '@smithy/[email protected]':
- dependencies:
- '@smithy/node-config-provider': 4.3.7
- '@smithy/protocol-http': 5.3.7
- '@smithy/service-error-classification': 4.2.7
- '@smithy/smithy-client': 4.10.2
- '@smithy/types': 4.11.0
- '@smithy/util-middleware': 4.2.7
- '@smithy/util-retry': 4.2.7
- '@smithy/uuid': 1.1.0
- tslib: 2.8.1
+ '@rollup/[email protected]':
+ optional: true
- '@smithy/[email protected]':
- dependencies:
- '@smithy/protocol-http': 5.3.7
- '@smithy/types': 4.11.0
- tslib: 2.8.1
+ '@sapphire/[email protected]': {}
- '@smithy/[email protected]':
- dependencies:
- '@smithy/types': 4.11.0
- tslib: 2.8.1
+ '@sapphire/[email protected]': {}
- '@smithy/[email protected]':
+ '@selderee/[email protected]':
dependencies:
- '@smithy/property-provider': 4.2.7
- '@smithy/shared-ini-file-loader': 4.4.2
- '@smithy/types': 4.11.0
- tslib: 2.8.1
+ domhandler: 5.0.3
+ selderee: 0.11.0
- '@smithy/[email protected]':
+ '@smithy/[email protected]':
dependencies:
- '@smithy/abort-controller': 4.2.7
- '@smithy/protocol-http': 5.3.7
- '@smithy/querystring-builder': 4.2.7
- '@smithy/types': 4.11.0
+ '@aws-crypto/crc32': 5.2.0
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@smithy/[email protected]':
+ '@smithy/[email protected]':
dependencies:
- '@smithy/types': 4.11.0
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@smithy/[email protected]':
+ '@smithy/[email protected]':
dependencies:
+ '@aws-crypto/crc32': 3.0.0
'@smithy/types': 1.2.0
+ '@smithy/util-hex-encoding': 1.1.0
tslib: 2.8.1
- '@smithy/[email protected]':
+ '@smithy/[email protected]':
dependencies:
- '@smithy/types': 4.11.0
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
- '@smithy/[email protected]':
+ '@smithy/[email protected]':
dependencies:
- '@smithy/types': 4.11.0
- '@smithy/util-uri-escape': 4.2.0
tslib: 2.8.1
- '@smithy/[email protected]':
+ '@smithy/[email protected]':
dependencies:
- '@smithy/types': 4.11.0
tslib: 2.8.1
- '@smithy/[email protected]':
+ '@smithy/[email protected]':
dependencies:
- '@smithy/types': 4.11.0
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
+ tslib: 2.8.1
- '@smithy/[email protected]':
+ '@smithy/[email protected]':
dependencies:
- '@smithy/types': 4.11.0
+ '@smithy/types': 1.2.0
tslib: 2.8.1
'@smithy/[email protected]':
@@ -5529,52 +5118,17 @@ snapshots:
'@smithy/util-utf8': 1.1.0
tslib: 2.8.1
- '@smithy/[email protected]':
+ '@smithy/[email protected]':
dependencies:
- '@smithy/is-array-buffer': 4.2.0
- '@smithy/protocol-http': 5.3.7
- '@smithy/types': 4.11.0
- '@smithy/util-hex-encoding': 4.2.0
- '@smithy/util-middleware': 4.2.7
- '@smithy/util-uri-escape': 4.2.0
- '@smithy/util-utf8': 4.2.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/core': 3.20.0
- '@smithy/middleware-endpoint': 4.4.1
- '@smithy/middleware-stack': 4.2.7
- '@smithy/protocol-http': 5.3.7
- '@smithy/types': 4.11.0
- '@smithy/util-stream': 4.5.8
+ '@smithy/core': 3.24.5
+ '@smithy/types': 4.14.2
tslib: 2.8.1
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
- '@smithy/[email protected]':
- dependencies:
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/querystring-parser': 4.2.7
- '@smithy/types': 4.11.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/util-buffer-from': 4.2.0
- '@smithy/util-utf8': 4.2.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- tslib: 2.8.1
-
- '@smithy/[email protected]':
+ '@smithy/[email protected]':
dependencies:
tslib: 2.8.1
@@ -5588,80 +5142,18 @@ snapshots:
'@smithy/is-array-buffer': 2.2.0
tslib: 2.8.1
- '@smithy/[email protected]':
- dependencies:
- '@smithy/is-array-buffer': 4.2.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/property-provider': 4.2.7
- '@smithy/smithy-client': 4.10.2
- '@smithy/types': 4.11.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/config-resolver': 4.4.5
- '@smithy/credential-provider-imds': 4.2.7
- '@smithy/node-config-provider': 4.3.7
- '@smithy/property-provider': 4.2.7
- '@smithy/smithy-client': 4.10.2
- '@smithy/types': 4.11.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/node-config-provider': 4.3.7
- '@smithy/types': 4.11.0
- tslib: 2.8.1
-
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
- '@smithy/[email protected]':
- dependencies:
- tslib: 2.8.1
-
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
- '@smithy/[email protected]':
- dependencies:
- '@smithy/types': 4.11.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/service-error-classification': 4.2.7
- '@smithy/types': 4.11.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/fetch-http-handler': 5.3.8
- '@smithy/node-http-handler': 4.4.7
- '@smithy/types': 4.11.0
- '@smithy/util-base64': 4.3.0
- '@smithy/util-buffer-from': 4.2.0
- '@smithy/util-hex-encoding': 4.2.0
- '@smithy/util-utf8': 4.2.0
- tslib: 2.8.1
-
'@smithy/[email protected]':
dependencies:
tslib: 2.8.1
- '@smithy/[email protected]':
- dependencies:
- tslib: 2.8.1
-
'@smithy/[email protected]':
dependencies:
'@smithy/util-buffer-from': 1.1.0
@@ -5672,27 +5164,12 @@ snapshots:
'@smithy/util-buffer-from': 2.2.0
tslib: 2.8.1
- '@smithy/[email protected]':
- dependencies:
- '@smithy/util-buffer-from': 4.2.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- '@smithy/abort-controller': 4.2.7
- '@smithy/types': 4.11.0
- tslib: 2.8.1
-
- '@smithy/[email protected]':
- dependencies:
- tslib: 2.8.1
-
'@so-ric/[email protected]':
dependencies:
color: 5.0.3
text-hex: 1.0.0
dependencies:
tslib: 2.8.1
@@ -5702,42 +5179,52 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]': {}
+ '@types/[email protected]': {}
- '@types/[email protected]': {}
+ '@types/[email protected]': {}
dependencies:
- '@types/node': 22.19.3
+ '@types/node': 22.19.19
form-data: 4.0.5
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.19.19
+
dependencies:
undici-types: 5.26.5
- '@types/[email protected]':
+ '@types/[email protected]':
dependencies:
undici-types: 6.21.0
- '@types/[email protected]':
+ '@types/[email protected]':
dependencies:
undici-types: 6.21.0
+ '@types/[email protected]': {}
+
'@types/[email protected]': {}
+ '@types/[email protected]':
+ dependencies:
+ '@types/node': 22.19.19
+ '@types/node-int64': 0.4.32
+ '@types/q': 1.5.8
+
'@types/[email protected]': {}
'@types/[email protected]': {}
- '@types/[email protected]': {}
-
'@types/[email protected]': {}
dependencies:
'@types/webidl-conversions': 7.0.3
- '@typespec/[email protected]':
+ '@typespec/[email protected]':
dependencies:
http-proxy-agent: 7.0.2
https-proxy-agent: 7.0.6
@@ -5745,7 +5232,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@upstash/[email protected]': {}
+ '@upstash/[email protected]': {}
'@vitest/[email protected]':
dependencies:
@@ -5754,13 +5241,13 @@ snapshots:
chai: 5.3.3
tinyrainbow: 1.2.0
dependencies:
'@vitest/spy': 2.1.9
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- vite: 5.4.21(@types/[email protected])
+ vite: 6.4.2(@types/[email protected])([email protected])
'@vitest/[email protected]':
dependencies:
@@ -5789,32 +5276,45 @@ snapshots:
'@vladfrangu/[email protected]': {}
- '@xmldom/[email protected]': {}
+ '@xmldom/[email protected]': {}
+
+ '@xterm/[email protected]':
+ optional: true
+
+ '@zenfs/[email protected]':
+ dependencies:
+ '@types/node': 22.19.19
+ buffer: 6.0.3
+ eventemitter3: 5.0.4
+ readable-stream: 4.7.0
+ utilium: 1.10.1
- '@zilliz/[email protected]':
+ '@zilliz/[email protected]':
dependencies:
- '@grpc/grpc-js': 1.7.3
- '@grpc/proto-loader': 0.7.15
- '@opentelemetry/api': 1.9.0
+ '@dsnp/parquetjs': 1.8.7
+ '@grpc/grpc-js': 1.14.4
+ '@grpc/proto-loader': 0.8.1
+ '@opentelemetry/api': 1.9.1
'@petamoriken/float16': 3.9.3
- dayjs: 1.11.19
+ dayjs: 1.11.21
generic-pool: 3.9.0
lru-cache: 9.1.2
- protobufjs: 7.5.4
+ protobufjs: 7.6.1
winston: 3.19.0
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
optional: true
-
dependencies:
event-target-shim: 5.0.1
dependencies:
@@ -5829,10 +5329,10 @@ snapshots:
dependencies:
humanize-ms: 1.2.1
dependencies:
fast-deep-equal: 3.1.3
- fast-uri: 3.1.0
+ fast-uri: 3.1.2
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
@@ -5850,10 +5350,10 @@ snapshots:
dependencies:
- '@swc/helpers': 0.5.21
+ '@swc/helpers': 0.5.23
'@types/command-line-args': 5.2.3
'@types/command-line-usage': 5.0.4
- '@types/node': 20.19.39
+ '@types/node': 20.19.41
command-line-args: 5.2.1
command-line-usage: 7.0.4
flatbuffers: 24.12.23
@@ -5877,9 +5377,9 @@ snapshots:
dependencies:
- ws: 8.18.3
+ ws: 8.21.0
transitivePeerDependencies:
- bufferutil
- utf-8-validate
@@ -5892,47 +5392,42 @@ snapshots:
optional: true
dependencies:
- bare-events: 2.8.2
+ bare-events: 2.8.3
bare-path: 3.0.0
- bare-stream: 2.7.0([email protected])
- bare-url: 2.3.2
+ bare-stream: 2.13.1([email protected])
+ bare-url: 2.4.3
fast-fifo: 1.3.2
transitivePeerDependencies:
- bare-abort-controller
- react-native-b4a
- optional: true
- optional: true
dependencies:
- bare-os: 3.6.2
- optional: true
+ bare-os: 3.9.1
dependencies:
- streamx: 2.23.0
+ streamx: 2.26.0
+ teex: 1.0.1
optionalDependencies:
- bare-events: 2.8.2
+ bare-events: 2.8.3
transitivePeerDependencies:
- - bare-abort-controller
- react-native-b4a
- optional: true
dependencies:
bare-path: 3.0.0
- optional: true
@@ -5948,14 +5443,20 @@ snapshots:
dependencies:
balanced-match: 1.0.2
concat-map: 0.0.1
optional: true
+
+
+
@@ -5974,9 +5475,9 @@ snapshots:
dependencies:
run-applescript: 7.1.0
dependencies:
- esbuild: 0.27.2
+ esbuild: 0.27.7
load-tsconfig: 0.2.5
@@ -5998,7 +5499,7 @@ snapshots:
dependencies:
'@mapbox/node-pre-gyp': 1.0.11
- nan: 2.24.0
+ nan: 2.27.0
simple-get: 3.1.1
transitivePeerDependencies:
- encoding
@@ -6008,7 +5509,7 @@ snapshots:
dependencies:
assertion-error: 2.0.1
- check-error: 2.1.1
+ check-error: 2.1.3
deep-eql: 5.0.2
loupe: 3.2.1
pathval: 2.0.1
@@ -6022,7 +5523,7 @@ snapshots:
ansi-styles: 4.3.0
supports-color: 7.2.0
dependencies:
@@ -6030,9 +5531,6 @@ snapshots:
- optional: true
-
@@ -6047,13 +5545,24 @@ snapshots:
- bare-buffer
- react-native-b4a
+ dependencies:
+ cliui: 8.0.1
+ isomorphic-fetch: 3.0.0
+ optionalDependencies:
+ cohere-ai: 7.14.0
+ transitivePeerDependencies:
+ - encoding
+
dependencies:
cliui: 8.0.1
isomorphic-fetch: 3.0.0
optionalDependencies:
cohere-ai: 7.14.0
+ ollama: 0.5.18
transitivePeerDependencies:
- encoding
@@ -6065,8 +5574,8 @@ snapshots:
dependencies:
- '@aws-sdk/client-sagemaker': 3.958.0
- '@aws-sdk/credential-providers': 3.958.0
+ '@aws-sdk/client-sagemaker': 3.1055.0
+ '@aws-sdk/credential-providers': 3.1055.0
'@aws-sdk/protocol-http': 3.374.0
'@aws-sdk/signature-v4': 3.374.0
form-data: 4.0.5
@@ -6074,11 +5583,10 @@ snapshots:
formdata-node: 6.0.3
js-base64: 3.7.2
node-fetch: 2.7.0
- qs: 6.11.2
+ qs: 6.15.2
readable-stream: 4.7.0
url-join: 4.0.1
transitivePeerDependencies:
- - aws-crt
- encoding
@@ -6145,10 +5653,6 @@ snapshots:
optional: true
- dependencies:
- simple-wcswidth: 1.1.2
-
@@ -6159,7 +5663,7 @@ snapshots:
dependencies:
@@ -6184,7 +5688,7 @@ snapshots:
dependencies:
bundle-name: 4.1.0
default-browser-id: 5.0.1
@@ -6216,7 +5720,7 @@ snapshots:
dependencies:
@@ -6238,7 +5742,7 @@ snapshots:
dependencies:
- underscore: 1.13.7
+ underscore: 1.13.8
dependencies:
@@ -6266,7 +5770,7 @@ snapshots:
dependencies:
es-errors: 1.3.0
@@ -6275,64 +5779,38 @@ snapshots:
es-errors: 1.3.0
get-intrinsic: 1.3.0
has-tostringtag: 1.0.2
- hasown: 2.0.2
+ hasown: 2.0.3
optionalDependencies:
- '@esbuild/aix-ppc64': 0.21.5
- '@esbuild/android-arm': 0.21.5
- '@esbuild/android-arm64': 0.21.5
- '@esbuild/android-x64': 0.21.5
- '@esbuild/darwin-arm64': 0.21.5
- '@esbuild/darwin-x64': 0.21.5
- '@esbuild/freebsd-arm64': 0.21.5
- '@esbuild/freebsd-x64': 0.21.5
- '@esbuild/linux-arm': 0.21.5
- '@esbuild/linux-arm64': 0.21.5
- '@esbuild/linux-ia32': 0.21.5
- '@esbuild/linux-loong64': 0.21.5
- '@esbuild/linux-mips64el': 0.21.5
- '@esbuild/linux-ppc64': 0.21.5
- '@esbuild/linux-riscv64': 0.21.5
- '@esbuild/linux-s390x': 0.21.5
- '@esbuild/linux-x64': 0.21.5
- '@esbuild/netbsd-x64': 0.21.5
- '@esbuild/openbsd-x64': 0.21.5
- '@esbuild/sunos-x64': 0.21.5
- '@esbuild/win32-arm64': 0.21.5
- '@esbuild/win32-ia32': 0.21.5
- '@esbuild/win32-x64': 0.21.5
-
- optionalDependencies:
- '@esbuild/aix-ppc64': 0.27.2
- '@esbuild/android-arm': 0.27.2
- '@esbuild/android-arm64': 0.27.2
- '@esbuild/android-x64': 0.27.2
- '@esbuild/darwin-arm64': 0.27.2
- '@esbuild/darwin-x64': 0.27.2
- '@esbuild/freebsd-arm64': 0.27.2
- '@esbuild/freebsd-x64': 0.27.2
- '@esbuild/linux-arm': 0.27.2
- '@esbuild/linux-arm64': 0.27.2
- '@esbuild/linux-ia32': 0.27.2
- '@esbuild/linux-loong64': 0.27.2
- '@esbuild/linux-mips64el': 0.27.2
- '@esbuild/linux-ppc64': 0.27.2
- '@esbuild/linux-riscv64': 0.27.2
- '@esbuild/linux-s390x': 0.27.2
- '@esbuild/linux-x64': 0.27.2
- '@esbuild/netbsd-arm64': 0.27.2
- '@esbuild/netbsd-x64': 0.27.2
- '@esbuild/openbsd-arm64': 0.27.2
- '@esbuild/openbsd-x64': 0.27.2
- '@esbuild/openharmony-arm64': 0.27.2
- '@esbuild/sunos-x64': 0.27.2
- '@esbuild/win32-arm64': 0.27.2
- '@esbuild/win32-ia32': 0.27.2
- '@esbuild/win32-x64': 0.27.2
+ '@esbuild/aix-ppc64': 0.27.7
+ '@esbuild/android-arm': 0.27.7
+ '@esbuild/android-arm64': 0.27.7
+ '@esbuild/android-x64': 0.27.7
+ '@esbuild/darwin-arm64': 0.27.7
+ '@esbuild/darwin-x64': 0.27.7
+ '@esbuild/freebsd-arm64': 0.27.7
+ '@esbuild/freebsd-x64': 0.27.7
+ '@esbuild/linux-arm': 0.27.7
+ '@esbuild/linux-arm64': 0.27.7
+ '@esbuild/linux-ia32': 0.27.7
+ '@esbuild/linux-loong64': 0.27.7
+ '@esbuild/linux-mips64el': 0.27.7
+ '@esbuild/linux-ppc64': 0.27.7
+ '@esbuild/linux-riscv64': 0.27.7
+ '@esbuild/linux-s390x': 0.27.7
+ '@esbuild/linux-x64': 0.27.7
+ '@esbuild/netbsd-arm64': 0.27.7
+ '@esbuild/netbsd-x64': 0.27.7
+ '@esbuild/openbsd-arm64': 0.27.7
+ '@esbuild/openbsd-x64': 0.27.7
+ '@esbuild/openharmony-arm64': 0.27.7
+ '@esbuild/sunos-x64': 0.27.7
+ '@esbuild/win32-arm64': 0.27.7
+ '@esbuild/win32-ia32': 0.27.7
+ '@esbuild/win32-x64': 0.27.7
@@ -6340,15 +5818,17 @@ snapshots:
dependencies:
- '@types/estree': 1.0.8
+ '@types/estree': 1.0.9
+
dependencies:
- bare-events: 2.8.2
+ bare-events: 2.8.3
transitivePeerDependencies:
- bare-abort-controller
@@ -6366,15 +5846,23 @@ snapshots:
+
+ dependencies:
+ path-expression-matcher: 1.5.0
+ xml-naming: 0.1.0
dependencies:
- strnum: 2.1.2
+ '@nodable/entities': 2.1.1
+ fast-xml-builder: 1.2.0
+ path-expression-matcher: 1.5.0
+ strnum: 2.3.0
optionalDependencies:
- picomatch: 4.0.3
+ picomatch: 4.0.4
@@ -6395,8 +5883,8 @@ snapshots:
dependencies:
magic-string: 0.30.21
- mlly: 1.8.0
- rollup: 4.54.0
+ mlly: 1.8.2
+ rollup: 4.60.4
@@ -6410,18 +5898,12 @@ snapshots:
- dependencies:
- asynckit: 0.4.0
- combined-stream: 1.0.8
- mime-types: 2.1.35
-
dependencies:
asynckit: 0.4.0
combined-stream: 1.0.8
es-set-tostringtag: 2.1.0
- hasown: 2.0.2
+ hasown: 2.0.3
mime-types: 2.1.35
@@ -6433,11 +5915,6 @@ snapshots:
- dependencies:
- minipass: 3.3.6
- optional: true
-
optional: true
@@ -6468,7 +5945,7 @@ snapshots:
https-proxy-agent: 7.0.6
is-stream: 2.0.1
node-fetch: 2.7.0
- uuid: 9.0.1
+ uuid: 14.0.0
transitivePeerDependencies:
- encoding
- supports-color
@@ -6491,18 +5968,18 @@ snapshots:
call-bind-apply-helpers: 1.0.2
es-define-property: 1.0.1
es-errors: 1.3.0
- es-object-atoms: 1.1.1
+ es-object-atoms: 1.1.2
function-bind: 1.1.2
get-proto: 1.0.1
gopd: 1.2.0
has-symbols: 1.1.0
- hasown: 2.0.2
+ hasown: 2.0.3
math-intrinsics: 1.1.0
dependencies:
dunder-proto: 1.0.1
- es-object-atoms: 1.1.1
+ es-object-atoms: 1.1.2
@@ -6513,7 +5990,7 @@ snapshots:
fs.realpath: 1.0.0
inflight: 1.0.6
inherits: 2.0.4
- minimatch: 3.1.2
+ minimatch: 3.1.5
once: 1.4.0
path-is-absolute: 1.0.1
optional: true
@@ -6524,7 +6001,7 @@ snapshots:
es6-error: 4.1.1
matcher: 3.0.0
roarr: 2.15.4
- semver: 7.7.3
+ semver: 7.8.1
serialize-error: 7.0.1
@@ -6550,15 +6027,15 @@ snapshots:
dependencies:
- '@graphql-typed-document-node/core': 3.2.0([email protected])
+ '@graphql-typed-document-node/core': 3.2.0([email protected])
cross-fetch: 3.2.0
- graphql: 16.12.0
+ graphql: 16.14.0
transitivePeerDependencies:
- encoding
dependencies:
@@ -6597,7 +6074,7 @@ snapshots:
optional: true
dependencies:
function-bind: 1.1.2
@@ -6656,6 +6133,8 @@ snapshots:
+
@@ -6668,7 +6147,7 @@ snapshots:
dependencies:
is-inside-container: 1.0.0
@@ -6681,6 +6160,10 @@ snapshots:
transitivePeerDependencies:
- encoding
+ dependencies:
+ ws: 8.21.0
+
@@ -6710,7 +6193,7 @@ snapshots:
lodash.isstring: 4.0.1
lodash.once: 4.1.1
ms: 2.1.3
- semver: 7.7.3
+ semver: 7.8.1
dependencies:
@@ -6732,17 +6215,13 @@ snapshots:
dependencies:
- '@types/uuid': 10.0.0
- chalk: 4.1.2
- console-table-printer: 2.15.0
p-queue: 6.6.2
- semver: 7.7.3
- uuid: 10.0.0
optionalDependencies:
- '@opentelemetry/api': 1.9.0
+ '@opentelemetry/api': 1.9.1
+ ws: 8.21.0
@@ -6750,57 +6229,107 @@ snapshots:
dependencies:
immediate: 3.0.6
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ optional: true
+
+ dependencies:
+ detect-libc: 2.1.2
+ optionalDependencies:
+ lightningcss-android-arm64: 1.32.0
+ lightningcss-darwin-arm64: 1.32.0
+ lightningcss-darwin-x64: 1.32.0
+ lightningcss-freebsd-x64: 1.32.0
+ lightningcss-linux-arm-gnueabihf: 1.32.0
+ lightningcss-linux-arm64-gnu: 1.32.0
+ lightningcss-linux-arm64-musl: 1.32.0
+ lightningcss-linux-x64-gnu: 1.32.0
+ lightningcss-linux-x64-musl: 1.32.0
+ lightningcss-win32-arm64-msvc: 1.32.0
+ lightningcss-win32-x64-msvc: 1.32.0
+ optional: true
+
dependencies:
- '@llamaindex/anthropic': 0.0.33(@aws-crypto/[email protected])(@huggingface/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/astra': 0.0.4(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- '@llamaindex/azure': 0.0.4(@aws-crypto/[email protected])(@aws-sdk/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/cohere': 0.0.4(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/core': 0.4.23(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/env': 0.1.27(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/google': 0.0.6(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/milvus': 0.0.4(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/mistral': 0.0.4(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/mixedbread': 0.0.4(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- '@llamaindex/mongodb': 0.0.4(@aws-crypto/[email protected])(@aws-sdk/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
+ '@llamaindex/mongodb': 0.0.4(@aws-crypto/[email protected])(@aws-sdk/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/ollama': 0.0.39(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/pinecone': 0.0.4(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/portkey-ai': 0.0.32(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/replicate': 0.0.32(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/upstash': 0.0.4(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
'@llamaindex/weaviate': 0.0.4(@aws-crypto/[email protected])(@huggingface/[email protected])([email protected])([email protected])([email protected])
- '@types/lodash': 4.17.21
- '@types/node': 22.19.3
- ajv: 8.17.1
+ '@types/lodash': 4.17.24
+ '@types/node': 22.19.19
+ ajv: 8.20.0
gpt-tokenizer: 2.9.0
- lodash: 4.17.21
- magic-bytes.js: 1.12.1
+ lodash: 4.18.1
+ magic-bytes.js: 1.13.0
transitivePeerDependencies:
- '@aws-crypto/sha256-js'
- '@aws-sdk/credential-providers'
+ - '@azure/core-client'
- '@edge-runtime/vm'
- '@google/generative-ai'
- '@huggingface/transformers'
- '@mongodb-js/zstd'
- '@vitest/browser'
- '@vitest/ui'
- - aws-crt
- bare-abort-controller
- bare-buffer
- bufferutil
@@ -6808,6 +6337,7 @@ snapshots:
- encoding
- gcp-metadata
- happy-dom
+ - jiti
- js-tiktoken
- jsdom
- kerberos
@@ -6832,11 +6362,13 @@ snapshots:
- terser
- tiktoken
- tree-sitter
+ - tsx
- typescript
- utf-8-validate
- voyageai
- web-tree-sitter
- ws
+ - yaml
- zod
@@ -6857,7 +6389,7 @@ snapshots:
dependencies:
@@ -6876,13 +6408,13 @@ snapshots:
dependencies:
duck: 0.1.12
option: 0.2.4
- underscore: 1.13.7
+ underscore: 1.13.8
dependencies:
@@ -6893,9 +6425,9 @@ snapshots:
semver: 6.3.1
optional: true
dependencies:
- '@xmldom/xmldom': 0.8.11
+ '@xmldom/xmldom': 0.8.13
argparse: 1.0.10
base64-js: 1.5.1
bluebird: 3.4.7
@@ -6903,7 +6435,7 @@ snapshots:
jszip: 3.10.1
lop: 0.4.2
path-is-absolute: 1.0.1
- underscore: 1.13.7
+ underscore: 1.13.8
xmlbuilder: 10.1.1
@@ -6927,65 +6459,48 @@ snapshots:
dependencies:
- brace-expansion: 1.1.12
+ brace-expansion: 1.1.15
optional: true
- dependencies:
- yallist: 4.0.0
- optional: true
-
- optional: true
-
-
- dependencies:
- minipass: 3.3.6
- yallist: 4.0.0
- optional: true
dependencies:
- minipass: 7.1.2
+ minipass: 7.1.3
- optional: true
-
dependencies:
- acorn: 8.15.0
+ acorn: 8.16.0
pathe: 2.0.3
pkg-types: 1.3.1
- ufo: 1.6.1
+ ufo: 1.6.4
dependencies:
'@types/whatwg-url': 11.0.5
whatwg-url: 14.2.0
dependencies:
- '@mongodb-js/saslprep': 1.4.4
+ '@mongodb-js/saslprep': 1.4.11
bson: 6.10.4
mongodb-connection-string-url: 3.0.2
optionalDependencies:
- '@aws-sdk/credential-providers': 3.958.0
+ '@aws-sdk/credential-providers': 3.1055.0
dependencies:
- '@mongodb-js/saslprep': 1.4.4
+ '@mongodb-js/saslprep': 1.4.11
bson: 6.10.4
mongodb-connection-string-url: 3.0.2
optionalDependencies:
- '@aws-sdk/credential-providers': 3.958.0
+ '@aws-sdk/credential-providers': 3.1055.0
@@ -6997,35 +6512,35 @@ snapshots:
object-assign: 4.1.1
thenify-all: 1.6.0
optional: true
dependencies:
- abort-controller-x: 0.4.3
- nice-grpc-common: 2.0.2
+ abort-controller-x: 0.5.0
+ nice-grpc-common: 2.0.3
dependencies:
ts-error: 1.0.6
dependencies:
- '@grpc/grpc-js': 1.14.3
- abort-controller-x: 0.4.3
- nice-grpc-common: 2.0.2
+ '@grpc/grpc-js': 1.14.4
+ abort-controller-x: 0.5.0
+ nice-grpc-common: 2.0.3
dependencies:
- semver: 7.7.3
+ semver: 7.8.1
@@ -7035,6 +6550,8 @@ snapshots:
+
dependencies:
abbrev: 1.1.1
@@ -7073,7 +6590,7 @@ snapshots:
dependencies:
- protobufjs: 6.11.4
+ protobufjs: 7.6.1
@@ -7090,7 +6607,7 @@ snapshots:
dependencies:
global-agent: 3.0.0
onnxruntime-common: 1.21.0
- tar: 7.5.2
+ tar: 7.5.15
dependencies:
@@ -7108,16 +6625,16 @@ snapshots:
long: 5.3.2
onnxruntime-common: 1.22.0-dev.20250409-89f8206ba4
platform: 1.3.6
- protobufjs: 7.5.4
+ protobufjs: 7.6.1
dependencies:
- default-browser: 5.4.0
+ default-browser: 5.5.0
define-lazy-prop: 3.0.0
is-inside-container: 1.0.0
wsl-utils: 0.1.0
dependencies:
'@types/node': 18.19.130
'@types/node-fetch': 2.6.13
@@ -7127,10 +6644,26 @@ snapshots:
formdata-node: 4.4.1
node-fetch: 2.7.0
optionalDependencies:
- ws: 8.18.3
+ ws: 8.21.0
zod: 3.25.76
transitivePeerDependencies:
- encoding
+ optional: true
+
+ dependencies:
+ '@types/node': 18.19.130
+ '@types/node-fetch': 2.6.13
+ abort-controller: 3.0.0
+ agentkeepalive: 4.6.0
+ form-data-encoder: 1.7.2
+ formdata-node: 4.4.1
+ node-fetch: 2.7.0
+ optionalDependencies:
+ ws: 8.21.0
+ zod: 4.4.3
+ transitivePeerDependencies:
+ - encoding
@@ -7159,6 +6692,8 @@ snapshots:
leac: 0.6.0
peberminta: 0.9.0
+
@@ -7169,12 +6704,12 @@ snapshots:
optional: true
dependencies:
pg: 8.16.3
@@ -7182,7 +6717,7 @@ snapshots:
dependencies:
pg: 8.16.3
@@ -7196,12 +6731,12 @@ snapshots:
transitivePeerDependencies:
- pg-native
dependencies:
pg: 8.16.3
- pg-cursor: 2.15.3([email protected])
+ pg-cursor: 2.20.0([email protected])
dependencies:
@@ -7213,13 +6748,13 @@ snapshots:
dependencies:
- pg-connection-string: 2.9.1
- pg-pool: 3.10.1([email protected])
- pg-protocol: 1.10.3
+ pg-connection-string: 2.13.0
+ pg-pool: 3.14.0([email protected])
+ pg-protocol: 1.14.0
pg-types: 2.2.0
pgpass: 1.0.5
optionalDependencies:
- pg-cloudflare: 1.2.7
+ pg-cloudflare: 1.4.0
dependencies:
@@ -7227,23 +6762,23 @@ snapshots:
dependencies:
confbox: 0.1.8
- mlly: 1.8.0
+ mlly: 1.8.2
pathe: 2.0.3
dependencies:
- playwright-core: 1.57.0
+ playwright-core: 1.60.0
optionalDependencies:
fsevents: 2.3.2
@@ -7251,15 +6786,15 @@ snapshots:
dependencies:
agentkeepalive: 4.6.0
dependencies:
lilconfig: 3.1.3
optionalDependencies:
- postcss: 8.5.6
+ postcss: 8.5.15
dependencies:
- nanoid: 3.3.11
+ nanoid: 3.3.12
picocolors: 1.1.1
source-map-js: 1.2.1
@@ -7281,8 +6816,8 @@ snapshots:
minimist: 1.2.8
mkdirp-classic: 0.5.3
napi-build-utils: 2.0.0
- node-abi: 3.85.0
- pump: 3.0.3
+ node-abi: 3.92.0
+ pump: 3.0.4
rc: 1.2.8
simple-get: 4.0.1
tar-fs: 2.1.4
@@ -7294,49 +6829,35 @@ snapshots:
- dependencies:
- '@protobufjs/aspromise': 1.1.2
- '@protobufjs/base64': 1.1.2
- '@protobufjs/codegen': 2.0.4
- '@protobufjs/eventemitter': 1.1.0
- '@protobufjs/fetch': 1.1.0
- '@protobufjs/float': 1.0.2
- '@protobufjs/inquire': 1.1.0
- '@protobufjs/path': 1.1.2
- '@protobufjs/pool': 1.1.0
- '@protobufjs/utf8': 1.1.0
- '@types/long': 4.0.2
- '@types/node': 22.19.3
- long: 4.0.0
-
dependencies:
'@protobufjs/aspromise': 1.1.2
'@protobufjs/base64': 1.1.2
- '@protobufjs/codegen': 2.0.4
- '@protobufjs/eventemitter': 1.1.0
- '@protobufjs/fetch': 1.1.0
+ '@protobufjs/codegen': 2.0.5
+ '@protobufjs/eventemitter': 1.1.1
+ '@protobufjs/fetch': 1.1.1
'@protobufjs/float': 1.0.2
- '@protobufjs/inquire': 1.1.0
+ '@protobufjs/inquire': 1.1.2
'@protobufjs/path': 1.1.2
'@protobufjs/pool': 1.1.0
- '@protobufjs/utf8': 1.1.0
- '@types/node': 22.19.3
+ '@protobufjs/utf8': 1.1.1
+ '@types/node': 22.19.19
long: 5.3.2
dependencies:
punycode: 2.3.1
dependencies:
end-of-stream: 1.4.5
once: 1.4.0
+
dependencies:
side-channel: 1.1.0
@@ -7377,9 +6898,7 @@ snapshots:
- dependencies:
- type-fest: 4.41.0
optionalDependencies:
@@ -7409,32 +6928,35 @@ snapshots:
semver-compare: 1.0.0
sprintf-js: 1.1.3
dependencies:
'@types/estree': 1.0.8
optionalDependencies:
- '@rollup/rollup-android-arm-eabi': 4.54.0
- '@rollup/rollup-android-arm64': 4.54.0
- '@rollup/rollup-darwin-arm64': 4.54.0
- '@rollup/rollup-darwin-x64': 4.54.0
- '@rollup/rollup-freebsd-arm64': 4.54.0
- '@rollup/rollup-freebsd-x64': 4.54.0
- '@rollup/rollup-linux-arm-gnueabihf': 4.54.0
- '@rollup/rollup-linux-arm-musleabihf': 4.54.0
- '@rollup/rollup-linux-arm64-gnu': 4.54.0
- '@rollup/rollup-linux-arm64-musl': 4.54.0
- '@rollup/rollup-linux-loong64-gnu': 4.54.0
- '@rollup/rollup-linux-ppc64-gnu': 4.54.0
- '@rollup/rollup-linux-riscv64-gnu': 4.54.0
- '@rollup/rollup-linux-riscv64-musl': 4.54.0
- '@rollup/rollup-linux-s390x-gnu': 4.54.0
- '@rollup/rollup-linux-x64-gnu': 4.54.0
- '@rollup/rollup-linux-x64-musl': 4.54.0
- '@rollup/rollup-openharmony-arm64': 4.54.0
- '@rollup/rollup-win32-arm64-msvc': 4.54.0
- '@rollup/rollup-win32-ia32-msvc': 4.54.0
- '@rollup/rollup-win32-x64-gnu': 4.54.0
- '@rollup/rollup-win32-x64-msvc': 4.54.0
+ '@rollup/rollup-android-arm-eabi': 4.60.4
+ '@rollup/rollup-android-arm64': 4.60.4
+ '@rollup/rollup-darwin-arm64': 4.60.4
+ '@rollup/rollup-darwin-x64': 4.60.4
+ '@rollup/rollup-freebsd-arm64': 4.60.4
+ '@rollup/rollup-freebsd-x64': 4.60.4
+ '@rollup/rollup-linux-arm-gnueabihf': 4.60.4
+ '@rollup/rollup-linux-arm-musleabihf': 4.60.4
+ '@rollup/rollup-linux-arm64-gnu': 4.60.4
+ '@rollup/rollup-linux-arm64-musl': 4.60.4
+ '@rollup/rollup-linux-loong64-gnu': 4.60.4
+ '@rollup/rollup-linux-loong64-musl': 4.60.4
+ '@rollup/rollup-linux-ppc64-gnu': 4.60.4
+ '@rollup/rollup-linux-ppc64-musl': 4.60.4
+ '@rollup/rollup-linux-riscv64-gnu': 4.60.4
+ '@rollup/rollup-linux-riscv64-musl': 4.60.4
+ '@rollup/rollup-linux-s390x-gnu': 4.60.4
+ '@rollup/rollup-linux-x64-gnu': 4.60.4
+ '@rollup/rollup-linux-x64-musl': 4.60.4
+ '@rollup/rollup-openbsd-x64': 4.60.4
+ '@rollup/rollup-openharmony-arm64': 4.60.4
+ '@rollup/rollup-win32-arm64-msvc': 4.60.4
+ '@rollup/rollup-win32-ia32-msvc': 4.60.4
+ '@rollup/rollup-win32-x64-gnu': 4.60.4
+ '@rollup/rollup-win32-x64-msvc': 4.60.4
fsevents: 2.3.3
@@ -7461,7 +6983,7 @@ snapshots:
optional: true
dependencies:
@@ -7478,9 +7000,9 @@ snapshots:
detect-libc: 2.1.2
node-addon-api: 6.1.0
prebuild-install: 7.1.3
- semver: 7.7.3
+ semver: 7.8.1
simple-get: 4.0.1
- tar-fs: 3.1.1
+ tar-fs: 3.1.2
tunnel-agent: 0.6.0
transitivePeerDependencies:
- bare-abort-controller
@@ -7489,9 +7011,9 @@ snapshots:
dependencies:
- '@img/colour': 1.0.0
+ '@img/colour': 1.1.0
detect-libc: 2.1.2
- semver: 7.7.3
+ semver: 7.8.1
optionalDependencies:
'@img/sharp-darwin-arm64': 0.34.5
'@img/sharp-darwin-x64': 0.34.5
@@ -7518,7 +7040,7 @@ snapshots:
'@img/sharp-win32-ia32': 0.34.5
'@img/sharp-win32-x64': 0.34.5
dependencies:
es-errors: 1.3.0
object-inspect: 1.13.4
@@ -7542,7 +7064,7 @@ snapshots:
dependencies:
es-errors: 1.3.0
object-inspect: 1.13.4
- side-channel-list: 1.0.0
+ side-channel-list: 1.0.1
side-channel-map: 1.0.1
side-channel-weakmap: 1.0.2
@@ -7570,7 +7092,7 @@ snapshots:
dependencies:
is-arrayish: 0.3.4
@@ -7594,11 +7116,11 @@ snapshots:
dependencies:
events-universal: 1.0.1
fast-fifo: 1.3.2
- text-decoder: 1.2.3
+ text-decoder: 1.2.7
transitivePeerDependencies:
- bare-abort-controller
- react-native-b4a
@@ -7623,7 +7145,7 @@ snapshots:
dependencies:
@@ -7632,7 +7154,7 @@ snapshots:
lines-and-columns: 1.2.4
mz: 2.7.0
pirates: 4.0.7
- tinyglobby: 0.2.15
+ tinyglobby: 0.2.16
ts-interface-checker: 0.1.13
@@ -7648,15 +7170,15 @@ snapshots:
dependencies:
chownr: 1.1.4
mkdirp-classic: 0.5.3
- pump: 3.0.3
+ pump: 3.0.4
tar-stream: 2.2.0
dependencies:
- pump: 3.0.3
- tar-stream: 3.1.7
+ pump: 3.0.4
+ tar-stream: 3.2.0
optionalDependencies:
- bare-fs: 4.5.2
+ bare-fs: 4.7.1
bare-path: 3.0.0
transitivePeerDependencies:
- bare-abort-controller
@@ -7671,36 +7193,35 @@ snapshots:
inherits: 2.0.4
readable-stream: 3.6.2
dependencies:
- b4a: 1.7.3
+ b4a: 1.8.1
+ bare-fs: 4.7.1
fast-fifo: 1.3.2
- streamx: 2.23.0
+ streamx: 2.26.0
transitivePeerDependencies:
- bare-abort-controller
+ - bare-buffer
- react-native-b4a
- dependencies:
- chownr: 2.0.0
- fs-minipass: 2.1.0
- minipass: 5.0.0
- minizlib: 2.1.2
- mkdirp: 1.0.4
- yallist: 4.0.0
- optional: true
-
dependencies:
'@isaacs/fs-minipass': 4.0.1
chownr: 3.0.0
- minipass: 7.1.2
+ minipass: 7.1.3
minizlib: 3.1.0
yallist: 5.0.0
+ dependencies:
+ streamx: 2.26.0
+ transitivePeerDependencies:
+ - bare-abort-controller
+ - react-native-b4a
+
dependencies:
- b4a: 1.7.3
+ b4a: 1.8.1
transitivePeerDependencies:
- react-native-b4a
@@ -7714,6 +7235,17 @@ snapshots:
dependencies:
any-promise: 1.3.0
+ dependencies:
+ browser-or-node: 1.3.0
+ isomorphic-ws: 4.0.1([email protected])
+ node-int64: 0.4.0
+ q: 1.5.1
+ ws: 8.21.0
+ transitivePeerDependencies:
+ - bufferutil
+ - utf-8-validate
+
dependencies:
readable-stream: 3.6.2
@@ -7722,10 +7254,10 @@ snapshots:
dependencies:
- fdir: 6.5.0([email protected])
- picomatch: 4.0.3
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.4
@@ -7752,7 +7284,7 @@ snapshots:
dependencies:
- node-addon-api: 8.5.0
+ node-addon-api: 8.8.0
node-gyp-build: 4.8.4
@@ -7765,27 +7297,27 @@ snapshots:
dependencies:
- bundle-require: 5.1.0([email protected])
+ bundle-require: 5.1.0([email protected])
cac: 6.7.14
chokidar: 4.0.3
consola: 3.4.2
debug: 4.4.3
- esbuild: 0.27.2
+ esbuild: 0.27.7
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
picocolors: 1.1.1
- postcss-load-config: 6.0.1([email protected])
+ postcss-load-config: 6.0.1([email protected])
resolve-from: 5.0.0
- rollup: 4.54.0
+ rollup: 4.60.4
source-map: 0.7.6
sucrase: 3.35.1
tinyexec: 0.3.2
- tinyglobby: 0.2.15
+ tinyglobby: 0.2.16
tree-kill: 1.2.2
optionalDependencies:
- postcss: 8.5.6
+ postcss: 8.5.15
typescript: 5.9.3
transitivePeerDependencies:
- jiti
@@ -7799,8 +7331,6 @@ snapshots:
-
optionalDependencies:
rxjs: 7.8.2
@@ -7811,17 +7341,17 @@ snapshots:
@@ -7841,23 +7371,28 @@ snapshots:
-
+ dependencies:
+ eventemitter3: 5.0.4
+ optionalDependencies:
+ '@xterm/xterm': 5.5.0
+
dependencies:
cac: 6.7.14
debug: 4.4.3
es-module-lexer: 1.7.0
pathe: 1.1.2
- vite: 5.4.21(@types/[email protected])
+ vite: 6.4.2(@types/[email protected])([email protected])
transitivePeerDependencies:
- '@types/node'
+ - jiti
- less
- lightningcss
- sass
@@ -7866,20 +7401,26 @@ snapshots:
- sugarss
- supports-color
- terser
+ - tsx
+ - yaml
dependencies:
- esbuild: 0.21.5
- postcss: 8.5.6
- rollup: 4.54.0
+ esbuild: 0.27.7
+ fdir: 6.5.0([email protected])
+ picomatch: 4.0.4
+ postcss: 8.5.15
+ rollup: 4.60.4
+ tinyglobby: 0.2.16
optionalDependencies:
- '@types/node': 22.19.3
+ '@types/node': 22.19.19
fsevents: 2.3.3
+ lightningcss: 1.32.0
dependencies:
'@vitest/expect': 2.1.9
- '@vitest/mocker': 2.1.9([email protected](@types/[email protected]))
+ '@vitest/mocker': 2.1.9([email protected](@types/[email protected])([email protected]))
'@vitest/pretty-format': 2.1.9
'@vitest/runner': 2.1.9
'@vitest/snapshot': 2.1.9
@@ -7895,12 +7436,13 @@ snapshots:
tinyexec: 0.3.2
tinypool: 1.1.1
tinyrainbow: 1.2.0
- vite: 5.4.21(@types/[email protected])
- vite-node: 2.1.9(@types/[email protected])
+ vite: 6.4.2(@types/[email protected])([email protected])
+ vite-node: 2.1.9(@types/[email protected])([email protected])
why-is-node-running: 2.3.0
optionalDependencies:
- '@types/node': 22.19.3
+ '@types/node': 22.19.19
transitivePeerDependencies:
+ - jiti
- less
- lightningcss
- msw
@@ -7910,17 +7452,20 @@ snapshots:
- sugarss
- supports-color
- terser
+ - tsx
+ - yaml
dependencies:
+ '@datastructures-js/deque': 1.0.8
abort-controller-x: 0.5.0
- graphql: 16.12.0
- graphql-request: 6.1.0([email protected])
+ graphql: 16.14.0
+ graphql-request: 6.1.0([email protected])
long: 5.3.2
- nice-grpc: 2.1.14
- nice-grpc-client-middleware-retry: 3.1.13
- nice-grpc-common: 2.0.2
- uuid: 9.0.1
+ nice-grpc: 2.1.16
+ nice-grpc-client-middleware-retry: 3.1.15
+ nice-grpc-common: 2.0.3
+ uuid: 14.0.0
transitivePeerDependencies:
- encoding
@@ -7984,20 +7529,21 @@ snapshots:
dependencies:
- is-wsl: 3.1.0
+ is-wsl: 3.1.1
+
- optional: true
@@ -8013,8 +7559,14 @@ snapshots:
y18n: 5.0.8
yargs-parser: 21.1.1
dependencies:
zod: 3.25.76
+ dependencies:
+ zod: 4.4.3
+
+
diff --git a/pyproject.toml b/pyproject.toml
index 10f533912..deb2f2d96 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -27,7 +27,7 @@ xformers = ["sie-server[xformers]"]
[dependency-groups]
dev = [
# Testing
- "pytest~=8.0",
+ "pytest>=9.0.3",
"pytest-sugar",
"pytest-asyncio",
"pytest-cov",
@@ -129,6 +129,8 @@ markers = [
"scaling: tests for autoscaling behavior (KEDA)",
"gke: tests that require a real GKE cluster",
"eks: tests that require a real EKS cluster",
+ "generation: tests that exercise generation endpoint contracts or a real generation worker",
+ "observability: tests that require optional local observability components",
"model: Model regression tests (download real weights, slow)"
]
@@ -379,6 +381,31 @@ ignore = [
"S311", # Pseudo-random generator is fine for synthetic text generation
"T201", # Script output is intentional
]
+# Rust scheduler replay harness (dev tool, not production)
+"scripts/perf/replay-scheduler-trace.py" = [
+ "ANN", # Annotations relaxed in dev scripts
+ "INP001", # Standalone script, not a package
+ "PLC0415", # Lazy imports for optional dependencies
+ "PLR2004", # Magic numbers (truncation thresholds, etc.)
+ "S311", # Pseudo-random fine for synthetic traces
+ "S404", # subprocess import (we shell out to cargo)
+ "S603", # subprocess.run with literal cargo argv (no shell)
+ "S607", # Partial executable path "cargo" via PATH is intentional
+ "T201", # Print output is intentional
+]
+# Tokeniser byte-identity fixture generator (dev tool, not production)
+"packages/sie_server/scripts/**/*" = [
+ "ANN", # Annotations relaxed in dev scripts
+ "D301", # Raw-string docstrings not enforced
+ "D415", # Multi-paragraph docstrings without trailing punctuation
+ "EXE001", # Shebang without +x permission - chmod is a deploy concern
+ "INP001", # Standalone scripts, not packages
+ "PLC0415", # Lazy imports of huggingface_hub / transformers
+ "RUF001", # Multilingual test data contains intentional non-ASCII
+ "S404", # subprocess import
+ "S603", # subprocess invocations with literal argv
+ "T201", # Print output is intentional
+]
# Mise task scripts - CLI scripts that use print, subprocess, etc.
"tools/mise_tasks/**/*" = [
"C901", # Complexity acceptable for CLI command handlers
@@ -438,6 +465,10 @@ exclude = [
"tools/benchview.py",
# modal sandbox script
"tools/modal_sandbox.py",
+ # Standalone dev scripts: import optional deps lazily, not part of the
+ # type-checked surface
+ "packages/sie_server/scripts/**",
+ "scripts/perf/**",
]
[tool.ty.rules]
diff --git a/uv.lock b/uv.lock
index 7ccb597f6..cd4540930 100644
--- a/uv.lock
+++ b/uv.lock
@@ -260,15 +260,15 @@ wheels = [
[[package]]
name = "authlib"
-version = "1.7.0"
+version = "1.7.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cryptography" },
{ name = "joserfc" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/d9/82/4d0603f30c1b4629b1f091bb266b0d7986434891d6940a8c87f8098db24e/authlib-1.7.0.tar.gz", hash = "sha256:b3e326c9aa9cc3ea95fe7d89fd880722d3608da4d00e8a27e061e64b48d801d5", size = 175890 }
+sdist = { url = "https://files.pythonhosted.org/packages/36/98/7d93f30d029643c0275dbc0bd6d5a6f670661ee6c9a94d93af7ab4887600/authlib-1.7.2.tar.gz", hash = "sha256:2cea25fefcd4e7173bdf1372c0afc265c8034b23a8cd5dcb6a9164b826c64231", size = 176511 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/ca/48/c954218b2a250e23f178f10167c4173fecb5a75d2c206f0a67ba58006c26/authlib-1.7.0-py2.py3-none-any.whl", hash = "sha256:e36817afb02f6f0b6bf55f150782499ddd6ddf44b402bb055d3263cc65ac9ae0", size = 258779 },
+ { url = "https://files.pythonhosted.org/packages/fb/95/adcb68e20c34162e9135f370d6e31737719c2b6f94bc953fe7ed1f10fe21/authlib-1.7.2-py2.py3-none-any.whl", hash = "sha256:3e1faedc9d87e7d56a164eca3ccb6ace0d61b94abe83e92242f8dc8bba9b4a9f", size = 259548 },
]
[[package]]
@@ -282,7 +282,7 @@ wheels = [
[[package]]
name = "banks"
-version = "2.4.1"
+version = "2.4.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "deprecated" },
@@ -292,9 +292,9 @@ dependencies = [
{ name = "platformdirs" },
{ name = "pydantic" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/47/5d/54c79aaaa9aa1278af24cae98d81d6ef635ad840f046bc2ccb5041ddeb1b/banks-2.4.1.tar.gz", hash = "sha256:8cbf1553f14c44d4f7e9c2064ad9212ce53ee4da000b2f8308d548b60db56655", size = 188033 }
+sdist = { url = "https://files.pythonhosted.org/packages/bd/51/08fb68d23f4b0f6256fe85dc86e9576941550f890b079352fba719e07b39/banks-2.4.2.tar.gz", hash = "sha256:cda6013bd377ea7b701933578bfb9370fc21ad70bc13cedfc3f5cb2c034ca3dc", size = 188633 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/b8/5a/f38b49e8b225b0c774e97c9495e52ab9ccdf6d82bde68c513bd736820eb2/banks-2.4.1-py3-none-any.whl", hash = "sha256:40e6d9b6e9b69fb403fa31f2853b3297e4919c1b6f2179b2119d2d4473c6ed13", size = 35032 },
+ { url = "https://files.pythonhosted.org/packages/00/b6/8dc5477681b782e2f99de703e7a99828883364b9e03a60d3e2c47053d56a/banks-2.4.2-py3-none-any.whl", hash = "sha256:5fe407cc48c101f3e13d1cf732b83b8246003337612f13c0705d2e81f6faffb7", size = 35050 },
]
[[package]]
@@ -348,6 +348,26 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/1a/39/47f9197bdd44df24d67ac8893641e16f386c984a0619ef2ee4c51fbbc019/beautifulsoup4-4.14.3-py3-none-any.whl", hash = "sha256:0918bfe44902e6ad8d57732ba310582e98da931428d231a5ecb9e7c703a735bb", size = 107721 },
]
+[[package]]
+name = "blake3"
+version = "0.4.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/b0/8d/43eafa8a785547c33b611068ffd6d914f5c5f96637d5b453abc556f095a0/blake3-0.4.1.tar.gz", hash = "sha256:0625c8679203d5a1d30f859696a3fd75b2f50587984690adab839ef112f4c043", size = 117686 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/50/f8/c5e6c5749aab2d84c177e8d86792aed8adaad023bfd045abfc6f053cdd57/blake3-0.4.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:fb98f18bc5e218ff1134acb3b9f0e3588ad5e6f38b7279cce4559c8ae9d780e6", size = 343905 },
+ { url = "https://files.pythonhosted.org/packages/e0/8f/184105e1a84ac108cfec8702307b588cb123e1a203e8538e8c3e9b0320da/blake3-0.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fe31163eb08fc3f82a2325e90cea88f2d7ad0265314a03de716f906b2a43be96", size = 329112 },
+ { url = "https://files.pythonhosted.org/packages/ae/15/8bcd0b3f854683f3dc524615d6c9c9b3db6554098f24f674347dd37d02b6/blake3-0.4.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d3c0631f69a5b3851cd89a50728b5ace0d6dbd276c52fc404b648efe08bdd7da", size = 358917 },
+ { url = "https://files.pythonhosted.org/packages/30/2d/fa4a1610f597c053f35be6bd3dfff19c295e26c04eaa0d1e44eee67c7cc4/blake3-0.4.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:1ff8ecf2bb68fa642c6b943dcd34872d5e2c12e166dd9d2c295b880427467a49", size = 361357 },
+ { url = "https://files.pythonhosted.org/packages/7b/02/62f1a31d2b5f6b1e0864d0eeed6bc664cf9c3e467ecd52bf9b1a4d3f41f5/blake3-0.4.1-cp312-cp312-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bc3bbaff1796f7ee5dc138761f8ad26e8f8586f2b4b12f25969c449a7a1a57aa", size = 428849 },
+ { url = "https://files.pythonhosted.org/packages/fc/00/48e65aca05c5a629f31a374b15f8213695783c6180a9fe0ca813d772259f/blake3-0.4.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de61bc9d5aee53e31cbb9c7e3c60601125c8c5e7f7805d5230fe3628b1b43137", size = 398628 },
+ { url = "https://files.pythonhosted.org/packages/ac/6e/c059b2efd212e5b7d8702cd558d73db624bef24840d4b408f5fea13d576f/blake3-0.4.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6fafa24b02862605c9995304d13b00d9e727f0352a61daad648c9c4a44063ccc", size = 408766 },
+ { url = "https://files.pythonhosted.org/packages/ec/c6/8f6717fbea55ec9eb21543aa6d8e1bd904d6d2dcc886b555aa3d3f450ba7/blake3-0.4.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a51f48ec21706a22b4954fc17da72bd177d82d22ee434da0c5dc3aafeef5b8d3", size = 1275086 },
+ { url = "https://files.pythonhosted.org/packages/44/b6/e0fa32626466040cb3ebca3dd31db49fce72fa1569fcf7dfeec9e05f9811/blake3-0.4.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:79b833f49902857c98bfd7dadac28f3bbc2e8c76b24108aa93518ff9eddf3e09", size = 534066 },
+ { url = "https://files.pythonhosted.org/packages/f4/a1/e381b0fabc06cd285554d0946ef323854121187ecc2a21857b8799be2b74/blake3-0.4.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:ae98654d5c83171236b444a5291276102a0b88fd927738872b03df404b2efd49", size = 542823 },
+ { url = "https://files.pythonhosted.org/packages/81/d2/7d5c71b78fbbef88b723d9af1bd647fe756ca0f8880a27f2ad5a7b97af55/blake3-0.4.1-cp312-none-win32.whl", hash = "sha256:510fd32d207ef2e28df3597847d5044117d110b0e549b2e467afa30a9f3ab7ee", size = 226815 },
+ { url = "https://files.pythonhosted.org/packages/fb/67/3fca4d812b3334fa1c9415fd7f10ceea32b0e9e29797d179af87ed94581c/blake3-0.4.1-cp312-none-win_amd64.whl", hash = "sha256:2a08eeb324da701b212f348e91ba5d2708c0a596bd6691207f2504f4f771644c", size = 210124 },
+]
+
[[package]]
name = "bleach"
version = "6.3.0"
@@ -1459,14 +1479,14 @@ wheels = [
[[package]]
name = "gitpython"
-version = "3.1.47"
+version = "3.1.50"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "gitdb" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/c1/bd/50db468e9b1310529a19fce651b3b0e753b5c07954d486cba31bbee9a5d5/gitpython-3.1.47.tar.gz", hash = "sha256:dba27f922bd2b42cb54c87a8ab3cb6beb6bf07f3d564e21ac848913a05a8a3cd", size = 216978 }
+sdist = { url = "https://files.pythonhosted.org/packages/33/f6/354ae6491228b5eb40e10d89c4d13c651fe1cf7556e35ebdded50cff57ce/gitpython-3.1.50.tar.gz", hash = "sha256:80da2d12504d52e1f998772dc5baf6e553f8d2fcfe1fcc226c9d9a2ee3372dcc", size = 219798 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/f2/c5/a1bc0996af85757903cf2bf444a7824e68e0035ce63fb41d6f76f9def68b/gitpython-3.1.47-py3-none-any.whl", hash = "sha256:489f590edfd6d20571b2c0e72c6a6ac6915ee8b8cd04572330e3842207a78905", size = 209547 },
+ { url = "https://files.pythonhosted.org/packages/20/7a/1c6e3562dfd8950adbb11ffbc65d21e7c89d01a6e4f137fa981056de25c5/gitpython-3.1.50-py3-none-any.whl", hash = "sha256:d352abe2908d07355014abdd21ddf798c2a961469239afec4962e9da884858f9", size = 212507 },
]
[[package]]
@@ -1989,11 +2009,11 @@ wheels = [
[[package]]
name = "idna"
-version = "3.13"
+version = "3.17"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/ce/cc/762dfb036166873f0059f3b7de4565e1b5bc3d6f28a414c13da27e442f99/idna-3.13.tar.gz", hash = "sha256:585ea8fe5d69b9181ec1afba340451fba6ba764af97026f92a91d4eef164a242", size = 194210 }
+sdist = { url = "https://files.pythonhosted.org/packages/b9/28/99c51f664567218d824af024c0251650fb27e4ca066df188dab0769c5b91/idna-3.17.tar.gz", hash = "sha256:5eb0cb53bc467c12eadcf6de83163ad8527cec9416f44b9b61b19caedad2b87f", size = 196048 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/5d/13/ad7d7ca3808a898b4612b6fe93cde56b53f3034dcde235acb1f0e1df24c6/idna-3.13-py3-none-any.whl", hash = "sha256:892ea0cde124a99ce773decba204c5552b69c3c67ffd5f232eb7696135bc8bb3", size = 68629 },
+ { url = "https://files.pythonhosted.org/packages/de/a7/f76514cc40ad6234098ecdebda08732d75964776c51a42845b7da10649e2/idna-3.17-py3-none-any.whl", hash = "sha256:466e48829084efe2548012b855df21540b96f2e20e51bd124c851536556a592c", size = 65316 },
]
[[package]]
@@ -2505,7 +2525,7 @@ wheels = [
[[package]]
name = "langchain-core"
-version = "0.3.84"
+version = "0.3.86"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "jsonpatch" },
@@ -2517,14 +2537,14 @@ dependencies = [
{ name = "typing-extensions" },
{ name = "uuid-utils" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/13/3e/1e70598fac522eaeeeb22f03107da06495160533b25ba4388be9cef01d55/langchain_core-0.3.84.tar.gz", hash = "sha256:814b75bfe67a8460a53f5839bae9505bbfffc7af6f1aa0a5155715563f5cc490", size = 599092 }
+sdist = { url = "https://files.pythonhosted.org/packages/fe/8d/d54586b8f65c6fc209db93916ff9e919e1cc14bad8fe66880ea4d7ea9d6c/langchain_core-0.3.86.tar.gz", hash = "sha256:671cbc96a325fe47f7dbab421236ada2d437bc4bfad0038102264885d0b462e2", size = 603154 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/8d/5b/ba75d5b80bd1f60ae799c8cbda5477eb7489fb21d40c967ec509bbd51933/langchain_core-0.3.84-py3-none-any.whl", hash = "sha256:d0b3a7b6473e30a2b3d4588ee09dc6471b8d38c46cd48f3e7c3d1ab6547f63cb", size = 459123 },
+ { url = "https://files.pythonhosted.org/packages/0c/93/ba19ca54701c6118e68f8785949b6c0eab1df3a5cfa5310508cc86877994/langchain_core-0.3.86-py3-none-any.whl", hash = "sha256:7d2a1c50d2d2a139dbc6465cd339f32d14aa43db5ac9bd232e5b567a238709e8", size = 461306 },
]
[[package]]
name = "langsmith"
-version = "0.7.37"
+version = "0.8.5"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "httpx" },
@@ -2537,9 +2557,9 @@ dependencies = [
{ name = "xxhash" },
{ name = "zstandard" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/e4/38/092f99a3326f0f6bb6ea62f388b16611d9cb619869ed7b0f3dae6c21c331/langsmith-0.7.37.tar.gz", hash = "sha256:e15ab27f5febbcfbaec4e6fa74ab71f0284f4c5965249cc732fe9344844290cb", size = 4433170 }
+sdist = { url = "https://files.pythonhosted.org/packages/17/eb/8883d1158c743d0aac350f09df7880714d27283497e8c80bb9fe3480f165/langsmith-0.8.5.tar.gz", hash = "sha256:3615243d99c12f4047f13042bdc05a373dce232d106a6511b3ca7b48c5af1c2c", size = 4462348 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/c6/76/fa99559d23ec9a39e1153f317a5ec99e7b967aec08b5faac04f8da603dd3/langsmith-0.7.37-py3-none-any.whl", hash = "sha256:64fc5fbf223fcdcc6ee44b08a5df4b2ab8a55e4d968e850c86b6b69fe0c258e3", size = 385948 },
+ { url = "https://files.pythonhosted.org/packages/23/85/968c88a63e32a59b3e5c68afd2fe114ce0708a125db0be1a85efc25fb2ea/langsmith-0.8.5-py3-none-any.whl", hash = "sha256:efc779f9d450dcaf9d97bc8894f4926276509d6e730e05289af9a64debce06ae", size = 399564 },
]
[[package]]
@@ -2598,7 +2618,7 @@ wheels = [
[[package]]
name = "litellm"
-version = "1.83.7"
+version = "1.86.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp" },
@@ -2614,9 +2634,9 @@ dependencies = [
{ name = "tiktoken" },
{ name = "tokenizers" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/77/2b/b58bf6bbcbc3d0e55d0a84fdf9128e5b1436517f46fce89b1cd8948ebb81/litellm-1.83.7.tar.gz", hash = "sha256:e2f2cb99df2e2b2eab63f1354faa45c88dd7c8d40c18eb648afb1b349c689633", size = 17791694 }
+sdist = { url = "https://files.pythonhosted.org/packages/01/ee/1f6f3f5d01e0910629b6af3757e82c47b8b87dca497a661a9c63280b4bd8/litellm-1.86.2.tar.gz", hash = "sha256:7d559ad48b97d796ff325af88fd7eebbdc66e58773fb5312130ab1cac968f8f3", size = 15380548 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/75/80/caeb4cdcad96451ba83ad3ba2a9da08b1e1a915fa845c489f56ea044488b/litellm-1.83.7-py3-none-any.whl", hash = "sha256:5784a1d9a9a4a8acd6ca1e347003a5e2e1b3c749b4d41e7da4904577adade111", size = 16069807 },
+ { url = "https://files.pythonhosted.org/packages/4d/37/4da1dd67157aaa11477d6c63e4725216bfc46b4661e581b490d17e5b2831/litellm-1.86.2-py3-none-any.whl", hash = "sha256:27096463be7add661513ada3d9039e8f1a6195859e604d30fde96c939efe0a03", size = 17013061 },
]
[[package]]
@@ -2806,14 +2826,14 @@ wheels = [
[[package]]
name = "mako"
-version = "1.3.11"
+version = "1.3.12"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "markupsafe" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/59/8a/805404d0c0b9f3d7a326475ca008db57aea9c5c9f2e1e39ed0faa335571c/mako-1.3.11.tar.gz", hash = "sha256:071eb4ab4c5010443152255d77db7faa6ce5916f35226eb02dc34479b6858069", size = 399811 }
+sdist = { url = "https://files.pythonhosted.org/packages/00/62/791b31e69ae182791ec67f04850f2f062716bbd205483d63a215f3e062d3/mako-1.3.12.tar.gz", hash = "sha256:9f778e93289bd410bb35daadeb4fc66d95a746f0b75777b942088b7fd7af550a", size = 400219 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/68/a5/19d7aaa7e433713ffe881df33705925a196afb9532efc8475d26593921a6/mako-1.3.11-py3-none-any.whl", hash = "sha256:e372c6e333cf004aa736a15f425087ec977e1fcbd2966aae7f17c8dc1da27a77", size = 78503 },
+ { url = "https://files.pythonhosted.org/packages/bc/b1/a0ec7a5a9db730a08daef1fdfb8090435b82465abbf758a596f0ea88727e/mako-1.3.12-py3-none-any.whl", hash = "sha256:8f61569480282dbf557145ce441e4ba888be453c30989f879f0d652e39f53ea9", size = 78521 },
]
[[package]]
@@ -4145,21 +4165,21 @@ wheels = [
[[package]]
name = "pillow"
-version = "11.3.0"
+version = "12.2.0"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/f3/0d/d0d6dea55cd152ce3d6767bb38a8fc10e33796ba4ba210cbab9354b6d238/pillow-11.3.0.tar.gz", hash = "sha256:3828ee7586cd0b2091b6209e5ad53e20d0649bbe87164a459d0676e035e8f523", size = 47113069 }
+sdist = { url = "https://files.pythonhosted.org/packages/8c/21/c2bcdd5906101a30244eaffc1b6e6ce71a31bd0742a01eb89e660ebfac2d/pillow-12.2.0.tar.gz", hash = "sha256:a830b1a40919539d07806aa58e1b114df53ddd43213d9c8b75847eee6c0182b5", size = 46987819 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/40/fe/1bc9b3ee13f68487a99ac9529968035cca2f0a51ec36892060edcc51d06a/pillow-11.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fdae223722da47b024b867c1ea0be64e0df702c5e0a60e27daad39bf960dd1e4", size = 5278800 },
- { url = "https://files.pythonhosted.org/packages/2c/32/7e2ac19b5713657384cec55f89065fb306b06af008cfd87e572035b27119/pillow-11.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:921bd305b10e82b4d1f5e802b6850677f965d8394203d182f078873851dada69", size = 4686296 },
- { url = "https://files.pythonhosted.org/packages/8e/1e/b9e12bbe6e4c2220effebc09ea0923a07a6da1e1f1bfbc8d7d29a01ce32b/pillow-11.3.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:eb76541cba2f958032d79d143b98a3a6b3ea87f0959bbe256c0b5e416599fd5d", size = 5871726 },
- { url = "https://files.pythonhosted.org/packages/8d/33/e9200d2bd7ba00dc3ddb78df1198a6e80d7669cce6c2bdbeb2530a74ec58/pillow-11.3.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:67172f2944ebba3d4a7b54f2e95c786a3a50c21b88456329314caaa28cda70f6", size = 7644652 },
- { url = "https://files.pythonhosted.org/packages/41/f1/6f2427a26fc683e00d985bc391bdd76d8dd4e92fac33d841127eb8fb2313/pillow-11.3.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:97f07ed9f56a3b9b5f49d3661dc9607484e85c67e27f3e8be2c7d28ca032fec7", size = 5977787 },
- { url = "https://files.pythonhosted.org/packages/e4/c9/06dd4a38974e24f932ff5f98ea3c546ce3f8c995d3f0985f8e5ba48bba19/pillow-11.3.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:676b2815362456b5b3216b4fd5bd89d362100dc6f4945154ff172e206a22c024", size = 6645236 },
- { url = "https://files.pythonhosted.org/packages/40/e7/848f69fb79843b3d91241bad658e9c14f39a32f71a301bcd1d139416d1be/pillow-11.3.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3e184b2f26ff146363dd07bde8b711833d7b0202e27d13540bfe2e35a323a809", size = 6086950 },
- { url = "https://files.pythonhosted.org/packages/0b/1a/7cff92e695a2a29ac1958c2a0fe4c0b2393b60aac13b04a4fe2735cad52d/pillow-11.3.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6be31e3fc9a621e071bc17bb7de63b85cbe0bfae91bb0363c893cbe67247780d", size = 6723358 },
- { url = "https://files.pythonhosted.org/packages/26/7d/73699ad77895f69edff76b0f332acc3d497f22f5d75e5360f78cbcaff248/pillow-11.3.0-cp312-cp312-win32.whl", hash = "sha256:7b161756381f0918e05e7cb8a371fff367e807770f8fe92ecb20d905d0e1c149", size = 6275079 },
- { url = "https://files.pythonhosted.org/packages/8c/ce/e7dfc873bdd9828f3b6e5c2bbb74e47a98ec23cc5c74fc4e54462f0d9204/pillow-11.3.0-cp312-cp312-win_amd64.whl", hash = "sha256:a6444696fce635783440b7f7a9fc24b3ad10a9ea3f0ab66c5905be1c19ccf17d", size = 6986324 },
- { url = "https://files.pythonhosted.org/packages/16/8f/b13447d1bf0b1f7467ce7d86f6e6edf66c0ad7cf44cf5c87a37f9bed9936/pillow-11.3.0-cp312-cp312-win_arm64.whl", hash = "sha256:2aceea54f957dd4448264f9bf40875da0415c83eb85f55069d89c0ed436e3542", size = 2423067 },
+ { url = "https://files.pythonhosted.org/packages/58/be/7482c8a5ebebbc6470b3eb791812fff7d5e0216c2be3827b30b8bb6603ed/pillow-12.2.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:2d192a155bbcec180f8564f693e6fd9bccff5a7af9b32e2e4bf8c9c69dbad6b5", size = 5308279 },
+ { url = "https://files.pythonhosted.org/packages/d8/95/0a351b9289c2b5cbde0bacd4a83ebc44023e835490a727b2a3bd60ddc0f4/pillow-12.2.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f3f40b3c5a968281fd507d519e444c35f0ff171237f4fdde090dd60699458421", size = 4695490 },
+ { url = "https://files.pythonhosted.org/packages/de/af/4e8e6869cbed569d43c416fad3dc4ecb944cb5d9492defaed89ddd6fe871/pillow-12.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:03e7e372d5240cc23e9f07deca4d775c0817bffc641b01e9c3af208dbd300987", size = 6284462 },
+ { url = "https://files.pythonhosted.org/packages/e9/9e/c05e19657fd57841e476be1ab46c4d501bffbadbafdc31a6d665f8b737b6/pillow-12.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b86024e52a1b269467a802258c25521e6d742349d760728092e1bc2d135b4d76", size = 8094744 },
+ { url = "https://files.pythonhosted.org/packages/2b/54/1789c455ed10176066b6e7e6da1b01e50e36f94ba584dc68d9eebfe9156d/pillow-12.2.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7371b48c4fa448d20d2714c9a1f775a81155050d383333e0a6c15b1123dda005", size = 6398371 },
+ { url = "https://files.pythonhosted.org/packages/43/e3/fdc657359e919462369869f1c9f0e973f353f9a9ee295a39b1fea8ee1a77/pillow-12.2.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:62f5409336adb0663b7caa0da5c7d9e7bdbaae9ce761d34669420c2a801b2780", size = 7087215 },
+ { url = "https://files.pythonhosted.org/packages/8b/f8/2f6825e441d5b1959d2ca5adec984210f1ec086435b0ed5f52c19b3b8a6e/pillow-12.2.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:01afa7cf67f74f09523699b4e88c73fb55c13346d212a59a2db1f86b0a63e8c5", size = 6509783 },
+ { url = "https://files.pythonhosted.org/packages/67/f9/029a27095ad20f854f9dba026b3ea6428548316e057e6fc3545409e86651/pillow-12.2.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:fc3d34d4a8fbec3e88a79b92e5465e0f9b842b628675850d860b8bd300b159f5", size = 7212112 },
+ { url = "https://files.pythonhosted.org/packages/be/42/025cfe05d1be22dbfdb4f264fe9de1ccda83f66e4fc3aac94748e784af04/pillow-12.2.0-cp312-cp312-win32.whl", hash = "sha256:58f62cc0f00fd29e64b29f4fd923ffdb3859c9f9e6105bfc37ba1d08994e8940", size = 6378489 },
+ { url = "https://files.pythonhosted.org/packages/5d/7b/25a221d2c761c6a8ae21bfa3874988ff2583e19cf8a27bf2fee358df7942/pillow-12.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:7f84204dee22a783350679a0333981df803dac21a0190d706a50475e361c93f5", size = 7084129 },
+ { url = "https://files.pythonhosted.org/packages/10/e1/542a474affab20fd4a0f1836cb234e8493519da6b76899e30bcc5d990b8b/pillow-12.2.0-cp312-cp312-win_arm64.whl", hash = "sha256:af73337013e0b3b46f175e79492d96845b16126ddf79c438d7ea7ff27783a414", size = 2463612 },
]
[[package]]
@@ -4670,15 +4690,15 @@ sdist = { url = "https://files.pythonhosted.org/packages/5d/ab/34ec41718af73c001
[[package]]
name = "pymdown-extensions"
-version = "10.21.2"
+version = "10.21.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "markdown" },
{ name = "pyyaml" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/df/08/f1c908c581fd11913da4711ea7ba32c0eee40b0190000996bb863b0c9349/pymdown_extensions-10.21.2.tar.gz", hash = "sha256:c3f55a5b8a1d0edf6699e35dcbea71d978d34ff3fa79f3d807b8a5b3fa90fbdc", size = 853922 }
+sdist = { url = "https://files.pythonhosted.org/packages/9e/26/d1015444da4d952a1ca487a236b522eb979766f0295a0bd0c5fc089989a9/pymdown_extensions-10.21.3.tar.gz", hash = "sha256:72cfcf55f07aea0d4af2c4f11dd4e52466ddfb1bb819673146398e0bd3a77354", size = 854140 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/f7/27/a2fc51a4a122dfd1015e921ae9d22fee3d20b0b8080d9a704578bf9deece/pymdown_extensions-10.21.2-py3-none-any.whl", hash = "sha256:5c0fd2a2bea14eb39af8ff284f1066d898ab2187d81b889b75d46d4348c01638", size = 268901 },
+ { url = "https://files.pythonhosted.org/packages/7e/85/545a951eecc270fcd688288c600017e2050a1aacb56c711d208586d3e470/pymdown_extensions-10.21.3-py3-none-any.whl", hash = "sha256:d7a5d08014fc571e80ca21dd6f854e31f94c489800350564d55d15b3c41e76b6", size = 269002 },
]
[[package]]
@@ -4826,7 +4846,7 @@ wheels = [
[[package]]
name = "pytest"
-version = "8.4.2"
+version = "9.0.3"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "colorama", marker = "sys_platform == 'win32'" },
@@ -4835,21 +4855,22 @@ dependencies = [
{ name = "pluggy" },
{ name = "pygments" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/a3/5c/00a0e072241553e1a7496d638deababa67c5058571567b92a7eaa258397c/pytest-8.4.2.tar.gz", hash = "sha256:86c0d0b93306b961d58d62a4db4879f27fe25513d4b969df351abdddb3c30e01", size = 1519618 }
+sdist = { url = "https://files.pythonhosted.org/packages/7d/0d/549bd94f1a0a402dc8cf64563a117c0f3765662e2e668477624baeec44d5/pytest-9.0.3.tar.gz", hash = "sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c", size = 1572165 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/a8/a4/20da314d277121d6534b3a980b29035dcd51e6744bd79075a6ce8fa4eb8d/pytest-8.4.2-py3-none-any.whl", hash = "sha256:872f880de3fc3a5bdc88a11b39c9710c3497a547cfa9320bc3c5e62fbf272e79", size = 365750 },
+ { url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249 },
]
[[package]]
name = "pytest-asyncio"
-version = "0.26.0"
+version = "1.4.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "pytest" },
+ { name = "typing-extensions" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/8e/c4/453c52c659521066969523e87d85d54139bbd17b78f09532fb8eb8cdb58e/pytest_asyncio-0.26.0.tar.gz", hash = "sha256:c4df2a697648241ff39e7f0e4a73050b03f123f760673956cf0d72a4990e312f", size = 54156 }
+sdist = { url = "https://files.pythonhosted.org/packages/43/7c/d36d04db312ecf4298932ef77e6e4a9e8ad017906e24e34f0b0c361a2473/pytest_asyncio-1.4.0.tar.gz", hash = "sha256:c6c0d2259945122819f171a32ecea2c349ead889ee28176caaf492143424be42", size = 58514 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/20/7f/338843f449ace853647ace35870874f69a764d251872ed1b4de9f234822c/pytest_asyncio-0.26.0-py3-none-any.whl", hash = "sha256:7b51ed894f4fbea1340262bdae5135797ebbe21d8638978e35d31c6d19f72fb0", size = 19694 },
+ { url = "https://files.pythonhosted.org/packages/03/e2/08a497ef684b88559c9cc5f4ad53a37e7b99e727094a86d6ea32536d5d3c/pytest_asyncio-1.4.0-py3-none-any.whl", hash = "sha256:933ca923a23075a87fb7070c0ec272a6848489824d887c85c812670932835aa1", size = 16930 },
]
[[package]]
@@ -4931,11 +4952,11 @@ wheels = [
[[package]]
name = "python-dotenv"
-version = "1.0.1"
+version = "1.2.2"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/bc/57/e84d88dfe0aec03b7a2d4327012c1627ab5f03652216c63d49846d7a6c58/python-dotenv-1.0.1.tar.gz", hash = "sha256:e324ee90a023d808f1959c46bcbc04446a10ced277783dc6ee09987c37ec10ca", size = 39115 }
+sdist = { url = "https://files.pythonhosted.org/packages/82/ed/0301aeeac3e5353ef3d94b6ec08bbcabd04a72018415dcb29e588514bba8/python_dotenv-1.2.2.tar.gz", hash = "sha256:2c371a91fbd7ba082c2c1dc1f8bf89ca22564a087c2c287cd9b662adde799cf3", size = 50135 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/6a/3e/b68c118422ec867fa7ab88444e1274aa40681c606d59ac27de5a5588f082/python_dotenv-1.0.1-py3-none-any.whl", hash = "sha256:f7b63ef50f1b690dddf550d03497b66d609393b40b564ed0d674909a68ebf16a", size = 19863 },
+ { url = "https://files.pythonhosted.org/packages/0b/d7/1959b9648791274998a9c3526f6d0ec8fd2233e4d4acce81bbae76b44b2a/python_dotenv-1.2.2-py3-none-any.whl", hash = "sha256:1d8214789a24de455a8b8bd8ae6fe3c6b69a5e3d64aa8a8e5d68e694bbcb285a", size = 22101 },
]
[[package]]
@@ -5599,7 +5620,7 @@ dev = [
{ name = "plotly", specifier = ">=6.1.1" },
{ name = "pre-commit", specifier = "~=4.0" },
{ name = "pydantic", specifier = ">=2.0" },
- { name = "pytest", specifier = "~=8.0" },
+ { name = "pytest", specifier = ">=9.0.3" },
{ name = "pytest-asyncio" },
{ name = "pytest-cov" },
{ name = "pytest-subprocess" },
@@ -5614,7 +5635,7 @@ dev = [
[[package]]
name = "sie-admin"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "packages/sie_admin" }
dependencies = [
{ name = "httpx" },
@@ -5647,7 +5668,7 @@ requires-dist = [
[[package]]
name = "sie-bench"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "packages/sie_bench" }
dependencies = [
{ name = "aiohttp" },
@@ -5659,6 +5680,7 @@ dependencies = [
{ name = "psutil" },
{ name = "pylate" },
{ name = "pypdfium2" },
+ { name = "rapidfuzz" },
{ name = "rich" },
{ name = "sie-sdk" },
{ name = "tiktoken" },
@@ -5719,6 +5741,7 @@ requires-dist = [
{ name = "pylate", marker = "extra == 'all'", specifier = ">=1,<2" },
{ name = "pylate", marker = "extra == 'pylate'", specifier = ">=1,<2" },
{ name = "pypdfium2", specifier = ">=5.6.0" },
+ { name = "rapidfuzz", specifier = ">=3.6" },
{ name = "rich", specifier = ">=13,<14" },
{ name = "sie-sdk", editable = "packages/sie_sdk" },
{ name = "tiktoken", specifier = ">=0.7" },
@@ -5730,7 +5753,7 @@ requires-dist = [
[[package]]
name = "sie-chroma"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "integrations/sie_chroma" }
dependencies = [
{ name = "chromadb" },
@@ -5796,13 +5819,13 @@ requires-dist = [
[package.metadata.requires-dev]
dev = [
- { name = "pytest", specifier = ">=8.3,<9" },
- { name = "pytest-asyncio", specifier = ">=0.24,<1" },
+ { name = "pytest", specifier = ">=9.0.3" },
+ { name = "pytest-asyncio", specifier = ">=1.0" },
]
[[package]]
name = "sie-crewai"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "integrations/sie_crewai" }
dependencies = [
{ name = "crewai" },
@@ -5827,7 +5850,7 @@ requires-dist = [
[[package]]
name = "sie-dspy"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "integrations/sie_dspy" }
dependencies = [
{ name = "dspy" },
@@ -5852,7 +5875,7 @@ requires-dist = [
[[package]]
name = "sie-haystack"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "integrations/sie_haystack" }
dependencies = [
{ name = "haystack-ai" },
@@ -5879,7 +5902,7 @@ requires-dist = [
[[package]]
name = "sie-lancedb"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "integrations/sie_lancedb" }
dependencies = [
{ name = "lancedb" },
@@ -5906,7 +5929,7 @@ requires-dist = [
[[package]]
name = "sie-langchain"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "integrations/sie_langchain" }
dependencies = [
{ name = "langchain-core" },
@@ -5933,7 +5956,7 @@ requires-dist = [
[[package]]
name = "sie-llamaindex"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "integrations/sie_llamaindex" }
dependencies = [
{ name = "llama-index-core" },
@@ -5960,7 +5983,7 @@ requires-dist = [
[[package]]
name = "sie-qdrant"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "integrations/sie_qdrant" }
dependencies = [
{ name = "qdrant-client" },
@@ -5983,7 +6006,7 @@ requires-dist = [
[[package]]
name = "sie-sdk"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "packages/sie_sdk" }
dependencies = [
{ name = "aiohttp" },
@@ -6025,16 +6048,17 @@ requires-dist = [
{ name = "msgpack", specifier = ">=1.1,<2" },
{ name = "msgpack-numpy", specifier = ">=0.4,<1" },
{ name = "numpy", specifier = ">=2,<3" },
- { name = "pillow", specifier = ">=11,<12" },
+ { name = "pillow", specifier = ">=12.2.0" },
{ name = "pyyaml", specifier = ">=6,<7" },
{ name = "websockets", specifier = ">=14,<15" },
]
[[package]]
name = "sie-server"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "packages/sie_server" }
dependencies = [
+ { name = "blake3" },
{ name = "docling" },
{ name = "einops" },
{ name = "fastapi" },
@@ -6047,7 +6071,6 @@ dependencies = [
{ name = "msgpack" },
{ name = "msgpack-numpy" },
{ name = "msgspec" },
- { name = "nats-py" },
{ name = "numpy" },
{ name = "open-clip-torch" },
{ name = "opencv-python-headless" },
@@ -6095,6 +6118,7 @@ xformers = [
[package.metadata]
requires-dist = [
+ { name = "blake3", specifier = ">=0.4,<1" },
{ name = "docling", specifier = ">=2,<3" },
{ name = "einops", specifier = ">=0.8,<1" },
{ name = "fastapi", specifier = ">=0.115,<1" },
@@ -6108,7 +6132,6 @@ requires-dist = [
{ name = "msgpack", specifier = ">=1.1,<2" },
{ name = "msgpack-numpy", specifier = ">=0.4,<1" },
{ name = "msgspec", specifier = ">=0.20.0" },
- { name = "nats-py", specifier = ">=2.9,<3" },
{ name = "numpy", specifier = ">=2,<3" },
{ name = "nvidia-ml-py", marker = "extra == 'gpu-metrics'", specifier = ">=13.5,<14" },
{ name = "open-clip-torch", specifier = ">=2.24" },
@@ -6118,7 +6141,7 @@ requires-dist = [
{ name = "opentelemetry-instrumentation-fastapi", specifier = ">=0.49b0,<1" },
{ name = "opentelemetry-sdk", specifier = ">=1.28,<2" },
{ name = "packaging", specifier = ">=24,<25" },
- { name = "pillow", specifier = ">=11,<12" },
+ { name = "pillow", specifier = ">=12.2.0" },
{ name = "prometheus-client", specifier = ">=0.21,<1" },
{ name = "pydantic", specifier = ">=2.9,<3" },
{ name = "pydantic-settings", specifier = ">=2.6,<3" },
@@ -6147,7 +6170,7 @@ dev = []
[[package]]
name = "sie-weaviate"
-version = "0.4.1"
+version = "0.4.2"
source = { editable = "integrations/sie_weaviate" }
dependencies = [
{ name = "sie-sdk" },
@@ -6996,21 +7019,21 @@ wheels = [
[[package]]
name = "ujson"
-version = "5.12.0"
+version = "5.12.1"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/cb/3e/c35530c5ffc25b71c59ae0cd7b8f99df37313daa162ce1e2f7925f7c2877/ujson-5.12.0.tar.gz", hash = "sha256:14b2e1eb528d77bc0f4c5bd1a7ebc05e02b5b41beefb7e8567c9675b8b13bcf4", size = 7158451 }
+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/84/f6/ac763d2108d28f3a40bb3ae7d2fafab52ca31b36c2908a4ad02cd3ceba2a/ujson-5.12.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:09b4beff9cc91d445d5818632907b85fb06943b61cb346919ce202668bf6794a", size = 56326 },
- { url = "https://files.pythonhosted.org/packages/25/46/d0b3af64dcdc549f9996521c8be6d860ac843a18a190ffc8affeb7259687/ujson-5.12.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ca0c7ce828bb76ab78b3991904b477c2fd0f711d7815c252d1ef28ff9450b052", size = 53910 },
- { url = "https://files.pythonhosted.org/packages/9a/10/853c723bcabc3e9825a079019055fc99e71b85c6bae600607a2b9d31d18d/ujson-5.12.0-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a2d79c6635ccffcbfc1d5c045874ba36b594589be81d50d43472570bb8de9c57", size = 57754 },
- { url = "https://files.pythonhosted.org/packages/f9/c6/6e024830d988f521f144ead641981c1f7a82c17ad1927c22de3242565f5c/ujson-5.12.0-cp312-cp312-manylinux_2_24_i686.manylinux_2_28_i686.whl", hash = "sha256:7e07f6f644d2c44d53b7a320a084eef98063651912c1b9449b5f45fcbdc6ccd2", size = 59936 },
- { url = "https://files.pythonhosted.org/packages/34/c9/c5f236af5abe06b720b40b88819d00d10182d2247b1664e487b3ed9229cf/ujson-5.12.0-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:085b6ce182cdd6657481c7c4003a417e0655c4f6e58b76f26ee18f0ae21db827", size = 57463 },
- { url = "https://files.pythonhosted.org/packages/ae/04/41342d9ef68e793a87d84e4531a150c2b682f3bcedfe59a7a5e3f73e9213/ujson-5.12.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:16b4fe9c97dc605f5e1887a9e1224287291e35c56cbc379f8aa44b6b7bcfe2bb", size = 1037239 },
- { url = "https://files.pythonhosted.org/packages/d4/81/dc2b7617d5812670d4ff4a42f6dd77926430ee52df0dedb2aec7990b2034/ujson-5.12.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:0d2e8db5ade3736a163906154ca686203acc7d1d30736cbf577c730d13653d84", size = 1196713 },
- { url = "https://files.pythonhosted.org/packages/b6/9c/80acff0504f92459ed69e80a176286e32ca0147ac6a8252cd0659aad3227/ujson-5.12.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:93bc91fdadcf046da37a214eaa714574e7e9b1913568e93bb09527b2ceb7f759", size = 1089742 },
- { url = "https://files.pythonhosted.org/packages/e3/f0/123ffaac17e45ef2b915e3e3303f8f4ea78bb8d42afad828844e08622b1e/ujson-5.12.0-cp312-cp312-win32.whl", hash = "sha256:2a248750abce1c76fbd11b2e1d88b95401e72819295c3b851ec73399d6849b3d", size = 39773 },
- { url = "https://files.pythonhosted.org/packages/b5/20/f3bd2b069c242c2b22a69e033bfe224d1d15d3649e6cd7cc7085bb1412ff/ujson-5.12.0-cp312-cp312-win_amd64.whl", hash = "sha256:1b5c6ceb65fecd28a1d20d1eba9dbfa992612b86594e4b6d47bb580d2dd6bcb3", size = 44040 },
- { url = "https://files.pythonhosted.org/packages/f0/a7/01b5a0bcded14cd2522b218f2edc3533b0fcbccdea01f3e14a2b699071aa/ujson-5.12.0-cp312-cp312-win_arm64.whl", hash = "sha256:9a5fcbe7b949f2e95c47ea8a80b410fcdf2da61c98553b45a4ee875580418b68", size = 38526 },
+ { 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 },
]
[[package]]
@@ -7041,11 +7064,11 @@ wheels = [
[[package]]
name = "urllib3"
-version = "2.6.3"
+version = "2.7.0"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/c7/24/5f1b3bdffd70275f6661c76461e25f024d5a38a46f04aaca912426a2b1d3/urllib3-2.6.3.tar.gz", hash = "sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed", size = 435556 }
+sdist = { url = "https://files.pythonhosted.org/packages/53/0c/06f8b233b8fd13b9e5ee11424ef85419ba0d8ba0b3138bf360be2ff56953/urllib3-2.7.0.tar.gz", hash = "sha256:231e0ec3b63ceb14667c67be60f2f2c40a518cb38b03af60abc813da26505f4c", size = 433602 }
wheels = [
- { url = "https://files.pythonhosted.org/packages/39/08/aaaad47bc4e9dc8c725e68f9d04865dbcb2052843ff09c97b08904852d84/urllib3-2.6.3-py3-none-any.whl", hash = "sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4", size = 131584 },
+ { url = "https://files.pythonhosted.org/packages/7f/3e/5db95bcf282c52709639744ca2a8b149baccf648e39c8cc87553df9eae0c/urllib3-2.7.0-py3-none-any.whl", hash = "sha256:9fb4c81ebbb1ce9531cce37674bbc6f1360472bc18ca9a553ede278ef7276897", size = 131087 },
]
[[package]]