Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
release: v0.6.15
github-actions[bot]7031451396a0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a689b9c39..3b3252e31 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,135 @@# Changelog+## v0.6.15++- chore(main): release 0.6.15+- fix(playground): keyboard-accessible tabs + associated form labels+- fix(server): address CI + review comments on the Apple Silicon re-land+- feat(server): land Apple Silicon as a primary device onto main+- fix(sidecar): start batch cancel before direct pulls+- fix(tilt): wait for complete trace before asserting span chain+- fix(gateway): harden batch direct fallback cancellation+- fix(gateway): cancel abandoned direct batch fallback work+- test(tracing): assert run_batch metadata and malformed traceparent+- fix(gateway): ignore pre-latch stale NAKs after republish+- fix(docs): drop otel.name from span-attribute table; tighten tracing dashboard test+- feat(helm): add SIE tracing dashboard and tempo datasource uid+- docs(gateway): document distributed tracing span chain and enable switch+- refactor(helm): migrate bundled Tempo to grafana-community chart 2.2.3+- refactor(helm): gate tempo datasource on grafana+- fix(gateway): use real RUSTSEC id for second quick-xml advisory+- feat(helm): add optional bundled Tempo tracing backend+- fix(gateway): ignore quick-xml <0.41 RustSec advisories in cargo-deny+- refactor(sie_gateway): clarify publish-seam comment, drop redundant otel.name+- feat(sie_gateway): emit gateway.publish span on non-streaming queue-publish path (#1596)+- feat(gateway): count dropped stale NAKs from abandoned attempts+- test(observability): use single import style in shutdown_tracing test+- feat(observability): bound tracing shutdown and trim env inputs across all four runtimes+- fix(models): serve gte-Qwen2-1.5B via sentence_transformer adapter (#1593)+- feat(observability): gate Rust tracing on SIE_TRACING_ENABLED+- test: update queue executor batch mocks+- test: cover queue runtime app wiring+- fix: complete empty preformed worker requests+- fix: address sidecar PR review feedback+- fix: clean stale Python queue ownership drift+- docs: clarify sidecar queue batching ownership+- fix: remove Python worker pull-loop path+- fix(server): serialize hot reload registry mutations+- fix(server): move load headroom behind adapter contract+- fix(server): make SGLang load eviction headroom-aware+- test(config): time-box idempotency mismatch request+- fix(config): shield idempotency failure cleanup+- fix(config): defer cancellation after config commit starts+- fix(config): handle idempotency in-flight races+- fix(server): cap LoRA drain to snapshot backlog so post-snapshot arrivals don't overshoot+- fix(gateway): keep signalling SSE incompleteness on lag; only skip cancel when done (#1602)+- perf(gateway): build the HRW ring from the by_bundle index, not a whole-cluster scan (#1607)+- fix(gateway): don't report a succeeded SSE generation as inter_chunk_timeout on consumer lag (#1602)+- fix(gateway): drop stale NAKs from abandoned attempts in handle_nak (#1601)+- perf(server): vectorize bge_m3_flash CLS gather to drop N per-encode GPU syncs (#1605)+- fix(server): bound the continuous-batching drain so a busy LoRA can't starve siblings (#1606)+- fix(server): stop mislabelling uint8 embeddings as "binary" on the queue path (#1603)+- fix(server): /v1/embeddings maps OOM to 503 RESOURCE_EXHAUSTED, not 500 (#1604)+- fix(server): unregister model from MemoryManager even if adapter.unload() raises (#1600)+- fix: select rustls provider at binary startup+- revert: restore gateway sidecar rustls defaults+- fix: select rustls provider for rust services+- fix(gateway): append forwarded embeddings headers to preserve multi-value tracestate+- fix(gateway): forward traceparent/tracestate through /v1/embeddings rewrite+- test(gateway): pin RetryAfter aliases to wire literals, not tautologies (#1574)+- fix(tracing): parent sidecar.dispatch on first valid inbound context+- refactor(gateway): injectable clock for TokenBucket (#1575, publisher PR 1/n)+- refactor(gateway): one typed RetryAfter home for cold-load retry hints (#1574)+- refactor(gateway): normalize rejected-request labels via sanitize_label (#1573)+- docs(server): ADR-0004 — cost is modality-native, not commensurable (#1571)+- refactor(server): controller owns its config write-back via apply_step (#1570, BatchPolicy PR 1/n)+- feat(tracing): emit sidecar.dispatch span from sie_server_sidecar (#1550)+- refactor(server): typed EvictionResult for evict_lru_excluding (#1569, ResidencyPolicy PR 1/n)+- fix(gateway): record demand on backpressure so KEDA scales the lane (#1568)+- refactor(server): single typed definition for the queue-path inference_error code (#1572)+- fix(gateway): route engine-pin errors through endpoint_error_response (#1567)+- chore(deps): refresh gateway Rust lockfile+- docs(gateway): use 'gateway' terminology in resolve_routing pool comment (#1543)+- refactor(gateway): fold pool + GPU resolution into resolve_routing (#1543, PR 3/3)+- refactor(gateway): wrap routing decision in resolve_routing (#1543, PR 2/3)+- refactor(gateway): extract resolve_bundle_for_request from proxy_request (#1543)+- test(gateway/config/server): shared conformance vectors for bundle_config_hash (#1542)+- refactor(server): make ModelRegistry.get() a pure read; add touch_lru() (#1541)+- refactor(tracing): use is_some() borrow check for inbound ctx branch+- test(tracing): bind a JetStream consumer in the encode propagation IT+- test(tracing): add NATS-gated integration test for encode trace propagation+- fix(tracing): attach inbound trace context for non-generation publishes+- feat(tracing): inject queue trace context for non-generation endpoints+- fix(adapters): guard empty-document MaxSim batches; strengthen single-doc test (#1539)+- refactor(preprocessor): extract shared _load_rgb image loader (#1540)+- refactor(adapters): shared multivector MaxSim scoring helpers (#1539)+- refactor(adapters): extract shared flash varlen position-id builder (#1538)+- test(server): add score/extract invalid-item regressions for decode_item seam (#1537)+- refactor(server): validate queue-path items through one decode_item seam (#1537)+- fix(candle): keep catalog additions candle-only+- fix(models): restore per-task MTEB instruction for stella_en_v5 (#1340)+- docs(helm): document collector suppression + exporterInsecure in chart README+- fix(helm): make bundled collector downstream OTLP TLS configurable+- fix(helm): suppress bundled collector when explicit tracing endpoint set+- fix(helm): set OTEL_EXPORTER_OTLP_PROTOCOL=grpc on traced pods+- feat(helm): add opt-in OTLP tracing wiring + bundled collector to sie-cluster+- fix(candle): harden native worker routing+- fix(tracing): assert items/metadata alignment before zip in scheduler batch+- feat(tracing): propagate trace context through the non-streaming worker loop+- fix(muvera): center tokens before SimHash to fix answerai @muvera Blackwell collapse (#1528)+- fix(candle): harden native worker runtime+- fix(sdk): raise actionable error on encode result-count desync (#1526)+- fix(models): load stock tokenizer for gte-Qwen2-7B-instruct (#1483)+- fix(server): skip EOS on empty input; cover non-default profile on queue path+- fix(models): serve embeddinggemma-300m via SentenceTransformerDenseAdapter (#1523)+- fix(server): apply profile runtime options and append EOS on cluster encode path (#1489)+- fix(candle): publish loaded models in health+- chore(deps): bump Rust gateway and sidecar dependencies+- fix: repair candle rebase fallout+- fix(gateway): separate queue timeouts from model loading+- fix(candle): run bge-m3 profile in bf16+- perf(candle): optimize bge-m3 xlm-r runtime path+- fix(candle): align readiness with loaded model state+- fix(candle): restore sidecar model readiness+- fix(sidecar): keep only config hash wiring+- fix(sidecar): bound scheduler bulk enqueue waves+- perf(sidecar): bulk enqueue scheduler batches+- feat: tune candle forward concurrency+- fix: remove candle replica fallback path+- feat: improve candle replica concurrency+- fix: log candle batch failure context+- fix: restore default candle cuda stream+- perf: improve candle worker concurrency and build cache+- fix: improve candle embedding runtime throughput+- fix: install gateway pool config hashes+- fix: preserve control-plane bundle hash in sidecar+- fix: align worker pool config hashes+- fix: export profile bundle targets+- fix: repair candle ci routing checks+- fix: harden candle bge-m3 runtime bring-up+- feat(candle): add native adapter runtime+- fix(muvera): drop same-dim count-sketch + retune colbert muvera configs (#1493)+## v0.6.14- chore(main): release 0.6.14diff --git a/README.md b/README.mdindex 088f0c6d6..a4077d14b 100644--- a/README.md+++ b/README.md@@ -50,18 +50,19 @@ One SIE cluster runs the inference behind a whole agent. Each task is a handful## Quickstart-SIE runs as a server you call over HTTP — a Docker container today, with a native macOS pip install coming in the Apple-Silicon release. Start it, install the SDK, run the example.+SIE runs as a server you call over HTTP — a Docker container, or a native macOS pip install for Apple Silicon. Start it, install the SDK, run the example.**1. Run the engine**```bash-# macOS (Apple Silicon) — today, run the Linux CPU image under emulation:-docker run --platform linux/amd64 -p 8080:8080 -v sie-hf-cache:/app/.cache/huggingface ghcr.io/superlinked/sie-server:latest-cpu-default-# Coming in the Apple-Silicon release (NOT yet on PyPI) — a native pip install served on Metal-# (requires Python 3.12). Embeddings + reranking:-# pip install "sie-server[local]" && sie-server serve-# Generation (Apple MLX), in its own env (uv one-liner, or pip install into a fresh venv):+# macOS (Apple Silicon) — native, served on Metal (requires Python 3.12).+# Embeddings + reranking (torch-MPS):+pip install "sie-server[local]" && sie-server serve+# Generation (Apple MLX), in its own env — keeps mlx-lm's transformers>=5 out of the+# embed/rerank lock:# uvx --with "mlx-lm>=0.30.7" --from sie-server sie-server serve -b sglang -p 8081+# Or run the Linux CPU image under emulation:+# docker run --platform linux/amd64 -p 8080:8080 -v sie-hf-cache:/app/.cache/huggingface ghcr.io/superlinked/sie-server:latest-cpu-default# Linux, CPUdocker run -p 8080:8080 -v sie-hf-cache:/app/.cache/huggingface ghcr.io/superlinked/sie-server:latest-cpu-defaultdiff --git a/deploy/helm/sie-cluster/Chart.lock b/deploy/helm/sie-cluster/Chart.lockindex a10f6e6d6..92bfdf03d 100644--- a/deploy/helm/sie-cluster/Chart.lock+++ b/deploy/helm/sie-cluster/Chart.lock@@ -14,6 +14,9 @@ dependencies:- name: alloyrepository: https://grafana.github.io/helm-chartsversion: 0.10.1+- name: tempo+ repository: https://grafana-community.github.io/helm-charts+ version: 2.2.3- name: kubernetes-event-exporterrepository: oci://registry-1.docker.io/bitnamichartsversion: 3.6.3@@ -26,5 +29,5 @@ dependencies:- name: trust-managerrepository: https://charts.jetstack.ioversion: v0.13.0-digest: sha256:523f3a647cb890c2b06d96b06097e871d3dec6fdef1fa3712c9c5bcc6a5c0fed-generated: "2026-05-26T13:51:40.00581+02:00"+digest: sha256:d9a00b62c8fb60d1481fce18a98aea0291ff81aa5b661d73b88d56845e3bbe64+generated: "2026-07-02T11:24:24.047532+02:00"diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex e80b2a0c0..d22720879 100644--- a/deploy/helm/sie-cluster/Chart.yaml+++ b/deploy/helm/sie-cluster/Chart.yaml@@ -4,8 +4,8 @@ description: >-SIE (Search Inference Engine) Kubernetes deployment with gateway, GPU workers,and observabilitytype: application-version: 0.6.14 # x-release-please-version-appVersion: v0.6.14 # x-release-please-version+version: 0.6.15 # x-release-please-version+appVersion: v0.6.15 # x-release-please-versionkeywords:- inference- embedding@@ -42,6 +42,11 @@ dependencies:version: 0.10.xrepository: https://grafana.github.io/helm-chartscondition: observability.logs.install,observability.logs.alloy.install+ # grafana/tempo was deprecated and moved to grafana-community/tempo.+ - name: tempo+ version: 2.2.3+ repository: https://grafana-community.github.io/helm-charts+ condition: observability.tracing.tempo.install- name: kubernetes-event-exporterversion: 3.6.3repository: oci://registry-1.docker.io/bitnamichartsdiff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex f1927abf7..e9d3cc797 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -638,10 +638,71 @@ telemetry:## Observability-Observability components (Prometheus, Grafana, Loki, DCGM Exporter, Alloy, Event Exporter) are included as optional sub-chart dependencies. Enable them in your values overlay (e.g. `kube-prometheus-stack.install: true`, `observability.logs.install: true`, or `kubernetes-event-exporter.install: true`).+Observability components (Prometheus, Grafana, Loki, Tempo, DCGM Exporter, Alloy, Event Exporter) are included as optional sub-chart dependencies. Enable them in your values overlay (e.g. `kube-prometheus-stack.install: true`, `observability.logs.install: true`, `observability.tracing.tempo.install: true`, or `kubernetes-event-exporter.install: true`).Pre-configured dashboards:- Cluster overview (QPS, latency, GPU utilization)- Per-model performance- Worker health+- Queue routing+- Generation+- Performance tuning+- SIE Tracing++### Distributed Tracing (OTLP)++Distributed tracing is **off by default** — the rendered chart is unchanged unless you opt in. Enabling injects the OpenTelemetry exporter env onto the gateway, worker sidecar, Python worker, and Rust worker so a request is traced end to end (OTLP gRPC, `:4317`). Non-generation endpoints (encode/score/extract/embeddings) publish through `gateway.publish` before `sidecar.dispatch` and `worker.run_batch`; generation (`/v1/generate`, `/v1/chat/completions`) uses `gateway.proxy_generate` / `gateway.proxy_chat` and `worker.streaming_processor`, bypassing the sidecar. Sampling defaults to a head-based parent sampler (`parentbased_traceidratio` at `0.05`), which honors an inbound `traceparent` decision and otherwise samples 5% of new traces.++**Bring your own collector** (Tempo, Jaeger, or an existing OTel Collector) — recommended:++```yaml+observability:+ tracing:+ enabled: true+ endpoint: "http://tempo:4317" # OTLP gRPC+```++Or with `--set`:++```bash+helm upgrade ... \+ --set observability.tracing.enabled=true \+ --set observability.tracing.endpoint=http://tempo:4317+```++**Bundled collector** (opt-in; never installed by default) — renders a minimal OTel Collector and points the pods at it automatically. Leave `collector.exporterEndpoint` empty to debug-log spans in the collector pod (handy for a first run), or set it to forward to Tempo/Jaeger:++```yaml+observability:+ tracing:+ enabled: true+ collector:+ install: true+ exporterEndpoint: "http://tempo:4317" # optional downstream; omit to debug-log+ exporterInsecure: true # set false for a TLS-enabled downstream+```++The bundled collector forwards over plaintext by default (`exporterInsecure: true`); set it to `false` when `exporterEndpoint` targets a TLS-enabled backend. Setting an explicit top-level `endpoint` takes precedence and **suppresses** the bundled collector even if `collector.install: true`, so pods export straight to your external backend and no unused collector is rendered.++**Bundled Tempo backend** (opt-in; never installed by default) — renders Grafana Tempo as an in-cluster trace backend via the `grafana-community/tempo` 2.2.3 chart (Tempo app 2.10.7) from the grafana-community repo. With tracing enabled and no explicit endpoint or bundled collector, the gateway and workers automatically export OTLP gRPC spans to `http://tempo:4317`. The Tempo query API is exposed at `http://tempo:3200`, and the chart renders a Grafana Tempo datasource ConfigMap for the already-enabled Grafana datasource sidecar:++```yaml+observability:+ tracing:+ enabled: true # required for gateway/worker span emission+ tempo:+ install: true # installs Tempo and defaults pods to http://tempo:4317+kube-prometheus-stack:+ install: true # required for bundled Grafana to pick up the datasource+```++Installing Tempo without `observability.tracing.enabled=true` is allowed; it creates an idle backend and, when bundled Grafana is installed, a datasource. Installing both the bundled collector and bundled Tempo points pods at the collector and makes the collector forward to `http://tempo:4317` unless `collector.exporterEndpoint` is set. An explicit top-level `observability.tracing.endpoint` always wins over both bundled modes.++The SIE Tracing dashboard renders with the standard dashboards gate (`dashboards.enabled=true` or `kube-prometheus-stack.install=true`). Its Tempo panels require a Grafana datasource with `uid: tempo`; the chart auto-provisions that datasource only when both `observability.tracing.tempo.install=true` and `kube-prometheus-stack.install=true`. External Grafana installs, or bundled Grafana pointed at an external Tempo via `observability.tracing.endpoint`, must provision the datasource themselves or the trace panels will report "datasource not found".++Bundled Tempo enables a persistent volume (`~10Gi`) and requires a default StorageClass in the target cluster; otherwise the Tempo pod will not schedule. The upstream chart also exposes unused legacy receiver Service ports (`9411`, `55680`, `55681`) even though SIE only configures OTLP gRPC ingest on `4317` and the query API on `3200`.++Tunables: `observability.tracing.sampler` / `samplerArg` (sampling), and `observability.tracing.serviceName.{gateway,worker,workerSidecar}` (the `OTEL_SERVICE_NAME` shown in the backend, defaulting to `sie-gateway` / `sie-server` / `sie-worker-sidecar`). When `enabled: true` you must set `endpoint`, `collector.install: true`, or `tempo.install: true`, or the chart fails fast.++Local / non-Helm note: the gateway, Python worker, and Rust worker-sidecar all require `SIE_TRACING_ENABLED=true` and an OTLP endpoint (`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`, or `OTEL_EXPORTER_OTLP_ENDPOINT`) before exporting traces. Setting only one yields no traces rather than a partial trace. In-cluster, the Helm chart sets both for you.diff --git a/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml b/deploy/helm/sie-cluster/files/alerts/sie-rules.yamlindex be2af88ee..f7e409389 100644--- a/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml+++ b/deploy/helm/sie-cluster/files/alerts/sie-rules.yaml@@ -82,14 +82,11 @@ groups:# - upstream_model_loading — worker WorkResult unanimous# MODEL_LOADING (model still# warming up).- # - upstream_timeout_model_loading — gateway-synthesised 503 +- # MODEL_LOADING when the- # result-await timeout fires- # (typically while a worker- # cold-loads the target model- # on demand).+ # - upstream_timeout_model_loading — legacy gateway-synthesised+ # 503 + MODEL_LOADING timeout+ # reason from older releases.#- # All three are auto-retried by the SDK under the SDK's+ # These are auto-retried by the SDK under the SDK's# ``provision_timeout_s`` / ``max_oom_retries`` budgets — see# ``packages/sie_sdk/src/sie_sdk/client/_shared.py``. Operators# still see these events via the dedicated informational alerts@@ -111,7 +108,7 @@ groups:severity: warningannotations:summary: "SIE non-retryable error rate > 5%"- description: "{{ $value | humanizePercentage }} of requests are failing with non-retryable errors (excludes RESOURCE_EXHAUSTED, MODEL_LOADING, and upstream_lora_loading which the SDK auto-retries)."+ description: "{{ $value | humanizePercentage }} of requests are failing with non-retryable errors (excludes RESOURCE_EXHAUSTED, MODEL_LOADING, legacy upstream_timeout_model_loading, and upstream_lora_loading retry signals)."- alert: SIEHighLatencyexpr: histogram_quantile(0.95, sum by (le) (rate(sie_gateway_request_latency_seconds_bucket[5m]))) > 5diff --git a/deploy/helm/sie-cluster/files/dashboards/tracing.json b/deploy/helm/sie-cluster/files/dashboards/tracing.jsonnew file mode 100644index 000000000..f867b3a13--- /dev/null+++ b/deploy/helm/sie-cluster/files/dashboards/tracing.json@@ -0,0 +1,246 @@+{+ "annotations": {+ "list": []+ },+ "description": "SIE distributed tracing dashboard for gateway, sidecar, and worker spans.",+ "editable": true,+ "fiscalYearStartMonth": 0,+ "graphTooltip": 1,+ "id": null,+ "links": [],+ "panels": [+ {+ "collapsed": false,+ "gridPos": { "h": 1, "w": 24, "x": 0, "y": 0 },+ "id": 100,+ "title": "RED Context",+ "type": "row"+ },+ {+ "fieldConfig": {+ "defaults": { "unit": "s" },+ "overrides": []+ },+ "gridPos": { "h": 7, "w": 8, "x": 0, "y": 1 },+ "id": 1,+ "options": {+ "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true },+ "tooltip": { "mode": "multi", "sort": "none" }+ },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "expr": "histogram_quantile(0.95, sum by (le, endpoint) (rate(sie_gateway_request_latency_seconds_bucket{namespace=~\"$namespace\"}[5m])))",+ "legendFormat": "{{endpoint}}",+ "refId": "A"+ }+ ],+ "title": "Gateway Request p95 by Endpoint",+ "type": "timeseries"+ },+ {+ "fieldConfig": {+ "defaults": { "unit": "s" },+ "overrides": []+ },+ "gridPos": { "h": 7, "w": 8, "x": 8, "y": 1 },+ "id": 2,+ "options": {+ "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true },+ "tooltip": { "mode": "multi", "sort": "none" }+ },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "expr": "histogram_quantile(0.95, sum by (le, operation) (rate(sie_gateway_queue_publish_seconds_bucket{namespace=~\"$namespace\"}[5m])))",+ "legendFormat": "publish {{operation}}",+ "refId": "A"+ },+ {+ "expr": "histogram_quantile(0.95, sum by (le, operation) (rate(sie_gateway_queue_result_wait_seconds_bucket{namespace=~\"$namespace\"}[5m])))",+ "legendFormat": "result wait {{operation}}",+ "refId": "B"+ }+ ],+ "title": "Queue Publish and Result-Wait p95",+ "type": "timeseries"+ },+ {+ "fieldConfig": {+ "defaults": { "unit": "s" },+ "overrides": []+ },+ "gridPos": { "h": 7, "w": 8, "x": 16, "y": 1 },+ "id": 3,+ "options": {+ "legend": { "calcs": [], "displayMode": "list", "placement": "bottom", "showLegend": true },+ "tooltip": { "mode": "multi", "sort": "none" }+ },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "expr": "histogram_quantile(0.95, sum by (le) (rate(sie_gateway_generation_ttft_seconds_bucket{namespace=~\"$namespace\"}[5m])))",+ "legendFormat": "gateway p95",+ "refId": "A"+ },+ {+ "expr": "histogram_quantile(0.95, sum by (le) (rate(sie_worker_generation_ttft_seconds_bucket{namespace=~\"$namespace\"}[5m])))",+ "legendFormat": "worker p95",+ "refId": "B"+ }+ ],+ "title": "Gateway vs Worker TTFT p95",+ "type": "timeseries"+ },+ {+ "collapsed": false,+ "gridPos": { "h": 1, "w": 24, "x": 0, "y": 8 },+ "id": 101,+ "title": "Trace Search",+ "type": "row"+ },+ {+ "datasource": { "type": "tempo", "uid": "tempo" },+ "gridPos": { "h": 7, "w": 8, "x": 0, "y": 9 },+ "id": 4,+ "options": {+ "showHeader": true,+ "sortBy": [+ {+ "desc": true,+ "displayName": "Duration"+ }+ ]+ },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "datasource": { "type": "tempo", "uid": "tempo" },+ "limit": 20,+ "query": "{duration > 1s}",+ "queryType": "traceql",+ "refId": "A",+ "tableType": "traces"+ }+ ],+ "title": "Recent Slow Traces",+ "type": "table"+ },+ {+ "datasource": { "type": "tempo", "uid": "tempo" },+ "gridPos": { "h": 7, "w": 8, "x": 8, "y": 9 },+ "id": 5,+ "options": { "showHeader": true },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "datasource": { "type": "tempo", "uid": "tempo" },+ "limit": 20,+ "query": "{status = error}",+ "queryType": "traceql",+ "refId": "A",+ "tableType": "traces"+ }+ ],+ "title": "Recent Error Traces",+ "type": "table"+ },+ {+ "datasource": { "type": "tempo", "uid": "tempo" },+ "gridPos": { "h": 7, "w": 8, "x": 16, "y": 9 },+ "id": 6,+ "options": { "showHeader": true },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "datasource": { "type": "tempo", "uid": "tempo" },+ "limit": 20,+ "query": "{name = \"gateway.publish\"}",+ "queryType": "traceql",+ "refId": "A",+ "tableType": "traces"+ }+ ],+ "title": "gateway.publish Traces",+ "type": "table"+ },+ {+ "datasource": { "type": "tempo", "uid": "tempo" },+ "gridPos": { "h": 7, "w": 8, "x": 0, "y": 16 },+ "id": 7,+ "options": { "showHeader": true },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "datasource": { "type": "tempo", "uid": "tempo" },+ "limit": 20,+ "query": "{name = \"sidecar.dispatch\"}",+ "queryType": "traceql",+ "refId": "A",+ "tableType": "traces"+ }+ ],+ "title": "sidecar.dispatch Traces",+ "type": "table"+ },+ {+ "datasource": { "type": "tempo", "uid": "tempo" },+ "gridPos": { "h": 7, "w": 8, "x": 8, "y": 16 },+ "id": 8,+ "options": { "showHeader": true },+ "pluginVersion": "10.0.0",+ "targets": [+ {+ "datasource": { "type": "tempo", "uid": "tempo" },+ "limit": 20,+ "query": "{name = \"gateway.proxy_generate\"}",+ "queryType": "traceql",+ "refId": "A",+ "tableType": "traces"+ }+ ],+ "title": "gateway.proxy_generate Traces",+ "type": "table"+ },+ {+ "gridPos": { "h": 7, "w": 8, "x": 16, "y": 16 },+ "id": 9,+ "options": {+ "content": "Tracing samples 5% of new roots by default and honors inbound parent decisions. Enable span export with observability.tracing.enabled. Tempo panels require a Tempo datasource with uid: tempo; the chart auto-provisions it only when observability.tracing.tempo.install and kube-prometheus-stack.install are both true.",+ "mode": "markdown"+ },+ "pluginVersion": "10.0.0",+ "title": "Tracing Notes",+ "type": "text"+ }+ ],+ "refresh": "10s",+ "schemaVersion": 38,+ "tags": ["sie", "tracing"],+ "templating": {+ "list": [+ {+ "current": { "selected": false, "text": "sie", "value": "sie" },+ "hide": 0,+ "includeAll": false,+ "label": "Namespace",+ "multi": false,+ "name": "namespace",+ "options": [],+ "query": "label_values(up, namespace)",+ "refresh": 2,+ "regex": "",+ "skipUrlSync": false,+ "sort": 0,+ "type": "query"+ }+ ]+ },+ "time": { "from": "now-1h", "to": "now" },+ "timepicker": {},+ "timezone": "",+ "title": "SIE Tracing",+ "uid": "sie-tracing",+ "version": 1,+ "weekStart": ""+}diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex 73c14ab01..3f11a5ec7 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -525,6 +525,52 @@ app.kubernetes.io/component: mcp-edge{{- printf "%s:%s" .Values.mcpEdge.image.repository $tag }}{{- end }}+{{/*+Rust Candle worker image tag.++Args (dict): root, poolName, pool, machineProfile.+Returns the tag only. The caller prepends workers.common.rust.image.repository.+*/}}+{{- define "sie-cluster.rustWorker.imageTag" -}}+{{- $root := .root -}}+{{- $poolName := .poolName -}}+{{- $pool := .pool -}}+{{- $machineProfile := .machineProfile -}}+{{- $rustImage := $root.Values.workers.common.rust.image -}}+{{- $fullTag := default "" $rustImage.fullTag -}}+{{- if $fullTag -}}+{{- $fullTag -}}+{{- else -}}+{{- $tagBase := default $root.Chart.AppVersion $rustImage.tag -}}+{{- $gpu := default dict $pool.gpu -}}+{{- $gpuCount := int (default 0 $gpu.count) -}}+{{- if eq $gpuCount 0 -}}+{{- $tagBase -}}+{{- else -}}+{{- $cudaPlatform := default "cuda12" $rustImage.cudaPlatform -}}+{{- $computeCap := default "" $rustImage.computeCapability -}}+{{- $capByProfile := default dict $rustImage.computeCapabilityByMachineProfile -}}+{{- if hasKey $capByProfile $machineProfile -}}+{{- $computeCap = printf "%v" (index $capByProfile $machineProfile) -}}+{{- end -}}+{{- if and $pool.gpuType (hasKey $capByProfile $pool.gpuType) -}}+{{- $computeCap = printf "%v" (index $capByProfile $pool.gpuType) -}}+{{- end -}}+{{- if hasKey $capByProfile $poolName -}}+{{- $computeCap = printf "%v" (index $capByProfile $poolName) -}}+{{- end -}}+{{- $poolCandle := default dict $pool.candle -}}+{{- if $poolCandle.cudaComputeCap -}}+{{- $computeCap = printf "%v" $poolCandle.cudaComputeCap -}}+{{- end -}}+{{- if not $computeCap -}}+{{- fail (printf "workers.pools.%s.engine=candle needs a Rust CUDA compute capability. Set workers.common.rust.image.computeCapabilityByMachineProfile[%q], workers.common.rust.image.computeCapability, or workers.pools.%s.candle.cudaComputeCap." $poolName $machineProfile $poolName) -}}+{{- end -}}+{{- printf "%s-%s-sm%s" $tagBase $cudaPlatform $computeCap -}}+{{- end -}}+{{- end -}}+{{- end }}+{{/*In-cluster URL the edge uses to reach the gateway (SIE_BASE_URL). Overridablevia mcpEdge.clusterBaseUrl; otherwise the in-namespace gateway Service.@@ -537,6 +583,77 @@ via mcpEdge.clusterBaseUrl; otherwise the in-namespace gateway Service.{{- end -}}{{- end }}+{{/*+Tracing: effective OTLP endpoint.++When the bundled collector is enabled and no explicit endpoint is set, the+endpoint defaults to the bundled collector's in-cluster gRPC address. Otherwise,+bundled Tempo is used when installed. The explicit+.Values.observability.tracing.endpoint always wins (may be empty).++Caller context: root (.) — the full Helm root context.+*/}}+{{- define "sie-cluster.tracing.endpoint" -}}+{{- if .Values.observability.tracing.endpoint -}}+{{- .Values.observability.tracing.endpoint -}}+{{- else if .Values.observability.tracing.collector.install -}}+{{- printf "http://%s-otel-collector:4317" (include "sie-cluster.fullname" .) -}}+{{- else if .Values.observability.tracing.tempo.install -}}+{{- "http://tempo:4317" -}}+{{- else -}}+{{- "" -}}+{{- end -}}+{{- end }}++{{/*+Tracing: effective bundled collector downstream OTLP endpoint.++The collector forwards to an explicit collector exporterEndpoint when set. If+bundled Tempo is installed and no downstream endpoint is configured, the+collector forwards to Tempo. Otherwise it returns empty so the collector debug+exporter is used.++Caller context: root (.) — the full Helm root context.+*/}}+{{- define "sie-cluster.tracing.collectorExporterEndpoint" -}}+{{- if .Values.observability.tracing.collector.exporterEndpoint -}}+{{- .Values.observability.tracing.collector.exporterEndpoint -}}+{{- else if .Values.observability.tracing.tempo.install -}}+{{- "http://tempo:4317" -}}+{{- else -}}+{{- "" -}}+{{- end -}}+{{- end }}++{{/*+Tracing: OTLP exporter env block.++Emits the five OTEL/SIE env vars required to activate distributed tracing on a+container. Fails fast when tracing is enabled but no endpoint is resolvable.++Args (dict): root — full Helm root context; serviceName — OTEL_SERVICE_NAME value.++Rendered lines are indented by the call site (use nindent in the include call).+*/}}+{{- define "sie-cluster.tracing.env" -}}+{{- $endpoint := include "sie-cluster.tracing.endpoint" .root -}}+{{- if not $endpoint -}}+{{- fail "observability.tracing.enabled=true requires observability.tracing.endpoint, observability.tracing.collector.install=true, or observability.tracing.tempo.install=true" -}}+{{- end -}}+- name: SIE_TRACING_ENABLED+ value: "true"+- name: OTEL_EXPORTER_OTLP_ENDPOINT+ value: {{ $endpoint | quote }}+- name: OTEL_EXPORTER_OTLP_PROTOCOL+ value: "grpc"+- name: OTEL_SERVICE_NAME+ value: {{ .serviceName | quote }}+- name: OTEL_TRACES_SAMPLER+ value: {{ .root.Values.observability.tracing.sampler | quote }}+- name: OTEL_TRACES_SAMPLER_ARG+ value: {{ .root.Values.observability.tracing.samplerArg | quote }}+{{- end }}+{{/*Name of the Secret holding the connector secrets. Uses an existing Secret whenmcpEdge.existingSecretName is set; otherwise the chart-managed one.diff --git a/deploy/helm/sie-cluster/templates/dashboard-configmaps.yaml b/deploy/helm/sie-cluster/templates/dashboard-configmaps.yamlindex 3ebb18d3f..d777d4899 100644--- a/deploy/helm/sie-cluster/templates/dashboard-configmaps.yaml+++ b/deploy/helm/sie-cluster/templates/dashboard-configmaps.yaml@@ -95,4 +95,20 @@ metadata:data:sie-perf-tuning.json: |-{{ .Files.Get "files/dashboards/perf-tuning.json" | indent 4 }}++---+apiVersion: v1+kind: ConfigMap+metadata:+ name: {{ include "sie-cluster.fullname" . }}-dashboard-tracing+ 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-tracing.json: |-+{{ .Files.Get "files/dashboards/tracing.json" | indent 4 }}{{- end }}diff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex d75d74319..51f80295a 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -19,8 +19,9 @@{{- /* Validate: `clusterRouting` is queue-only today. The Rust gateway hasno direct-mode code path; "direct" belongs to Python-gateway deploymentsand 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.+ get queue behavior). Queue workers rely on the worker-sidecar as the+ NATS consumer; Python exposes IPC, health, and readiness for that sidecar+ (see packages/sie_server/src/sie_server/app/app_factory.py).Queue mode requires NATS+JetStream; large-payload offload additionallyrequires a shared object-store payload store. */}}{{- $routing := default "queue" .Values.clusterRouting }}@@ -271,6 +272,9 @@ spec:- name: SIE_GATEWAY_POLLING_WATCHERvalue: "true"{{- end }}+ {{- if .Values.observability.tracing.enabled }}+ {{- include "sie-cluster.tracing.env" (dict "root" . "serviceName" .Values.observability.tracing.serviceName.gateway) | nindent 12 }}+ {{- end }}{{- with .Values.gateway.extraEnv }}# Operator-supplied env passthrough (parity with workers.common.extraEnv).{{- toYaml . | nindent 12 }}diff --git a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml b/deploy/helm/sie-cluster/templates/keda-scaledobject.yamlindex a1ef84f47..fa320e5eb 100644--- a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml+++ b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml@@ -188,17 +188,13 @@ data:# - upstream_model_loading: worker is cold-loading the# target model on demand (explicit MODEL_LOADING result).# The SDK retries under `provision_timeout_s`.- # - upstream_timeout_model_loading: gateway-synthesised- # MODEL_LOADING when the result-await timeout fires (most- # commonly during the same cold-load case as above, but- # observed via the timeout instead of an explicit result).- # SDK retries with the same budget.+ # - upstream_timeout_model_loading: legacy gateway-synthesised+ # MODEL_LOADING timeout reason from older releases.# - upstream_lora_loading: worker is loading a LoRA adapter# on demand. SDK retries with LORA_LOADING budget.# Genuine "the gateway is dropping requests because the pool- # is undersized" signals (timeout/capacity/no_workers other- # than the cold-load timeout) still drive scale-up via this- # trigger.+ # is undersized" signals (timeout/capacity/no_workers) still+ # drive scale-up via this trigger.## Note on regex anchoring: PromQL ``=~`` / ``!~`` are RE2 with# implicit full-string anchors. The list below matchesdiff --git a/deploy/helm/sie-cluster/templates/otel-collector.yaml b/deploy/helm/sie-cluster/templates/otel-collector.yamlnew file mode 100644index 000000000..e34167d7c--- /dev/null+++ b/deploy/helm/sie-cluster/templates/otel-collector.yaml@@ -0,0 +1,101 @@+{{- /* An explicit tracing.endpoint points pods at an external backend, so the bundled collector is suppressed to avoid an orphaned Deployment/Service/ConfigMap. */ -}}+{{- if and .Values.observability.tracing.enabled .Values.observability.tracing.collector.install (not .Values.observability.tracing.endpoint) }}+{{- $fullname := include "sie-cluster.fullname" . }}+{{- $exp := include "sie-cluster.tracing.collectorExporterEndpoint" . }}+---+apiVersion: v1+kind: ConfigMap+metadata:+ name: {{ $fullname }}-otel-collector+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.labels" . | nindent 4 }}+ app.kubernetes.io/component: otel-collector+data:+ collector.yaml: |+ receivers:+ otlp:+ protocols:+ grpc:+ endpoint: "0.0.0.0:4317"++ exporters:+ {{- if $exp }}+ otlp:+ endpoint: {{ $exp | quote }}+ tls:+ insecure: {{ .Values.observability.tracing.collector.exporterInsecure }}+ {{- else }}+ debug:+ verbosity: detailed+ {{- end }}++ service:+ pipelines:+ traces:+ receivers: [otlp]+ {{- if $exp }}+ exporters: [otlp]+ {{- else }}+ exporters: [debug]+ {{- end }}+---+apiVersion: apps/v1+kind: Deployment+metadata:+ name: {{ $fullname }}-otel-collector+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.labels" . | nindent 4 }}+ app.kubernetes.io/component: otel-collector+spec:+ replicas: 1+ selector:+ matchLabels:+ {{- include "sie-cluster.selectorLabels" . | nindent 6 }}+ app.kubernetes.io/component: otel-collector+ template:+ metadata:+ labels:+ {{- include "sie-cluster.labels" . | nindent 8 }}+ app.kubernetes.io/component: otel-collector+ spec:+ containers:+ - name: otel-collector+ image: "{{ .Values.observability.tracing.collector.image.repository }}:{{ .Values.observability.tracing.collector.image.tag }}"+ args:+ - "--config=/etc/otel/collector.yaml"+ ports:+ - name: otlp-grpc+ containerPort: 4317+ protocol: TCP+ volumeMounts:+ - name: config+ mountPath: /etc/otel+ {{- with .Values.observability.tracing.collector.resources }}+ resources:+ {{- toYaml . | nindent 12 }}+ {{- end }}+ volumes:+ - name: config+ configMap:+ name: {{ $fullname }}-otel-collector+---+apiVersion: v1+kind: Service+metadata:+ name: {{ $fullname }}-otel-collector+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.labels" . | nindent 4 }}+ app.kubernetes.io/component: otel-collector+spec:+ selector:+ {{- include "sie-cluster.selectorLabels" . | nindent 4 }}+ app.kubernetes.io/component: otel-collector+ ports:+ - name: otlp-grpc+ port: 4317+ targetPort: 4317+ protocol: TCP+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/tempo-datasource-configmap.yaml b/deploy/helm/sie-cluster/templates/tempo-datasource-configmap.yamlnew file mode 100644index 000000000..e8ee1f6b6--- /dev/null+++ b/deploy/helm/sie-cluster/templates/tempo-datasource-configmap.yaml@@ -0,0 +1,21 @@+{{- if and .Values.observability.tracing.tempo.install (index .Values "kube-prometheus-stack" "install") }}+---+apiVersion: v1+kind: ConfigMap+metadata:+ name: {{ include "sie-cluster.fullname" . }}-datasource-tempo+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.labels" . | nindent 4 }}+ app.kubernetes.io/component: datasource+data:+ tempo-datasource.yaml: |-+ apiVersion: 1+ datasources:+ - name: Tempo+ uid: tempo+ type: tempo+ access: proxy+ url: http://tempo:3200+ isDefault: false+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml b/deploy/helm/sie-cluster/templates/worker-image-prepull.yamlindex 9163c8fff..f9e30c0d5 100644--- a/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml+++ b/deploy/helm/sie-cluster/templates/worker-image-prepull.yaml@@ -3,6 +3,7 @@{{- range $poolName, $pool := .Values.workers.pools }}{{- if $pool.enabled }}{{- $platform := default $root.Values.workers.common.platform $pool.platform }}+{{- $machineProfile := default $poolName $pool.machineProfile }}{{- $rs := $root.Values.workers.common.workerSidecar }}{{- $rsTag := default $root.Chart.AppVersion $rs.image.tag }}{{- $rsImage := printf "%s:%s" $rs.image.repository $rsTag }}@@ -20,6 +21,11 @@{{- end }}{{- $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 }}+{{- $engine := default (default $root.Values.workers.common.engine $pool.engine) $bundleCfg.engine }}+{{- if not (or (eq $engine "pytorch") (eq $engine "candle")) }}+{{- fail (printf "workers.pools.%s.bundles.%s.engine must be one of: pytorch, candle" $poolName $bundleName) }}+{{- end }}+{{- $rust := $root.Values.workers.common.rust }}---apiVersion: apps/v1kind: DaemonSet@@ -51,9 +57,17 @@ spec:terminationGracePeriodSeconds: 0initContainers:- name: pull-worker-image+ {{- if eq $engine "candle" }}+ {{- $rustTag := include "sie-cluster.rustWorker.imageTag" (dict "root" $root "poolName" $poolName "pool" $pool "machineProfile" $machineProfile) }}+ {{- $rustImage := printf "%s:%s" $rust.image.repository $rustTag }}+ image: {{ $rustImage }}+ imagePullPolicy: {{ $rust.image.pullPolicy }}+ command: ["/sie-server-rust", "--version"]+ {{- else }}image: {{ $workerImage }}imagePullPolicy: {{ $root.Values.workers.common.image.pullPolicy }}command: ["true"]+ {{- end }}resources:requests:cpu: "1m"diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex d1e0f6f52..a5efd044b 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -1,14 +1,14 @@{{- $root := . -}}{{/*Safety guard: the worker-sidecar container is the production data path (NATS ->-Rust -> UDS IPC -> Python adapter process). The sidecar needs+Rust sidecar -> UDS IPC -> colocated adapter process). The sidecar needs``SIE_NATS_URL`` and refuses to start without one, so enabling thesidecar without NATS produces a pod that CrashLoops forever. Failfast 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)" }}+{{- fail "clusterRouting=queue requires workers.common.workerSidecar.enabled=true (adapter processes do not consume JetStream directly)" }}{{- 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)" }}@@ -38,6 +38,7 @@ fast at render time.{{- $platform := default $root.Values.workers.common.platform $pool.platform }}{{- $machineProfile := default $poolName $pool.machineProfile }}{{- $queuePool := default (default "default" $root.Values.workers.common.queuePool) $pool.queuePool | lower }}+{{- $payloadStoreUrl := include "sie-cluster.payloadStoreUrl" $root }}{{- range $bundleName, $bundleCfg := $pool.bundles }}{{- if dig "enabled" true $bundleCfg }}{{- if not (hasKey $bundleCfg "minReplicas") }}@@ -71,6 +72,27 @@ fast at render time.{{- if and $requiredPlatform (ne $requiredPlatform $platform) }}{{- fail (printf "workers.pools.%s.bundles.%s: image bundle %q is built only for platform %q, but this pool resolves to %q. The release pipeline publishes %s-%s (not %s-%s), so the worker image would ImagePullBackOff. Set this pool's `platform: %s`." $poolName $bundleName $imageBundle $requiredPlatform $platform $requiredPlatform $imageBundle $platform $imageBundle $requiredPlatform) }}{{- end }}+{{- $engine := default (default $root.Values.workers.common.engine $pool.engine) $bundleCfg.engine }}+{{- if not (or (eq $engine "pytorch") (eq $engine "candle")) }}+{{- fail (printf "workers.pools.%s.bundles.%s.engine must be one of: pytorch, candle" $poolName $bundleName) }}+{{- end }}+{{- if and (eq $engine "candle") (ne $bundle "candle") }}+{{- fail (printf "workers.pools.%s.bundles.%s.engine=candle requires bundle=candle so gateway routing and worker heartbeats agree" $poolName $bundleName) }}+{{- end }}+{{- $poolCandle := default dict $pool.candle }}+{{- $candleModelIds := list }}+{{- if $poolCandle.modelIds }}+{{- if kindIs "slice" $poolCandle.modelIds }}+{{- $candleModelIds = $poolCandle.modelIds }}+{{- else }}+{{- $candleModelIds = list $poolCandle.modelIds }}+{{- end }}+{{- else if $poolCandle.modelId }}+{{- $candleModelIds = list $poolCandle.modelId }}+{{- end }}+{{- if and (eq $engine "candle") (eq (len $candleModelIds) 0) }}+{{- fail (printf "workers.pools.%s.bundles.%s.engine=candle requires workers.pools.%s.candle.modelId or candle.modelIds" $poolName $bundleName $poolName) }}+{{- end }}---apiVersion: apps/v1kind: StatefulSet@@ -82,6 +104,7 @@ metadata:sie.superlinked.com/gpu-type: {{ $pool.gpuType | quote }}sie.superlinked.com/machine-profile: {{ $machineProfile | quote }}sie.superlinked.com/bundle: {{ $bundle | quote }}+ sie.superlinked.com/engine: {{ $engine | quote }}sie.superlinked.com/pool: {{ $poolName | quote }}spec:serviceName: {{ include "sie-cluster.worker.serviceName" $root }}@@ -104,6 +127,7 @@ spec:sie.superlinked.com/gpu-type: {{ $pool.gpuType | quote }}sie.superlinked.com/machine-profile: {{ $machineProfile | quote }}sie.superlinked.com/bundle: {{ $bundle | quote }}+ sie.superlinked.com/engine: {{ $engine | quote }}sie.superlinked.com/pool: {{ $poolName | quote }}annotations:# Prometheus scraping@@ -127,6 +151,15 @@ spec:containers:- name: worker{{- $imageTag := default $root.Chart.AppVersion $root.Values.workers.common.image.tag }}+ {{- $rust := $root.Values.workers.common.rust }}+ {{- if eq $engine "candle" }}+ {{- $rustTag := include "sie-cluster.rustWorker.imageTag" (dict "root" $root "poolName" $poolName "pool" $pool "machineProfile" $machineProfile) }}+ image: {{ printf "%s:%s" $rust.image.repository $rustTag }}+ imagePullPolicy: {{ $rust.image.pullPolicy }}+ args:+ - --host=0.0.0.0+ - --port={{ $root.Values.workers.common.port }}+ {{- else }}image: {{ printf "%s:%s-%s-%s" $root.Values.workers.common.image.repository $imageTag $platform $imageBundle }}imagePullPolicy: {{ $root.Values.workers.common.image.pullPolicy }}args:@@ -137,6 +170,7 @@ spec:{{- if $root.Values.workers.common.clusterCache.enabled }}- --cluster-cache=$(SIE_CLUSTER_CACHE){{- end }}+ {{- end }}ports:- name: httpcontainerPort: {{ $root.Values.workers.common.port }}@@ -151,13 +185,33 @@ spec:# Bundle for multi-bundle routing- name: SIE_BUNDLEvalue: {{ $bundle | quote }}- # Shared cold-load timeout used by Python SGLang health waits.+ # Shared cold-load timeout used by worker health waits.- name: SIE_MODEL_READY_TIMEOUT_Svalue: {{ $modelReadyTimeoutS | quote }}# Lets engine-backed adapters reject startup budgets kubelet would# kill before completion.- name: SIE_WORKER_LIVENESS_BUDGET_Svalue: {{ $workerLivenessBudgetS | quote }}+ {{- if eq $engine "candle" }}+ - name: SIE_WORKER_ID+ valueFrom:+ fieldRef:+ fieldPath: metadata.name+ - name: SIE_ENGINE+ value: "candle"+ - name: SIE_CANDLE_MODELS+ value: {{ join "," $candleModelIds | quote }}+ {{- if $poolCandle.profile }}+ - name: SIE_CANDLE_PROFILE+ value: {{ $poolCandle.profile | quote }}+ {{- end }}+ - name: SIE_CANDLE_BATCH_BUDGET+ value: {{ $root.Values.workers.common.rust.candle.batchBudget | default 64 | quote }}+ - name: SIE_CANDLE_MAX_CONCURRENT_FORWARDS+ value: {{ $root.Values.workers.common.rust.candle.maxConcurrentForwards | default 1 | quote }}+ - name: SIE_CANDLE_NORMALIZE+ value: {{ $root.Values.workers.common.rust.candle.normalize | default true | quote }}+ {{- end }}# Device configuration (cpu if no GPU, cuda otherwise)- name: SIE_DEVICEvalue: {{ if gt (int $pool.gpu.count) 0 }}cuda{{ else }}cpu{{ end }}@@ -189,26 +243,14 @@ spec:- name: SIE_CLUSTER_CACHEvalue: {{ $root.Values.workers.common.clusterCache.url | quote }}{{- end }}- {{- 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 }}- name: SIE_POOLvalue: {{ $queuePool | quote }}{{- with $root.Values.queueRouting }}+ # Used by Python's IPC outcome path for retryable backend+ # failures. The sidecar owns fetch budget, delivery budget,+ # stream retention, and payload-store reads.- name: SIE_NAK_DELAY_Svalue: {{ .nakDelaySec | default 5 | quote }}- - name: SIE_MAX_DELIVER- value: {{ .maxDeliver | default 20 | quote }}- - name: SIE_STREAM_MAX_AGE_S- value: {{ .streamMaxAgeSec | default 1800 | quote }}- - name: SIE_NATS_FETCH_BUDGET- value: {{ .natsFetchBudget | default 64 | quote }}- {{- end }}- {{- $payloadStoreUrl := include "sie-cluster.payloadStoreUrl" $root }}- {{- if $payloadStoreUrl }}- - name: SIE_PAYLOAD_STORE_URL- value: {{ $payloadStoreUrl | quote }}{{- end }}# Telemetry{{- if and $root.Values.telemetry (hasKey $root.Values.telemetry "enabled") (not $root.Values.telemetry.enabled) }}@@ -224,21 +266,19 @@ spec:- name: SIE_DEPLOYMENT_ENVvalue: {{ 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+ # worker-sidecar owns the NATS loop; the adapter process+ # 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_PATHvalue: /var/run/sie/ipc.sock+ - name: SIE_TOKENIZER_STAGING_DIR+ value: /var/run/sie/tokenizers- name: SIE_IPC_REQUIRE_HEARTBEATvalue: "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 }}+ {{- if $root.Values.observability.tracing.enabled }}+ {{- include "sie-cluster.tracing.env" (dict "root" $root "serviceName" $root.Values.observability.tracing.serviceName.worker) | nindent 12 }}{{- end }}{{- with $root.Values.workers.common.extraEnv }}{{- toYaml . | nindent 12 }}@@ -295,11 +335,12 @@ spec:{{- 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.+ # the worker 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 }}+ {{- $candleBatcher := default dict $root.Values.workers.common.rust.candle.batcher }}image: {{ printf "%s:%s" $rs.image.repository $rsTag }}imagePullPolicy: {{ $rs.image.pullPolicy }}ports:@@ -311,6 +352,8 @@ spec:value: {{ $rs.metricsPort | quote }}- name: SIE_IPC_SOCKET_PATHvalue: /var/run/sie/ipc.sock+ - name: SIE_TOKENIZER_STAGING_DIR+ value: /var/run/sie/tokenizers- name: SIE_POOLvalue: {{ $queuePool | quote }}- name: SIE_BUNDLE@@ -347,7 +390,7 @@ spec:{{- 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.+ # /v1/configs/export through adapter IPC.- name: SIE_CONFIG_SERVICE_URLvalue: {{ include "sie-cluster.config.internalUrl" $root | quote }}{{- if $root.Values.config.auth.adminTokenSecretName }}@@ -403,7 +446,7 @@ spec:value: {{ $rs.maxConcurrentBatches | quote }}{{- end }}{{- if $rs.ipcPoolSize }}- # Size of the Rust-to-Python IPC connection pool. Should match+ # Size of the sidecar-to-adapter 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@@ -457,15 +500,25 @@ spec:value: {{ $rs.pipelineDepth | quote }}{{- end }}{{- if $rs.batcher }}- {{- if $rs.batcher.coalesceMs }}+ {{- if and $rs.batcher.coalesceMs (not (and (eq $engine "candle") $candleBatcher.coalesceMs)) }}- name: SIE_BATCHER_COALESCE_MSvalue: {{ $rs.batcher.coalesceMs | quote }}{{- end }}- {{- if $rs.batcher.maxBatchRequests }}+ {{- if and $rs.batcher.maxBatchRequests (not (and (eq $engine "candle") $candleBatcher.maxBatchRequests)) }}- name: SIE_BATCHER_MAX_BATCH_REQUESTSvalue: {{ $rs.batcher.maxBatchRequests | quote }}{{- end }}{{- end }}+ {{- if eq $engine "candle" }}+ {{- if $candleBatcher.coalesceMs }}+ - name: SIE_BATCHER_COALESCE_MS+ value: {{ $candleBatcher.coalesceMs | quote }}+ {{- end }}+ {{- if $candleBatcher.maxBatchRequests }}+ - name: SIE_BATCHER_MAX_BATCH_REQUESTS+ value: {{ $candleBatcher.maxBatchRequests | quote }}+ {{- end }}+ {{- end }}{{- if $rs.adaptive }}{{- if $rs.adaptive.minQuantumMs }}- name: SIE_ADAPTIVE_MIN_QUANTUM_MS@@ -480,12 +533,15 @@ spec:value: {{ $rs.adaptive.targetP50Ms | quote }}{{- end }}{{- end }}+ {{- if $root.Values.observability.tracing.enabled }}+ {{- include "sie-cluster.tracing.env" (dict "root" $root "serviceName" $root.Values.observability.tracing.serviceName.workerSidecar) | nindent 12 }}+ {{- 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+ # Off by default while the adapter container's existing# /healthz + /readyz on port 8080 remain the K8s contract.startupProbe:httpGet:@@ -547,7 +603,7 @@ spec:emptyDir:sizeLimit: {{ $root.Values.workers.common.cacheStorageSize }}{{- if $root.Values.workers.common.workerSidecar.enabled }}- # Shared Unix-socket directory between the Python adapter and+ # Shared Unix-socket directory between the worker adapter and# the worker-sidecar (in-Pod IPC, no network hop).- name: sie-ipcemptyDir:diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex ea710417d..64a363092 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -325,6 +325,61 @@ workers:tag: ""pullPolicy: IfNotPresent+ # -- Default worker execution engine. `pytorch` renders the Python+ # `sie-server` container. `candle` renders the Rust `sie-server-rust`+ # native Candle worker container.+ # Can be overridden per pool or per bundle lane.+ engine: pytorch++ rust:+ image:+ repository: ghcr.io/superlinked/sie-server-rust+ # -- Base image tag, without the CUDA target suffix. Leave empty to use+ # -- .Chart.AppVersion. For Candle pools, the template appends+ # -- `-<cudaPlatform>-sm<computeCapability>` automatically.+ tag: ""+ # -- Exact image tag override. Use only for ad-hoc/perf images whose+ # -- tag already includes the CUDA target suffix.+ fullTag: ""+ # -- CUDA platform segment used for the Rust Candle image suffix.+ cudaPlatform: cuda12+ # -- Fallback CUDA compute capability. Prefer the machine-profile map+ # -- below, or per-pool `candle.cudaComputeCap`, so heterogeneous GPU+ # -- fleets pull the correct compiled kernel image.+ computeCapability: ""+ # -- Default Rust Candle image target by resolved machine profile,+ # -- gpuType, or pool key. The current release publishes the L4 target+ # -- (`sie-server-rust:<version>-cuda12-sm89`) only. Add non-L4 entries+ # -- here or set per-pool `candle.cudaComputeCap` only when that SM image+ # -- is explicitly published.+ computeCapabilityByMachineProfile:+ l4: "89"+ l4-spot: "89"+ nvidia-l4: "89"+ pullPolicy: IfNotPresent+ resources:+ requests:+ cpu: "500m"+ memory: "512Mi"+ limits:+ cpu: "2"+ memory: "2Gi"+ candle:+ batchBudget: 64+ normalize: true+ # -- Maximum concurrent forward passes allowed inside one loaded+ # Candle model process. Default 1 preserves the conservative single+ # forward path; raise during GPU tuning to test whether Candle can+ # safely overlap same-model work without loading duplicate weights.+ maxConcurrentForwards: 1+ # -- Candle-native workers run the model directly from the+ # worker-sidecar IPC batch. Keep the default conservative for+ # BGE-M3: larger coalesce/batch limits can form ~16k-token+ # groups on L4 and hurt p99 without improving throughput.+ batcher:+ coalesceMs: 3+ maxBatchRequests: 12+# -- Platform variant for worker images (e.g. "cuda12", "cpu")platform: cuda12@@ -354,18 +409,6 @@ workers:# explicit empty override disables inherited preloading for that lane.preloadModels: []- # -- 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-# -- Physical NATS queue pool consumed by workers in queue-routing mode.# The default baseline queue pool is `default`, so SDK calls like# `gpu="l4"` route to `(pool=default, machineProfile=l4)` without@@ -486,15 +529,15 @@ workers:# -- 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+ # calls into the colocated adapter process 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+ # data path (NATS -> Rust sidecar -> UDS IPC -> adapter process).+ # Adapter processes do not pull from NATS on their own, so queue-mode worker pools# require this sidecar to provide a JetStream consumer.enabled: trueimage:@@ -513,7 +556,7 @@ workers:# -- 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+ # -- Size of the sidecar-to-adapter IPC connection pool. Each slot is an# independent Unix-domain socket; concurrent batches check out a# slot, perform their round-trip, and return it to the pool.# Should be >= maxConcurrentBatches so the IPC layer is never@@ -550,7 +593,7 @@ workers:# -- 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.+ # replaying /v1/configs/export through adapter IPC.configReconcile:enabled: true# -- Epoch poll cadence in milliseconds.@@ -560,7 +603,7 @@ workers:# after the startup export.fullExportIntervalMs: 300000# -- K8s probes on the worker-sidecar.- # Disabled by default while the Python container's existing+ # Disabled by default while the adapter container's existing# /healthz + /readyz remain the K8s contract.probes:enabled: false@@ -578,17 +621,19 @@ workers:timeoutSeconds: 3failureThreshold: 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.+ # the adapter process. The Rust sidecar binary defaults to 2;+ # making it explicit here 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.+ # batch executing while the next forms/ships over IPC. For Python+ # adapters, higher values mostly park frames behind the single+ # model-worker executor. Candle uses the same single-resident-model+ # contract and should be tuned by batch/coalesce depth first.# 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.+ # -- Rust scheduler batcher tuning for queue-mode workers. These+ # defaults keep sidecar-owned batch formation responsive while+ # leaving the Python adapter process to execute each IPC frame as+ # one forward pass.batcher:# -- Coalesce window ceiling in ms. Lower = more responsive# to inflow jitter and bounds tail latency when traffic is@@ -598,10 +643,10 @@ workers:# 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.+ # -- FetchExpiryController tuning (the Rust sidecar pull-loop+ # batch-coalesce quantum). The narrow 2/15/50 window keeps+ # queue-path coalescing bounded while still allowing short bursts+ # to batch.adaptive:# -- Quantum floor in ms (`SIE_ADAPTIVE_MIN_QUANTUM_MS`).minQuantumMs: 2@@ -642,6 +687,8 @@ workers:## Pool-level keys (shared across bundles on this hardware):# enabled: bool. Skip rendering the whole pool when false.+ # engine: Optional runtime engine default for bundle lanes in this+ # pool. `pytorch` (default) or `candle`.# gpu.count: int. 0 disables nvidia.com/gpu request on the pod.# gpu.product: string. nvidia.com/gpu.product node-label match.# gpuType: GPU/node label used for node selection and display.@@ -657,14 +704,30 @@ workers:# in this worker group. Overrides workers.common.preloadModels.# queuePool: string. Optional override of common.queuePool.# Defaults to `default` via workers.common.queuePool.- # resources: requests/limits for the Python ``worker``- # container (the GPU-bound forward-pass server).+ # resources: requests/limits for the GPU-bound ``worker``+ # container. For `engine: candle`, this is the Rust+ # native worker image instead of Python.# runtimeClassName: Optional override of common.runtimeClassName.+ # candle.modelId: Primary Hugging Face model id loaded by the Rust Candle+ # worker. Required when `engine: candle` unless+ # `candle.modelIds` is set.+ # candle.modelIds: Optional list, or comma-separated string, of Hugging+ # Face model ids loaded by the Rust worker. Defaults to+ # `[candle.modelId]`.+ # candle.profile: Optional catalog profile pinned to this Rust Candle+ # adapter process. Leave empty for default-only native+ # models; set to `candle` only for side-by-side profile+ # variants such as `model:candle`.+ # candle.cudaComputeCap:+ # Optional per-pool Rust Candle CUDA compute capability+ # override. If omitted, the chart resolves it from+ # workers.common.rust.image.computeCapabilityByMachineProfile.# tolerations: extra tolerations on top of the chart defaults.## bundles: map keyed by bundle name (matches a bundle in sie_config;# otherwise the sidecar refuses to start). Per-bundle keys:# enabled: bool, default true. Skip this bundle on this pool.+ # engine: Optional runtime engine override for this bundle lane.# imageBundle: string. Optional image-tag bundle suffix override.# Set only when the logical bundle reuses another# bundle's image (e.g. `sglang-embedding` -> `sglang`).@@ -678,6 +741,11 @@ workers:## Each queuePool/machineProfile/bundle lane renders one StatefulSet +# KEDA ScaledObject + PDB + image-prepull DaemonSet, named worker-{pool}-{bundle}.+ #+ # NOTE: `engine: candle` serves an explicit native model allowlist via+ # `candle.modelId` or `candle.modelIds`. Multiple model ids can share a+ # pool when GPU memory and startup budget allow it; use additional pools+ # for different GPU shapes, batch settings, or profile pinning.pools:# L4 GPU@@ -1482,6 +1550,90 @@ observability:# -- Install bundled Alloy. Can be enabled alone when forwarding to an# external Loki endpoint via alloy.logs.lokiUrl.install: false+ tracing:+ # -- Master switch for distributed tracing. OFF by default; when false the+ # rendered chart is a byte-for-byte no-op (no env, no collector). Set true to+ # inject the OTLP exporter env on the gateway and worker pods with one flag.+ enabled: false+ # -- OTLP gRPC endpoint (e.g. http://tempo:4317) that the gateway and workers+ # export spans to. Point at your own Tempo/Jaeger/OTel-Collector. Leave empty+ # and set collector.install=true or tempo.install=true to use a bundled target below.+ endpoint: ""+ # -- Head-based sampler. parentbased_traceidratio honors an inbound sampling+ # decision from a propagated traceparent and samples new roots at samplerArg.+ # The SDK default is 1.0 (100%), so the low ratio is set explicitly here.+ sampler: parentbased_traceidratio+ samplerArg: "0.05"+ # -- Per-component OTEL_SERVICE_NAME shown in the trace backend. Defaults match+ # each binary's built-in default where one exists.+ serviceName:+ gateway: sie-gateway+ worker: sie-server+ workerSidecar: sie-worker-sidecar+ # -- Optional bundled OTLP collector (opt-in; mirrors the Loki/Alloy pattern).+ # Never installed by default. When install=true, a minimal OTel Collector+ # Deployment+Service+ConfigMap is rendered and `endpoint` above defaults to it.+ collector:+ install: false+ image:+ repository: otel/opentelemetry-collector-contrib+ tag: "0.119.0" # pin a recent real released tag; operator-overridable+ # -- Downstream OTLP endpoint the bundled collector forwards spans to+ # (e.g. Tempo/Jaeger). Leave empty to debug-log spans in the collector pod+ # logs (handy for first-run verification).+ exporterEndpoint: ""+ # -- Disable TLS on the downstream OTLP exporter. Defaults to true for+ # plaintext in-cluster backends; set false when exporterEndpoint targets a+ # TLS-enabled collector (e.g. a managed Tempo/Jaeger over https).+ exporterInsecure: true+ resources: {}+ tempo:+ # -- Install bundled Tempo as an in-cluster trace backend. Off by default.+ # When enabled without an explicit endpoint or bundled collector, traced+ # pods export OTLP gRPC spans to http://tempo:4317.+ install: false++# -- Tempo trace backend (Tier 2 - optional)+# Installed when observability.tracing.tempo.install=true.+tempo:+ # -- Force a predictable service name so OTLP exporters/Grafana can use+ # static URLs regardless of the Helm release name.+ fullnameOverride: tempo+ tempo:+ resources:+ requests:+ cpu: "100m"+ memory: "256Mi"+ limits:+ cpu: "500m"+ memory: "1Gi"+ server:+ http_listen_port: 3200+ receivers:+ # grafana-community/tempo _ports.tpl reads these receiver keys without+ # nil guards and only emits Service ports for non-empty endpoints. Keep+ # unused receiver keys with empty endpoints to render safely and suppress+ # ports; omitting/nulling them can break rendering or restore chart+ # 0.0.0.0 defaults via Helm deep-merge.+ otlp:+ protocols:+ grpc:+ endpoint: "0.0.0.0:4317"+ http:+ endpoint: ""+ jaeger:+ protocols:+ grpc:+ endpoint: ""+ thrift_binary:+ endpoint: ""+ thrift_compact:+ endpoint: ""+ thrift_http:+ endpoint: ""+ persistence:+ enabled: true+ size: "10Gi"# -- Loki log aggregation (Tier 2 - optional)# Installed when observability.logs.install=true or observability.logs.loki.install=true.diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex b0256ed71..53a62086f 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.6.14"+version = "0.6.15"description = "SIE integration for ChromaDB"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.tomlindex e3f7d7025..166911be6 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.6.14"+version = "0.6.15"description = "SIE integration for CrewAI"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.tomlindex a50f991ba..17763f993 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.6.14"+version = "0.6.15"description = "SIE integration for DSPy"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.tomlindex 0a9ddc281..69b515d0e 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.6.14"+version = "0.6.15"description = "SIE integration for Haystack"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.tomlindex a9b34fa2f..2806b52e8 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.6.14"+version = "0.6.15"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 70721df80..26a15d835 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.6.14"+version = "0.6.15"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex 0dd5a809b..b2c46061a 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.6.14"+version = "0.6.15"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 03beaae2a..36b0563e7 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.6.14"+version = "0.6.15"description = "SIE integration for Qdrant"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.jsonindex c383b9ae7..500a5921a 100644--- a/integrations/sie_ts_chroma/package.json+++ b/integrations/sie_ts_chroma/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-chroma",- "version": "0.6.14",+ "version": "0.6.15","description": "SIE embedding function for ChromaDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.jsonindex 029f450d9..b18b28713 100644--- a/integrations/sie_ts_lancedb/package.json+++ b/integrations/sie_ts_lancedb/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-lancedb",- "version": "0.6.14",+ "version": "0.6.15","description": "SIE embedding function and reranker for LanceDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.jsonindex e2df9265d..ea830fae6 100644--- a/integrations/sie_ts_langchain/package.json+++ b/integrations/sie_ts_langchain/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-langchain",- "version": "0.6.14",+ "version": "0.6.15","description": "SIE embeddings integration for LangChain.js","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.jsonindex ad4d230d5..a78ef42f8 100644--- a/integrations/sie_ts_llamaindex/package.json+++ b/integrations/sie_ts_llamaindex/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-llamaindex",- "version": "0.6.14",+ "version": "0.6.15","description": "SIE embeddings integration for LlamaIndex.TS","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.tomlindex 2006c852b..899578aa0 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.6.14"+version = "0.6.15"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_config/src/sie_config/config_api.py b/packages/sie_config/src/sie_config/config_api.pyindex e73609545..e08e3de9e 100644--- a/packages/sie_config/src/sie_config/config_api.py+++ b/packages/sie_config/src/sie_config/config_api.py@@ -56,7 +56,7 @@ class _IdempotencyState:completed response bytes — no loop-bound primitives in it — socarrying it forward is what lets `TestClient` (which spins up afresh `asyncio` loop per request) still observe prior results.- - `lock` and every `asyncio.Event` in `in_flight` are loop-bound+ - `lock` and every `_IdempotencyInFlight.event` are loop-boundand must be rebuilt any time the running loop changes. We dothis lazily in `_get_idempotency_state`: when the running loopdoesn't match `_loop`, we swap `lock` for a fresh one and drop@@ -69,7 +69,7 @@ class _IdempotencyState:def __init__(self) -> None:self.cache: OrderedDict[str, tuple[int, str, str]] = OrderedDict()self.lock = asyncio.Lock()- self.in_flight: dict[str, asyncio.Event] = {}+ self.in_flight: dict[str, _IdempotencyInFlight] = {}self._loop = asyncio.get_running_loop()def rebind_to_current_loop(self) -> None:@@ -91,6 +91,18 @@ class _IdempotencyState:self.in_flight.clear()+class _IdempotencyInFlight:+ """Loop-bound state for one in-flight idempotent write."""++ __slots__ = ("event", "exception", "payload_hash", "succeeded")++ def __init__(self, payload_hash: str) -> None:+ self.event = asyncio.Event()+ self.exception: BaseException | None = None+ self.payload_hash = payload_hash+ self.succeeded = False++# Per-app write lock is stored on `app.state._config_write_lock` and# lazily created on first use. We cannot use a module-level# `asyncio.Lock()` here because `asyncio.Lock` binds to the running@@ -313,7 +325,7 @@ def _require_model_registry(request: Request) -> ModelRegistry:@router.get("/models")async def list_models(request: Request) -> dict[str, Any]:- """List all registered model IDs with their profiles and source."""+ """List routable model/profile identities with their profiles and source."""_check_read_auth(request)model_registry = _require_model_registry(request)config_store: ConfigStore | None = getattr(request.app.state, "config_store", None)@@ -321,9 +333,10 @@ async def list_models(request: Request) -> dict[str, Any]:api_models = set(await asyncio.to_thread(config_store.list_models)) if config_store else set()models = []- for model_name in model_registry.list_models():- profile_names = sorted(model_registry.get_model_profile_names(model_name))- source = "api" if model_name in api_models else "filesystem"+ for model_name in model_registry.list_serving_models():+ profile_names = sorted(model_registry.get_route_profile_names(model_name))+ catalog_model_name = model_registry.get_catalog_model_name(model_name)+ source = "api" if catalog_model_name in api_models else "filesystem"models.append({"model_id": model_name,@@ -402,16 +415,41 @@ async def add_model(request: Request) -> Response:body_hash = hashlib.sha256(body).hexdigest()idem = _get_idempotency_state(request.app.state) if idempotency_key else Noneif idempotency_key and idem is not None:- # Track whether we already waited on an in-flight event. If we- # did, and the subsequent cache lookup misses (the original- # request's entry was LRU-evicted in the meantime), we must NOT- # re-execute the write — that would double-apply the config and- # bump the epoch twice. Return a synthesized 200 "already- # processed" response instead; the idempotency contract says- # "never execute twice for the same key", it says nothing about- # guaranteeing the original body is still replayable.- already_waited = False+ # Track the in-flight record we waited on. A cache miss after+ # waiting can mean either "successful response was evicted" or+ # "the owner failed/cancelled before caching"; only the former+ # may synthesize success.+ waited_in_flight: _IdempotencyInFlight | None = None+ owner_in_flight: _IdempotencyInFlight | None = Nonewhile True:+ if waited_in_flight is not None:+ if waited_in_flight.exception is not None:+ if isinstance(waited_in_flight.exception, asyncio.CancelledError):+ raise HTTPException(+ status_code=503,+ detail={+ "error": "idempotent_inflight_cancelled",+ "idempotency_key": idempotency_key,+ "message": (+ "The prior in-flight request with this Idempotency-Key was cancelled "+ "before it completed. Retry the request to execute it."+ ),+ },+ ) from waited_in_flight.exception+ raise waited_in_flight.exception+ if not waited_in_flight.succeeded:+ raise HTTPException(+ status_code=503,+ detail={+ "error": "idempotent_inflight_aborted",+ "idempotency_key": idempotency_key,+ "message": (+ "The prior in-flight request with this Idempotency-Key ended without "+ "a completed response. Retry the request to execute it."+ ),+ },+ )+async with idem.lock:cached = idem.cache.get(idempotency_key)if cached is not None:@@ -429,37 +467,62 @@ async def add_model(request: Request) -> Response:status_code=cached_status,media_type="application/json",)- in_flight_event = idem.in_flight.get(idempotency_key)- if in_flight_event is None:- if already_waited:- # Woken by a completer but the response was- # evicted before we grabbed the lock. Replay-safe- # synthesized response: tell the caller the write- # was already applied and they should trust the- # prior success. Not 200-from-cache because we- # can't echo created_profiles faithfully — the- # caller should re-read GET /v1/configs/models/{id}- # if they need the post-state.- return Response(- content=orjson.dumps(- {- "error": "idempotent_replay_evicted",- "idempotency_key": idempotency_key,- "message": (- "A prior request with this Idempotency-Key completed successfully, "- "but its cached response was evicted. The write was applied exactly once; "- "query GET /v1/configs/models/{id} to see the current state."- ),- }- ).decode(),- status_code=200,- media_type="application/json",- )+ if waited_in_flight is not None:+ # Woken by a completer but the response was evicted+ # before we grabbed the lock. This waiter belongs to+ # that completed owner, not to any later same-key+ # retry that may have started after eviction.+ return Response(+ content=orjson.dumps(+ {+ "error": "idempotent_replay_evicted",+ "idempotency_key": idempotency_key,+ "message": (+ "A prior request with this Idempotency-Key completed successfully, "+ "but its cached response was evicted. The write was applied exactly once; "+ "query GET /v1/configs/models/{id} to see the current state."+ ),+ }+ ).decode(),+ status_code=200,+ media_type="application/json",+ )+ in_flight = idem.in_flight.get(idempotency_key)+ if in_flight is None:# Genuinely first request for this key.- idem.in_flight[idempotency_key] = asyncio.Event()+ owner_in_flight = _IdempotencyInFlight(body_hash)+ idem.in_flight[idempotency_key] = owner_in_flightbreak- already_waited = True- await in_flight_event.wait()+ if body_hash != in_flight.payload_hash:+ raise HTTPException(+ status_code=422,+ detail={+ "error": "idempotency_mismatch",+ "message": "Idempotency-Key reused with different payload.",+ },+ )+ waited_in_flight = in_flight+ await in_flight.event.wait()++ cancellation_deferred = False++ async def _await_committed(awaitable: Any) -> Any:+ """Finish post-commit awaits even if the request task is cancelled."""+ nonlocal cancellation_deferred+ task = asyncio.ensure_future(awaitable)+ while True:+ try:+ return await asyncio.shield(task)+ except asyncio.CancelledError:+ current_task = asyncio.current_task()+ if current_task is None or not current_task.cancelling():+ raise+ cancellation_deferred = True+ while current_task.cancelling():+ current_task.uncancel()+ if task.done():+ return task.result()+try:try:config = yaml.safe_load(body.decode())@@ -633,7 +696,7 @@ async def add_model(request: Request) -> Response:config_yaml = yaml.dump(merged_config, default_flow_style=False, sort_keys=False)# Disk write BEFORE registry mutation.- await asyncio.to_thread(config_store.write_model, model_id, config_yaml)+ await _await_committed(asyncio.to_thread(config_store.write_model, model_id, config_yaml))# 4. Commit to in-memory registry now that disk is durable.# Validation already ran above; this call is expected to@@ -673,7 +736,7 @@ async def add_model(request: Request) -> Response:# 5. Increment epoch atomically. This is a read-modify-write# on `ConfigStore`, so it MUST stay inside `write_lock`.if config_store and created_profiles:- epoch = await asyncio.to_thread(config_store.increment_epoch)+ epoch = await _await_committed(asyncio.to_thread(config_store.increment_epoch))# Refresh the `sie_config_models_total` gauge now that the# registry has been mutated. Cheap (in-memory dict scan)@@ -681,7 +744,9 @@ async def add_model(request: Request) -> Response:# one that corresponds to the epoch we just bumped.if created_profiles:total = len(model_registry.list_models())- api_count = len(await asyncio.to_thread(config_store.list_models)) if config_store else 0+ api_count = 0+ if config_store:+ api_count = len(await _await_committed(asyncio.to_thread(config_store.list_models)))sie_metrics.update_models_gauge(api_count=api_count,filesystem_count=max(total - api_count, 0),@@ -694,18 +759,27 @@ async def add_model(request: Request) -> Response:bundle_config_hashes = {}for bundle_id in affected_bundles:bundle_config_hashes[bundle_id] = model_registry.compute_bundle_config_hash(bundle_id)+ all_bundle_pool_config_hashes = model_registry.compute_bundle_pool_config_hashes()+ bundle_pool_config_hashes = {+ bundle_id: all_bundle_pool_config_hashes.get(bundle_id, {}) for bundle_id in affected_bundles+ }+ model_pool = model_registry.get_model_pool_name(model_id)nats_publish_failed = Falsepartial_publish_failed_bundles: list[str] = []if nats_publisher and nats_publisher.connected and created_profiles:try:- await nats_publisher.publish_config_notification(- model_id=model_id,- profiles_added=created_profiles,- affected_bundles=affected_bundles,- bundle_config_hashes=bundle_config_hashes,- epoch=epoch,- model_config_yaml=config_yaml,+ await _await_committed(+ nats_publisher.publish_config_notification(+ model_id=model_id,+ profiles_added=created_profiles,+ affected_bundles=affected_bundles,+ bundle_config_hashes=bundle_config_hashes,+ epoch=epoch,+ model_config_yaml=config_yaml,+ model_pool=model_pool,+ bundle_pool_config_hashes=bundle_pool_config_hashes,+ ))except PartialPublishError as e:logger.exception(@@ -734,9 +808,10 @@ async def add_model(request: Request) -> Response:"nats_publish_failed: Config persisted but NATS notification failed. Workers may not be updated.")+ profile_bundles = model_registry.get_model_profile_bundles(model_id, set(created_profiles))routable_bundles_by_profile = {}for profile_name in created_profiles:- routable_bundles_by_profile[profile_name] = affected_bundles+ routable_bundles_by_profile[profile_name] = profile_bundles.get(profile_name, [])status_code = 201 if created_profiles else 200response_body: dict[str, Any] = {@@ -751,22 +826,31 @@ async def add_model(request: Request) -> Response:response_json = orjson.dumps(response_body).decode()if idempotency_key and idem is not None:- async with idem.lock:+ await _await_committed(idem.lock.acquire())+ try:idem.cache[idempotency_key] = (status_code, response_json, body_hash)idem.cache.move_to_end(idempotency_key)while len(idem.cache) > _MAX_IDEMPOTENCY_CACHE_SIZE:idem.cache.popitem(last=False)- event = idem.in_flight.pop(idempotency_key, None)- if event is not None:- event.set()-- except Exception:+ if owner_in_flight is not None:+ owner_in_flight.succeeded = True+ if idem.in_flight.get(idempotency_key) is owner_in_flight:+ idem.in_flight.pop(idempotency_key, None)+ owner_in_flight.event.set()+ finally:+ idem.lock.release()++ except (Exception, asyncio.CancelledError) as e:# Clean up in-flight marker on any error so waiters aren't stuck forever- if idempotency_key and idem is not None:- async with idem.lock:- event = idem.in_flight.pop(idempotency_key, None)- if event is not None:- event.set()+ if idempotency_key and idem is not None and owner_in_flight is not None:+ await _await_committed(idem.lock.acquire())+ try:+ owner_in_flight.exception = e+ if idem.in_flight.get(idempotency_key) is owner_in_flight:+ idem.in_flight.pop(idempotency_key, None)+ owner_in_flight.event.set()+ finally:+ idem.lock.release()raise# Emit audit log@@ -780,6 +864,9 @@ async def add_model(request: Request) -> Response:body_bytes=len(body),)+ if cancellation_deferred:+ raise asyncio.CancelledError+return Response(content=response_json,status_code=status_code,@@ -876,6 +963,7 @@ async def list_bundles(request: Request) -> dict[str, Any]:bundles.append({"bundle_id": info.name,+ "engine": info.engine,"priority": info.priority,"adapter_count": len(info.adapters),"source": "filesystem",@@ -900,6 +988,7 @@ async def get_bundle(request: Request, bundle_id: str) -> Response:data = {"name": info.name,+ "engine": info.engine,"priority": info.priority,"source": "filesystem","adapters": info.adapters,@@ -992,40 +1081,43 @@ async def export_snapshot(request: Request) -> Response:models = []for model_name in model_registry.list_models():- model_info = model_registry.get_model_info(model_name)- raw_yaml = (await asyncio.to_thread(config_store.read_model, model_name)) if config_store else None+ full_config = model_registry.get_full_config(model_name)+ if config_store is None and full_config:+ model_config = full_config+ raw_yaml = yaml.dump(full_config, default_flow_style=False, sort_keys=False)+ else:+ raw_yaml = (await asyncio.to_thread(config_store.read_model, model_name)) if config_store else None- if raw_yaml is None:- raw_yaml = await asyncio.to_thread(_load_filesystem_yaml, model_registry.models_dir, model_name)+ if raw_yaml is None:+ raw_yaml = await asyncio.to_thread(_load_filesystem_yaml, model_registry.models_dir, model_name)- if raw_yaml:- try:- model_config = yaml.safe_load(raw_yaml) or {"sie_id": model_name}- except yaml.YAMLError:+ if raw_yaml:+ try:+ model_config = yaml.safe_load(raw_yaml) or {"sie_id": model_name}+ except yaml.YAMLError:+ model_config = None+ raw_yaml = None+ else:model_config = None- else:- model_config = None-- # Fall back to the registry's in-memory merged config whenever- # we don't have authoritative raw YAML on disk. This covers- # no-ConfigStore deployments (default) and API-added models,- # both of which previously exported as `{"sie_id": ...}` and- # caused a fresh gateway's bootstrap to drop all profiles.- if not model_config or not model_config.get("profiles"):- full = model_registry.get_full_config(model_name)- if full:- model_config = full- if not raw_yaml:- raw_yaml = yaml.dump(full, default_flow_style=False, sort_keys=False)- elif not model_config:- model_config = {"sie_id": model_name}++ # Fall back to the registry's in-memory merged config whenever+ # we don't have authoritative raw YAML on disk. This covers+ # API-added models and broken raw YAML without collapsing to+ # `{"sie_id": ...}` during gateway bootstrap.+ if not model_config or not model_config.get("profiles"):+ if full_config:+ model_config = full_config+ raw_yaml = yaml.dump(full_config, default_flow_style=False, sort_keys=False)+ elif not model_config:+ model_config = {"sie_id": model_name}models.append({"model_id": model_name,"model_config": model_config,"raw_yaml": raw_yaml,- "affected_bundles": model_info.bundles if model_info else [],+ "affected_bundles": model_registry.get_model_export_bundles(model_name),+ "pool": model_registry.get_model_pool_name(model_name),})@@ -1033,12 +1125,14 @@ async def export_snapshot(request: Request) -> Response:bundle_id: model_registry.compute_bundle_config_hash(bundle_id)for bundle_id in model_registry.list_bundles()}+ bundle_pool_config_hashes = model_registry.compute_bundle_pool_config_hashes()snapshot = {"snapshot_version": 1,"epoch": epoch,"generated_at": datetime.now(UTC).isoformat(),"bundle_config_hashes": bundle_config_hashes,+ "bundle_pool_config_hashes": bundle_pool_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.pyindex 38716e833..0cf89f821 100644--- a/packages/sie_config/src/sie_config/model_registry.py+++ b/packages/sie_config/src/sie_config/model_registry.py@@ -4,6 +4,7 @@ import copyimport hashlibimport jsonimport logging+import reimport threadingfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -20,57 +21,174 @@ _PROFILE_HASH_FIELDS = ("adapter_path", "max_batch_tokens", "compute_precision",def _canonical_profile_dict(profile: dict) -> dict:"""Extract canonical routable fields from a raw profile dict for hashing."""- return {k: profile.get(k) for k in _PROFILE_HASH_FIELDS}+ return {+ k: _canonical_adapter_options(profile.get(k)) if k == "adapter_options" else profile.get(k)+ for k in _PROFILE_HASH_FIELDS+ }def _is_hash_falsy(value: object) -> bool:- if value is None:- return True- if value is False:+ """Falsy for bundle-hash canonicalization: ``None``, ``False``, ``0`` / ``0.0``,+ or an empty ``str``/``list``/``tuple``/``dict`` — mirrors the gateway's Rust+ ``canonicalize_adapter_options`` (see #1542).+ """+ if value is None or value is False:return Trueif isinstance(value, int | float) and value == 0:return Truereturn isinstance(value, str | list | tuple | dict) and len(value) == 0-def _canonical_adapter_options_for_hash(adapter_options: object) -> object | None:- """Mirror gateway canonicalization for adapter_options in bundle hashes."""- if isinstance(adapter_options, dict) and not any(not _is_hash_falsy(value) for value in adapter_options.values()):+def _canonical_adapter_options(adapter_options: object) -> object | None:+ """Mirror the gateway (Rust) ``canonicalize_adapter_options`` for adapter_options+ in bundle hashes: drop keys whose value is an empty nested map, then collapse to+ ``None`` when every remaining value is falsy (null/false/0/0.0/``""``/``[]``/``{}``).+ Diverging from the gateway leaves workers stuck in ``pending_workers`` (#1542).+ """+ if not isinstance(adapter_options, dict):+ return adapter_options+ compact = {key: value for key, value in adapter_options.items() if not (isinstance(value, dict) and not value)}+ if not compact or all(_is_hash_falsy(value) for value in compact.values()):return None- return adapter_options+ return compact-def _resolve_profile_for_hash(profiles: dict, profile_name: str) -> dict:- """Resolve profile inheritance into the fields covered by bundle hashes."""+def _merge_hash_adapter_options(parent_options: object, child_options: object) -> object | None:+ """Merge inherited adapter_options using the worker's profile resolution rules."""+ if not isinstance(child_options, dict):+ return (+ _canonical_adapter_options(child_options)+ if child_options is not None+ else _canonical_adapter_options(parent_options)+ )- def resolve(name: str, seen: set[str]) -> dict:- if name in seen:- msg = f"Profile '{name}' has an inheritance cycle"- raise ValueError(msg)- seen.add(name)+ merged: dict[str, object] = {}+ if isinstance(parent_options, dict):+ merged.update({str(key): copy.deepcopy(value) for key, value in parent_options.items()})+ for key_obj, value in child_options.items():+ key = str(key_obj)+ if key in {"loadtime", "runtime"} and isinstance(value, dict):+ if value:+ merged[key] = copy.deepcopy(value)+ continue+ merged[key] = copy.deepcopy(value)+ return _canonical_adapter_options(merged)+++def _resolved_profile_hash_config(+ profiles: dict,+ profile_name: str,+ seen: set[str] | None = None,+) -> dict[str, object] | None:+ """Return hash-relevant profile fields after applying ``extends``."""+ if seen is None:+ seen = set()+ if profile_name in seen:+ return None+ seen.add(profile_name)- profile = profiles.get(name)- if not isinstance(profile, dict):- msg = f"Profile '{name}' not found"- raise ValueError(msg)+ profile = profiles.get(profile_name)+ if not isinstance(profile, dict):+ return None++ parent_name = profile.get("extends")+ if isinstance(parent_name, str) and parent_name:+ resolved = _resolved_profile_hash_config(profiles, parent_name, seen)+ if resolved is None:+ return None+ else:+ resolved = {+ "adapter_path": None,+ "max_batch_tokens": None,+ "compute_precision": None,+ "adapter_options": None,+ }++ for key in ("adapter_path", "max_batch_tokens", "compute_precision"):+ value = profile.get(key)+ if value is not None:+ resolved[key] = value++ if "adapter_options" in profile:+ resolved["adapter_options"] = _merge_hash_adapter_options(+ resolved.get("adapter_options"),+ profile.get("adapter_options"),+ )+ else:+ resolved["adapter_options"] = _canonical_adapter_options(resolved.get("adapter_options"))++ return resolved- parent_name = profile.get("extends")- if parent_name:- resolved = resolve(str(parent_name), seen)- else:- resolved = dict.fromkeys(_PROFILE_HASH_FIELDS)- for field_name in ("adapter_path", "max_batch_tokens", "compute_precision"):- value = profile.get(field_name)- if value is not None:- resolved[field_name] = value+_PROFILE_NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")- if "adapter_options" in profile:- resolved["adapter_options"] = _canonical_adapter_options_for_hash(profile.get("adapter_options"))- return resolved+def _adapter_module_from_path(adapter_path: object) -> str | None:+ """Extract ``module`` from ``module:Class`` adapter paths."""+ if not isinstance(adapter_path, str) or not adapter_path:+ return None+ module_path = adapter_path.split(":", maxsplit=1)[0]+ return module_path or None+- return resolve(profile_name, set())+def _validate_profile_name(profile_name: str) -> None:+ """Validate profile names that become ``base:profile`` route ids."""+ if not _PROFILE_NAME_RE.fullmatch(profile_name):+ msg = (+ f"Profile name '{profile_name}' must match [A-Za-z0-9._-]+ (no '/', ':', whitespace, or other punctuation)"+ )+ raise ValueError(msg)+++def _effective_adapter_path(profiles: dict, profile_name: str) -> str | None:+ """Return the adapter path for a profile, following ``extends`` if needed."""+ current: str | None = profile_name+ seen: set[str] = set()+ while current:+ if current in seen:+ return None+ seen.add(current)+ profile = profiles.get(current)+ if not isinstance(profile, dict):+ return None+ adapter_path = profile.get("adapter_path")+ if isinstance(adapter_path, str) and adapter_path:+ return adapter_path+ parent = profile.get("extends")+ current = parent if isinstance(parent, str) and parent else None+ return None+++def _adapter_modules_for_profiles(profiles: dict, profile_names: set[str] | None = None) -> set[str]:+ """Collect effective adapter modules for selected profiles."""+ selected = profile_names if profile_names is not None else set(profiles.keys())+ modules: set[str] = set()+ for profile_name in selected:+ adapter_path = _effective_adapter_path(profiles, profile_name)+ module_path = _adapter_module_from_path(adapter_path)+ if module_path:+ modules.add(module_path)+ return modules+++def _base_route_adapter_modules(profiles: dict) -> set[str]:+ """Adapter modules used when callers request the base model id."""+ if "default" not in profiles:+ return set()+ module_path = _adapter_module_from_path(_effective_adapter_path(profiles, "default"))+ return {module_path} if module_path else set()+++def _matching_bundle_names(adapter_modules: set[str], bundles: dict[str, BundleInfo]) -> list[str]:+ """Return bundle ids compatible with the provided adapter modules."""+ if not adapter_modules:+ return []+ matching_bundles: list[tuple[int, str]] = []+ for bundle in bundles.values():+ if adapter_modules & set(bundle.adapters):+ matching_bundles.append((bundle.priority, bundle.name))+ matching_bundles.sort(key=lambda x: (x[0], x[1]))+ return [bundle_name for _, bundle_name in matching_bundles]class ModelNotFoundError(Exception):@@ -115,22 +233,37 @@ class ProfileConflictError(ValueError):# 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"})+KNOWN_ENGINES: frozenset[str] = frozenset({"pytorch", "candle"})DEFAULT_ENGINE: str = "pytorch"+DEFAULT_MODEL_POOL: str = "default"_MAX_POOL_NAME_LEN = 128# 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+# bug, not a runtime fall-through. Extend this 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.",),+ "candle": ("sie_server_rust.adapters.candle",),}+def _adapter_mismatches_engine(adapter: str, engine: str) -> bool:+ expected_prefixes = _ENGINE_ADAPTER_PREFIXES.get(engine, ())+ if engine == DEFAULT_ENGINE:+ foreign_prefixes = tuple(+ prefix+ for other_engine, prefixes in _ENGINE_ADAPTER_PREFIXES.items()+ if other_engine != engine+ for prefix in prefixes+ )+ return adapter.startswith(foreign_prefixes)+ return bool(expected_prefixes) and not adapter.startswith(expected_prefixes)++def _normalize_pool_name(config: dict) -> None:"""Validate and canonicalize an optional model-level pool name."""if "pool" not in config:@@ -160,6 +293,17 @@ def _normalize_pool_name(config: dict) -> None:config["pool"] = pool+def _model_pool_name(full_config: dict[str, object] | None) -> str:+ """Return the canonical routing pool for a model config snapshot."""+ if not full_config:+ return DEFAULT_MODEL_POOL+ raw_pool = full_config.get("pool")+ if not isinstance(raw_pool, str):+ return DEFAULT_MODEL_POOL+ pool = raw_pool.strip().lower()+ return pool or DEFAULT_MODEL_POOL++@dataclassclass BundleInfo:"""Information about a bundle.@@ -176,11 +320,12 @@ class BundleInfo:in the event of an ambiguous resolution. Surfaced asmetadata; 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.+ (``"pytorch"`` for the Python adapter image, ``"candle"``+ for the native Rust worker; 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@@ -232,6 +377,9 @@ class ModelRegistry:self._bundles: dict[str, BundleInfo] = {}self._models: dict[str, ModelInfo] = {}self._model_names_lower: dict[str, str] = {} # lowercase -> canonical+ self._profile_variant_models: dict[str, ModelInfo] = {}+ self._profile_variant_names_lower: dict[str, str] = {} # lowercase -> canonical variant+ self._profile_variant_base_models: dict[str, str] = {} # variant -> base modelself._model_adapter_modules: dict[str, set[str]] = {} # model -> adapter modulesself._model_profiles: dict[str, set[str]] = {} # model -> profile namesself._model_profile_configs: dict[str, dict[str, dict]] = {} # model -> {profile_name: config_dict}@@ -277,7 +425,11 @@ class ModelRegistry:new_bundles: dict[str, BundleInfo] = {}new_models: dict[str, ModelInfo] = {}new_model_names_lower: dict[str, str] = {}+ new_profile_variant_models: dict[str, ModelInfo] = {}+ new_profile_variant_names_lower: dict[str, str] = {}+ new_profile_variant_base_models: dict[str, str] = {}new_model_adapter_modules: dict[str, set[str]] = {}+ new_model_route_adapter_modules: dict[str, set[str]] = {}new_model_profiles: dict[str, set[str]] = {}new_model_profile_configs: dict[str, dict[str, dict]] = {}new_model_full_configs: dict[str, dict] = {}@@ -321,19 +473,18 @@ class ModelRegistry:# 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,- )+ bad_adapters = [a for a in adapters if _adapter_mismatches_engine(a, engine)]+ if bad_adapters:+ logger.error(+ "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; skipping load.",+ name,+ engine,+ _ENGINE_ADAPTER_PREFIXES.get(engine, ()),+ bad_adapters,+ )+ continuenew_bundles[name] = BundleInfo(name=name,@@ -365,27 +516,48 @@ class ModelRegistry:with config_path.open() as f:config = yaml.safe_load(f)- model_name = config.get("sie_id") or config.get("name")- if model_name:- adapter_modules: set[str] = set()+ raw_model_name = config.get("sie_id") or config.get("name")+ if raw_model_name:+ model_name = str(raw_model_name)profiles = config.get("profiles", {})- for profile in profiles.values():- adapter_path = profile.get("adapter_path", "")- if adapter_path:- module_path = adapter_path.split(":", maxsplit=1)[0]- adapter_modules.add(module_path)+ if not isinstance(profiles, dict):+ msg = f"Model '{model_name}' profiles must be a mapping"+ raise ValueError(msg)++ profile_names = {str(profile_name) for profile_name in profiles}+ for profile_name in profile_names:+ if profile_name != "default":+ _validate_profile_name(profile_name)++ adapter_modules = _adapter_modules_for_profiles(profiles)+ route_adapter_modules = _base_route_adapter_modules(profiles)new_models[model_name] = ModelInfo(name=model_name)new_model_adapter_modules[model_name] = adapter_modules+ new_model_route_adapter_modules[model_name] = route_adapter_modulesnew_model_names_lower[model_name.lower()] = model_namelogger.debug("Discovered model: %s (adapters: %s)", model_name, adapter_modules)- new_model_profiles[model_name] = set(profiles.keys())+ new_model_profiles[model_name] = profile_namesnew_model_profile_configs[model_name] = {- pname: _canonical_profile_dict(pdata) for pname, pdata in profiles.items()+ str(pname): _canonical_profile_dict(pdata) for pname, pdata in profiles.items()}if isinstance(config, dict):new_model_full_configs[model_name] = dict(config)+ for profile_name in sorted(profiles):+ if profile_name == "default":+ continue+ adapter_path = _effective_adapter_path(profiles, profile_name)+ module_path = _adapter_module_from_path(adapter_path)+ variant_modules = {module_path} if module_path else set()+ variant_name = f"{model_name}:{profile_name}"+ new_profile_variant_models[variant_name] = ModelInfo(+ name=variant_name,+ bundles=_matching_bundle_names(variant_modules, new_bundles),+ )+ new_profile_variant_names_lower[variant_name.lower()] = variant_name+ new_profile_variant_base_models[variant_name] = model_name+except Exception:logger.exception("Failed to load model config: %s", config_path)else:@@ -393,18 +565,8 @@ class ModelRegistry:# Compute mappingsfor model_name, model_info in new_models.items():- adapter_modules = new_model_adapter_modules.get(model_name, set())- if not adapter_modules:- continue-- matching_bundles: list[tuple[int, str]] = []- for bundle in new_bundles.values():- if adapter_modules & set(bundle.adapters):- matching_bundles.append((bundle.priority, bundle.name))-- if matching_bundles:- matching_bundles.sort(key=lambda x: x[0])- model_info.bundles = [b[1] for b in matching_bundles]+ route_adapter_modules = new_model_route_adapter_modules.get(model_name, set())+ model_info.bundles = _matching_bundle_names(route_adapter_modules, new_bundles)# Detect baked-in inconsistency: any model profile whose adapter# module is not declared in *any* bundle. We report the missing@@ -448,6 +610,9 @@ class ModelRegistry:self._bundles = new_bundlesself._models = new_modelsself._model_names_lower = new_model_names_lower+ self._profile_variant_models = new_profile_variant_models+ self._profile_variant_names_lower = new_profile_variant_names_lower+ self._profile_variant_base_models = new_profile_variant_base_modelsself._model_adapter_modules = new_model_adapter_modulesself._model_profiles = new_model_profilesself._model_profile_configs = new_model_profile_configs@@ -464,10 +629,6 @@ class ModelRegistry:def resolve_bundle(self, model: str, bundle_override: str | None = None) -> str:"""Resolve which bundle to use for a model.- Lock-free: reads dict references that are atomically swapped by- ``reload()``. The GIL guarantees a single pointer read is atomic- in CPython, so concurrent hot-reload cannot produce a torn read.-Args:model: Model name (e.g., "BAAI/bge-m3").bundle_override: Optional explicit bundle (e.g., "default").@@ -479,53 +640,68 @@ class ModelRegistry:ModelNotFoundError: Model not in any bundle (404).BundleConflictError: Override bundle doesn't support model (409)."""- # Snapshot references (atomic in CPython -- GIL protects pointer reads)- models = self._models- model_names_lower = self._model_names_lower-- # Normalize model name (case-insensitive lookup)- canonical_model = model_names_lower.get(model.lower())- if canonical_model is None:- # Try exact match- if model not in models:+ with self._lock:+ models = self._models+ model_names_lower = self._model_names_lower+ profile_variant_models = self._profile_variant_models+ profile_variant_names_lower = self._profile_variant_names_lower++ # Normalize model name (case-insensitive lookup)+ canonical_model = model_names_lower.get(model.lower())+ if canonical_model is None:+ canonical_variant = profile_variant_names_lower.get(model.lower())+ if canonical_variant is not None:+ canonical_model = canonical_variant+ model_info = profile_variant_models.get(canonical_model)+ else:+ model_info = None+ # Try exact match+ if model_info is None and model in profile_variant_models:+ canonical_model = model+ model_info = profile_variant_models.get(canonical_model)+ elif model_info is None and model in models:+ canonical_model = model+ model_info = models.get(canonical_model)+ elif model_info is None:+ raise ModelNotFoundError(model)+ else:+ model_info = models.get(canonical_model)+ if model_info is None or not model_info.bundles:raise ModelNotFoundError(model)- canonical_model = model-- model_info = models.get(canonical_model)- if model_info is None or not model_info.bundles:- raise ModelNotFoundError(model)-- if bundle_override is not None:- # Validate override is compatible- if bundle_override not in model_info.bundles:- raise BundleConflictError(- model=model,- bundle=bundle_override,- compatible_bundles=model_info.bundles,- )- return bundle_override- # Return highest priority (first in sorted list)- return model_info.bundles[0]+ if bundle_override is not None:+ # Validate override is compatible+ if bundle_override not in model_info.bundles:+ raise BundleConflictError(+ model=model,+ bundle=bundle_override,+ compatible_bundles=model_info.bundles,+ )+ return bundle_override++ # Return highest priority (first in sorted list)+ return model_info.bundles[0]def get_model_info(self, model: str) -> ModelInfo | None:"""Get model info including compatible bundles.- Lock-free: reads dict references atomically swapped by ``reload()``.-Args:model: Model name.Returns:ModelInfo if found, None otherwise."""- models = self._models- model_names_lower = self._model_names_lower- # Try case-insensitive lookup first- canonical = model_names_lower.get(model.lower())- if canonical:- return models.get(canonical)- return models.get(model)+ with self._lock:+ # Try case-insensitive lookup first+ canonical = self._model_names_lower.get(model.lower())+ if canonical:+ return self._models.get(canonical)+ variant = self._profile_variant_names_lower.get(model.lower())+ if variant:+ return self._profile_variant_models.get(variant)+ if model in self._profile_variant_models:+ return self._profile_variant_models.get(model)+ return self._models.get(model)def list_models(self) -> list[str]:"""List all known model names.@@ -533,7 +709,83 @@ class ModelRegistry:Returns:Sorted list of model names."""- return sorted(self._models.keys())+ with self._lock:+ return sorted(self._models.keys())++ def list_serving_models(self) -> list[str]:+ """List routable model/profile identities.++ Unlike :meth:`list_models`, this is a serving surface: profile-only+ configs omit the bare base id and expose only their ``base:profile``+ variants. ``list_models`` intentionally remains catalog inventory so+ export/bootstrap can serialize the base YAML once.+ """+ with self._lock:+ serving: set[str] = {model_name for model_name, model_info in self._models.items() if model_info.bundles}+ serving.update(+ model_name for model_name, model_info in self._profile_variant_models.items() if model_info.bundles+ )+ return sorted(serving)++ def get_catalog_model_name(self, model_name: str) -> str:+ """Return the base catalog config id for a serving route identity."""+ with self._lock:+ canonical_variant = self._profile_variant_names_lower.get(model_name.lower())+ if canonical_variant is not None:+ return self._profile_variant_base_models.get(canonical_variant, canonical_variant)+ if model_name in self._profile_variant_models:+ return self._profile_variant_base_models.get(model_name, model_name)+ canonical = self._model_names_lower.get(model_name.lower())+ return canonical or model_name++ def get_route_profile_names(self, model_name: str) -> set[str]:+ """Return profile names represented by a serving route identity."""+ with self._lock:+ canonical_variant = self._profile_variant_names_lower.get(model_name.lower())+ if canonical_variant is not None:+ return {canonical_variant.rsplit(":", maxsplit=1)[1]}+ if model_name in self._profile_variant_models:+ return {model_name.rsplit(":", maxsplit=1)[1]}+ return self.get_model_profile_names(model_name)++ def get_model_profile_bundles(+ self,+ model_name: str,+ profile_names: set[str] | None = None,+ ) -> dict[str, list[str]]:+ """Return compatible bundles for each selected catalog profile."""+ with self._lock:+ canonical = self._model_names_lower.get(model_name.lower(), model_name)+ full_config = self._model_full_configs.get(canonical, {})+ profiles = full_config.get("profiles", {}) if isinstance(full_config, dict) else {}+ if not isinstance(profiles, dict):+ return {}+ selected = profile_names if profile_names is not None else self._model_profiles.get(canonical, set())+ out: dict[str, list[str]] = {}+ for profile_name in sorted(selected):+ if profile_name not in profiles:+ continue+ module_path = _adapter_module_from_path(_effective_adapter_path(profiles, profile_name))+ modules = {module_path} if module_path else set()+ out[profile_name] = _matching_bundle_names(modules, self._bundles)+ return out++ def get_model_export_bundles(self, model_name: str) -> list[str]:+ """Return union of bundles targeted by any profile on a catalog model."""+ with self._lock:+ canonical = self._model_names_lower.get(model_name.lower(), model_name)+ full_config = self._model_full_configs.get(canonical, {})+ profiles = full_config.get("profiles", {}) if isinstance(full_config, dict) else {}+ if not isinstance(profiles, dict):+ return []+ modules = _adapter_modules_for_profiles(profiles, self._model_profiles.get(canonical, set()))+ return _matching_bundle_names(modules, self._bundles)++ def get_model_pool_name(self, model_name: str) -> str:+ """Return the canonical routing pool for a catalog model."""+ with self._lock:+ canonical = self._model_names_lower.get(model_name.lower(), model_name)+ return _model_pool_name(self._model_full_configs.get(canonical, {}))def list_bundles(self) -> list[str]:"""List all bundle names.@@ -541,9 +793,9 @@ class ModelRegistry:Returns:List of bundle names sorted by priority."""- bundles = self._bundles- bundles_sorted = sorted(bundles.values(), key=lambda b: b.priority)- return [b.name for b in bundles_sorted]+ with self._lock:+ bundles_sorted = sorted(self._bundles.values(), key=lambda b: b.priority)+ return [b.name for b in bundles_sorted]def compute_bundles_hash(self) -> str:"""Stable SHA-256 over the registry's full bundle surface.@@ -604,11 +856,10 @@ class ModelRegistry:return ""for bundle_id in bundle_ids:model_pools = {}- for model_name, model_info in sorted(self._models.items()):- if bundle_id not in model_info.bundles:+ for model_name in sorted(self._models):+ if bundle_id not in self.get_model_export_bundles(model_name):continue- pool = self._model_full_configs.get(model_name, {}).get("pool") or "default"- model_pools[model_name] = str(pool).strip().lower() or "default"+ model_pools[model_name] = _model_pool_name(self._model_full_configs.get(model_name, {}))by_bundle[bundle_id] = {"bundle_config_hash": self.compute_bundle_config_hash(bundle_id),"model_pools": model_pools,@@ -625,7 +876,8 @@ class ModelRegistry:Returns:BundleInfo if found, None otherwise."""- return self._bundles.get(bundle)+ with self._lock:+ return self._bundles.get(bundle)def get_models_for_bundle(self, bundle: str) -> list[str]:"""Get all models that can be served by a bundle.@@ -636,8 +888,14 @@ class ModelRegistry:Returns:List of model names."""- models = self._models- return [model_name for model_name, model_info in models.items() if bundle in model_info.bundles]+ with self._lock:+ models = self._models+ profile_variant_models = self._profile_variant_models+ return [+ model_name+ for model_name, model_info in {**models, **profile_variant_models}.items()+ if bundle in model_info.bundles+ ]def model_exists(self, model: str) -> bool:"""Check if a model exists in the registry.@@ -648,9 +906,12 @@ class ModelRegistry:Returns:True if model is known, False otherwise."""- if model.lower() in self._model_names_lower:- return True- return model in self._models+ with self._lock:+ if model.lower() in self._model_names_lower:+ return True+ if model.lower() in self._profile_variant_names_lower:+ return True+ return model in self._models or model in self._profile_variant_modelsdef validate_model_config(self,@@ -700,19 +961,25 @@ class ModelRegistry:msg = "Field 'profiles' must be a mapping of profile_name -> profile_config"raise ValueError(msg)- new_adapter_modules: set[str] = set()for profile_name, profile in profiles.items():+ _validate_profile_name(str(profile_name))if not isinstance(profile, dict):msg = f"Profile '{profile_name}' must be a mapping"raise ValueError(msg)- adapter_path = profile.get("adapter_path", "")+ adapter_path = _effective_adapter_path(profiles, str(profile_name))if not adapter_path:if not profile.get("extends"):msg = f"Profile '{profile_name}' missing adapter_path"raise ValueError(msg)continue- module_path = adapter_path.split(":", maxsplit=1)[0]- new_adapter_modules.add(module_path)++ existing_full_profiles = self._model_full_configs.get(sie_id, {}).get("profiles", {})+ merged_profiles_for_routing = dict(existing_full_profiles) if isinstance(existing_full_profiles, dict) else {}+ merged_profiles_for_routing.update(profiles)+ new_adapter_modules = _adapter_modules_for_profiles(+ merged_profiles_for_routing,+ {str(profile_name) for profile_name in profiles},+ )all_bundle_adapters: set[str] = set()for bundle in self._bundles.values():@@ -756,20 +1023,8 @@ class ModelRegistry:# Compute the post-apply adapter set so bundle mappings reflect# the hypothetical new state. This is a pure computation on a# local copy — no self._* mutation.- post_adapter_modules: set[str] = set(self._model_adapter_modules.get(sie_id, set()))- for profile_name in created_profiles:- adapter_path = profiles[profile_name].get("adapter_path", "")- if adapter_path:- post_adapter_modules.add(adapter_path.split(":", maxsplit=1)[0])- if not existing:- post_adapter_modules = new_adapter_modules-- matching_bundles: list[tuple[int, str]] = []- for bundle in self._bundles.values():- if post_adapter_modules & set(bundle.adapters):- matching_bundles.append((bundle.priority, bundle.name))- matching_bundles.sort(key=lambda x: x[0])- affected_bundles = [b[1] for b in matching_bundles]+ post_adapter_modules = _adapter_modules_for_profiles(merged_profiles_for_routing)+ affected_bundles = _matching_bundle_names(post_adapter_modules, self._bundles)# Reject changes that land in zero bundles. `extends`-only# profiles skip the `adapter_path` collection step, so@@ -838,31 +1093,6 @@ class ModelRegistry:# semantics of CPython dict assignment is what keeps those# readers lock-free and correct — in-place mutation (set.add,# list.append, dict.update on a live value) would break that.- new_adapter_modules_set: set[str]- if existing:- base_modules = self._model_adapter_modules.get(sie_id, set())- new_adapter_modules_set = set(base_modules)- for profile_name in created_profiles:- adapter_path = profiles[profile_name].get("adapter_path", "")- if adapter_path:- module_path = adapter_path.split(":", maxsplit=1)[0]- new_adapter_modules_set.add(module_path)- else:- new_adapter_modules_set = set()- for profile in profiles.values():- adapter_path = profile.get("adapter_path", "")- if adapter_path:- new_adapter_modules_set.add(adapter_path.split(":", maxsplit=1)[0])-- matching_bundles: list[tuple[int, str]] = []- for bundle in self._bundles.values():- if new_adapter_modules_set & set(bundle.adapters):- matching_bundles.append((bundle.priority, bundle.name))- matching_bundles.sort(key=lambda x: x[0])- affected_bundles = [b[1] for b in matching_bundles]-- new_model_info = ModelInfo(name=sie_id, bundles=list(affected_bundles))-new_profile_names = set(self._model_profiles.get(sie_id, set()))new_profile_names.update(created_profiles)@@ -899,6 +1129,44 @@ class ModelRegistry:if "sie_id" not in new_full_config:new_full_config["sie_id"] = sie_id+ new_adapter_modules_set = _adapter_modules_for_profiles(merged_profiles_full)+ route_adapter_modules = _base_route_adapter_modules(merged_profiles_full)+ affected_bundles = _matching_bundle_names(new_adapter_modules_set, self._bundles)+ new_model_info = ModelInfo(+ name=sie_id,+ bundles=_matching_bundle_names(route_adapter_modules, self._bundles),+ )++ new_profile_variant_models = {+ name: info+ for name, info in self._profile_variant_models.items()+ if self._profile_variant_base_models.get(name) != sie_id+ }+ new_profile_variant_names_lower = {+ lower: name+ for lower, name in self._profile_variant_names_lower.items()+ if self._profile_variant_base_models.get(name) != sie_id+ }+ new_profile_variant_base_models = {+ name: base for name, base in self._profile_variant_base_models.items() if base != sie_id+ }+ for profile_name in sorted(new_profile_names):+ if profile_name == "default":+ continue+ adapter_path = _effective_adapter_path(merged_profiles_full, profile_name)+ module_path = _adapter_module_from_path(adapter_path)+ variant_modules = {module_path} if module_path else set()+ variant_name = f"{sie_id}:{profile_name}"+ new_profile_variant_models[variant_name] = ModelInfo(+ name=variant_name,+ bundles=_matching_bundle_names(variant_modules, self._bundles),+ )+ new_profile_variant_names_lower[variant_name.lower()] = variant_name+ new_profile_variant_base_models[variant_name] = sie_id+ affected_bundles.extend(new_profile_variant_models[variant_name].bundles)+ affected_bundles.sort()+ affected_bundles = list(dict.fromkeys(affected_bundles))+# Atomic swaps (CPython guarantees single-pointer-store is# not interleaved with a concurrent pointer-load under the GIL).self._models = {**self._models, sie_id: new_model_info}@@ -907,6 +1175,9 @@ class ModelRegistry:**self._model_names_lower,sie_id.lower(): sie_id,}+ self._profile_variant_models = new_profile_variant_models+ self._profile_variant_names_lower = new_profile_variant_names_lower+ self._profile_variant_base_models = new_profile_variant_base_modelsself._model_adapter_modules = {**self._model_adapter_modules,sie_id: new_adapter_modules_set,@@ -961,7 +1232,11 @@ class ModelRegistry:def get_model_profile_names(self, model_name: str) -> set[str]:"""Get known profile names for a model."""- return set(self._model_profiles.get(model_name, set()))+ with self._lock:+ canonical_variant = self._profile_variant_names_lower.get(model_name.lower())+ if canonical_variant or model_name in self._profile_variant_models:+ return {"default"}+ return set(self._model_profiles.get(model_name, set()))def get_full_config(self, model_name: str) -> dict | None:"""Return a deep-copied snapshot of the full merged model config.@@ -971,13 +1246,14 @@ class ModelRegistry:in-memory state for both filesystem-seeded and API-added models.Returns ``None`` for unknown models."""- full = self._model_full_configs.get(model_name)- if full is None:- return None- # Full deep copy: the docstring promises a snapshot, and shallow-copying- # only top-level keys leaves nested lists/dicts outside ``profiles``- # aliased to registry-owned state so a mutating caller could corrupt it.- return copy.deepcopy(full)+ with self._lock:+ full = self._model_full_configs.get(model_name)+ if full is None:+ return None+ # Full deep copy: the docstring promises a snapshot, and shallow-copying+ # only top-level keys leaves nested lists/dicts outside ``profiles``+ # aliased to registry-owned state so a mutating caller could corrupt it.+ return copy.deepcopy(full)def compute_bundle_config_hash(self, bundle_id: str) -> str:"""Compute the config hash for a specific bundle.@@ -997,48 +1273,83 @@ class ModelRegistry:if cached is not None:return cached- bundle = self._bundles.get(bundle_id)- if not bundle:- return ""+ result = self._compute_bundle_config_hash_locked(bundle_id)+ self._bundle_hash_cache[bundle_id] = result+ return result++ def compute_bundle_config_hash_for_pool(self, bundle_id: str, pool_name: str) -> str:+ """Compute the worker-parity config hash for a bundle within one pool."""+ normalized_pool = (pool_name or "").strip().lower() or DEFAULT_MODEL_POOL+ with self._lock:+ return self._compute_bundle_config_hash_locked(bundle_id, normalized_pool)++ def compute_bundle_pool_config_hashes(self) -> dict[str, dict[str, str]]:+ """Return worker-parity config hashes grouped by bundle and model pool."""+ with self._lock:+ hashes: dict[str, dict[str, str]] = {bundle_id: {} for bundle_id in self._bundles}+ pools_by_bundle: dict[str, set[str]] = {bundle_id: set() for bundle_id in self._bundles}+ for model_name in sorted(self._models):+ pool = _model_pool_name(self._model_full_configs.get(model_name, {}))+ for bundle_id in self.get_model_export_bundles(model_name):+ if bundle_id in self._bundles:+ pools_by_bundle.setdefault(bundle_id, set()).add(pool)++ for bundle_id, pools in pools_by_bundle.items():+ for pool in sorted(pools):+ hash_value = self._compute_bundle_config_hash_locked(bundle_id, pool)+ if hash_value:+ hashes[bundle_id][pool] = hash_value+ return hashes++ def _compute_bundle_config_hash_locked(self, bundle_id: str, pool_name: str | None = None) -> str:+ bundle = self._bundles.get(bundle_id)+ if not bundle:+ return ""- bundle_adapter_set = set(bundle.adapters)- items: list[dict] = []+ normalized_pool = (pool_name or "").strip().lower() or None+ bundle_adapter_set = set(bundle.adapters)+ items: list[dict] = []- for model_name, model_info in sorted(self._models.items()):- if bundle_id not in model_info.bundles:+ for model_name in sorted(self._models):+ full_config = self._model_full_configs.get(model_name, {})+ if normalized_pool is not None and _model_pool_name(full_config) != normalized_pool:+ continue++ adapter_modules = self._model_adapter_modules.get(model_name, set())+ # Only include if model has adapters in this bundle+ if adapter_modules & bundle_adapter_set:+ full_profiles = full_config.get("profiles", {}) if isinstance(full_config, dict) else {}+ if not isinstance(full_profiles, dict):+ full_profiles = {}+ profiles_for_hash = []+ # Hash only the fields that affect inference behaviour,+ # matching the worker-side hash in+ # ``sie_server.api.ws._compute_bundle_config_hash``.+ for pname in sorted(self.get_model_profile_names(model_name)):+ # Only include profiles whose adapter is routable in this bundle+ filtered_cfg = _resolved_profile_hash_config(full_profiles, pname)+ if filtered_cfg is None:+ continue+ p_adapter = filtered_cfg.get("adapter_path", "")+ if isinstance(p_adapter, str) and p_adapter:+ p_module = p_adapter.split(":", maxsplit=1)[0]+ if p_module not in bundle_adapter_set:+ continue+ profiles_for_hash.append({"name": pname, "config": filtered_cfg})+ if not profiles_for_hash:continue- adapter_modules = self._model_adapter_modules.get(model_name, set())- # Only include if model has adapters in this bundle- if adapter_modules & bundle_adapter_set:- full_profiles = self._model_full_configs.get(model_name, {}).get("profiles", {})- profiles_for_hash = []- # Hash only the fields that affect inference behaviour,- # matching the worker-side hash in- # ``sie_server.api.ws._compute_bundle_config_hash``.- for pname in sorted(self.get_model_profile_names(model_name)):- # Only include profiles whose adapter is routable in this bundle- p_cfg = _resolve_profile_for_hash(full_profiles, pname)- p_adapter = p_cfg.get("adapter_path", "")- if p_adapter:- p_module = p_adapter.split(":", maxsplit=1)[0]- if p_module not in bundle_adapter_set:- continue- filtered_cfg = {k: p_cfg.get(k) for k in _PROFILE_HASH_FIELDS}- profiles_for_hash.append({"name": pname, "config": filtered_cfg})- items.append(- {- "sie_id": model_name,- "profiles": profiles_for_hash,- }- )+ items.append(+ {+ "sie_id": model_name,+ "profiles": profiles_for_hash,+ }+ )- if not items:- return ""+ if not items:+ return ""- serialized = orjson.dumps(items, option=orjson.OPT_SORT_KEYS)- result = hashlib.sha256(serialized).hexdigest()- self._bundle_hash_cache[bundle_id] = result- return result+ serialized = orjson.dumps(items, option=orjson.OPT_SORT_KEYS)+ return hashlib.sha256(serialized).hexdigest()def parse_model_spec(model_spec: str) -> tuple[str | None, str]:diff --git a/packages/sie_config/src/sie_config/nats_publisher.py b/packages/sie_config/src/sie_config/nats_publisher.pyindex 8931102ae..46dc7477d 100644--- a/packages/sie_config/src/sie_config/nats_publisher.py+++ b/packages/sie_config/src/sie_config/nats_publisher.py@@ -238,6 +238,8 @@ class NatsPublisher:bundle_config_hashes: dict[str, str],epoch: int,model_config_yaml: str,+ model_pool: str = "default",+ bundle_pool_config_hashes: dict[str, dict[str, str]] | None = None,) -> None:"""Publish config change notifications to NATS.@@ -249,9 +251,10 @@ class NatsPublisher:worker-sidecar containers consume the bundle-scoped subject. The samepayload shape goes to both subjects so every subscriber sees the full- set of fields that ``sie_gateway`` expects+ set of fields that ``sie_gateway`` and worker sidecars expect(``router_id``, ``bundle_id``, ``epoch``, ``bundle_config_hash``,- ``model_id``, ``profiles_added``, ``model_config``, ``affected_bundles``).+ ``model_id``, ``profiles_added``, ``model_config``,+ ``affected_bundles``, ``pool``, ``bundle_pool_config_hashes``).See ``packages/sie_gateway/src/nats/manager.rs::ConfigNotification``.Args:@@ -261,6 +264,8 @@ class NatsPublisher:bundle_config_hashes: Dict of bundle_id -> new hash for each affected bundle.epoch: The new epoch value after this mutation.model_config_yaml: Full model config YAML content.+ model_pool: Canonical pool assignment for the changed model.+ bundle_pool_config_hashes: Nested bundle_id -> pool -> hash map.Raises:RuntimeError: If NATS is not connected.@@ -287,6 +292,8 @@ class NatsPublisher:raise ValueError(msg)nc = cast("nats.NATS", self._nc)+ normalized_pool = model_pool.strip().lower() or "default"+ pool_hashes = bundle_pool_config_hashes or {}# Publish each bundle delta individually, collecting failures# rather than short-circuiting on the first exception. If we@@ -306,6 +313,8 @@ class NatsPublisher:"profiles_added": profiles_added,"model_config": model_config_yaml,"affected_bundles": affected_bundles,+ "pool": normalized_pool,+ "bundle_pool_config_hashes": pool_hashes,}encoded = orjson.dumps(payload)diff --git a/packages/sie_config/tests/test_canonical_profile_conformance.py b/packages/sie_config/tests/test_canonical_profile_conformance.pynew file mode 100644index 000000000..9b6c97158--- /dev/null+++ b/packages/sie_config/tests/test_canonical_profile_conformance.py@@ -0,0 +1,46 @@+"""Conformance: sie_config's bundle_config_hash adapter_options canonicalization+matches the shared cross-language vectors (issue #1542).++The same `conformance/bundle_config_hash/canonical_profile_falsy_vectors.json`+fixture is asserted by the gateway Rust suite+(``packages/sie_gateway/src/types/model.rs``) and the sie_server suite, so the+config service's ``_canonical_adapter_options`` cannot drift from the gateway's+Rust ``canonicalize_adapter_options`` — a divergence would leave workers stuck in+``pending_workers`` with a ``bundle_config_hash`` that never matches the gateway's.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import pytest+from sie_config.model_registry import _canonical_adapter_options+++def _load_vectors() -> dict[str, Any]:+ for parent in Path(__file__).resolve().parents:+ fixture = parent / "conformance" / "bundle_config_hash" / "canonical_profile_falsy_vectors.json"+ if fixture.exists():+ return json.loads(fixture.read_text())+ msg = "canonical_profile_falsy_vectors.json not found in any parent directory"+ raise FileNotFoundError(msg)+++_VECTORS = _load_vectors()++[email protected]("case", _VECTORS["strip_to_none"], ids=lambda c: c["name"])+def test_falsy_only_options_strip_to_none(case: dict[str, Any]) -> None:+ assert _canonical_adapter_options(case["adapter_options"]) is None++[email protected]("case", _VECTORS["keep_unchanged"], ids=lambda c: c["name"])+def test_meaningful_options_kept_unchanged(case: dict[str, Any]) -> None:+ assert _canonical_adapter_options(case["adapter_options"]) == case["adapter_options"]++[email protected]("case", _VECTORS["transform"], ids=lambda c: c["name"])+def test_loadtime_runtime_compaction(case: dict[str, Any]) -> None:+ assert _canonical_adapter_options(case["adapter_options"]) == case["expected"]diff --git a/packages/sie_config/tests/test_config_api.py b/packages/sie_config/tests/test_config_api.pyindex c27d5990e..a7e3481c8 100644--- a/packages/sie_config/tests/test_config_api.py+++ b/packages/sie_config/tests/test_config_api.py@@ -1,6 +1,10 @@+import asyncioimport tempfile+import threadingfrom pathlib import Path+import httpx+import pytestimport yamlfrom fastapi import FastAPIfrom fastapi.testclient import TestClient@@ -25,8 +29,17 @@ def _create_test_app(return app-def _write_bundle(bundles_dir: Path, name: str, adapters: list[str], priority: int = 10) -> None:+def _write_bundle(+ bundles_dir: Path,+ name: str,+ adapters: list[str],+ priority: int = 10,+ *,+ engine: str | None = None,+) -> None:bundle = {"name": name, "priority": priority, "adapters": adapters}+ if engine is not None:+ bundle["engine"] = engine(bundles_dir / f"{name}.yaml").write_text(yaml.dump(bundle))@@ -71,6 +84,31 @@ class TestConfigAPIModels:assert data["models"][0]["model_id"] == "test/model"assert data["models"][0]["source"] == "filesystem"+ def test_list_models_uses_profile_only_candle_route_identity(self) -> None:+ with tempfile.TemporaryDirectory() as tmpdir:+ root = Path(tmpdir)+ bundles = root / "bundles"+ models = root / "models"+ bundles.mkdir()+ models.mkdir()+ _write_bundle(bundles, "candle", ["sie_server_rust.adapters.candle"], priority=30, engine="candle")+ (models / "candle-only.yaml").write_text(+ "sie_id: org/candle-only\n"+ "profiles:\n"+ " candle:\n"+ " adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter\n"+ )+ app = _create_test_app(bundles, models)+ client = TestClient(app)++ resp = client.get("/v1/configs/models")++ assert resp.status_code == 200+ models_body = resp.json()["models"]+ assert [model["model_id"] for model in models_body] == ["org/candle-only:candle"]+ assert models_body[0]["profiles"] == ["candle"]+ assert models_body[0]["source"] == "filesystem"+def test_get_model_not_found(self) -> None:resp = self.client.get("/v1/configs/models/nonexistent/model")assert resp.status_code == 404@@ -105,6 +143,7 @@ class TestConfigAPIModels:assert export.status_code == 200models = {m["model_id"]: m for m in export.json()["models"]}assert models["pool/model"]["model_config"]["pool"] == "customer-a"+ assert models["pool/model"]["pool"] == "customer-a"assert "pool: customer-a" in models["pool/model"]["raw_yaml"]def test_append_model_profile_preserves_pool_in_export(self) -> None:@@ -132,6 +171,7 @@ class TestConfigAPIModels:models = {m["model_id"]: m for m in export.json()["models"]}entry = models["pool/model"]assert entry["model_config"]["pool"] == "customer-a"+ assert entry["pool"] == "customer-a"assert set(entry["model_config"]["profiles"]) == {"default", "fast"}assert "pool: customer-a" in entry["raw_yaml"]@@ -254,12 +294,14 @@ class TestConfigAPIBundles:bundles = resp.json()["bundles"]assert len(bundles) == 2assert bundles[0]["bundle_id"] == "default"+ assert bundles[0]["engine"] == "pytorch"assert bundles[0]["priority"] == 10def test_get_bundle(self) -> None:resp = self.client.get("/v1/configs/bundles/default")assert resp.status_code == 200assert "application/x-yaml" in resp.headers["content-type"]+ assert "engine: pytorch" in resp.textdef test_get_bundle_not_found(self) -> None:resp = self.client.get("/v1/configs/bundles/nonexistent")@@ -463,9 +505,11 @@ class TestConfigAPIExport:assert data["bundle_config_hashes"]["default"] == self.app.state.model_registry.compute_bundle_config_hash("default")+ assert data["bundle_pool_config_hashes"]["default"]["default"] == data["bundle_config_hashes"]["default"]assert len(data["models"]) == 1assert data["models"][0]["model_id"] == "test/model"assert data["models"][0]["affected_bundles"] == ["default"]+ assert data["models"][0]["pool"] == "default"def test_export_includes_api_added_models(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"@@ -486,8 +530,31 @@ class TestConfigAPIExport:data = resp.json()assert data["models"] == []assert data["bundle_config_hashes"] == {"default": ""}+ assert data["bundle_pool_config_hashes"] == {"default": {}}assert data["epoch"] == 0+ def test_export_bundle_pool_hashes_are_scoped_by_model_pool(self) -> None:+ _write_model(+ self._models,+ "tenant/model",+ "sie_server.adapters.bert_flash:BertFlashAdapter",+ pool="customer-a",+ )+ registry: ModelRegistry = self.app.state.model_registry+ registry.reload()++ resp = self.client.get("/v1/configs/export")+ assert resp.status_code == 200+ data = resp.json()++ global_hash = data["bundle_config_hashes"]["default"]+ default_pool_hash = data["bundle_pool_config_hashes"]["default"]["default"]+ tenant_pool_hash = data["bundle_pool_config_hashes"]["default"]["customer-a"]+ assert default_pool_hash == registry.compute_bundle_config_hash_for_pool("default", "default")+ assert tenant_pool_hash == registry.compute_bundle_config_hash_for_pool("default", "customer-a")+ assert global_hash != default_pool_hash+ assert global_hash != tenant_pool_hash+def test_export_generated_at_is_utc_iso8601(self) -> None:from datetime import datetime@@ -644,9 +711,101 @@ class TestConfigAPIExportNoConfigStore:models = {m["model_id"]: m for m in resp.json()["models"]}entry = models["mem/model"]assert entry["model_config"]["pool"] == "customer-a"+ assert entry["pool"] == "customer-a"assert set(entry["model_config"]["profiles"]) == {"default", "fast"}assert "pool: customer-a" in entry["raw_yaml"]+ def test_export_targets_variant_bundle_for_filesystem_model_without_store(self) -> None:+ _write_bundle(+ self._bundles,+ "default",+ ["sie_server.adapters.bert_flash", "sie_server.adapters.bge_m3_flash"],+ )+ _write_bundle(self._bundles, "candle", ["sie_server_rust.adapters.candle"], priority=30, engine="candle")+ (self._models / "BAAI__bge-m3.yaml").write_text(+ "sie_id: BAAI/bge-m3\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bge_m3_flash:BGEM3FlashAdapter\n"+ " max_batch_tokens: 16384\n"+ " candle:\n"+ " extends: default\n"+ " adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter\n"+ )+ self.app = _create_test_app(self._bundles, self._models, config_store_dir=None)+ self.client = TestClient(self.app)++ resp = self.client.get("/v1/configs/export")++ assert resp.status_code == 200+ data = resp.json()+ models = {m["model_id"]: m for m in data["models"]}+ entry = models["BAAI/bge-m3"]+ assert entry["affected_bundles"] == ["default", "candle"]+ assert entry["pool"] == "default"+ assert set(entry["model_config"]["profiles"]) == {"default", "candle"}+ registry: ModelRegistry = self.app.state.model_registry+ assert data["bundle_pool_config_hashes"]["candle"]["default"] == registry.compute_bundle_config_hash_for_pool(+ "candle", "default"+ )+ candle_applied = [m for m in data["models"] if "candle" in m["affected_bundles"]]+ assert [m["model_id"] for m in candle_applied] == ["BAAI/bge-m3"]++ def test_export_prefers_registry_merge_for_filesystem_append_without_store(self) -> None:+ _write_bundle(+ self._bundles,+ "default",+ ["sie_server.adapters.bert_flash", "sie_server.adapters.bge_m3_flash"],+ )+ _write_bundle(self._bundles, "candle", ["sie_server_rust.adapters.candle"], priority=30, engine="candle")+ (self._models / "BAAI__bge-m3.yaml").write_text(+ "sie_id: BAAI/bge-m3\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bge_m3_flash:BGEM3FlashAdapter\n"+ " max_batch_tokens: 16384\n"+ )+ self.app = _create_test_app(self._bundles, self._models, config_store_dir=None)+ self.client = TestClient(self.app)++ appended = (+ "sie_id: BAAI/bge-m3\n"+ "profiles:\n"+ " candle:\n"+ " extends: default\n"+ " adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter\n"+ )+ post = self.client.post("/v1/configs/models", content=appended)+ assert post.status_code == 201+ assert post.json()["routable_bundles_by_profile"] == {"candle": ["candle"]}++ resp = self.client.get("/v1/configs/export")++ assert resp.status_code == 200+ models = {m["model_id"]: m for m in resp.json()["models"]}+ entry = models["BAAI/bge-m3"]+ assert entry["affected_bundles"] == ["default", "candle"]+ assert set(entry["model_config"]["profiles"]) == {"default", "candle"}+ assert "candle:" in entry["raw_yaml"]++ def test_export_replaces_invalid_raw_yaml_with_registry_config(self) -> None:+ _write_model(self._models, "test/model", "sie_server.adapters.bert_flash:BertFlashAdapter")+ app = _create_test_app(self._bundles, self._models, str(self._root / "invalid_store"))+ client = TestClient(app)+ store: ConfigStore = app.state.config_store+ store.write_model("test/model", "profiles: [")++ resp = client.get("/v1/configs/export")++ assert resp.status_code == 200+ models = {m["model_id"]: m for m in resp.json()["models"]}+ entry = models["test/model"]+ assert entry["raw_yaml"] != "profiles: ["+ assert "profiles:" in entry["raw_yaml"]+ assert entry["model_config"]["profiles"]["default"]["adapter_path"] == (+ "sie_server.adapters.bert_flash:BertFlashAdapter"+ )+def test_nats_delta_carries_merged_yaml_without_store(self) -> None:"""On the NATS publish path, the delta payload must be the fullmerged model YAML (not the incremental request body) so a fresh@@ -1020,6 +1179,367 @@ class TestIdempotencyEvictionSafety:"idempotent replay must NOT bump the epoch")+ def test_concurrent_same_key_waiter_gets_cached_success(self, monkeypatch) -> None:+ body = (+ "sie_id: idem/concurrent-success\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bert_flash:A\n"+ " max_batch_tokens: 1\n"+ )+ original_write_model = self.app.state.config_store.write_model+ release_write = threading.Event()+ calls: list[str] = []++ async def run() -> None:+ loop = asyncio.get_running_loop()+ write_started = asyncio.Event()++ def blocking_write_model(model_id: str, config_yaml: str) -> None:+ calls.append(model_id)+ loop.call_soon_threadsafe(write_started.set)+ if not release_write.wait(timeout=5):+ raise RuntimeError("timed out waiting to release write")+ original_write_model(model_id, config_yaml)++ monkeypatch.setattr(self.app.state.config_store, "write_model", blocking_write_model)++ transport = httpx.ASGITransport(app=self.app)+ async with httpx.AsyncClient(transport=transport, base_url="http://t") as ac:+ owner = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-success"})+ )+ await asyncio.wait_for(write_started.wait(), timeout=1)++ waiter = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-success"})+ )+ await asyncio.sleep(0.05)+ assert not waiter.done(), "same-key request did not wait on the in-flight owner"++ release_write.set()+ owner_resp, waiter_resp = await asyncio.gather(owner, waiter)++ assert owner_resp.status_code == 201, owner_resp.text+ assert waiter_resp.status_code == 201, waiter_resp.text+ assert waiter_resp.json() == owner_resp.json()+ assert calls == ["idem/concurrent-success"]++ asyncio.run(run())+ assert self.client.get("/v1/configs/epoch").json()["epoch"] == 1++ def test_concurrent_same_key_different_body_returns_422_while_owner_in_flight(self, monkeypatch) -> None:+ owner_body = (+ "sie_id: idem/concurrent-mismatch-a\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bert_flash:A\n"+ " max_batch_tokens: 1\n"+ )+ mismatch_body = (+ "sie_id: idem/concurrent-mismatch-b\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bert_flash:A\n"+ " max_batch_tokens: 1\n"+ )+ original_write_model = self.app.state.config_store.write_model+ release_write = threading.Event()+ calls: list[str] = []++ async def run() -> None:+ loop = asyncio.get_running_loop()+ write_started = asyncio.Event()++ def blocking_write_model(model_id: str, config_yaml: str) -> None:+ calls.append(model_id)+ loop.call_soon_threadsafe(write_started.set)+ if not release_write.wait(timeout=5):+ raise RuntimeError("timed out waiting to release write")+ original_write_model(model_id, config_yaml)++ monkeypatch.setattr(self.app.state.config_store, "write_model", blocking_write_model)++ transport = httpx.ASGITransport(app=self.app)+ async with httpx.AsyncClient(transport=transport, base_url="http://t") as ac:+ owner = asyncio.create_task(+ ac.post("/v1/configs/models", content=owner_body, headers={"Idempotency-Key": "K-mismatch"})+ )+ await asyncio.wait_for(write_started.wait(), timeout=1)++ try:+ mismatch = await asyncio.wait_for(+ ac.post(+ "/v1/configs/models",+ content=mismatch_body,+ headers={"Idempotency-Key": "K-mismatch"},+ ),+ timeout=1,+ )+ assert mismatch.status_code == 422, mismatch.text+ assert mismatch.json()["detail"]["error"] == "idempotency_mismatch"+ finally:+ release_write.set()++ owner_resp = await asyncio.wait_for(owner, timeout=1)+ assert owner_resp.status_code == 201, owner_resp.text+ assert calls == ["idem/concurrent-mismatch-a"]++ asyncio.run(run())+ assert self.client.get("/v1/configs/epoch").json()["epoch"] == 1++ def test_concurrent_same_key_waiter_gets_owner_failure(self, monkeypatch) -> None:+ body = (+ "sie_id: idem/concurrent-failure\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bert_flash:A\n"+ " max_batch_tokens: 1\n"+ )+ release_write = threading.Event()+ calls: list[str] = []++ async def run() -> None:+ loop = asyncio.get_running_loop()+ write_started = asyncio.Event()++ def failing_write_model(model_id: str, _config_yaml: str) -> None:+ calls.append(model_id)+ loop.call_soon_threadsafe(write_started.set)+ if not release_write.wait(timeout=5):+ raise RuntimeError("timed out waiting to release write")+ raise RuntimeError("injected store write failure")++ monkeypatch.setattr(self.app.state.config_store, "write_model", failing_write_model)++ transport = httpx.ASGITransport(app=self.app, raise_app_exceptions=False)+ async with httpx.AsyncClient(transport=transport, base_url="http://t") as ac:+ owner = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-failure"})+ )+ await asyncio.wait_for(write_started.wait(), timeout=1)++ waiter = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-failure"})+ )+ await asyncio.sleep(0.05)+ assert not waiter.done(), "same-key request did not wait on the in-flight owner"++ release_write.set()+ owner_resp, waiter_resp = await asyncio.gather(owner, waiter)++ assert owner_resp.status_code == 500, owner_resp.text+ assert waiter_resp.status_code == 500, waiter_resp.text+ assert "idempotent_replay_evicted" not in waiter_resp.text+ assert calls == ["idem/concurrent-failure"]++ asyncio.run(run())+ assert self.client.get("/v1/configs/epoch").json()["epoch"] == 0++ def test_waiter_reports_failed_owner_even_if_later_retry_starts_first(self, monkeypatch) -> None:+ body = (+ "sie_id: idem/concurrent-failure-retry\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bert_flash:A\n"+ " max_batch_tokens: 1\n"+ )+ original_write_model = self.app.state.config_store.write_model+ release_first_write = threading.Event()+ calls: list[str] = []+ call_lock = threading.Lock()++ async def run() -> None:+ loop = asyncio.get_running_loop()+ write_started = asyncio.Event()+ write_failed = asyncio.Event()++ def first_write_fails(model_id: str, config_yaml: str) -> None:+ with call_lock:+ calls.append(model_id)+ call_index = len(calls)+ if call_index == 1:+ loop.call_soon_threadsafe(write_started.set)+ if not release_first_write.wait(timeout=5):+ raise RuntimeError("timed out waiting to release failed write")+ loop.call_soon_threadsafe(write_failed.set)+ raise RuntimeError("injected first store write failure")+ original_write_model(model_id, config_yaml)++ monkeypatch.setattr(self.app.state.config_store, "write_model", first_write_fails)++ transport = httpx.ASGITransport(app=self.app, raise_app_exceptions=False)+ async with httpx.AsyncClient(transport=transport, base_url="http://t") as ac:+ owner = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-fail-retry"})+ )+ await asyncio.wait_for(write_started.wait(), timeout=1)++ waiter = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-fail-retry"})+ )+ await asyncio.sleep(0.05)+ assert not waiter.done(), "same-key request did not wait on the in-flight owner"++ idem = self.app.state._config_idempotency_state+ await idem.lock.acquire()+ try:+ release_first_write.set()+ await asyncio.wait_for(write_failed.wait(), timeout=1)+ await asyncio.sleep(0.05)+ retry = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-fail-retry"})+ )+ await asyncio.sleep(0.05)+ finally:+ idem.lock.release()++ owner_resp, waiter_resp, retry_resp = await asyncio.gather(owner, waiter, retry)++ assert owner_resp.status_code == 500, owner_resp.text+ assert waiter_resp.status_code == 500, waiter_resp.text+ assert "idempotent_replay_evicted" not in waiter_resp.text+ assert retry_resp.status_code == 201, retry_resp.text+ assert calls == ["idem/concurrent-failure-retry", "idem/concurrent-failure-retry"]++ asyncio.run(run())+ assert self.client.get("/v1/configs/epoch").json()["epoch"] == 1++ def test_concurrent_same_key_cancellation_waits_for_durable_outcome(self, monkeypatch) -> None:+ body = (+ "sie_id: idem/concurrent-cancel\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bert_flash:A\n"+ " max_batch_tokens: 1\n"+ )+ original_write_model = self.app.state.config_store.write_model+ release_write = threading.Event()+ calls: list[str] = []+ call_lock = threading.Lock()++ async def run() -> None:+ loop = asyncio.get_running_loop()+ write_started = asyncio.Event()++ def slow_write_model(model_id: str, config_yaml: str) -> None:+ with call_lock:+ calls.append(model_id)+ call_index = len(calls)+ if call_index == 1:+ loop.call_soon_threadsafe(write_started.set)+ if not release_write.wait(timeout=5):+ raise RuntimeError("timed out waiting to release cancelled write")+ original_write_model(model_id, config_yaml)++ monkeypatch.setattr(self.app.state.config_store, "write_model", slow_write_model)++ transport = httpx.ASGITransport(app=self.app)+ async with httpx.AsyncClient(transport=transport, base_url="http://t") as ac:+ owner = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-cancel"})+ )+ await asyncio.wait_for(write_started.wait(), timeout=1)++ waiter = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-cancel"})+ )+ await asyncio.sleep(0.05)+ assert not waiter.done(), "same-key request did not wait on the in-flight owner"++ owner.cancel()+ await asyncio.sleep(0.05)+ assert not owner.done(), "cancelled owner returned before the store write finished"+ assert not waiter.done(), "waiter returned before the owner published its durable outcome"+ release_write.set()++ try:+ owner_result = await asyncio.wait_for(owner, timeout=1)+ except asyncio.CancelledError:+ pass+ else:+ pytest.fail(f"cancelled owner unexpectedly returned {owner_result!r}")++ waiter_resp = await asyncio.wait_for(waiter, timeout=1)+ assert waiter_resp.status_code == 201, waiter_resp.text++ retry_resp = await ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-cancel"})+ assert retry_resp.status_code == 201, retry_resp.text+ assert retry_resp.json() == waiter_resp.json()++ asyncio.run(run())+ assert calls == ["idem/concurrent-cancel"]+ assert self.client.get("/v1/configs/epoch").json()["epoch"] == 1++ def test_pre_commit_cancellation_cleanup_survives_second_cancel(self, monkeypatch) -> None:+ body = (+ "sie_id: idem/pre-commit-cancel\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.bert_flash:A\n"+ " max_batch_tokens: 1\n"+ )+ original_read_model = self.app.state.config_store.read_model+ release_read = threading.Event()+ calls: list[str] = []++ async def run() -> None:+ loop = asyncio.get_running_loop()+ read_started = asyncio.Event()++ def blocking_read_model(model_id: str) -> str | None:+ calls.append(model_id)+ loop.call_soon_threadsafe(read_started.set)+ if not release_read.wait(timeout=5):+ raise RuntimeError("timed out waiting to release read")+ return original_read_model(model_id)++ monkeypatch.setattr(self.app.state.config_store, "read_model", blocking_read_model)++ transport = httpx.ASGITransport(app=self.app)+ async with httpx.AsyncClient(transport=transport, base_url="http://t") as ac:+ owner = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-pre-cancel"})+ )+ await asyncio.wait_for(read_started.wait(), timeout=1)++ waiter = asyncio.create_task(+ ac.post("/v1/configs/models", content=body, headers={"Idempotency-Key": "K-pre-cancel"})+ )+ await asyncio.sleep(0.05)+ assert not waiter.done(), "same-key request did not wait on the in-flight owner"++ idem = self.app.state._config_idempotency_state+ await idem.lock.acquire()+ try:+ owner.cancel()+ await asyncio.sleep(0.05)+ assert not owner.done(), "owner cleanup finished while idempotency lock was held"+ assert not waiter.done(), "waiter returned before cancellation cleanup completed"++ owner.cancel()+ await asyncio.sleep(0.05)+ assert not owner.done(), "second cancellation interrupted idempotency cleanup"+ assert not waiter.done(), "second cancellation left waiter with a partial outcome"+ finally:+ idem.lock.release()+ release_read.set()++ try:+ owner_result = await asyncio.wait_for(owner, timeout=1)+ except asyncio.CancelledError:+ pass+ else:+ pytest.fail(f"cancelled owner unexpectedly returned {owner_result!r}")++ waiter_resp = await asyncio.wait_for(waiter, timeout=1)+ assert waiter_resp.status_code == 503, waiter_resp.text+ assert waiter_resp.json()["detail"]["error"] == "idempotent_inflight_cancelled"++ asyncio.run(run())+ assert calls == ["idem/pre-commit-cancel"]+ assert self.client.get("/v1/configs/epoch").json()["epoch"] == 0+def test_concurrent_writes_serialize_and_bump_epoch_once_each(self) -> None:# Real concurrent-write regression: fire off N POSTs from the same# async event loop and assert (a) every write succeeded, (b) the@@ -1030,10 +1550,6 @@ class TestIdempotencyEvictionSafety:# — without the lock, two concurrent `increment_epoch` calls both# read N, both write N+1, and the final epoch would be N+1 instead# of N+M.- import asyncio-- import httpx-async def run() -> None:transport = httpx.ASGITransport(app=self.app)async with httpx.AsyncClient(transport=transport, base_url="http://t") as ac:@@ -1076,10 +1592,6 @@ class TestIdempotencyEvictionSafety:# snapshot's `epoch` never exceeds `len(models_in_snapshot) -# preseed_count` (each successful write bumps the epoch once and# adds exactly one model).- import asyncio-- import httpx-async def run() -> None:transport = httpx.ASGITransport(app=self.app)async with httpx.AsyncClient(transport=transport, base_url="http://t") as ac:diff --git a/packages/sie_config/tests/test_config_store.py b/packages/sie_config/tests/test_config_store.pyindex e355b7309..70e5745d3 100644--- a/packages/sie_config/tests/test_config_store.py+++ b/packages/sie_config/tests/test_config_store.py@@ -30,6 +30,14 @@ class TestConfigStore:assert self.store.increment_epoch() == 2assert self.store.increment_epoch() == 3+ def test_read_epoch_returns_zero_for_empty_file(self) -> None:+ (Path(self.store.base_dir) / "epoch").write_text("")+ assert self.store.read_epoch() == 0++ def test_read_epoch_returns_zero_for_corrupt_file(self) -> None:+ (Path(self.store.base_dir) / "epoch").write_text("not-an-int")+ assert self.store.read_epoch() == 0+def test_write_and_read_model(self) -> None:yaml_content = "sie_id: BAAI/bge-m3\nhf_id: BAAI/bge-m3\n"self.store.write_model("BAAI/bge-m3", yaml_content)diff --git a/packages/sie_config/tests/test_model_registry.py b/packages/sie_config/tests/test_model_registry.pyindex 04c2bd6a3..a7ec5f0ce 100644--- a/packages/sie_config/tests/test_model_registry.py+++ b/packages/sie_config/tests/test_model_registry.py@@ -330,13 +330,92 @@ class TestModelRegistryAdapterMatching:"name: sglang\npriority: 20\nadapters:\n - sie_server.adapters.sglang\n")(models_dir / "multi.yaml").write_text(- "name: multi/model\nprofiles:\n cpu:\n adapter_path: sie_server.adapters.sentence_transformer:STAdapter\n gpu:\n adapter_path: sie_server.adapters.sglang:SGLangAdapter\n"+ "name: multi/model\nprofiles:\n default:\n adapter_path: sie_server.adapters.sentence_transformer:STAdapter\n gpu:\n adapter_path: sie_server.adapters.sglang:SGLangAdapter\n")registry = ModelRegistry(bundles_dir, models_dir)info = registry.get_model_info("multi/model")assert info is not None- assert "default" in info.bundles- assert "sglang" in info.bundles+ assert info.bundles == ["default"]+ variant = registry.get_model_info("multi/model:gpu")+ assert variant is not None+ assert variant.bundles == ["sglang"]++ def test_profile_variant_routes_through_profile_adapter(self) -> None:+ with tempfile.TemporaryDirectory() as tmpdir:+ tmppath = Path(tmpdir)+ bundles_dir = tmppath / "bundles"+ models_dir = tmppath / "models"+ bundles_dir.mkdir()+ models_dir.mkdir()+ (bundles_dir / "default.yaml").write_text(+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.sentence_transformer\n"+ )+ (bundles_dir / "candle.yaml").write_text(+ "name: candle\npriority: 30\nengine: candle\nadapters:\n - sie_server_rust.adapters.candle\n"+ )+ (models_dir / "dual.yaml").write_text(+ "sie_id: dual/model\n"+ "profiles:\n"+ " default:\n"+ " adapter_path: sie_server.adapters.sentence_transformer:STAdapter\n"+ " candle:\n"+ " adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter\n"+ )++ registry = ModelRegistry(bundles_dir, models_dir)++ assert registry.resolve_bundle("dual/model") == "default"+ base = registry.get_model_info("dual/model")+ assert base is not None+ assert base.bundles == ["default"]+ assert registry.get_model_profile_bundles("dual/model") == {+ "candle": ["candle"],+ "default": ["default"],+ }+ assert registry.get_model_export_bundles("dual/model") == ["default", "candle"]++ assert registry.model_exists("dual/model:candle")+ assert "dual/model:candle" not in registry.list_models()+ variant = registry.get_model_info("dual/model:candle")+ assert variant is not None+ assert variant.bundles == ["candle"]+ assert registry.get_model_profile_names("dual/model:candle") == {"default"}+ assert registry.resolve_bundle("dual/model:candle") == "candle"+ assert "dual/model:candle" in registry.get_models_for_bundle("candle")+ assert registry.list_serving_models() == ["dual/model", "dual/model:candle"]+ assert registry.get_catalog_model_name("dual/model:candle") == "dual/model"+ assert registry.get_route_profile_names("dual/model:candle") == {"candle"}++ with pytest.raises(BundleConflictError) as exc_info:+ registry.resolve_bundle("dual/model:candle", bundle_override="default")+ assert exc_info.value.compatible_bundles == ["candle"]++ def test_profile_only_candle_model_list_exposes_variant_route(self) -> None:+ with tempfile.TemporaryDirectory() as tmpdir:+ tmppath = Path(tmpdir)+ bundles_dir = tmppath / "bundles"+ models_dir = tmppath / "models"+ bundles_dir.mkdir()+ models_dir.mkdir()+ (bundles_dir / "candle.yaml").write_text(+ "name: candle\npriority: 30\nengine: candle\nadapters:\n - sie_server_rust.adapters.candle\n"+ )+ (models_dir / "candle-only.yaml").write_text(+ "sie_id: org/candle-only\n"+ "profiles:\n"+ " candle:\n"+ " adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter\n"+ )++ registry = ModelRegistry(bundles_dir, models_dir)++ assert registry.list_models() == ["org/candle-only"]+ assert registry.list_serving_models() == ["org/candle-only:candle"]+ with pytest.raises(ModelNotFoundError):+ registry.resolve_bundle("org/candle-only")+ assert registry.resolve_bundle("org/candle-only:candle") == "candle"+ assert registry.get_catalog_model_name("org/candle-only:candle") == "org/candle-only"+ assert registry.get_route_profile_names("org/candle-only:candle") == {"candle"}class TestModelRegistryThreadSafety:@@ -671,7 +750,7 @@ class TestUnrouteableModelsSurface:(models_dir / "mixed.yaml").write_text("sie_id: mixed/model\n""profiles:\n"- " cpu:\n"+ " default:\n"" adapter_path: sie_server.adapters.good:Adapter\n"" gpu:\n"" adapter_path: sie_server.adapters.missing:Adapter\n"@@ -796,7 +875,7 @@ class TestEngineField:for rec in caplog.records)- def test_engine_namespace_mismatch_is_warned_but_loads(self, caplog: pytest.LogCaptureFixture) -> None:+ def test_engine_namespace_mismatch_is_rejected(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(@@ -805,19 +884,18 @@ class TestEngineField:"priority: 10\n""adapters:\n"" - sie_server.adapters.bert_flash\n"- " - some_unrelated.module\n"+ " - sie_server_rust.adapters.candle\n")- with caplog.at_level(logging.WARNING, logger="sie_config.model_registry"):+ with caplog.at_level(logging.ERROR, 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 info is Noneassert any(- rec.levelname == "WARNING" and "some_unrelated.module" in rec.getMessage() for rec in caplog.records+ rec.levelname == "ERROR" and "sie_server_rust.adapters.candle" in rec.getMessage()+ for rec in caplog.records)- def test_known_engines_only_pytorch(self) -> None:- assert frozenset({"pytorch"}) == KNOWN_ENGINES+ def test_known_engines_include_candle(self) -> None:+ assert frozenset({"pytorch", "candle"}) == KNOWN_ENGINESdiff --git a/packages/sie_config/tests/test_model_registry_mutation.py b/packages/sie_config/tests/test_model_registry_mutation.pyindex 5d85e0e5b..bca6f76d9 100644--- a/packages/sie_config/tests/test_model_registry_mutation.py+++ b/packages/sie_config/tests/test_model_registry_mutation.py@@ -20,6 +20,8 @@ def _setup_registry(for name, adapters in bundles.items():data = {"name": name, "priority": 10, "adapters": adapters}+ if any(adapter.startswith("sie_server_rust.adapters.candle") for adapter in adapters):+ data["engine"] = "candle"(bundles_dir / f"{name}.yaml").write_text(yaml.dump(data))if models:@@ -259,6 +261,37 @@ class TestAddModelConfig:bundle = registry.resolve_bundle("sglang/model")assert bundle == "sglang"+ def test_append_profile_creates_profile_variant_route(self) -> None:+ registry, _ = _setup_registry(+ self._root / "profile_variant",+ bundles={+ "default": ["sie_server.adapters.bert_flash"],+ "candle": ["sie_server_rust.adapters.candle"],+ },+ models={"existing/model": "sie_server.adapters.bert_flash:B"},+ )++ created, skipped, bundles = registry.add_model_config(+ {+ "sie_id": "existing/model",+ "profiles": {+ "candle": {+ "adapter_path": "sie_server_rust.adapters.candle:CandleEmbeddingAdapter",+ "max_batch_tokens": 8192,+ },+ },+ }+ )++ assert created == ["candle"]+ assert skipped == []+ assert set(bundles) == {"default", "candle"}+ assert registry.resolve_bundle("existing/model") == "default"+ assert registry.resolve_bundle("existing/model:candle") == "candle"+ variant = registry.get_model_info("existing/model:candle")+ assert variant is not None+ assert variant.bundles == ["candle"]+class TestGetFullConfig:"""Covers the in-memory full-config snapshot used by `/v1/configs/export`@@ -436,6 +469,36 @@ class TestComputeBundleConfigHash:h2 = registry.compute_bundle_config_hash("default")assert h1 == h2+ def test_hash_preserves_falsy_adapter_options(self) -> None:+ with_false, _ = _setup_registry(self._root / "falsy_false")+ with_false.add_model_config(+ {+ "sie_id": "m1",+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.bert_flash:B",+ "max_batch_tokens": 1,+ "adapter_options": {"runtime": {"normalize": False, "truncate_to": 0}},+ }+ },+ }+ )+ without_options, _ = _setup_registry(self._root / "falsy_empty")+ without_options.add_model_config(+ {+ "sie_id": "m1",+ "profiles": {+ "default": {+ "adapter_path": "sie_server.adapters.bert_flash:B",+ "max_batch_tokens": 1,+ "adapter_options": {"runtime": {}},+ }+ },+ }+ )++ assert with_false.compute_bundle_config_hash("default") != without_options.compute_bundle_config_hash("default")+def test_hash_scoped_to_bundle(self) -> None:registry, _ = _setup_registry(self._root / "scoped",diff --git a/packages/sie_config/tests/test_nats_publisher.py b/packages/sie_config/tests/test_nats_publisher.pyindex e617496e7..578e4523f 100644--- a/packages/sie_config/tests/test_nats_publisher.py+++ b/packages/sie_config/tests/test_nats_publisher.py@@ -133,10 +133,8 @@ class TestNatsPublisherPublish:@pytest.mark.asyncioasync def test_publish_payload_matches_rust_contract(self) -> None:- """Each publish carries the full ConfigNotification shape expected by- ``sie_gateway/src/nats/manager.rs::ConfigNotification``: router_id,- bundle_id, epoch, bundle_config_hash, model_id, profiles_added,- model_config, affected_bundles.+ """Each publish carries the ConfigNotification superset consumed by+ the gateway and worker sidecars."""publisher = NatsPublisher()mock_nc = AsyncMock()@@ -156,10 +154,12 @@ class TestNatsPublisherPublish:"bundle_id","epoch","bundle_config_hash",+ "bundle_pool_config_hashes","model_id","profiles_added","model_config","affected_bundles",+ "pool",}for call in mock_nc.publish.call_args_list:payload = json.loads(call.args[1].decode())@@ -170,6 +170,8 @@ class TestNatsPublisherPublish:assert payload["router_id"] == publisher.router_idassert payload["model_config"] == "full yaml content"assert payload["affected_bundles"] == ["default", "sglang"]+ assert payload["pool"] == "default"+ assert payload["bundle_pool_config_hashes"] == {}@pytest.mark.asyncioasync def test_publish_bundle_subject_carries_its_own_hash(self) -> None:@@ -197,6 +199,34 @@ class TestNatsPublisherPublish:assert bundle_payloads["sie.config.models.sglang"]["bundle_id"] == "sglang"assert bundle_payloads["sie.config.models.sglang"]["bundle_config_hash"] == "hash2"+ @pytest.mark.asyncio+ async def test_publish_payload_carries_pool_hashes_for_workers(self) -> None:+ publisher = NatsPublisher()+ mock_nc = AsyncMock()+ mock_nc.is_connected = True+ publisher._nc = mock_nc+ publisher._connected = True+ await publisher.publish_config_notification(+ model_id="org/model",+ profiles_added=["candle"],+ affected_bundles=["candle"],+ bundle_config_hashes={"candle": "global-hash"},+ epoch=8,+ model_config_yaml="yaml",+ model_pool="Customer-A",+ bundle_pool_config_hashes={+ "candle": {+ "default": "default-hash",+ "customer-a": "tenant-hash",+ }+ },+ )++ payload = json.loads(mock_nc.publish.call_args_list[0].args[1].decode())+ assert payload["pool"] == "customer-a"+ assert payload["bundle_config_hash"] == "global-hash"+ assert payload["bundle_pool_config_hashes"]["candle"]["customer-a"] == "tenant-hash"+@pytest.mark.asyncioasync def test_publish_all_payload_matches_paired_bundle_payload(self) -> None:"""The payload sent to _all for a given bundle is byte-identical to thediff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lockindex cc5bedd3b..d762ac7d9 100644--- a/packages/sie_gateway/Cargo.lock+++ b/packages/sie_gateway/Cargo.lock@@ -39,6 +39,17 @@ dependencies = ["libc",]+[[package]]+name = "annotate-snippets"+version = "0.12.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f211a51805bc641f3ad5b7664c77d2547af685cc33b4cd8d31964027a46f13f1"+dependencies = [+ "anstyle",+ "memchr",+ "unicode-width",+]+[[package]]name = "anstream"version = "1.0.0"@@ -91,19 +102,25 @@ dependencies = [[[package]]name = "anyhow"-version = "1.0.102"+version = "1.0.103"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"+checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"[[package]]name = "arc-swap"-version = "1.9.1"+version = "1.9.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6a3a1fd6f75306b68087b831f025c712524bcb19aad54e557b1129cfa0a2b207"+checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b"dependencies = ["rustversion",]+[[package]]+name = "arraydeque"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"+[[package]]name = "assert-json-diff"version = "2.0.2"@@ -128,9 +145,9 @@ dependencies = [[[package]]name = "async-nats"-version = "0.49.0"+version = "0.49.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "407486109ea5cfdf53fde05f46996dadf0547518a4d49f050d25f405ae31ed2d"+checksum = "fad3cd6df81292728e2a8cb1f1dcb4d7e7a1ab59b80c14fbbcba2baf9d5cf86a"dependencies = ["base64","bytes",@@ -143,7 +160,7 @@ dependencies = ["rand 0.10.1","regex","ring",- "rustls-native-certs 0.8.4",+ "rustls-native-certs","rustls-pki-types","rustls-webpki","serde",@@ -208,30 +225,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"[[package]]-name = "axum"-version = "0.7.9"+name = "aws-lc-rs"+version = "1.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f"+checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00"dependencies = [- "async-trait",- "axum-core 0.4.5",- "bytes",- "futures-util",- "http",- "http-body",- "http-body-util",- "itoa",- "matchit 0.7.3",- "memchr",- "mime",- "percent-encoding",- "pin-project-lite",- "rustversion",- "serde",- "sync_wrapper",- "tower 0.5.3",- "tower-layer",- "tower-service",+ "aws-lc-sys",+ "zeroize",+]++[[package]]+name = "aws-lc-sys"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4"+dependencies = [+ "cc",+ "cmake",+ "dunce",+ "fs_extra",][[package]]@@ -240,7 +252,7 @@ version = "0.8.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"dependencies = [- "axum-core 0.5.6",+ "axum-core","base64","bytes","form_urlencoded",@@ -251,7 +263,7 @@ dependencies = ["hyper","hyper-util","itoa",- "matchit 0.8.4",+ "matchit","memchr","mime","percent-encoding",@@ -263,33 +275,13 @@ dependencies = ["sha1","sync_wrapper","tokio",- "tokio-tungstenite 0.29.0",- "tower 0.5.3",+ "tokio-tungstenite",+ "tower","tower-layer","tower-service","tracing",]-[[package]]-name = "axum-core"-version = "0.4.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199"-dependencies = [- "async-trait",- "bytes",- "futures-util",- "http",- "http-body",- "http-body-util",- "mime",- "pin-project-lite",- "rustversion",- "sync_wrapper",- "tower-layer",- "tower-service",-]-[[package]]name = "axum-core"version = "0.5.6"@@ -310,14 +302,14 @@ dependencies = [][[package]]-name = "backoff"-version = "0.4.0"+name = "backon"+version = "1.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b62ddb9cb1ec0a098ad4bbf9344d0713fa193ae1a80af55febcff2627b6a00c1"+checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef"dependencies = [- "getrandom 0.2.17",- "instant",- "rand 0.8.6",+ "fastrand",+ "gloo-timers",+ "tokio",][[package]]@@ -340,9 +332,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"[[package]]name = "bitflags"-version = "2.12.1"+version = "2.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "84d7ced0ae9557296835c32bf1b1e02b44c746701f898460fb000d7eaa84f00a"+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"[[package]]name = "block-buffer"@@ -353,6 +345,15 @@ dependencies = ["generic-array",]+[[package]]+name = "block-buffer"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"+dependencies = [+ "hybrid-array",+]+[[package]]name = "bumpalo"version = "3.20.3"@@ -361,20 +362,22 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"[[package]]name = "bytes"-version = "1.11.1"+version = "1.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"+checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"dependencies = ["serde",][[package]]name = "cc"-version = "1.2.63"+version = "1.2.65"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f"+checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96"dependencies = ["find-msvc-tools",+ "jobserver",+ "libc","shlex",]@@ -392,9 +395,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"[[package]]name = "chacha20"-version = "0.10.0"+version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"dependencies = ["cfg-if","cpufeatures 0.3.0",@@ -403,15 +406,13 @@ dependencies = [[[package]]name = "chrono"-version = "0.4.44"+version = "0.4.45"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"dependencies = ["iana-time-zone",- "js-sys","num-traits","serde",- "wasm-bindgen","windows-link",]@@ -455,12 +456,31 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"+[[package]]+name = "cmake"+version = "0.1.58"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"+dependencies = [+ "cc",+]+[[package]]name = "colorchoice"version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"+[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]+[[package]]name = "concurrent-queue"version = "2.5.0"@@ -477,14 +497,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"[[package]]-name = "core-foundation"-version = "0.9.4"+name = "const-oid"+version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"-dependencies = [- "core-foundation-sys",- "libc",-]+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"[[package]]name = "core-foundation"@@ -521,12 +537,13 @@ dependencies = [][[package]]-name = "crossbeam-channel"-version = "0.5.15"+name = "crc-fast"+version = "1.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2"+checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5"dependencies = [- "crossbeam-utils",+ "digest 0.10.7",+ "spin",][[package]]@@ -545,6 +562,15 @@ dependencies = ["typenum",]+[[package]]+name = "crypto-common"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"+dependencies = [+ "hybrid-array",+]+[[package]]name = "curve25519-dalek"version = "4.1.3"@@ -554,7 +580,7 @@ dependencies = ["cfg-if","cpufeatures 0.2.17","curve25519-dalek-derive",- "digest",+ "digest 0.10.7","fiat-crypto","rustc_version","subtle",@@ -573,9 +599,9 @@ dependencies = [[[package]]name = "darling"-version = "0.20.11"+version = "0.23.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"+checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"dependencies = ["darling_core","darling_macro",@@ -583,11 +609,10 @@ dependencies = [[[package]]name = "darling_core"-version = "0.20.11"+version = "0.23.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"+checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"dependencies = [- "fnv","ident_case","proc-macro2","quote",@@ -597,9 +622,9 @@ dependencies = [[[package]]name = "darling_macro"-version = "0.20.11"+version = "0.23.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"+checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"dependencies = ["darling_core","quote",@@ -644,13 +669,45 @@ version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "092966b41edc516079bdf31ec78a2e0588d1d0c08f78b91d8307215928642b2b"+[[package]]+name = "defmt"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6e524506490a1953d237cb87b1cfc1e46f88c18f10a22dfe0f507dc6bfc7f7f"+dependencies = [+ "bitflags 1.3.2",+ "defmt-macros",+]++[[package]]+name = "defmt-macros"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0a27770e9c8f719a79d8b638281f4d828f77d8fd61e0bd94451b9b85e576a0b"+dependencies = [+ "defmt-parser",+ "proc-macro-error2",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "defmt-parser"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"+dependencies = [+ "thiserror 2.0.18",+]+[[package]]name = "der"version = "0.7.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"dependencies = [- "const-oid",+ "const-oid 0.9.6","pem-rfc7468","zeroize",]@@ -661,18 +718,49 @@ version = "0.5.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"dependencies = [- "powerfmt","serde_core",]+[[package]]+name = "derive_more"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"+dependencies = [+ "derive_more-impl",+]++[[package]]+name = "derive_more-impl"+version = "2.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "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",+ "block-buffer 0.10.4",+ "crypto-common 0.1.7",+]++[[package]]+name = "digest"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"+dependencies = [+ "block-buffer 0.12.1",+ "const-oid 0.10.2",+ "crypto-common 0.2.2",][[package]]@@ -686,6 +774,12 @@ dependencies = ["syn",]+[[package]]+name = "dunce"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"+[[package]]name = "dyn-clone"version = "1.0.20"@@ -709,7 +803,7 @@ checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"dependencies = ["curve25519-dalek","ed25519",- "sha2",+ "sha2 0.10.9","signature","subtle",]@@ -732,20 +826,38 @@ version = "1.16.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"+[[package]]+name = "encoding_rs"+version = "0.8.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"+dependencies = [+ "cfg-if",+]++[[package]]+name = "encoding_rs_io"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1cc3c5651fb62ab8aa3103998dade57efdd028544bd300516baa31840c252a83"+dependencies = [+ "encoding_rs",+]+[[package]]name = "enum-ordinalize"-version = "4.3.2"+version = "4.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4a1091a7bb1f8f2c4b28f1fe2cef4980ca2d410a3d727d67ecc3178c9b0800f0"+checksum = "07f808d588c10e464ea6f7d3eaed500049eff30aaac103460f61828c2d65b3eb"dependencies = ["enum-ordinalize-derive",][[package]]name = "enum-ordinalize-derive"-version = "4.3.2"+version = "4.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8ca9601fb2d62598ee17836250842873a413586e5d7ed88b356e38ddbb0ec631"+checksum = "42e528e2d34ba8a67a1a650b86beae8ef69fc5fdb638016f386b973226590432"dependencies = ["proc-macro2","quote",@@ -801,16 +913,6 @@ version = "0.2.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"-[[package]]-name = "filetime"-version = "0.2.29"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"-dependencies = [- "cfg-if",- "libc",-]-[[package]]name = "find-msvc-tools"version = "0.1.9"@@ -825,9 +927,9 @@ checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"[[package]]name = "foldhash"-version = "0.1.5"+version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"[[package]]name = "form_urlencoded"@@ -848,6 +950,12 @@ dependencies = ["winapi",]+[[package]]+name = "fs_extra"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"+[[package]]name = "fsevent-sys"version = "4.1.0"@@ -984,29 +1092,43 @@ dependencies = [[[package]]name = "getrandom"-version = "0.4.2"+version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"dependencies = ["cfg-if","libc","r-efi 6.0.0","rand_core 0.10.1",- "wasip2",- "wasip3",][[package]]-name = "glob"-version = "0.3.3"+name = "gloo-timers"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994"+dependencies = [+ "futures-channel",+ "futures-core",+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "granit-parser"+version = "0.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"+checksum = "f50ba32164f9e098d5da618776a32afbb32270adcbe3d3d006107dae11e37c91"+dependencies = [+ "arraydeque",+ "smallvec",+][[package]]name = "h2"-version = "0.4.14"+version = "0.4.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733"+checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155"dependencies = ["atomic-waker","bytes",@@ -1014,19 +1136,13 @@ dependencies = ["futures-core","futures-sink","http",- "indexmap 2.14.0",+ "indexmap","slab","tokio","tokio-util","tracing",]-[[package]]-name = "hashbrown"-version = "0.12.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"-[[package]]name = "hashbrown"version = "0.14.5"@@ -1035,9 +1151,9 @@ checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"[[package]]name = "hashbrown"-version = "0.15.5"+version = "0.16.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"dependencies = ["allocator-api2","equivalent",@@ -1050,30 +1166,6 @@ version = "0.17.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"-[[package]]-name = "headers"-version = "0.4.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb"-dependencies = [- "base64",- "bytes",- "headers-core",- "http",- "httpdate",- "mime",- "sha1",-]--[[package]]-name = "headers-core"-version = "0.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4"-dependencies = [- "http",-]-[[package]]name = "heck"version = "0.5.0"@@ -1092,15 +1184,6 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"-[[package]]-name = "home"-version = "0.5.12"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"-dependencies = [- "windows-sys 0.61.2",-]-[[package]]name = "hostname"version = "0.4.2"@@ -1114,9 +1197,9 @@ dependencies = [[[package]]name = "http"-version = "1.4.1"+version = "1.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8be7462df143984c4598a256ef469b251d7d7f9e271135073e78fc535414f3d0"+checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"dependencies = ["bytes","itoa",@@ -1163,6 +1246,15 @@ version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"+[[package]]+name = "hybrid-array"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c"+dependencies = [+ "typenum",+]+[[package]]name = "hyper"version = "1.10.1"@@ -1185,26 +1277,6 @@ dependencies = ["want",]-[[package]]-name = "hyper-http-proxy"-version = "1.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7ad4b0a1e37510028bc4ba81d0e38d239c39671b0f0ce9e02dfa93a8133f7c08"-dependencies = [- "bytes",- "futures-util",- "headers",- "http",- "hyper",- "hyper-rustls",- "hyper-util",- "pin-project-lite",- "rustls-native-certs 0.7.3",- "tokio",- "tokio-rustls",- "tower-service",-]-[[package]]name = "hyper-rustls"version = "0.27.9"@@ -1216,11 +1288,10 @@ dependencies = ["hyper-util","log","rustls",- "rustls-native-certs 0.8.4",+ "rustls-native-certs","tokio","tokio-rustls","tower-service",- "webpki-roots 1.0.7",][[package]]@@ -1253,7 +1324,7 @@ dependencies = ["libc","percent-encoding","pin-project-lite",- "socket2 0.6.4",+ "socket2","tokio","tower-service","tracing",@@ -1365,12 +1436,6 @@ dependencies = ["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"@@ -1398,16 +1463,6 @@ dependencies = ["icu_properties",]-[[package]]-name = "indexmap"-version = "1.9.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"-dependencies = [- "autocfg",- "hashbrown 0.12.3",-]-[[package]]name = "indexmap"version = "2.14.0"@@ -1422,11 +1477,11 @@ dependencies = [[[package]]name = "inotify"-version = "0.9.6"+version = "0.11.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8069d3ec154eb856955c1c0fbffefbf5f3c40a104ec912d4797314c1801abff"+checksum = "533e68a5842e734946fe159fb03fc9bbbb254f590dd0d8ad321ae5ff7beca2c1"dependencies = [- "bitflags 1.3.2",+ "bitflags 2.13.0","inotify-sys","libc",]@@ -1440,15 +1495,6 @@ dependencies = ["libc",]-[[package]]-name = "instant"-version = "0.1.13"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222"-dependencies = [- "cfg-if",-]-[[package]]name = "ipnet"version = "2.12.0"@@ -1463,18 +1509,18 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"[[package]]name = "itertools"-version = "0.13.0"+version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"dependencies = ["either",][[package]]name = "itertools"-version = "0.14.0"+version = "0.15.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"dependencies = ["either",]@@ -1485,35 +1531,118 @@ version = "1.0.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"+[[package]]+name = "jiff"+version = "0.2.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccfe6121cbe750cf81efa362d85c0bde7ea298ec43092d3a193baca59cdbd634"+dependencies = [+ "defmt",+ "jiff-static",+ "log",+ "portable-atomic",+ "portable-atomic-util",+ "serde_core",+]++[[package]]+name = "jiff-static"+version = "0.2.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e165e897f662d428f3cd3828a919dbe067c2d42bb1031eede74ef9d27ecdedd2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "jni"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"+dependencies = [+ "cfg-if",+ "combine",+ "jni-macros",+ "jni-sys",+ "log",+ "simd_cesu8",+ "thiserror 2.0.18",+ "walkdir",+ "windows-link",+]++[[package]]+name = "jni-macros"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "simd_cesu8",+ "syn",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn",+]++[[package]]+name = "jobserver"+version = "0.1.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"+dependencies = [+ "getrandom 0.3.4",+ "libc",+]+[[package]]name = "js-sys"-version = "0.3.99"+version = "0.3.103"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11"+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"dependencies = ["cfg-if","futures-util",- "once_cell","wasm-bindgen",][[package]]name = "json-patch"-version = "3.0.1"+version = "4.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "863726d7afb6bc2590eeff7135d923545e5e964f004c2ccf8716c25e70a86f08"+checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72"dependencies = ["jsonptr","serde","serde_json",- "thiserror 1.0.69",+ "thiserror 2.0.18",][[package]]name = "jsonpath-rust"-version = "0.7.5"+version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0c00ae348f9f8fd2d09f82a98ca381c60df9e0820d8d79fce43e649b4dc3128b"+checksum = "633a7320c4bb672863a3782e89b9094ad70285e097ff6832cddd0ec615beadfa"dependencies = ["pest","pest_derive",@@ -1524,9 +1653,9 @@ dependencies = [[[package]]name = "jsonptr"-version = "0.6.3"+version = "0.7.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5dea2b27dd239b2556ed7a25ba842fe47fd602e7fc7433c2a8d6106d4d9edd70"+checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe"dependencies = ["serde","serde_json",@@ -1534,14 +1663,13 @@ dependencies = [[[package]]name = "k8s-openapi"-version = "0.24.0"+version = "0.28.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2c75b990324f09bef15e791606b7b7a296d02fc88a344f6eba9390970a870ad5"+checksum = "d9c6922f6afe80418dd6019818af5d0d34584c371780ff09b9752370c25b4abb"dependencies = ["base64",- "chrono",+ "jiff","serde",- "serde-value","serde_json",]@@ -1561,15 +1689,15 @@ version = "1.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"dependencies = [- "bitflags 2.12.1",+ "bitflags 2.13.0","libc",][[package]]name = "kube"-version = "0.98.0"+version = "4.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "32053dc495efad4d188c7b33cc7c02ef4a6e43038115348348876efd39a53cba"+checksum = "4bb9108095346a7096d11feeaff419c75dddcac1b2f59acb38d7bf3d13c3e146"dependencies = ["k8s-openapi","kube-client",@@ -1580,51 +1708,49 @@ dependencies = [[[package]]name = "kube-client"-version = "0.98.0"+version = "4.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9d34ad38cdfbd1fa87195d42569f57bb1dda6ba5f260ee32fef9570b7937a0c9"+checksum = "d0f628e05bc2264c21fe10d3d675117dc9b43ea3bf4fb07262a222679757537b"dependencies = ["base64","bytes",- "chrono","either","futures",- "home","http","http-body","http-body-util","hyper",- "hyper-http-proxy","hyper-rustls","hyper-timeout","hyper-util",+ "jiff","jsonpath-rust","k8s-openapi","kube-core","pem","rustls",- "rustls-pemfile","secrecy","serde",+ "serde-saphyr","serde_json",- "serde_yaml","thiserror 2.0.18","tokio","tokio-util",- "tower 0.5.3",- "tower-http",+ "tower",+ "tower-http 0.6.11","tracing",][[package]]name = "kube-core"-version = "0.98.0"+version = "4.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "97aa830b288a178a90e784d1b0f1539f2d200d2188c7b4a3146d9dc983d596f3"+checksum = "c1b02f5933ba06140d58c7d6727f6c319f0962ec6a344aa5e21e475e891deaa8"dependencies = [- "chrono",+ "derive_more","form_urlencoded","http",+ "jiff","json-patch","k8s-openapi","schemars",@@ -1636,34 +1762,33 @@ dependencies = [[[package]]name = "kube-derive"-version = "0.98.0"+version = "4.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "37745d8a4076b77e0b1952e94e358726866c8e14ec94baaca677d47dcdb98658"+checksum = "fe171898707dadf1818ef94e81ef57f6beb7edf9ba87b9e814c045dad356c7aa"dependencies = ["darling","proc-macro2","quote",+ "serde","serde_json","syn",][[package]]name = "kube-runtime"-version = "0.98.0"+version = "4.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7a41af186a0fe80c71a13a13994abdc3ebff80859ca6a4b8a6079948328c135b"+checksum = "99ddec66c540c7cf29a5b41fe4a657a53687f95c346e03bdf00585b70a1bab21"dependencies = ["ahash","async-broadcast","async-stream",- "async-trait",- "backoff",+ "backon","educe","futures",- "hashbrown 0.15.5",+ "hashbrown 0.16.1","hostname","json-patch",- "jsonptr","k8s-openapi","kube-client","parking_lot",@@ -1682,12 +1807,6 @@ 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"@@ -1723,9 +1842,9 @@ dependencies = [[[package]]name = "log"-version = "0.4.31"+version = "0.4.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "113b30b4cd05f7c06868fdb2854f66a7b9fece9a48425351cd532e810d74024f"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"[[package]]name = "lru-slab"@@ -1742,12 +1861,6 @@ dependencies = ["regex-automata",]-[[package]]-name = "matchit"-version = "0.7.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"-[[package]]name = "matchit"version = "0.8.4"@@ -1756,19 +1869,19 @@ checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"[[package]]name = "md-5"-version = "0.10.6"+version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"+checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"dependencies = ["cfg-if",- "digest",+ "digest 0.11.3",][[package]]name = "memchr"-version = "2.8.1"+version = "2.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"+checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"[[package]]name = "mime"@@ -1778,25 +1891,26 @@ checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"[[package]]name = "mio"-version = "0.8.11"+version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c"+checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"dependencies = ["libc","log","wasi",- "windows-sys 0.48.0",+ "windows-sys 0.61.2",][[package]]-name = "mio"-version = "1.2.1"+name = "nix"+version = "0.31.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"dependencies = [+ "bitflags 2.13.0",+ "cfg-if",+ "cfg_aliases","libc",- "wasi",- "windows-sys 0.61.2",][[package]]@@ -1814,23 +1928,37 @@ dependencies = ["signatory",]+[[package]]+name = "nohash-hasher"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451"+[[package]]name = "notify"-version = "6.1.1"+version = "8.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6205bd8bb1e454ad2e27422015fb5e4f2bcc7e08fa8f27058670d208324a4d2d"+checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3"dependencies = [- "bitflags 2.12.1",- "crossbeam-channel",- "filetime",+ "bitflags 2.13.0","fsevent-sys","inotify","kqueue","libc","log",- "mio 0.8.11",+ "mio",+ "notify-types","walkdir",- "windows-sys 0.48.0",+ "windows-sys 0.60.2",+]++[[package]]+name = "notify-types"+version = "2.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a"+dependencies = [+ "bitflags 2.13.0",][[package]]@@ -1878,34 +2006,45 @@ dependencies = [[[package]]name = "object_store"-version = "0.11.2"+version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3cfccb68961a56facde1163f9319e0d15743352344e7808a11795fb99698dcaf"+checksum = "765784b4390c6bcf80316e5a22f4e3661b639c9d8c83246856643c27d8ce9dbe"dependencies = ["async-trait",+ "aws-lc-rs","base64","bytes","chrono",- "futures",+ "crc-fast",+ "form_urlencoded",+ "futures-channel",+ "futures-core",+ "futures-util",+ "http",+ "http-body-util","httparse","humantime","hyper",- "itertools 0.13.0",+ "itertools 0.15.0","md-5",+ "nix","parking_lot","percent-encoding","quick-xml",- "rand 0.8.6",+ "rand 0.10.1","reqwest",- "ring",- "rustls-pemfile",+ "rustls-pki-types","serde","serde_json",- "snafu",+ "serde_urlencoded",+ "thiserror 2.0.18","tokio","tracing","url","walkdir",+ "wasm-bindgen-futures",+ "web-time",+ "windows-sys 0.61.2",][[package]]@@ -1920,12 +2059,6 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"-[[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"@@ -1934,23 +2067,23 @@ checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"[[package]]name = "opentelemetry"-version = "0.24.0"+version = "0.32.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4c365a63eec4f55b7efeceb724f1336f26a9cf3427b70e59e2cd2a5b947fba96"+checksum = "b0142c63252a9e054e68a4c61a5778f7b14f576274d593f8ce883d191a099682"dependencies = ["futures-core","futures-sink","js-sys",- "once_cell","pin-project-lite",- "thiserror 1.0.69",+ "thiserror 2.0.18",+ "tracing",][[package]]name = "opentelemetry-http"-version = "0.13.0"+version = "0.32.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ad31e9de44ee3538fb9d64fe3376c1362f406162434609e79aea2a41a0af78ab"+checksum = "5683015d09e2df236ef005b17f6f196f0d5f6313c4fa43a7b6a53b52776e4331"dependencies = ["async-trait","bytes",@@ -1960,51 +2093,48 @@ dependencies = [[[package]]name = "opentelemetry-otlp"-version = "0.17.0"+version = "0.32.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6b925a602ffb916fb7421276b86756027b37ee708f9dce2dbdcc51739f07e727"+checksum = "9966929966d17620d7c316c643ba62631826e10021409357772d5eea84f62c35"dependencies = [- "async-trait",- "futures-core","http","opentelemetry","opentelemetry-proto","opentelemetry_sdk","prost",- "thiserror 1.0.69",+ "thiserror 2.0.18","tokio","tonic",+ "tonic-types",][[package]]name = "opentelemetry-proto"-version = "0.7.0"+version = "0.32.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "30ee9f20bff9c984511a02f082dc8ede839e4a9bf15cc2487c8d6fea5ad850d9"+checksum = "56d658ba1faf63f7b9c492cfbe6e0ec365440a16132d3270c1065f7b33f1b638"dependencies = ["opentelemetry","opentelemetry_sdk","prost","tonic",+ "tonic-prost",][[package]]name = "opentelemetry_sdk"-version = "0.24.1"+version = "0.32.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "692eac490ec80f24a17828d49b40b60f5aeaccdfe6a503f939713afd22bc28df"+checksum = "9b59f80e1ac4d5ff7a2db8fb6c80badb7f0f3f858211fba08dd9aaec750894f9"dependencies = [- "async-trait","futures-channel","futures-executor","futures-util",- "glob",- "once_cell","opentelemetry","percent-encoding",- "rand 0.8.6",- "serde_json",- "thiserror 1.0.69",+ "portable-atomic",+ "rand 0.9.4",+ "thiserror 2.0.18","tokio","tokio-stream",]@@ -2112,7 +2242,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "89815c69d36021a140146f26659a81d6c2afa33d216d736dd4be5381a7362220"dependencies = ["pest",- "sha2",+ "sha2 0.10.9",][[package]]@@ -2157,6 +2287,15 @@ version = "1.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"+[[package]]+name = "portable-atomic-util"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"+dependencies = [+ "portable-atomic",+]+[[package]]name = "potential_utf"version = "0.1.5"@@ -2182,12 +2321,24 @@ dependencies = [][[package]]-name = "prettyplease"-version = "0.2.37"+name = "proc-macro-error-attr2"+version = "2.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"+checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"dependencies = ["proc-macro2",+ "quote",+]++[[package]]+name = "proc-macro-error2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"+dependencies = [+ "proc-macro-error-attr2",+ "proc-macro2",+ "quote","syn",]@@ -2206,7 +2357,7 @@ version = "0.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cc5b72d8145275d844d4b5f6d4e1eef00c8cd889edb6035c21675d1bb1f45c9f"dependencies = [- "bitflags 2.12.1",+ "bitflags 2.13.0","hex","procfs-core","rustix 0.38.44",@@ -2218,7 +2369,7 @@ version = "0.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "239df02d8349b06fc07398a3a1697b06418223b1c7725085e801e7c0fc6a12ec"dependencies = [- "bitflags 2.12.1",+ "bitflags 2.13.0","hex",]@@ -2241,9 +2392,9 @@ dependencies = [[[package]]name = "prost"-version = "0.13.5"+version = "0.14.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5"+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"dependencies = ["bytes","prost-derive",@@ -2251,9 +2402,9 @@ dependencies = [[[package]]name = "prost-derive"-version = "0.13.5"+version = "0.14.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d"+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"dependencies = ["anyhow","itertools 0.14.0",@@ -2262,6 +2413,15 @@ dependencies = ["syn",]+[[package]]+name = "prost-types"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"+dependencies = [+ "prost",+]+[[package]]name = "protobuf"version = "3.7.2"@@ -2284,9 +2444,9 @@ dependencies = [[[package]]name = "quick-xml"-version = "0.37.5"+version = "0.40.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"+checksum = "2474bd2e5029e7ccb6abb2ba48cf2383a333851dedf495901544281590c7da7f"dependencies = ["memchr","serde",@@ -2294,9 +2454,9 @@ dependencies = [[[package]]name = "quinn"-version = "0.11.9"+version = "0.11.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"+checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"dependencies = ["bytes","cfg_aliases",@@ -2305,7 +2465,7 @@ dependencies = ["quinn-udp","rustc-hash","rustls",- "socket2 0.6.4",+ "socket2","thiserror 2.0.18","tokio","tracing",@@ -2314,10 +2474,11 @@ dependencies = [[[package]]name = "quinn-proto"-version = "0.11.14"+version = "0.11.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"+checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e"dependencies = [+ "aws-lc-rs","bytes","getrandom 0.3.4","lru-slab",@@ -2342,16 +2503,16 @@ dependencies = ["cfg_aliases","libc","once_cell",- "socket2 0.6.4",+ "socket2","tracing","windows-sys 0.60.2",][[package]]name = "quote"-version = "1.0.45"+version = "1.0.46"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"dependencies = ["proc-macro2",]@@ -2396,7 +2557,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"dependencies = ["chacha20",- "getrandom 0.4.2",+ "getrandom 0.4.3","rand_core 0.10.1",]@@ -2450,14 +2611,34 @@ version = "0.5.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"dependencies = [- "bitflags 2.12.1",+ "bitflags 2.13.0",+]++[[package]]+name = "ref-cast"+version = "1.0.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",][[package]]name = "regex"-version = "1.12.3"+version = "1.12.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"+checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba"dependencies = ["aho-corasick","memchr",@@ -2478,15 +2659,15 @@ dependencies = [[[package]]name = "regex-syntax"-version = "0.8.10"+version = "0.8.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"[[package]]name = "reqwest"-version = "0.12.28"+version = "0.13.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"dependencies = ["base64","bytes",@@ -2505,24 +2686,22 @@ dependencies = ["pin-project-lite","quinn","rustls",- "rustls-native-certs 0.8.4","rustls-pki-types",+ "rustls-platform-verifier","serde","serde_json",- "serde_urlencoded","sync_wrapper","tokio","tokio-rustls","tokio-util",- "tower 0.5.3",- "tower-http",+ "tower",+ "tower-http 0.6.11","tower-service","url","wasm-bindgen","wasm-bindgen-futures","wasm-streams","web-sys",- "webpki-roots 1.0.7",][[package]]@@ -2590,7 +2769,7 @@ version = "0.38.44"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"dependencies = [- "bitflags 2.12.1",+ "bitflags 2.13.0","errno","libc","linux-raw-sys 0.4.15",@@ -2603,7 +2782,7 @@ version = "1.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"dependencies = [- "bitflags 2.12.1",+ "bitflags 2.13.0","errno","libc","linux-raw-sys 0.12.1",@@ -2612,10 +2791,11 @@ dependencies = [[[package]]name = "rustls"-version = "0.23.40"+version = "0.23.41"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b"+checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f"dependencies = [+ "aws-lc-rs","log","once_cell","ring",@@ -2627,47 +2807,52 @@ dependencies = [[[package]]name = "rustls-native-certs"-version = "0.7.3"+version = "0.8.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5"+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"dependencies = [- "openssl-probe 0.1.6",- "rustls-pemfile",+ "openssl-probe","rustls-pki-types","schannel",- "security-framework 2.11.1",+ "security-framework",][[package]]-name = "rustls-native-certs"-version = "0.8.4"+name = "rustls-pki-types"+version = "1.14.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"+checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9"dependencies = [- "openssl-probe 0.2.1",- "rustls-pki-types",- "schannel",- "security-framework 3.7.0",+ "web-time",+ "zeroize",][[package]]-name = "rustls-pemfile"-version = "2.2.0"+name = "rustls-platform-verifier"+version = "0.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"+checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"dependencies = [- "rustls-pki-types",+ "core-foundation",+ "core-foundation-sys",+ "jni",+ "log",+ "once_cell",+ "rustls",+ "rustls-native-certs",+ "rustls-platform-verifier-android",+ "rustls-webpki",+ "security-framework",+ "security-framework-sys",+ "webpki-root-certs",+ "windows-sys 0.61.2",][[package]]-name = "rustls-pki-types"-version = "1.14.1"+name = "rustls-platform-verifier-android"+version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9"-dependencies = [- "web-time",- "zeroize",-]+checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"[[package]]name = "rustls-webpki"@@ -2675,6 +2860,7 @@ version = "0.103.13"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"dependencies = [+ "aws-lc-rs","ring","rustls-pki-types","untrusted",@@ -2712,11 +2898,12 @@ dependencies = [[[package]]name = "schemars"-version = "0.8.22"+version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615"+checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"dependencies = ["dyn-clone",+ "ref-cast","schemars_derive","serde","serde_json",@@ -2724,9 +2911,9 @@ dependencies = [[[package]]name = "schemars_derive"-version = "0.8.22"+version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d"+checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f"dependencies = ["proc-macro2","quote",@@ -2749,27 +2936,14 @@ dependencies = ["zeroize",]-[[package]]-name = "security-framework"-version = "2.11.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"-dependencies = [- "bitflags 2.12.1",- "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 2.12.1",- "core-foundation 0.10.1",+ "bitflags 2.13.0",+ "core-foundation","core-foundation-sys","libc","security-framework-sys",@@ -2795,10 +2969,29 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"name = "serde"version = "1.0.228"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde-saphyr"+version = "0.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5897b4c3faadadd35fdb6689f015641f3bc481d5adaaac56231ea15aeb243db3"dependencies = [- "serde_core",- "serde_derive",+ "ahash",+ "annotate-snippets",+ "base64",+ "encoding_rs_io",+ "getrandom 0.3.4",+ "granit-parser",+ "nohash-hasher",+ "num-traits",+ "serde",+ "smallvec",+ "zmij",][[package]]@@ -2914,7 +3107,7 @@ version = "0.9.34+deprecated"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"dependencies = [- "indexmap 2.14.0",+ "indexmap","itoa","ryu","serde",@@ -2929,7 +3122,7 @@ checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",][[package]]@@ -2940,7 +3133,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",+]++[[package]]+name = "sha2"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+ "digest 0.11.3",][[package]]@@ -2960,15 +3164,14 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-gateway"-version = "0.6.14"+version = "0.6.15"dependencies = ["arc-swap","async-nats","async-trait",- "axum 0.8.9",+ "axum","base64","bytes",- "chrono","clap","dashmap","fs2",@@ -2987,24 +3190,25 @@ dependencies = ["opentelemetry_sdk","percent-encoding","prometheus",- "rand 0.8.6",+ "rand 0.10.1","reqwest","rmp","rmp-serde","rmpv",+ "rustls","serde","serde_bytes","serde_json","serde_yaml",- "sha2",+ "sha2 0.11.0","subtle","tempfile","thiserror 2.0.18","tokio","tokio-stream",- "tokio-tungstenite 0.26.2",- "tower 0.5.3",- "tower-http",+ "tokio-tungstenite",+ "tower",+ "tower-http 0.7.0","tracing","tracing-opentelemetry","tracing-subscriber",@@ -3043,52 +3247,37 @@ version = "2.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"dependencies = [- "digest",+ "digest 0.10.7","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"+name = "simd_cesu8"+version = "1.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"+checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33"+dependencies = [+ "rustc_version",+ "simdutf8",+][[package]]-name = "snafu"-version = "0.8.9"+name = "simdutf8"+version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e84b3f4eacbf3a1ce05eac6763b4d629d60cbc94d632e4092c54ade71f1e1a2"-dependencies = [- "snafu-derive",-]+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"[[package]]-name = "snafu-derive"-version = "0.8.9"+name = "slab"+version = "0.4.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451"-dependencies = [- "heck",- "proc-macro2",- "quote",- "syn",-]+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"[[package]]-name = "socket2"-version = "0.5.10"+name = "smallvec"+version = "1.15.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"-dependencies = [- "libc",- "windows-sys 0.52.0",-]+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"[[package]]name = "socket2"@@ -3100,6 +3289,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "spin"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d5fe4ccb98d9c292d56fec89a5e07da7fc4cf0dc11e156b41793132775d3e591"+[[package]]name = "spki"version = "0.7.3"@@ -3130,9 +3325,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"[[package]]name = "syn"-version = "2.0.117"+version = "2.0.118"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"+checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"dependencies = ["proc-macro2","quote",@@ -3166,7 +3361,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand",- "getrandom 0.4.2",+ "getrandom 0.4.3","once_cell","rustix 1.1.4","windows-sys 0.61.2",@@ -3223,12 +3418,11 @@ dependencies = [[[package]]name = "time"-version = "0.3.47"+version = "0.3.51"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"+checksum = "85c17d80feb7334b40c484e45ed1a5273dfd8bfda537c3be2e74a06a6686f327"dependencies = ["deranged",- "itoa","num-conv","powerfmt","serde_core",@@ -3238,15 +3432,15 @@ dependencies = [[[package]]name = "time-core"-version = "0.1.8"+version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"[[package]]name = "time-macros"-version = "0.2.27"+version = "0.2.30"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"+checksum = "dcef1a61bdb119096e153208ec5cbec23944ce8bca13be5c7f60c634f7403935"dependencies = ["num-conv","time-core",@@ -3285,11 +3479,11 @@ checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"dependencies = ["bytes","libc",- "mio 1.2.1",+ "mio","parking_lot","pin-project-lite","signal-hook-registry",- "socket2 0.6.4",+ "socket2","tokio-macros","windows-sys 0.61.2",]@@ -3327,18 +3521,6 @@ dependencies = ["tokio-util",]-[[package]]-name = "tokio-tungstenite"-version = "0.26.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084"-dependencies = [- "futures-util",- "log",- "tokio",- "tungstenite 0.26.2",-]-[[package]]name = "tokio-tungstenite"version = "0.29.0"@@ -3348,7 +3530,7 @@ dependencies = ["futures-util","log","tokio",- "tungstenite 0.29.0",+ "tungstenite",][[package]]@@ -3388,16 +3570,13 @@ dependencies = [[[package]]name = "tonic"-version = "0.12.3"+version = "0.14.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "877c5b330756d856ffcc4553ab34a5684481ade925ecc54bcd1bf02b1d0d4d52"+checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"dependencies = [- "async-stream","async-trait",- "axum 0.7.9","base64","bytes",- "h2","http","http-body","http-body-util",@@ -3406,34 +3585,35 @@ dependencies = ["hyper-util","percent-encoding","pin-project",- "prost",- "socket2 0.5.10",+ "sync_wrapper","tokio","tokio-stream",- "tower 0.4.13",+ "tower","tower-layer","tower-service","tracing",][[package]]-name = "tower"-version = "0.4.13"+name = "tonic-prost"+version = "0.14.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c"+checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0"dependencies = [- "futures-core",- "futures-util",- "indexmap 1.9.3",- "pin-project",- "pin-project-lite",- "rand 0.8.6",- "slab",- "tokio",- "tokio-util",- "tower-layer",- "tower-service",- "tracing",+ "bytes",+ "prost",+ "tonic",+]++[[package]]+name = "tonic-types"+version = "0.14.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8"+dependencies = [+ "prost",+ "prost-types",+ "tonic",][[package]]@@ -3444,7 +3624,9 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"dependencies = ["futures-core","futures-util",+ "indexmap","pin-project-lite",+ "slab","sync_wrapper","tokio","tokio-util",@@ -3460,20 +3642,35 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"dependencies = ["base64",- "bitflags 2.12.1",+ "bitflags 2.13.0","bytes","futures-util","http","http-body","mime","pin-project-lite",- "tower 0.5.3",+ "tower","tower-layer","tower-service","tracing","url",]+[[package]]+name = "tower-http"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b11f75e912b0c2be01b63d8cf8057b8c3f97cf34abb3d431a3a4c8675498e233"+dependencies = [+ "bitflags 2.13.0",+ "bytes",+ "http",+ "percent-encoding",+ "pin-project-lite",+ "tower-layer",+ "tower-service",+]+[[package]]name = "tower-layer"version = "0.3.3"@@ -3532,14 +3729,12 @@ dependencies = [[[package]]name = "tracing-opentelemetry"-version = "0.25.0"+version = "0.33.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a9784ed4da7d921bc8df6963f8c80a0e4ce34ba6ba76668acadd3edbd985ff3b"+checksum = "adbc64cba7137545b8044cb1fe9814f7aacf3c6b5f9b45be8bb5db538befdb26"dependencies = ["js-sys",- "once_cell","opentelemetry",- "opentelemetry_sdk","smallvec","tracing","tracing-core",@@ -3595,23 +3790,6 @@ dependencies = ["tokio",]-[[package]]-name = "tungstenite"-version = "0.26.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"-dependencies = [- "bytes",- "data-encoding",- "http",- "httparse",- "log",- "rand 0.9.4",- "sha1",- "thiserror 2.0.18",- "utf-8",-]-[[package]]name = "tungstenite"version = "0.29.0"@@ -3647,10 +3825,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"[[package]]-name = "unicode-xid"-version = "0.2.6"+name = "unicode-width"+version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"[[package]]name = "unsafe-libyaml"@@ -3676,12 +3854,6 @@ dependencies = ["serde",]-[[package]]-name = "utf-8"-version = "0.7.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"-[[package]]name = "utf8_iter"version = "1.0.4"@@ -3700,7 +3872,7 @@ version = "5.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8bde15df68e80b16c7d16b9616e80770ad158988daa56a27dccd1e55558b0160"dependencies = [- "indexmap 2.14.0",+ "indexmap","serde","serde_json","utoipa-gen",@@ -3719,11 +3891,11 @@ dependencies = [[[package]]name = "uuid"-version = "1.23.2"+version = "1.23.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7"+checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53"dependencies = [- "getrandom 0.4.2",+ "getrandom 0.4.3","js-sys","wasm-bindgen",]@@ -3767,27 +3939,18 @@ 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"+version = "1.0.4+wasi-0.2.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"dependencies = [- "wit-bindgen 0.51.0",+ "wit-bindgen",][[package]]name = "wasm-bindgen"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409"+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"dependencies = ["cfg-if","once_cell",@@ -3798,9 +3961,9 @@ dependencies = [[[package]]name = "wasm-bindgen-futures"-version = "0.4.72"+version = "0.4.76"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9473dbd2991ae90b6291c3c32c30c6187ac49aa32f9905d1cce280ec1e110b0f"+checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d"dependencies = ["js-sys","wasm-bindgen",@@ -3808,9 +3971,9 @@ dependencies = [[[package]]name = "wasm-bindgen-macro"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6"+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"dependencies = ["quote","wasm-bindgen-macro-support",@@ -3818,9 +3981,9 @@ dependencies = [[[package]]name = "wasm-bindgen-macro-support"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e"+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"dependencies = ["bumpalo","proc-macro2",@@ -3831,40 +3994,18 @@ dependencies = [[[package]]name = "wasm-bindgen-shared"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437"+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"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 2.14.0",- "wasm-encoder",- "wasmparser",-]-[[package]]name = "wasm-streams"-version = "0.4.2"+version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"+checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"dependencies = ["futures-util","js-sys",@@ -3873,23 +4014,11 @@ dependencies = ["web-sys",]-[[package]]-name = "wasmparser"-version = "0.244.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"-dependencies = [- "bitflags 2.12.1",- "hashbrown 0.15.5",- "indexmap 2.14.0",- "semver",-]-[[package]]name = "web-sys"-version = "0.3.99"+version = "0.3.103"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6d621441cfc37b84979402712047321980c178f299193a3589d05b99e8763436"+checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"dependencies = ["js-sys","wasm-bindgen",@@ -3905,20 +4034,29 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "webpki-root-certs"+version = "1.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267"+dependencies = [+ "rustls-pki-types",+]+[[package]]name = "webpki-roots"version = "0.26.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"dependencies = [- "webpki-roots 1.0.7",+ "webpki-roots 1.0.8",][[package]]name = "webpki-roots"-version = "1.0.7"+version = "1.0.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d"+checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"dependencies = ["rustls-pki-types",]@@ -4013,15 +4151,6 @@ dependencies = ["windows-link",]-[[package]]-name = "windows-sys"-version = "0.48.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"-dependencies = [- "windows-targets 0.48.5",-]-[[package]]name = "windows-sys"version = "0.52.0"@@ -4058,21 +4187,6 @@ dependencies = ["windows-link",]-[[package]]-name = "windows-targets"-version = "0.48.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"-dependencies = [- "windows_aarch64_gnullvm 0.48.5",- "windows_aarch64_msvc 0.48.5",- "windows_i686_gnu 0.48.5",- "windows_i686_msvc 0.48.5",- "windows_x86_64_gnu 0.48.5",- "windows_x86_64_gnullvm 0.48.5",- "windows_x86_64_msvc 0.48.5",-]-[[package]]name = "windows-targets"version = "0.52.6"@@ -4106,12 +4220,6 @@ dependencies = ["windows_x86_64_msvc 0.53.1",]-[[package]]-name = "windows_aarch64_gnullvm"-version = "0.48.5"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"-[[package]]name = "windows_aarch64_gnullvm"version = "0.52.6"@@ -4124,12 +4232,6 @@ 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"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"-[[package]]name = "windows_aarch64_msvc"version = "0.52.6"@@ -4142,12 +4244,6 @@ 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"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"-[[package]]name = "windows_i686_gnu"version = "0.52.6"@@ -4172,12 +4268,6 @@ 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"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"-[[package]]name = "windows_i686_msvc"version = "0.52.6"@@ -4190,12 +4280,6 @@ 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"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"-[[package]]name = "windows_x86_64_gnu"version = "0.52.6"@@ -4208,12 +4292,6 @@ 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"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"-[[package]]name = "windows_x86_64_gnullvm"version = "0.52.6"@@ -4226,12 +4304,6 @@ 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"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"-[[package]]name = "windows_x86_64_msvc"version = "0.52.6"@@ -4267,100 +4339,12 @@ dependencies = ["url",]-[[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 2.14.0",- "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 2.12.1",- "indexmap 2.14.0",- "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 2.14.0",- "log",- "semver",- "serde",- "serde_derive",- "serde_json",- "unicode-xid",- "wasmparser",-]-[[package]]name = "writeable"version = "0.6.3"@@ -4375,9 +4359,9 @@ checksum = "fdd20c5420375476fbd4394763288da7eb0cc0b8c11deed431a91562af7335d3"[[package]]name = "yoke"-version = "0.8.2"+version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"dependencies = ["stable_deref_trait","yoke-derive",@@ -4398,18 +4382,18 @@ dependencies = [[[package]]name = "zerocopy"-version = "0.8.50"+version = "0.8.52"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3b065d4f0e55f82fae73202e189638116a87c55ab6b8e6c2721e13dd9d854ad1"+checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f"dependencies = ["zerocopy-derive",][[package]]name = "zerocopy-derive"-version = "0.8.50"+version = "0.8.52"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0b631b19d36a892ab55420c92dbc83ccd79274f25be714855d3074aa71cab639"+checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930"dependencies = ["proc-macro2","quote",@@ -4439,9 +4423,9 @@ dependencies = [[[package]]name = "zeroize"-version = "1.8.2"+version = "1.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"[[package]]name = "zerotrie"diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex 41a231539..cd7fc04c5 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.6.14"+version = "0.6.15"edition = "2021"publish = false@@ -15,8 +15,9 @@ tokio = { version = "1", features = ["full"] }tokio-stream = { version = "0.1", features = ["sync"] }hyper = { version = "1", features = ["full"] }hyper-util = { version = "0.1", features = ["tokio"] }-reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] }-tokio-tungstenite = "0.26"+reqwest = { version = "0.13", default-features = false, features = ["json", "stream", "rustls"] }+rustls = { version = "0.23", default-features = false, features = ["ring"] }+tokio-tungstenite = "0.29"futures-util = "0.3"serde = { version = "1", features = ["derive"] }serde_json = "1"@@ -28,27 +29,24 @@ prometheus = { version = "0.14", features = ["process"] }thiserror = "2"dashmap = "6"tower = "0.5"-tower-http = { version = "0.6", features = ["cors"] }+tower-http = { version = "0.7", features = ["cors"] }bytes = "1"# Phase 4: Model registry + hot reloadarc-swap = "1"-sha2 = "0.10"-notify = "6"+sha2 = "0.11"+notify = "8"# Phase 5: Authsubtle = "2"# Phase 6: Kubernetes discovery-kube = { version = "0.98", features = ["runtime", "derive"] }-k8s-openapi = { version = "0.24", features = ["latest"] }-rand = "0.8"--# Phase 7: Pool management (chrono for DateTime)-chrono = { version = "0.4", features = ["serde"] }+kube = { version = "4", features = ["runtime", "derive"] }+k8s-openapi = { version = "0.28", features = ["latest"] }+rand = "0.10"# Phase 11: Request coalescing (MD5 for params hash)-md-5 = "0.10"+md-5 = "0.11"# HRW direct-dispatch routing (xxh3 64-bit hashing of routing keys)xxhash-rust = { version = "0.8", features = ["xxh3"] }@@ -69,7 +67,7 @@ serde_bytes = "0.11"percent-encoding = "2"# Cloud payload store backends (opt-in)-object_store = { version = "0.11", optional = true, features = ["aws", "gcp", "azure"] }+object_store = { version = "0.14", optional = true, features = ["aws", "gcp", "azure"] }url = { version = "2", optional = true }utoipa = "5.4.0"@@ -78,15 +76,13 @@ utoipa = "5.4.0"# span around proxy/publish, and injects the resulting context into# the JetStream work envelope so the worker can continue the trace.#-# Versions tracked together — the 0.24/0.17/0.25 set is the latest-# mutually-compatible point release as of this addition. OTel does-# break compat across minor versions; bumping requires updating all-# four lines.-opentelemetry = "0.24"-opentelemetry_sdk = { version = "0.24", features = ["rt-tokio"] }-opentelemetry-otlp = { version = "0.17", default-features = false, features = ["grpc-tonic", "trace"] }-opentelemetry-http = "0.13"-tracing-opentelemetry = "0.25"+# Versions tracked together. OTel breaks compatibility across minor+# versions, so bumping requires updating all five lines.+opentelemetry = "0.32"+opentelemetry_sdk = { version = "0.32", features = ["rt-tokio"] }+opentelemetry-otlp = { version = "0.32", default-features = false, features = ["grpc-tonic", "trace"] }+opentelemetry-http = "0.32"+tracing-opentelemetry = "0.33"[features]default = []diff --git a/packages/sie_gateway/README.md b/packages/sie_gateway/README.mdindex ce5d6c7e7..9142fd0b5 100644--- a/packages/sie_gateway/README.md+++ b/packages/sie_gateway/README.md@@ -67,7 +67,7 @@ Key options:--k8s-port <PORT> K8s worker port (default: 8080)-l, --log-level <LEVEL> Log level (default: info)--json-logs Enable structured JSON logging- --health-mode <MODE> Worker health transport (supported: ws; default: ws)+ --health-mode <MODE> Worker health transport (supported: ws, nats; default: ws)--bundles-dir <PATH> Bundles directory--models-dir <PATH> Models directory@@ -99,7 +99,7 @@ Each `--flag` above has a matching `SIE_*` environment variable (see next sectio| `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` | `false` | Disable producer validation entirely (dev/local only). `main` emits a startup audit warning when on || `SIE_LOG_LEVEL` | `info` | Log level (`debug`, `info`, `warn`, `error`) || `SIE_LOG_JSON` | `false` | Structured JSON logging (for Loki) |-| `SIE_GATEWAY_REQUEST_TIMEOUT` | `30.0` | Request timeout in seconds |+| `SIE_GATEWAY_REQUEST_TIMEOUT` | `120.0` | Non-generation queue result wait timeout in seconds || `SIE_GATEWAY_MAX_STREAM_PENDING` | `50000` | Max pending stream items per JetStream work stream || `SIE_GATEWAY_DEFAULT_MAX_TOKENS` | `1024` | Output-token cap applied to `/v1/chat/completions` requests that omit both `max_completion_tokens` and `max_tokens`. OpenAI treats the field as optional, so the gateway defaults rather than rejecting — generic clients (Open WebUI) rely on this || `SIE_GATEWAY_ENABLE_POOLS` | `false` | Enable pool management |@@ -158,7 +158,7 @@ Common behaviors:- `404` for unknown models once the in-memory registry has bootstrapped from `sie-config` (fast-fail; avoids queueing requests for typo'd model ids)- `503` + `Retry-After` + `X-SIE-Error-Code: PROVISIONING` on scale-from-zero, whether or not `X-SIE-MACHINE-PROFILE` was set (records pending demand for KEDA)- `503` + `Retry-After` for no-consumer or backpressure publish failures-- `503` + `X-SIE-Error-Code: MODEL_LOADING` + `Retry-After: 5` for queue result timeouts (typically a worker cold-loading the target model). SDK clients with `wait_for_capacity=True` retry under the existing `provision_timeout_s` budget.+- `504` + `X-SIE-Error-Code: GATEWAY_TIMEOUT` + `Retry-After: 5` on non-generation queue routes when a queued request was published but no worker result reached the gateway before `SIE_GATEWAY_REQUEST_TIMEOUT`. Generation routes use their own streaming/direct-dispatch timeout contract. Worker-emitted `MODEL_LOADING` remains a separate retryable `503 MODEL_LOADING` signal.- `503` + `X-SIE-Error-Code: RESOURCE_EXHAUSTED` + `Retry-After: 5` when every item in a batch fails with the same retryable code (`RESOURCE_EXHAUSTED` from worker-side OOM recovery exhaustion, `MODEL_LOADING` from a worker still warming up). The SDK auto-retries with bounded exponential backoff. Mixed batches keep returning `500 all_items_failed` with per-item `code` fields in the response body so callers can see which items hit which failure mode.The same gateway-owned OpenAPI contract is available at runtime via `GET /openapi.json` and as a committed static artifact at `packages/sie_gateway/openapi.json`. Regenerate it with `mise run openapi` before committing API-surface changes.diff --git a/packages/sie_gateway/deny.toml b/packages/sie_gateway/deny.tomlindex 699167912..a81c43086 100644--- a/packages/sie_gateway/deny.toml+++ b/packages/sie_gateway/deny.toml@@ -14,18 +14,14 @@ yanked = "deny"# the corresponding transitive bump lands (kube-rs, async-nats,# prometheus), drop the entry — `cargo-deny` warns on unmatched ignores.ignore = [- # ── Vulnerabilities (transitive, blocked on upstream dep bumps) ──- { id = "RUSTSEC-2024-0437", reason = "protobuf v2 stack overflow on malformed input; transitive via prometheus 0.13 (which pins protobuf=2.28). Fixed by bumping prometheus." },- { id = "RUSTSEC-2026-0049", reason = "rustls-webpki <0.103.13 CRL distribution-point matching; transitive via async-nats 0.38 (pulls webpki 0.102). Fixed by bumping async-nats >=0.39." },- { id = "RUSTSEC-2026-0098", reason = "rustls-webpki URI name-constraint bypass; transitive via async-nats 0.38. Fixed by bumping async-nats >=0.39." },- { id = "RUSTSEC-2026-0099", reason = "rustls-webpki wildcard name-constraint accept; transitive via async-nats 0.38. Fixed by bumping async-nats >=0.39." },- { id = "RUSTSEC-2026-0104", reason = "rustls-webpki CRL parsing panic; transitive via async-nats 0.38. Fixed by bumping async-nats >=0.39." },-- # ── Unmaintained / unsound (low impact, all transitive) ──- { id = "RUSTSEC-2025-0012", reason = "`backoff` crate unmaintained; transitive via kube-runtime 0.98. Fixed by bumping kube-rs (newer versions migrated to `backon`)." },- { id = "RUSTSEC-2024-0384", reason = "`instant` unmaintained; transitive via backoff -> kube-runtime. Resolves with the kube-rs bump above." },- { id = "RUSTSEC-2025-0134", reason = "`rustls-pemfile` archived; transitive via kube-client 0.98. Resolves with the kube-rs bump above." },- { id = "RUSTSEC-2026-0097", reason = "`rand` soundness issue only triggers under a custom `log` impl that calls `rand::rng()`; sie-gateway uses tracing-subscriber and never reaches that path." },+ # Two quick-xml 0.40.1 DoS advisories, both fixed in the breaking 0.41.0+ # release. quick-xml comes in only transitively via object_store 0.14.0+ # (latest), which pins quick-xml ^0.40.1, so there is no version to update+ # to yet, and it parses only trusted cloud-provider API responses, not+ # attacker-controlled XML. Drop both when object_store ships a release+ # depending on quick-xml >=0.41.+ { id = "RUSTSEC-2026-0194", reason = "quick-xml <0.41 quadratic duplicate-attribute parse DoS (upstream #969); transitive via object_store 0.14.0 (pins ^0.40.1); awaiting upstream bump" },+ { id = "RUSTSEC-2026-0195", reason = "quick-xml <0.41 namespace-declaration allocation DoS (upstream #970); transitive via object_store 0.14.0 (pins ^0.40.1); awaiting upstream bump" },][licenses]diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 309faf8c1..1cdbf247b 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -32,7 +32,7 @@ The gateway's contract with admin tooling for post-write readiness is `GET /v1/cKey terms used throughout this document:-- **Bundle**: a model-compatibility grouping. Answers "which workers can serve this model?". Defined by a `name`, a `priority`, and an `adapters[]` list of Python module paths. The source of truth is `sie-config`'s filesystem (image-baked at `SIE_BUNDLES_DIR`, default `/app/bundles`); `sie-config` loads them at startup to drive write validation and exposes them via `GET /v1/configs/bundles` + `GET /v1/configs/bundles/{id}`. The gateway no longer bakes its own copy: `state::config_bootstrap::BootstrapClient::fetch_bundles` pulls them at startup and installs them into `ModelRegistry` via `install_bundles` before any model fetch. Neither service *persists* bundles, and there is no `POST /v1/configs/bundles` on either side — bundle changes are a `sie-config` redeploy and the gateway picks them up on its next bootstrap (or on the next poller-driven catch-up; see §4.2).+- **Bundle**: a model-compatibility grouping. Answers "which workers can serve this model?". Defined by a `name`, a `priority`, an optional `engine`, and an `adapters[]` list of adapter module identifiers. The source of truth is `sie-config`'s filesystem (image-baked at `SIE_BUNDLES_DIR`, default `/app/bundles`); `sie-config` loads them at startup to drive write validation and exposes them via `GET /v1/configs/bundles` + `GET /v1/configs/bundles/{id}`. The gateway no longer bakes its own copy: `state::config_bootstrap::BootstrapClient::fetch_bundles` pulls them at startup and installs them into `ModelRegistry` via `install_bundles` before any model fetch. Neither service *persists* bundles, and there is no `POST /v1/configs/bundles` on either side — bundle changes are a `sie-config` redeploy and the gateway picks them up on its next bootstrap (or on the next poller-driven catch-up; see §4.2).- **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.@@ -60,7 +60,7 @@ Rules enforced on the inference path:- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. Explicit `X-SIE-Pool` selects a logical pool; the gateway publishes to that pool's backing queue pool (`PoolSpec.queue_pool`, default `default`) and stamps the logical pool into the work item as `admission_pool`. Deliveries with hashes unknown to the worker-sidecar, or logical pools that do not assign that worker, 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 records pending demand for KEDA and returns a retryable `503` provisioning response with `Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. SIE-native surfaces use the SDK retry envelope (`{"error":{"code","message"}}`); OpenAI-compatible surfaces (`/v1/generate`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`) use the OpenAI error envelope, because standard OpenAI clients parse 2xx as successful model output. 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 treats the miss as the same pre-execution provisioning state and returns the same retryable `503 PROVISIONING` contract (`Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and surface-specific error envelope). 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.+- On queue result timeouts the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5`. This means the gateway accepted and published the work item, but no worker result reached the gateway before `SIE_GATEWAY_REQUEST_TIMEOUT`; it must not be collapsed into worker-emitted `MODEL_LOADING`, which remains a separate retryable `503 MODEL_LOADING` 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.@@ -105,10 +105,11 @@ NATS publish behavior:Idempotency:-- Writes accept an `Idempotency-Key` header. The state (`_IdempotencyState` on `request.app.state`) holds an LRU response cache and per-key `asyncio.Event`s for in-flight deduplication.+- Writes accept an `Idempotency-Key` header. The state (`_IdempotencyState` on `request.app.state`) holds an LRU response cache and per-key in-flight records for deduplication. Each in-flight record carries the owner's payload hash, completion event, and terminal success/failure/cancellation outcome for current waiters.- A duplicate key with the same body returns the cached response without re-executing.- A duplicate key with a different body returns `422 idempotency_mismatch`.-- A duplicate key whose cached response has been LRU-evicted between the in-flight wait and the cache read returns a synthesized `200 idempotent_replay_evicted` response. The write is never executed twice for the same key.+- A duplicate key whose successful cached response has been LRU-evicted between the in-flight wait and the cache read returns a synthesized `200 idempotent_replay_evicted` response. The write is never executed twice for the same key.+- A duplicate key waiting on an in-flight owner that fails does not synthesize success. If the owner is cancelled before any irreversible write-side effect begins, current waiters see `503 idempotent_inflight_cancelled`, and a later non-overlapping retry can execute normally because failures are not stored in the replay cache. Once the owner enters the commit phase (durable store write or registry mutation), cancellation is deferred until the real outcome is known, so same-key waiters replay the committed success/failure instead of retrying against an unknown background write.Model-ID validation (`_validate_model_id`):@@ -258,7 +259,7 @@ Computation rules:## 7. Cross-Service Hash Parity-`bundle_config_hash` is computed independently by `sie-config`, the gateway, and workers. The `sie-config` export/epoch surface keeps the global per-bundle hash for bootstrap and drift detection. Gateway hot routing/readiness compares workers against the hash for the same materialized scope the worker serves: the default pool scope for unfiltered workers, or the named physical queue-pool scope for workers filtered by `SIE_POOL`. Logical API pools may draw from a different backing queue pool via `PoolSpec.queue_pool`; for the admin-tooling readiness flow to work, gateway and worker hashes must be byte-identical for that backing bundle/pool scope. A model config's top-level `pool` must therefore match the physical queue scope that will materialize it; dynamic logical pools backed by `default` should use default-scoped model configs unless a dedicated worker queue exists.+`bundle_config_hash` is computed independently by `sie-config`, the gateway, and workers. The `sie-config` export/epoch surface keeps the global per-bundle hash for bootstrap and drift detection, while export snapshots and live NATS deltas also carry per-bundle/per-pool hashes for worker convergence. Worker sidecars apply only models whose top-level `pool` matches their own `SIE_POOL`, then advertise that pool-scoped hash. Gateway hot routing/readiness compares workers against the hash for the same materialized scope the worker serves: the default pool scope for unfiltered workers, or the named physical queue-pool scope for workers filtered by `SIE_POOL`. Logical API pools may draw from a different backing queue pool via `PoolSpec.queue_pool`; for the admin-tooling readiness flow to work, gateway and worker hashes must be byte-identical for that backing bundle/pool scope. A model config's top-level `pool` must therefore match the physical queue scope that will materialize it; dynamic logical pools backed by `default` should use default-scoped model configs unless a dedicated worker queue exists.The hash is a SHA-256 over a JSON-serialized, sort-keys representation of a structured object. The outer shape is an array of models, each with `sie_id` and `profiles: [{name, config: {...4 fields...}}]`, where the inner `config` for each profile is strictly the four routable-profile fields: `adapter_path`, `max_batch_tokens`, `compute_precision`, `adapter_options`. Any field outside that whitelist is excluded from the hash so that non-routable edits (e.g. comments, description-style metadata) cannot unnecessarily invalidate worker acks. Python uses `orjson.dumps(..., OPT_SORT_KEYS)`; Rust mirrors this via `serde_json::to_vec` over `BTreeMap`-backed canonical types.@@ -288,9 +289,10 @@ Per-subject transport:|---|---|---|---|| Pool inference work (`encode` / `score` / `extract`) | `sie.work.{pool}.{machine_profile}.{bundle}.{model}` | JetStream | Durability and max-delivery semantics required. Work-item payload is msgpack. One stream per pool (`WORK_POOL_{pool}`) captures ordinary non-generation work for the pool, while worker consumers filter one concrete machine-profile/bundle lane; see §8.2. || Worker direct-dispatch | `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}` | JetStream | Worker-specific stream used by generation and by capped logical batch pools that must target an assigned worker instead of allowing unassigned workers on the same backing queue to burn JetStream delivery attempts. |-| 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. |+| Batch direct cancel | `batch_cancel.{router_id}.{worker_id}.{request_id}` | NATS Core | Best-effort worker-scoped signal emitted only after non-streaming worker-direct fallback publishes are durably acked on the pool subject. Sidecars ACK-drop queued worker-direct encode/score/extract items for the request; pool fallback items are never cancelled by this signal. |+| 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 may retry (the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5` — see §2). Result payload is msgpack. || Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Gateway durability comes from the snapshot/export path (§4), not the bus. JSON payload (control plane, not hot path). The gateway subscribes on `_all`; worker-sidecar containers subscribe on their bundle subject and apply through Python IPC. |-| Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`) and supervises the subscriber task: reconnects normally resume in `async-nats`, but a terminated subscription stream is recreated with bounded backoff because there is no full-state health poller. 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. |+| Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`) and supervises the subscriber task: reconnects normally resume in `async-nats`, but a terminated subscription stream is recreated with bounded backoff because there is no full-state health poller. Worker-sidecar containers publish this heartbeat and include the latest bundle hash after successful config apply. Helm sidecar deployments set `health_mode=nats`; the gateway binary default remains `ws` so standalone/test deployments can use the Python WebSocket path. || DLQ advisories | `$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>` | NATS Core (advisory) | JetStream emits these; gateway replicas subscribe in `queue/dlq.rs` and publish to `DEAD_LETTERS` with a deterministic `Nats-Msg-Id`, so JetStream dedupes replica fan-out. || 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 `_`. |@@ -320,9 +322,9 @@ The stream's subject filter `sie.work.{pool}.*.*.*` matches exactly one token eaTo prevent that, the Rust gateway's `work_subject(pool, machine_profile, bundle, model)` in `packages/sie_gateway/src/queue/publisher.rs` calls a private `normalize_model_id` helper that mirrors the Python SDK (`sie_sdk.queue_types.normalize_model_id`): `/` → `__`, `.` → `_dot_`, and `*`/`>`/space → `_`. So `vidore/colqwen2.5-v0.2` on the default RTX 6000 default-bundle lane publishes on `sie.work.default.rtx6000.default.vidore__colqwen2_dot_5-v0_dot_2` — exactly six tokens, matches the lane consumer filter. The DLQ token extractor in `queue/dlq.rs` splits the advisory subject on `.` and takes `parts[5]`, which with the normalization in place is already a single safe token.-Worker direct-dispatch uses `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`, which has one additional token after the model. That subject intentionally does not match the pool stream's `sie.work.{pool}.*.*.*` filter. The sidecar binds this worker-specific stream at startup. It stays idle for ordinary pool-queued encode/score/extract traffic, but it is required for two cases: generation direct-dispatch and capped logical batch pools whose `admission_pool` assigns only a subset of workers on a shared backing queue. In the capped logical case the gateway builds an HRW ring from the assigned healthy workers for that lane and publishes to one worker subject, allowing lazy model load without unassigned peers repeatedly NAKing the same message into `max_deliver`. If a non-streaming worker-direct publish fails, the gateway immediately retries on the pool subject; if published work is still missing after the short fallback delay, it republishes the missing items once to the pool subject so a disappeared worker-specific consumer does not strand the request until the client timeout.+Worker direct-dispatch uses `sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`, which has one additional token after the model. That subject intentionally does not match the pool stream's `sie.work.{pool}.*.*.*` filter. The sidecar binds this worker-specific stream at startup. It stays idle for ordinary pool-queued encode/score/extract traffic, but it is required for two cases: generation direct-dispatch and capped logical batch pools whose `admission_pool` assigns only a subset of workers on a shared backing queue. In the capped logical case the gateway builds an HRW ring from the assigned healthy workers for that lane and publishes to one worker subject, allowing lazy model load without unassigned peers repeatedly NAKing the same message into `max_deliver`. If a non-streaming worker-direct publish fails, the gateway immediately retries on the pool subject; if published work is still missing after the short fallback delay, it republishes the missing items once to the pool subject so a disappeared worker-specific consumer does not strand the request until the client timeout. The gateway emits `batch_cancel.{router_id}.{worker_id}.{request_id}` only after the pool fallback publishes are durably acked, and the original sidecar only ACK-drops matching queued worker-direct batch items that have not reached IPC. Sidecar `WorkResult` payloads also carry a direct-origin marker, so once the gateway has confirmed fallback for an item index it ignores any late direct-origin result for that index rather than allowing mixed direct/pool completion. In-flight direct work may still consume GPU, but it cannot win the collector after confirmed fallback.-The same isolation applies in the gateway. Ordinary `encode` / `score` / `extract` and `/v1/embeddings` requests stay on the pool JetStream subject and keep the pre-generation queue-publish hot path. Capped logical pool requests may use worker direct-dispatch to preserve admission semantics; they still do not pay generation-specific proxy spans or trace-context envelope injection. 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.+The same isolation applies in the gateway. Ordinary `encode` / `score` / `extract` and `/v1/embeddings` requests stay on the pool JetStream subject and keep the pre-generation queue-publish hot path. All recognized inference endpoints — generation and non-generation alike — inject the active W3C trace context into the queue work-item envelope (`injects_queue_trace_context`), so the worker span attaches to the gateway span across the pool/sidecar boundary; unrecognized labels fail closed. This is independent of generation-specific gateway proxy spans: capped logical pool requests may use worker direct-dispatch to preserve admission semantics, and non-generation endpoints do not pay generation proxy-span overhead. When tracing export is enabled, non-generation endpoints open the lightweight `gateway.publish` span around queue publish; generation endpoints open `gateway.proxy_generate` / `gateway.proxy_chat` spans on their streaming paths. 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@@ -335,7 +337,8 @@ Publishers and consumers:The `ConfigNotification` JSON payload carries the following fields, verified against `packages/sie_gateway/src/nats/manager.rs` and `packages/sie_config/src/sie_config/nats_publisher.py`:- `router_id` on the wire (Python publisher key). The Rust gateway parses this into a struct field named `producer_id`; `router_id` is declared as a `#[serde(alias)]` on the Rust side for forward compatibility.-- `bundle_id`, `epoch`, `bundle_config_hash`, `model_id`.+- `bundle_id`, `epoch`, `bundle_config_hash`, `model_id`, `pool`.+- `bundle_pool_config_hashes` — nested `bundle_id -> pool -> hash` map used by gateways and sidecars to compare worker acks against the same pool-scoped bundle projection the worker applied.- `profiles_added` — list of profile names created by this write.- `model_config` — raw YAML string of the full model config.- `affected_bundles` — list of every bundle affected by this write. Each affected bundle receives its own message, so a `_all` subscriber sees N messages per write with their respective `bundle_id` / `bundle_config_hash` populated.@@ -446,6 +449,14 @@ Config service (`sie-config`):- `SIE_BUNDLES_DIR`, `SIE_MODELS_DIR` — bundle and model source directories. **`sie-config` is the source of truth**: it reads these at startup, validates writes against them, and re-serves the bundle list at `GET /v1/configs/bundles` for the gateway's bootstrap. Defaults via `sharedPaths.{bundlesDir,modelsDir}` (`/app/bundles`, `/app/models`) and image-baked.- `SIE_LOG_LEVEL`, `SIE_LOG_JSON` — log verbosity and structured-JSON toggle (both also exposed as CLI flags).+Tracing (all runtimes):++- `SIE_TRACING_ENABLED` and an OTLP endpoint are both required before spans are exported by the gateway, worker sidecar, Python worker, or Rust worker. The trace-specific `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` takes precedence over the generic `OTEL_EXPORTER_OTLP_ENDPOINT`; whitespace-only values are ignored. All four runtimes install the W3C trace-context propagator even when the exporter is off, so inbound `traceparent` / `tracestate` can still flow through queue envelopes.+- `OTEL_SERVICE_NAME` controls the service name shown in the tracing backend. Helm defaults are `sie-gateway` for the gateway, `sie-worker-sidecar` for the sidecar, and `sie-server` for the worker container. If the Rust worker runs without the Helm-provided env, its binary default is `sie-server-rust`.+- `OTEL_TRACES_SAMPLER` / `OTEL_TRACES_SAMPLER_ARG` configure head sampling. Helm defaults them to `parentbased_traceidratio` / `0.05`, so an inbound sampled decision is honored and new traces are sampled at 5%.+- `OTEL_EXPORTER_OTLP_PROTOCOL=grpc` is the supported chart path. The Python worker also has a local-dev `--tracing` CLI flag, which enables tracing to `localhost:4317`.+- Helm `observability.tracing.enabled` injects the exporter env block on gateway, worker, and sidecar containers. Rendering fails fast when no endpoint can be resolved from `observability.tracing.endpoint`, the bundled collector, or bundled Tempo.+## 14. Endpoint Reference### `sie-gateway`@@ -575,13 +586,54 @@ The most important alert across both services. Fires when any gateway's view ofSustained non-zero for >1 minute means either NATS Core deltas are not flowing (pub/sub has no replay, so a disconnected gateway silently falls behind) or the config poller is stuck. The poller normally closes this gap within its poll interval regardless of NATS health, so a sustained alert here is always an actionable incident.+### 15.10 Distributed tracing++Tracing uses W3C `traceparent` / `tracestate` propagation through the gateway queue envelopes described in §8.2 (`injects_queue_trace_context`). The SDKs are not instrumented today: a trace roots at the gateway unless the caller's own HTTP stack injects a context.++Non-streaming queue path (`/v1/encode`, `/v1/score`, `/v1/extract`, `/v1/embeddings`):++```+optional client traceparent+ -> gateway.publish+ -> sidecar.dispatch+ -> worker.run_batch+```++`/v1/embeddings` is rewritten to `/v1/encode`, and the gateway explicitly forwards `traceparent` / `tracestate` onto the queue work item. `gateway.publish` is opened only when the exporter is active; otherwise the gateway scopes the inbound context over publish so downstream workers can still attach to the caller's trace. The sidecar opens `sidecar.dispatch` around the coalesced batch, then serializes that span back onto IPC items so `worker.run_batch` nests under it. If the sidecar exporter is off, it falls back to the original gateway context.++Generation path (`/v1/generate`, `/v1/chat/completions`):++```+optional client traceparent+ -> gateway.proxy_generate or gateway.proxy_chat+ -> worker.streaming_processor+```++Streaming generation bypasses the sidecar. The gateway opens `gateway.proxy_generate` (the OTel-renamed export of the internal `gateway.proxy` tracing span) for native generation or `gateway.proxy_chat` for OpenAI-compatible chat, injects that context into the streaming work item, and the Python worker extracts it before `worker.streaming_processor`.++Batch fan-in parents on the first valid inbound context and records the remaining distinct valid contexts as OpenTelemetry links. The sidecar does this before `sidecar.dispatch`; Python and Rust workers do the same before `worker.run_batch`. The propagator is installed even when export is off, so trace context flows with tracing disabled. Runtime shutdown uses a bounded ~3 s trace flush. The Helm default sampler is `parentbased_traceidratio` at `0.05`, which preserves inbound sampling decisions and samples 5% of new roots.++Current span attributes:++| Span | Runtime | Attributes |+| ---- | ------- | ---------- |+| `gateway.publish` | Rust gateway, non-streaming queue publish | `sie.endpoint`, `sie.model`, `sie.pool`, `sie.publish_ms` |+| `sidecar.dispatch` | Rust worker sidecar | `sie.op`, `sie.model`, `sie.batch_id`, `sie.batch_size` |+| `worker.run_batch` | Python worker | `sie.model`, `sie.batch_id`, `sie.op`, `sie.adapter`, `sie.batch_size` |+| `worker.run_batch` | Rust worker | `sie.op`, `sie.model`, `sie.batch_id`, `sie.batch_size` |+| `gateway.proxy_generate` | Rust gateway, `/v1/generate` | `sie.endpoint`, `sie.request_id`, `sie.model` |+| `gateway.proxy_chat` | Rust gateway, `/v1/chat/completions` | `http.route`, `sie.routing_key_kind`, `sie.model`, `sie.request_id` |+| `worker.streaming_processor` | Python worker, streaming generation | `sie.request_id`, `sie.attempt_id`, `sie.model`, `sie.adapter` |++Operationally, §16.2 shows where the queue envelope is created in the request walk-through. The chart README's "Distributed Tracing (OTLP)" section documents the Helm enable switch. When tracing dashboards are enabled, traces surface in Grafana through the Tempo datasource (`uid: tempo`) and the `SIE Tracing` dashboard.+## 16. Worked Example: end-to-end requestThis section walks a concrete `encode` request through the system so the moving parts in §1–§15 have an explicit reference trace.### 16.1 Bundles and model → bundle resolution-A **bundle** defines which Python adapter modules a worker deployment can run. Two shapes ship today:+A **bundle** defines which adapter module identifiers a worker deployment can run. Three shapes ship today:**`default` bundle** (priority `10`) — ~37 adapters for smaller BERT-class and cross-encoder models:@@ -609,7 +661,18 @@ adapters:- sie_server.adapters.sglang```-`ModelRegistry` maps a model to a bundle by matching the model's `adapter_path` module against each bundle's `adapters` list, then preferring the lowest-priority bundle in the match set:+**`candle` bundle** (priority `30`) — a Rust `sie-server-rust` IPC worker backed by native Candle execution:++```yaml+# bundles/candle.yaml+name: candle+priority: 30+engine: candle+adapters:+- sie_server_rust.adapters.candle+```++`ModelRegistry` maps a requested model/profile identity to a bundle by resolving the requested profile's `adapter_path` module, matching that module against each bundle's `adapters` list, then preferring the lowest-priority bundle in the match set. The base model id means the `default` profile; non-default profiles are routable as `base-model:profile` aliases. Models that are only available through the native Candle runtime use `default` with the Candle adapter, while `:candle` is reserved for side-by-side native variants of models that also have another default path:```Model: BAAI/bge-m3@@ -623,8 +686,18 @@ Model: Qwen/Qwen3-Embedding-4Badapter module: sie_server.adapters.sglang→ matches "sglang" bundle→ routes to "sglang" workers++Model: intfloat/e5-small-v2:candle+ base model: intfloat/e5-small-v2+ profile: candle+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter module: sie_server_rust.adapters.candle+ → matches "candle" bundle+ → routes to "candle" workers```+The `engine` field on a bundle describes the worker runtime shape and can be used as an operator/debug filter, but normal product routing should choose a profile variant or explicit compatible bundle rather than asking application clients to know engine headers.+This mapping is computed at startup and whenever the model registry reloads (filesystem hot reload, NATS config delta, or successful bootstrap/poll). No per-model hand-wiring.### 16.2 A single request from client to responsediff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex a93aeb8b5..ceeb4bffd 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -49,6 +49,9 @@},"type": "array"},+ "engine": {+ "type": "string"+ },"name": {"type": "string"},@@ -62,6 +65,7 @@},"required": ["name",+ "engine","priority","source","adapters"@@ -81,6 +85,9 @@"minimum": 0,"type": "integer"},+ "engine": {+ "type": "string"+ },"priority": {"format": "int32","type": "integer"@@ -91,6 +98,7 @@},"required": ["bundle_id",+ "engine","priority","adapter_count","source",@@ -2997,7 +3005,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.6.14"+ "version": "0.6.15"},"openapi": "3.1.0","paths": {@@ -3840,18 +3848,6 @@]}},- {- "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",@@ -4147,18 +4143,6 @@]}},- {- "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",@@ -4485,18 +4469,6 @@]}},- {- "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",@@ -5624,18 +5596,6 @@]}},- {- "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.rsindex a5aaac92d..eed369eb2 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -123,6 +123,15 @@ fn env_float(key: &str, fallback: f64) -> f64 {.unwrap_or(fallback)}+fn env_finite_float(key: &str, fallback: f64) -> f64 {+ let value = env_float(key, fallback);+ assert!(+ value.is_finite(),+ "{key} must be a finite floating point value"+ );+ value+}+fn env_u64(key: &str, fallback: u64) -> u64 {env::var(key).ok()@@ -341,7 +350,7 @@ impl Config {|| env_bool("SIE_GATEWAY_POLLING_WATCHER"),multi_router: env_bool("SIE_MULTI_ROUTER"),- request_timeout: env_float("SIE_GATEWAY_REQUEST_TIMEOUT", 30.0),+ request_timeout: env_finite_float("SIE_GATEWAY_REQUEST_TIMEOUT", 120.0),max_stream_pending: env_u64("SIE_GATEWAY_MAX_STREAM_PENDING", 50_000),stream_max_age_s: env_u64("SIE_STREAM_MAX_AGE_S", 1_800),@@ -476,34 +485,47 @@ mod tests {static ENV_LOCK: Mutex<()> = Mutex::new(());fn with_env<F: FnOnce()>(vars: &[(&str, &str)], f: F) {- let _guard = ENV_LOCK.lock().unwrap();+ let guard = ENV_LOCK+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());let old: Vec<(&str, Option<String>)> =vars.iter().map(|(k, _)| (*k, env::var(k).ok())).collect();for (k, v) in vars {env::set_var(k, v);}- f();+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));for (k, old_val) in old {match old_val {Some(v) => env::set_var(k, v),None => env::remove_var(k),}}+ drop(guard);+ if let Err(panic) = result {+ std::panic::resume_unwind(panic);+ }}fn without_env<F: FnOnce()>(keys: &[&str], f: F) {- let _guard = ENV_LOCK.lock().unwrap();+ let guard = ENV_LOCK+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());let old: Vec<(&str, Option<String>)> =keys.iter().map(|k| (*k, env::var(k).ok())).collect();for k in keys {env::remove_var(k);}- f();+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f));for (k, old_val) in old {- if let Some(v) = old_val {- env::set_var(k, v);+ match old_val {+ Some(v) => env::set_var(k, v),+ None => env::remove_var(k),}}+ drop(guard);+ if let Err(panic) = result {+ std::panic::resume_unwind(panic);+ }}// ── env_bool ───────────────────────────────────────────────────@@ -811,6 +833,30 @@ mod tests {});}+ #[test]+ fn test_request_timeout_default_is_120_seconds() {+ without_env(&["SIE_GATEWAY_REQUEST_TIMEOUT"], || {+ let cfg = Config::load();+ assert!((cfg.request_timeout - 120.0).abs() < f64::EPSILON);+ });+ }++ #[test]+ fn test_request_timeout_from_env() {+ with_env(&[("SIE_GATEWAY_REQUEST_TIMEOUT", "45.5")], || {+ let cfg = Config::load();+ assert!((cfg.request_timeout - 45.5).abs() < f64::EPSILON);+ });+ }++ #[test]+ #[should_panic(expected = "SIE_GATEWAY_REQUEST_TIMEOUT must be a finite floating point value")]+ fn test_request_timeout_rejects_non_finite_env() {+ with_env(&[("SIE_GATEWAY_REQUEST_TIMEOUT", "NaN")], || {+ let _ = Config::load();+ });+ }+#[test]fn test_config_service_url_from_env() {with_env(diff --git a/packages/sie_gateway/src/discovery/k8s_discovery.rs b/packages/sie_gateway/src/discovery/k8s_discovery.rsindex a55b22629..2e66c77cc 100644--- a/packages/sie_gateway/src/discovery/k8s_discovery.rs+++ b/packages/sie_gateway/src/discovery/k8s_discovery.rs@@ -7,7 +7,7 @@ use k8s_openapi::api::core::v1::Endpoints;use kube::api::{Api, ListParams};use kube::runtime::watcher::{self, Event};use kube::Client;-use rand::prelude::*;+use rand::RngExt as _;use tokio::sync::Mutex;use tracing::{info, warn};@@ -64,8 +64,8 @@ impl K8sDiscovery {// Add jitter (20%)let jitter_factor = {- let mut rng = rand::thread_rng();- rng.gen_range(0.8..1.2)+ let mut rng = rand::rng();+ rng.random_range(0.8..1.2)};let sleep_duration =Duration::from_secs_f64(backoff.as_secs_f64() * jitter_factor);diff --git a/packages/sie_gateway/src/endpoint.rs b/packages/sie_gateway/src/endpoint.rsindex 0bfb72ecc..71f90246f 100644--- a/packages/sie_gateway/src/endpoint.rs+++ b/packages/sie_gateway/src/endpoint.rs@@ -28,8 +28,23 @@ impl InferenceEndpoint {matches!(self, Self::Generate)}+ pub(crate) fn uses_publish_gateway_span(self) -> bool {+ matches!(+ self,+ Self::Encode | Self::Score | Self::Extract | Self::Embeddings+ )+ }+pub(crate) fn injects_queue_trace_context(self) -> bool {- matches!(self, Self::Generate)+ // Every recognized inference endpoint serializes the active W3C+ // trace context into its queue work-item envelope so the worker+ // span attaches to the gateway span. This is independent of+ // `uses_generation_gateway_tracing` (proxy/gateway spans), which+ // stays generation-only. `Unknown` fails closed.+ matches!(+ self,+ Self::Encode | Self::Score | Self::Extract | Self::Embeddings | Self::Generate+ )}}@@ -38,11 +53,15 @@ mod tests {use super::InferenceEndpoint;#[test]- fn non_generation_queue_labels_do_not_enable_generation_features() {+ fn non_generation_queue_labels_inject_trace_context_without_generation_tracing() {+ // Non-generation endpoints inject queue trace context (so worker+ // spans attach to the gateway span) but must NOT enable the+ // generation-only gateway/proxy spans.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());+ assert!(endpoint.uses_publish_gateway_span());+ assert!(endpoint.injects_queue_trace_context());}}@@ -50,6 +69,7 @@ mod tests {fn generate_is_the_only_generation_trace_endpoint() {let endpoint = InferenceEndpoint::from_label("generate");assert!(endpoint.uses_generation_gateway_tracing());+ assert!(!endpoint.uses_publish_gateway_span());assert!(endpoint.injects_queue_trace_context());}@@ -58,6 +78,7 @@ mod tests {let endpoint = InferenceEndpoint::from_label("chat");assert_eq!(endpoint, InferenceEndpoint::Unknown);assert!(!endpoint.uses_generation_gateway_tracing());+ assert!(!endpoint.uses_publish_gateway_span());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.rsindex 8c46fb278..9c5920029 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -280,6 +280,7 @@ pub async fn get_bundle_configs(State(state): State<Arc<AppState>>) -> impl Intojson!({"bundle_id": info.name,+ "engine": info.engine,"priority": info.priority,"adapter_count": info.adapters.len(),"source": "gateway-registry",@@ -320,6 +321,7 @@ pub async fn get_bundle_config(let doc = json!({"name": info.name,+ "engine": info.engine,"priority": info.priority,"source": "gateway-registry","adapters": info.adapters,@@ -607,6 +609,7 @@ mod tests {let bundles = parsed["bundles"].as_array().unwrap();assert_eq!(bundles.len(), 1);assert_eq!(bundles[0]["bundle_id"], "default");+ assert_eq!(bundles[0]["engine"], "pytorch");assert_eq!(bundles[0]["source"], "gateway-registry");}@@ -629,6 +632,7 @@ mod tests {assert_eq!(response.status(), StatusCode::OK);let body = String::from_utf8(body_bytes(response).await).unwrap();assert!(body.contains("name: default"));+ assert!(body.contains("engine: pytorch"));assert!(body.contains("source: gateway-registry"));}diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex fedf879fe..4e2818076 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -317,7 +317,7 @@ mod tests {#[cfg(test)]mod route_tests {- use std::collections::HashMap;+ use std::collections::{BTreeSet, HashMap};use std::sync::Arc;use std::time::Duration;@@ -384,6 +384,11 @@ mod route_tests {"name: default\nadapters:\n - module\ndefault: true\n",).unwrap();+ std::fs::write(+ bundles_dir.path().join("candle.yaml"),+ "name: candle\npriority: 30\nengine: candle\nadapters:\n - sie_server_rust.adapters.candle\n",+ )+ .unwrap();let config = Arc::new(test_config(bundles_dir.path().to_str().unwrap(),@@ -434,6 +439,74 @@ mod route_tests {.unwrap();}+ fn seed_candle_variant_model(state: &AppState, model_id: &str) {+ let mut profiles = HashMap::new();+ profiles.insert(+ "default".to_string(),+ ProfileConfig {+ adapter_path: Some("module:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ profiles.insert(+ "candle".to_string(),+ ProfileConfig {+ adapter_path: Some(+ "sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),+ ),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ state+ .model_registry+ .add_model_config(ModelConfig {+ name: model_id.to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ tasks: None,+ max_sequence_length: None,+ })+ .unwrap();+ }++ fn seed_profile_only_candle_model(state: &AppState, model_id: &str) {+ let mut profiles = HashMap::new();+ profiles.insert(+ "candle".to_string(),+ ProfileConfig {+ adapter_path: Some(+ "sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),+ ),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ state+ .model_registry+ .add_model_config(ModelConfig {+ name: model_id.to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ tasks: None,+ max_sequence_length: None,+ })+ .unwrap();+ }+// End-to-end through the routing entry point (proxy::resolve_model_and_bundle),// not just the pure resolver: a `sql` job alias whose target carries a BF16// bundle routes model="sql" to that bundle, a `code` alias to the FP8 bundle@@ -638,6 +711,82 @@ mod route_tests {assert_eq!(body["models"].as_array().unwrap().len(), 1);}+ #[tokio::test]+ async fn test_list_models_advertises_profile_variants() {+ let (app, state, _bundles_dir, _models_dir) = build_router_with_state().await;+ seed_candle_variant_model(&state, "acme/embed");++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/models")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let body = body_json(response).await;++ let native_ids: BTreeSet<&str> = body["models"]+ .as_array()+ .unwrap()+ .iter()+ .map(|model| model["name"].as_str().unwrap())+ .collect();+ assert_eq!(+ native_ids,+ BTreeSet::from(["acme/embed", "acme/embed:candle"])+ );++ let openai_ids: BTreeSet<&str> = body["data"]+ .as_array()+ .unwrap()+ .iter()+ .map(|model| model["id"].as_str().unwrap())+ .collect();+ assert_eq!(+ openai_ids,+ BTreeSet::from(["acme/embed", "acme/embed:candle"])+ );+ }++ #[tokio::test]+ async fn test_list_models_advertises_profile_only_candle_models_as_variants() {+ let (app, state, _bundles_dir, _models_dir) = build_router_with_state().await;+ seed_profile_only_candle_model(&state, "acme/candle-only");++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/models")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let body = body_json(response).await;++ let native_ids: BTreeSet<&str> = body["models"]+ .as_array()+ .unwrap()+ .iter()+ .map(|model| model["name"].as_str().unwrap())+ .collect();+ assert_eq!(native_ids, BTreeSet::from(["acme/candle-only:candle"]));++ let openai_ids: BTreeSet<&str> = body["data"]+ .as_array()+ .unwrap()+ .iter()+ .map(|model| model["id"].as_str().unwrap())+ .collect();+ assert_eq!(openai_ids, BTreeSet::from(["acme/candle-only:candle"]));+ }+#[tokio::test]async fn test_list_models_includes_registry_and_worker_only_models() {let (app, state, _bundles_dir, _models_dir) = build_router_with_state().await;diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 73734cb45..57cf01c71 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -21,7 +21,7 @@ use crate::metrics;use crate::queue::publisher;use crate::server::AppState;-use crate::state::model_registry::ResolveError;+use crate::state::model_registry::{ModelRegistry, ResolveError};use crate::state::pool_manager::{normalize_pool_name, PoolManager, DEFAULT_POOL_NAME};use crate::state::worker_registry::{QueueRoute, WorkerRegistry};use crate::types::AuditEntry;@@ -55,12 +55,45 @@ pub(crate) fn system_fingerprint(model: &str) -> String {input.push_str(GATEWAY_VERSION);format!("fp_{:016x}", xxhash_rust::xxh3::xxh3_64(input.as_bytes()))}++/// The `Retry-After` hints (seconds, as the wire strings stamped directly onto+/// retryable capacity responses) the gateway returns for each cold-load /+/// provisioning condition. One typed home for what were six loose constants,+/// and the seam a future PR populates from config to make these an operator+/// dial without a rebuild (see #1574). The named `*_RETRY_AFTER` constants+/// below are thin aliases over [`RetryAfter::DEFAULT`], so existing call sites+/// are unchanged.+#[derive(Clone, Copy, Debug)]+pub(crate) struct RetryAfter {+ pub provisioning: &'static str,+ pub backpressure: &'static str,+ pub gateway_timeout: &'static str,+ pub model_loading: &'static str,+ pub resource_exhausted: &'static str,+ pub lora_loading: &'static str,+}++impl RetryAfter {+ /// Compile-time defaults. `provisioning` is the longer pre-execution+ /// capacity-miss hint (kept within the range common OpenAI SDKs honor);+ /// the rest are short transient-retry hints.+ pub const DEFAULT: RetryAfter = RetryAfter {+ provisioning: "60",+ backpressure: "5",+ gateway_timeout: "5",+ model_loading: "5",+ resource_exhausted: "5",+ lora_loading: "5",+ };+}+/// Provisioning is a retryable pre-execution capacity miss, not an accepted/// asynchronous job. Keep the Retry-After hint within the range common OpenAI/// SDKs honor directly.-pub(crate) const PROVISIONING_RETRY_AFTER: &str = "60";-const BACKPRESSURE_RETRY_AFTER: &str = "5";-const MODEL_LOADING_RETRY_AFTER: &str = "5";+pub(crate) const PROVISIONING_RETRY_AFTER: &str = RetryAfter::DEFAULT.provisioning;+const BACKPRESSURE_RETRY_AFTER: &str = RetryAfter::DEFAULT.backpressure;+const GATEWAY_TIMEOUT_RETRY_AFTER: &str = RetryAfter::DEFAULT.gateway_timeout;+const MODEL_LOADING_RETRY_AFTER: &str = RetryAfter::DEFAULT.model_loading;const MODEL_LOADING_ERROR_CODE: &str = "MODEL_LOADING";/// Server-side OOM recovery exhausted. Workers stamp this on/// ``WorkResult.error_code`` when the per-batch ``cache_clear → evict_lru@@ -69,12 +102,12 @@ const MODEL_LOADING_ERROR_CODE: &str = "MODEL_LOADING";/// with bounded exponential backoff. The worker is **not** marked/// unhealthy — it lost an allocation race, it isn't broken.const RESOURCE_EXHAUSTED_ERROR_CODE: &str = "RESOURCE_EXHAUSTED";-const RESOURCE_EXHAUSTED_RETRY_AFTER: &str = "5";+const RESOURCE_EXHAUSTED_RETRY_AFTER: &str = RetryAfter::DEFAULT.resource_exhausted;/// Worker is loading a LoRA adapter on demand. The SDK retries this with/// the same ``provision_timeout_s`` budget it uses for ``MODEL_LOADING``;/// see ``sie_sdk.client._shared.LORA_LOADING_*``.const LORA_LOADING_ERROR_CODE: &str = "LORA_LOADING";-const LORA_LOADING_RETRY_AFTER: &str = "5";+const LORA_LOADING_RETRY_AFTER: &str = RetryAfter::DEFAULT.lora_loading;/// Terminal model load failure (non-retryable). Matches ``sie_server`` HTTP 502/// contract so ``sie_sdk`` can short-circuit before the ``MODEL_LOADING`` retry/// budget (see ``raise_if_model_load_failed``).@@ -485,6 +518,36 @@ fn record_provisioning_response(gpu: &str, bundle: &str, status: StatusCode) {.inc();}+/// Record metrics for a failed publish attempt and, for backpressure, also+/// record pending demand so KEDA scales the saturated lane.+///+/// `backpressure` means a worker exists but its lane is saturated, so the+/// lane is exactly the one to scale up. Unlike the no-worker path (which+/// records demand upstream in `resolve_routing`), nothing else signals+/// demand for an already-provisioned-but-saturated lane — without this a+/// backpressure spike returns 503 but never triggers a scale-up, so KEDA+/// stays flat while the pool stays hot. See #1568.+///+/// Returns the `Retry-After` value the caller should surface (`None` for a+/// generic publish failure). The `no consumers` case is handled by the+/// caller — it needs a provisioning response / surface-specific retry.+fn record_publish_failure(+ state: &AppState,+ pool: &str,+ gpu: &str,+ bundle: &str,+ err_lower: &str,+) -> Option<&'static str> {+ if err_lower.contains("backpressure") {+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "backpressure");+ state.demand_tracker.record(pool, gpu, bundle);+ Some(BACKPRESSURE_RETRY_AFTER)+ } else {+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "queue_publish_failed");+ None+ }+}+fn build_provisioning_response_for_surface(gpu: &str,bundle: &str,@@ -712,7 +775,6 @@ async fn batch_publish_target(("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,@@ -742,7 +804,6 @@ 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,@@ -772,7 +833,6 @@ 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,@@ -870,47 +930,112 @@ pub async fn proxy_generate(state: State<Arc<AppState>>, req: Request) -> impl Iproxy_request(state, req, "generate").await}-async fn proxy_request(- State(state): State<Arc<AppState>>,- req: Request,+/// Resolve a request's model id to its serving bundle.+///+/// Extracted from `proxy_request` (#1543) so the model→bundle decision is one+/// testable unit instead of being inlined in the 2000-line handler. Behaviour+/// is identical to the block it replaces: on any failure it returns the exact+/// caller-facing error `Response` (boxed to keep the `Result` small) that the+/// inline code produced — model-not-found 404, bundle-routing-conflict 409, or+/// the unknown-model 404 when the registry is populated. With an empty registry+/// it falls back to the caller's bundle override (or `"default"`).+fn resolve_bundle_for_request(+ registry: &ModelRegistry,+ model_name: &str,+ bundle_override: &str,+ engine_pin: Option<&str>,endpoint: &str,-) -> Response {- // SDK version skew detection- check_sdk_version(req.headers());- let provisioning_surface = provisioning_surface_for_endpoint(endpoint);-- // 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);+) -> Result<String, Box<Response>> {+ let bundle_override_ref = if bundle_override.is_empty() {+ None+ } else {+ Some(bundle_override)+ };+ let bundle = if registry.model_exists(model_name) {+ match registry.resolve_bundle_with_engine(model_name, bundle_override_ref, engine_pin) {+ Ok(b) => b,+ Err(ResolveError::ModelNotFound(e)) => {+ return Err(Box::new(endpoint_error_response(+ endpoint,+ StatusCode::NOT_FOUND,+ err_code::MODEL_NOT_FOUND,+ oai_type::MODEL_NOT_FOUND,+ oai_code::MODEL_NOT_FOUND,+ Some("model"),+ e.to_string(),+ )));+ }+ Err(ResolveError::BundleConflict(e)) => {+ // Bundle conflict is non-OpenAI shaped; keep legacy envelope+ // even for generate so the extra ``compatible_bundles`` array+ // stays accessible to existing clients.+ let mut m = Map::new();+ m.insert(+ "compatible_bundles".to_string(),+ json!(e.compatible_bundles),+ );+ return Err(Box::new(+ (+ StatusCode::CONFLICT,+ Json(json_detail_merge(+ err_code::BUNDLE_ROUTING_CONFLICT,+ e.to_string(),+ m,+ )),+ )+ .into_response(),+ ));+ }}- Some(proxy_span)+ } else if registry.has_any_models() {+ return Err(Box::new(endpoint_error_response(+ endpoint,+ StatusCode::NOT_FOUND,+ err_code::MODEL_NOT_FOUND,+ oai_type::MODEL_NOT_FOUND,+ oai_code::MODEL_NOT_FOUND,+ Some("model"),+ format!("Model '{}' not found", model_name),+ )));+ } else if bundle_override.is_empty() {+ "default".to_string()} else {- None+ bundle_override.to_string()};- let _proxy_span_guard = proxy_span.as_ref().map(|span| span.enter());+ Ok(bundle)+}+/// The routing decision for a request: canonical model name, serving bundle,+/// and engine. Produced by [`resolve_routing`].+struct RoutingResult {+ model_name: String,+ bundle: String,+ engine: String,+ gpu: String,+ pool_name: String,+ gpu_configured: bool,+}++/// Resolve a request into its routing decision (model → bundle → engine).+///+/// Extracted from `proxy_request` (#1543) so the routing decision is one unit,+/// composed of the already-tested `decode_model_path` / `resolve_model_spec_with_aliases`+/// / `parse_engine_pin` / [`resolve_bundle_for_request`] helpers. Behaviour is+/// identical to the inline block it replaces: on any failure it returns the+/// exact caller-facing error `Response` (boxed) the handler produced.+async fn resolve_routing(+ state: &AppState,+ headers: &HeaderMap,+ path: &str,+ endpoint: &str,+) -> Result<RoutingResult, Box<Response>> {// Extract model from path: /v1/{endpoint}/{model...}let prefix = format!("/v1/{}/", endpoint);- let path = req.uri().path().to_string();let raw_model = path.strip_prefix(&prefix).unwrap_or("");let model = match decode_model_path(raw_model) {Ok(model) => model,Err(message) => {- return endpoint_error_response(+ return Err(Box::new(endpoint_error_response(endpoint,StatusCode::BAD_REQUEST,err_code::INVALID_REQUEST,@@ -918,7 +1043,7 @@ async fn proxy_request(oai_code::INVALID_REQUEST,Some("model"),message,- );+ )));}};@@ -928,7 +1053,7 @@ async fn proxy_request(// empty `machine_profile` to `"unknown"` internally; `bundle`// gets the same treatment here for cardinality discipline.metrics::record_rejected_request_for_pool("unknown", "", "unknown", "model_required");- return endpoint_error_response(+ return Err(Box::new(endpoint_error_response(endpoint,StatusCode::BAD_REQUEST,err_code::INVALID_REQUEST,@@ -936,7 +1061,7 @@ async fn proxy_request(oai_code::INVALID_REQUEST,Some("model"),"model is required",- );+ )));}// Parse model spec: [bundle:/]org/model, expanding a job/friendly alias@@ -946,42 +1071,38 @@ async fn proxy_request(resolve_model_spec_with_aliases(&state.config.model_aliases, &model, |m| {state.model_registry.resolve_canonical_model_name(m)});- let bundle_override_ref = if bundle_override.is_empty() {- None- } else {- 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+ // Hidden operator/debug header: normal clients should select explicit+ // model profile variants (for example ``model:candle``) or compatible+ // bundle overrides. Lowercase normalisation + UTF-8 validation lives in// ``parse_engine_pin`` (unit-tested below).- let engine_pin = match parse_engine_pin(req.headers()) {+ let engine_pin = match parse_engine_pin(headers) {EnginePinParse::None => None,EnginePinParse::Some(eng) => Some(eng),EnginePinParse::Unknown(raw) => {use crate::types::bundle::KNOWN_ENGINES;- return (+ // Route through endpoint_error_response so `generate` (an OpenAI-+ // envelope endpoint that also flows through here) gets the OpenAI+ // shape instead of the native `detail` one. See #1567.+ return Err(Box::new(endpoint_error_response(+ endpoint,StatusCode::BAD_REQUEST,- Json(json_detail(- err_code::INVALID_REQUEST,- format!("X-SIE-Engine value {:?} is not in {:?}", raw, KNOWN_ENGINES),- )),- )- .into_response();+ err_code::INVALID_REQUEST,+ oai_type::INVALID_REQUEST,+ oai_code::INVALID_REQUEST,+ None,+ format!("X-SIE-Engine value {:?} is not in {:?}", raw, KNOWN_ENGINES),+ )));}EnginePinParse::InvalidUtf8 => {- return (+ return Err(Box::new(endpoint_error_response(+ endpoint,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();+ err_code::INVALID_REQUEST,+ oai_type::INVALID_REQUEST,+ oai_code::INVALID_REQUEST,+ None,+ "X-SIE-Engine header must be valid UTF-8 (got non-printable bytes)",+ )));}};@@ -992,60 +1113,13 @@ async fn proxy_request(// 3. Model unknown, registry empty → fall back to caller's bundle// 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_with_engine(- &model_name,- bundle_override_ref,- engine_pin.as_deref(),- ) {- Ok(b) => b,- Err(ResolveError::ModelNotFound(e)) => {- return endpoint_error_response(- endpoint,- StatusCode::NOT_FOUND,- err_code::MODEL_NOT_FOUND,- oai_type::MODEL_NOT_FOUND,- oai_code::MODEL_NOT_FOUND,- Some("model"),- e.to_string(),- );- }- Err(ResolveError::BundleConflict(e)) => {- // Bundle conflict is non-OpenAI shaped; keep legacy- // envelope even for generate so the extra- // ``compatible_bundles`` array stays accessible to- // existing clients.- let mut m = Map::new();- m.insert(- "compatible_bundles".to_string(),- json!(e.compatible_bundles),- );- return (- StatusCode::CONFLICT,- Json(json_detail_merge(- err_code::BUNDLE_ROUTING_CONFLICT,- e.to_string(),- m,- )),- )- .into_response();- }- }- } else if state.model_registry.has_any_models() {- return endpoint_error_response(- endpoint,- StatusCode::NOT_FOUND,- err_code::MODEL_NOT_FOUND,- oai_type::MODEL_NOT_FOUND,- oai_code::MODEL_NOT_FOUND,- Some("model"),- format!("Model '{}' not found", model_name),- );- } else if bundle_override.is_empty() {- "default".to_string()- } else {- bundle_override.clone()- };+ let bundle = resolve_bundle_for_request(+ &state.model_registry,+ &model_name,+ &bundle_override,+ engine_pin.as_deref(),+ endpoint,+ )?;let engine = state.model_registry@@ -1055,15 +1129,13 @@ async fn proxy_request(.unwrap_or_else(|| crate::types::bundle::DEFAULT_ENGINE.to_string());// Parse GPU from X-SIE-MACHINE-PROFILE header- let mut gpu = req- .headers()+ let mut gpu = headers.get("x-sie-machine-profile").and_then(|v| v.to_str().ok()).unwrap_or("").to_string();- let mut pool_name = req- .headers()+ let mut pool_name = headers.get("x-sie-pool").and_then(|v| v.to_str().ok()).unwrap_or("")@@ -1076,17 +1148,16 @@ async fn proxy_request(gpu = parts[1].to_string();}- // Validate the caller-supplied pool against a strict allowlist- // BEFORE it can flow into the JetStream work subject- // `sie.work.{pool}.{machine_profile}.{bundle}.{model}`. An- // out-of-charset pool would otherwise- // re-tokenise the subject (subject injection) and silently mis-route- // the request, so reject with an OpenAI-shaped 400 rather than- // mangle. Empty pool means "router picks the default pool" and is- // left untouched.+ // Validate the caller-supplied pool against a strict allowlist BEFORE it can+ // flow into the JetStream work subject+ // `sie.work.{pool}.{machine_profile}.{bundle}.{model}`. An out-of-charset+ // pool would otherwise re-tokenise the subject (subject injection) and+ // silently mis-route the request, so reject with an OpenAI-shaped 400 rather+ // than mangle. Empty pool means "gateway picks the default pool" and is left+ // untouched.if !pool_name.is_empty() && !is_valid_pool_name(&pool_name) {metrics::record_rejected_request_for_pool("unknown", &gpu, &bundle, "invalid_pool");- return endpoint_error_response(+ return Err(Box::new(endpoint_error_response(endpoint,StatusCode::BAD_REQUEST,err_code::INVALID_REQUEST,@@ -1094,7 +1165,7 @@ async fn proxy_request(oai_code::INVALID_REQUEST,Some("pool"),"Invalid pool name: only [A-Za-z0-9_-] are allowed (max 128 chars)",- );+ )));}if !pool_name.is_empty() {pool_name = normalize_pool_name(&pool_name);@@ -1108,7 +1179,7 @@ async fn proxy_request(.await{metrics::record_rejected_request_for_pool(&pool_name, &gpu, &bundle, "pool_mismatch");- return endpoint_error_response(+ return Err(Box::new(endpoint_error_response(endpoint,StatusCode::BAD_REQUEST,err_code::INVALID_REQUEST,@@ -1116,7 +1187,7 @@ async fn proxy_request(oai_code::INVALID_REQUEST,Some("pool"),message,- );+ )));}// Resolve bare GPU to spot variant@@ -1124,9 +1195,9 @@ async fn proxy_request(gpu = resolve_machine_profile(&gpu, &state.config.gpu_profile_map);}- // Validate GPU is configured. Compute this *before* tagging the- // metric label slot so an arbitrary, unconfigured, caller-supplied- // GPU never reaches a Prometheus label (unbounded cardinality / DoS).+ // Validate GPU is configured. Compute this *before* tagging the metric label+ // slot so an arbitrary, unconfigured, caller-supplied GPU never reaches a+ // Prometheus label (unbounded cardinality / DoS).let gpu_configured = gpu.is_empty()|| state.config.configured_gpus.is_empty()|| state@@ -1135,6 +1206,79 @@ async fn proxy_request(.iter().any(|cg| cg.eq_ignore_ascii_case(&gpu));+ Ok(RoutingResult {+ model_name,+ bundle,+ engine,+ gpu,+ pool_name,+ gpu_configured,+ })+}++async fn proxy_request(+ State(state): State<Arc<AppState>>,+ req: Request,+ endpoint: &str,+) -> Response {+ // SDK version skew detection+ check_sdk_version(req.headers());+ let provisioning_surface = provisioning_surface_for_endpoint(endpoint);++ // 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;+ let _ = proxy_span.set_parent(parent_cx);+ }+ Some(proxy_span)+ } else {+ None+ };+ let _proxy_span_guard = proxy_span.as_ref().map(|span| span.enter());++ // #1500: non-generation endpoints (encode / score / extract /+ // embeddings) do not open a billed gateway span, but the+ // queue-publish path still needs the inbound W3C context so+ // `inject_current_context()` re-emits it into the work-item envelope+ // (otherwise the worker's `worker.run_batch` span roots a fresh trace+ // instead of continuing the client's). We capture the extracted+ // context here and scope it over the publish future via+ // `with_context` (Send- and thread-hop-safe, unlike attaching a+ // `!Send` `ContextGuard` across the handler's awaits). The generation+ // branch already establishes the context via its proxy span.+ // Borrow `proxy_span` (don't move it) — `_proxy_span_guard` holds a+ // live borrow of it via `span.enter()` for the rest of the handler.+ let inbound_publish_cx = if proxy_span.is_some() {+ None+ } else {+ Some(crate::observability::propagation::extract_context_from_headers(req.headers()))+ };++ let RoutingResult {+ model_name,+ bundle,+ engine,+ gpu,+ pool_name,+ gpu_configured,+ } = match resolve_routing(&state, req.headers(), req.uri().path(), endpoint).await {+ Ok(r) => r,+ Err(resp) => return *resp,+ };+// Publish the canonical `machine_profile` to the HTTP metrics// middleware via a request extension slot. The middleware reads// this AFTER the inner service responds, so every downstream@@ -1364,7 +1508,7 @@ async fn proxy_request(}};- queue_mode_proxy(+ let publish_fut = queue_mode_proxy(&state,work_publisher,endpoint,@@ -1382,8 +1526,46 @@ async fn proxy_request(Instant::now(),&bundle_config_hash,batch_target,- )- .await+ );+ // Scope an OTel context over the publish so the work-item envelope+ // carries it (#1500): when the exporter is on we open a `gateway.publish`+ // span and scope *its* context (first arm, #1596); otherwise we scope the+ // raw inbound context (second arm). `with_context` re-attaches on every+ // poll, so `Context::current()` is correct across the publish's own+ // `.await`s and tokio thread hops — and the future stays `Send`, unlike+ // holding a `!Send` `ContextGuard` across awaits.+ use opentelemetry::trace::FutureExt;+ use tracing::Instrument;+ let cls = crate::endpoint::InferenceEndpoint::from_label(endpoint);+ match inbound_publish_cx {+ Some(inbound_cx)+ if cls.uses_publish_gateway_span()+ && crate::observability::tracing::exporter_enabled() =>+ {+ // #1596: give the non-streaming queue-publish path a sampled gateway+ // span so we get edge latency attribution + a stable trace root. We+ // scope the span's OWN context (not the raw inbound context) over the+ // publish so the worker attaches to `gateway.publish`.+ let span = tracing::info_span!(+ "gateway.publish",+ sie.endpoint = endpoint,+ sie.model = %model_name,+ sie.pool = %effective_pool,+ sie.publish_ms = tracing::field::Empty,+ );+ {+ use tracing_opentelemetry::OpenTelemetrySpanExt;+ let _ = span.set_parent(inbound_cx);+ }+ let publish_cx = {+ use tracing_opentelemetry::OpenTelemetrySpanExt;+ span.context()+ };+ publish_fut.with_context(publish_cx).instrument(span).await+ }+ Some(inbound_cx) => publish_fut.with_context(inbound_cx).await,+ None => publish_fut.await,+ }}fn should_trace_proxy_request(endpoint: &str) -> bool {@@ -1716,18 +1898,10 @@ async fn queue_mode_proxy().into_response();- if lower.contains("backpressure") {- metrics::record_rejected_request_for_pool(pool, gpu, bundle, "backpressure");+ if let Some(retry_after) = record_publish_failure(state, pool, gpu, bundle, &lower) {response.headers_mut().insert(HeaderName::from_static("retry-after"),- HeaderValue::from_static(BACKPRESSURE_RETRY_AFTER),- );- } else {- metrics::record_rejected_request_for_pool(- pool,- gpu,- bundle,- "queue_publish_failed",+ HeaderValue::from_static(retry_after),);}@@ -1751,11 +1925,14 @@ async fn queue_mode_proxy(}}let publish_elapsed = publish_start.elapsed();+ tracing::Span::current().record("sie.publish_ms", publish_elapsed.as_millis() as i64);- // Wait for results (use configured request_timeout instead of hardcoded 300s)- let timeout_secs = state.config.request_timeout as u64;+ // Wait for results (use configured request_timeout instead of hardcoded 300s).+ // Preserve fractional env values instead of truncating them through `as u64`.+ let timeout = Duration::from_secs_f64(state.config.request_timeout.max(0.001));+ let timeout_secs = timeout.as_secs_f64();let wait_start = Instant::now();- let results = match tokio::time::timeout(Duration::from_secs(timeout_secs), rx).await {+ let results = match tokio::time::timeout(timeout, rx).await {Ok(Ok(results)) => results,Ok(Err(_)) => {metrics::record_rejected_request_for_pool(pool, gpu, bundle, "result_channel_closed");@@ -1769,27 +1946,13 @@ async fn queue_mode_proxy(.into_response();}Err(_) => {- // Upstream timeout: the most common cause is a worker cold-loading- // the target model on demand. The worker NAKs the JetStream message- // and redelivers after load, but that cycle typically exceeds our- // per-request timeout on the first call. Surface this as- // 503 + MODEL_LOADING so SDK clients with wait_for_capacity=True- // retry using the existing model-loading contract rather than- // failing the cold-start request. Genuinely hung upstreams are- // still bounded by the SDK's provision_timeout_s budget.- //- // The rejection reason is intentionally only the specific- // `upstream_timeout_model_loading` — emitting both that- // and a generic `result_timeout` for the same event would- // double-count the timeout on the error-rate dashboards- // and break rate alerts that sum across reasons.- metrics::record_rejected_request_for_pool(- pool,- gpu,- bundle,- "upstream_timeout_model_loading",- );- return build_model_loading_timeout_response(model, timeout_secs);+ // The gateway accepted and published work, but no worker result+ // arrived before the request deadline. This is not the same signal+ // as worker-emitted MODEL_LOADING: under heavy load it usually+ // means queue/head-of-line delay or a lost NATS Core result, and+ // reporting it as MODEL_LOADING hides the real bottleneck.+ metrics::record_rejected_request_for_pool(pool, gpu, bundle, "upstream_result_timeout");+ return build_queue_result_timeout_response(model, timeout_secs);}};let wait_elapsed = wait_start.elapsed();@@ -2273,17 +2436,9 @@ pub(crate) async fn run_streaming_generate(let retry_after = if lower.contains("no consumers") {metrics::record_rejected_request_for_pool(pool, gpu, bundle, "no_consumers");Some(PROVISIONING_RETRY_AFTER)- } else if lower.contains("backpressure") {- metrics::record_rejected_request_for_pool(pool, gpu, bundle, "backpressure");- Some(BACKPRESSURE_RETRY_AFTER)} else {- metrics::record_rejected_request_for_pool(- pool,- gpu,- bundle,- "queue_publish_failed",- );- None+ // backpressure (records demand for KEDA) / generic failure. #1568+ record_publish_failure(state, pool, gpu, bundle, &lower)};return Err(StreamingDriverErr::PublishFailed {message: e,@@ -5152,7 +5307,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res);{use tracing_opentelemetry::OpenTelemetrySpanExt;- chat_span.set_parent(parent_cx);+ let _ = chat_span.set_parent(parent_cx);}let _chat_span_guard = chat_span.enter();@@ -7036,39 +7191,37 @@ fn build_retryable_error_response(code: &'static str, message: &str) -> Responseresp}-/// Build a `503 + MODEL_LOADING` response for an upstream timeout.+/// Build a gateway-owned timeout response for a queued request whose worker+/// result did not arrive within the configured request deadline.///-/// Mirrors the contract the SDK already implements for worker-emitted-/// `MODEL_LOADING` errors (see `sie_sdk.client._shared`):+/// Worker-emitted `MODEL_LOADING` still uses the retryable 503 worker contract.+/// This path is different: the gateway already accepted/published the request+/// and timed out waiting for the NATS Core result, so surface an explicit+/// gateway timeout instead of pretending the model is still loading.///-/// * status: 503 Service Unavailable-/// * body: `{"error": {"code": "MODEL_LOADING", "message": ...}}`-/// * headers: `Retry-After: 5`, plus the standard `X-SIE-*` version pair.-fn build_model_loading_timeout_response(model: &str, timeout_secs: u64) -> Response {+/// * status: 504 Gateway Timeout+/// * body: `{"detail": {"code": "GATEWAY_TIMEOUT", "message": ...}}`+/// * headers: `Retry-After: 5`, `X-SIE-Error-Code: GATEWAY_TIMEOUT`, plus the+/// standard `X-SIE-*` version pair.+fn build_queue_result_timeout_response(model: &str, timeout_secs: f64) -> Response {let mut resp = (- StatusCode::SERVICE_UNAVAILABLE,- Json(json!({- "error": {- "code": MODEL_LOADING_ERROR_CODE,- "message": format!(- "Model '{}' did not respond within {}s; worker may be loading the model on demand. Please retry.",- model, timeout_secs- ),- },- })),+ StatusCode::GATEWAY_TIMEOUT,+ Json(json_detail(+ err_code::GATEWAY_TIMEOUT,+ format!(+ "Timed out waiting {:.1}s for queued result from model '{}'. The request was published, but no worker result reached the gateway before the deadline.",+ timeout_secs, model+ ),+ )),).into_response();resp.headers_mut().insert(HeaderName::from_static("retry-after"),- HeaderValue::from_static(MODEL_LOADING_RETRY_AFTER),+ HeaderValue::from_static(GATEWAY_TIMEOUT_RETRY_AFTER),);- // Advertised in architecture-guide.md, README.md, and- // docs/queue-based-routing.md. The SDK parses the body (see- // sie_sdk.client._shared.get_error_code), but external clients and- // retry/observability middleware key off this header.resp.headers_mut().insert(HeaderName::from_static("x-sie-error-code"),- HeaderValue::from_static(MODEL_LOADING_ERROR_CODE),+ HeaderValue::from_static(err_code::GATEWAY_TIMEOUT),);resp.headers_mut().insert(HeaderName::from_static("x-sie-version"),@@ -7396,6 +7549,26 @@ fn is_openai_embeddings_forwarded_header(name: &str) -> bool {.any(|allowed| name.eq_ignore_ascii_case(allowed))}+/// Headers copied from an inbound ``/v1/embeddings`` request onto the+/// internal ``/v1/encode`` request it is rewritten into. Auth/routing+/// hints plus the W3C trace headers (`traceparent`/`tracestate`) so the+/// worker span continues the client's trace instead of rooting a fresh+/// one — every other endpoint already injects queue trace context, and+/// without this embeddings would be the lone disconnected path.+fn is_openai_embeddings_inner_request_header(name: &str) -> bool {+ [+ "authorization",+ "x-sie-machine-profile",+ "x-sie-pool",+ "x-sie-engine",+ "x-sie-sdk-version",+ "traceparent",+ "tracestate",+ ]+ .iter()+ .any(|allowed| name.eq_ignore_ascii_case(allowed))+}+/// Re-surface a SIE-native error response from the inner ``/v1/encode``/// call (used to service ``/v1/embeddings``) in the OpenAI ``{error:{…}}``/// envelope. The inner path emits ``{detail:{code,message}}`` (and, for the@@ -9679,7 +9852,6 @@ 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(@@ -9800,14 +9972,12 @@ pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Relet extensions = parts.extensions;let mut inner_headers = HeaderMap::new();for (name, val) in hdr.iter() {- let n = name.as_str();- if n.eq_ignore_ascii_case("authorization")- || n.eq_ignore_ascii_case("x-sie-machine-profile")- || n.eq_ignore_ascii_case("x-sie-pool")- || n.eq_ignore_ascii_case("x-sie-engine")- || n.eq_ignore_ascii_case("x-sie-sdk-version")- {- inner_headers.insert(name.clone(), val.clone());+ if is_openai_embeddings_inner_request_header(name.as_str()) {+ // `append`, not `insert`: W3C `tracestate` may arrive as+ // multiple header fields and `HeaderMap::iter()` yields each+ // separately — `insert` would drop all but the last, so a+ // multi-line `tracestate` would be truncated before forwarding.+ inner_headers.append(name.clone(), val.clone());}}inner_headers.insert(@@ -10245,6 +10415,93 @@ mod tests {);}+ #[test]+ fn test_resolve_bundle_for_request_empty_registry_falls_back_to_caller() {+ // With an empty registry (no models), the resolver falls back to the+ // caller's bundle override, or "default" when none is given — the same+ // branch the inline `proxy_request` block took before #1543.+ let bundles_dir = tempfile::TempDir::new().unwrap();+ let models_dir = tempfile::TempDir::new().unwrap();+ let registry = ModelRegistry::new(bundles_dir.path(), models_dir.path(), true);+ assert!(!registry.has_any_models());++ let default = resolve_bundle_for_request(®istry, "org/model", "", None, "encode")+ .expect("empty registry + no override resolves");+ assert_eq!(default, "default");++ let overridden =+ resolve_bundle_for_request(®istry, "org/model", "custom-bundle", None, "encode")+ .expect("empty registry preserves caller bundle");+ assert_eq!(overridden, "custom-bundle");+ }++ #[tokio::test]+ async fn test_endpoint_error_response_envelope_matches_endpoint() {+ // generate/chat use the OpenAI `{error:{...}}` envelope; native endpoints+ // keep `{detail:{...}}`. The engine-pin errors now route through this+ // helper so a bad X-SIE-Engine on /v1/generate gets the OpenAI shape+ // rather than the native one. See #1567.+ let openai = endpoint_error_response(+ "generate",+ StatusCode::BAD_REQUEST,+ err_code::INVALID_REQUEST,+ oai_type::INVALID_REQUEST,+ oai_code::INVALID_REQUEST,+ None,+ "bad engine",+ );+ let native = endpoint_error_response(+ "encode",+ StatusCode::BAD_REQUEST,+ err_code::INVALID_REQUEST,+ oai_type::INVALID_REQUEST,+ oai_code::INVALID_REQUEST,+ None,+ "bad engine",+ );+ let openai_body: serde_json::Value = serde_json::from_slice(+ &axum::body::to_bytes(openai.into_body(), usize::MAX)+ .await+ .unwrap(),+ )+ .unwrap();+ let native_body: serde_json::Value = serde_json::from_slice(+ &axum::body::to_bytes(native.into_body(), usize::MAX)+ .await+ .unwrap(),+ )+ .unwrap();+ assert!(+ openai_body.get("error").is_some(),+ "generate must use the OpenAI envelope"+ );+ assert!(+ native_body.get("detail").is_some(),+ "encode must use the native envelope"+ );+ }++ #[test]+ fn test_retry_after_defaults_pin_wire_values() {+ // These Retry-After wire strings are part of the capacity contract+ // clients/SDKs honor; pin them. See #1574.+ assert_eq!(RetryAfter::DEFAULT.provisioning, "60");+ assert_eq!(RetryAfter::DEFAULT.backpressure, "5");+ assert_eq!(RetryAfter::DEFAULT.gateway_timeout, "5");+ assert_eq!(RetryAfter::DEFAULT.model_loading, "5");+ assert_eq!(RetryAfter::DEFAULT.resource_exhausted, "5");+ assert_eq!(RetryAfter::DEFAULT.lora_loading, "5");+ // The named constants alias the typed home — pin each against its wire+ // literal (not against `RetryAfter::DEFAULT.*`, which would be a+ // tautological `x == x`), so a broken alias is actually caught.+ assert_eq!(PROVISIONING_RETRY_AFTER, "60");+ assert_eq!(BACKPRESSURE_RETRY_AFTER, "5");+ assert_eq!(GATEWAY_TIMEOUT_RETRY_AFTER, "5");+ assert_eq!(MODEL_LOADING_RETRY_AFTER, "5");+ assert_eq!(RESOURCE_EXHAUSTED_RETRY_AFTER, "5");+ assert_eq!(LORA_LOADING_RETRY_AFTER, "5");+ }+fn admission_test_state(pool_manager: Arc<PoolManager>) -> AppState {let bundles_dir = tempfile::TempDir::new().unwrap();let models_dir = tempfile::TempDir::new().unwrap();@@ -10463,6 +10720,46 @@ mod tests {state.demand_tracker.clear(demand_pool, "l4", bundle);}+ #[tokio::test]+ async fn test_record_publish_failure_backpressure_records_demand() {+ // Backpressure (a present-but-saturated worker) must record pending+ // demand so KEDA scales the lane; a generic publish failure must not.+ // See #1568.+ let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));+ let state = admission_test_state(Arc::clone(&pm));+ let bp_pool = "test-bp-demand-pool";+ let other_pool = "test-other-failure-pool";+ let bundle = "test-bp-demand-bundle";++ let retry = record_publish_failure(+ &state,+ bp_pool,+ "l4",+ bundle,+ "stream publish failed: backpressure (lane saturated)",+ );+ assert_eq!(retry, Some(BACKPRESSURE_RETRY_AFTER));+ let demand = metrics::PENDING_DEMAND+ .with_label_values(&[bp_pool, "l4", bundle])+ .get();+ assert!(+ (demand - 1.0).abs() < f64::EPSILON,+ "backpressure must record pending demand for KEDA"+ );+ state.demand_tracker.clear(bp_pool, "l4", bundle);++ let retry_other =+ record_publish_failure(&state, other_pool, "l4", bundle, "connection reset by peer");+ assert_eq!(retry_other, None);+ let demand_other = metrics::PENDING_DEMAND+ .with_label_values(&[other_pool, "l4", bundle])+ .get();+ assert!(+ (demand_other - 0.0).abs() < f64::EPSILON,+ "a generic publish failure must not record demand"+ );+ }+#[tokio::test]async fn test_batch_publish_target_directs_capped_logical_pool_to_assigned_cold_worker() {let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));@@ -11400,6 +11697,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: false,};let body = build_generate_success_body("Qwen/Qwen3-4B-Instruct", &[&r], false);let value: serde_json::Value = serde_json::from_slice(&body).unwrap();@@ -11540,62 +11838,50 @@ mod tests {assert_eq!(value["tpot_ms"], 45.2);}- // ── build_model_loading_timeout_response ──────────────────────+ // ── build_queue_result_timeout_response ──────────────────────//- // The queue proxy used to return 504 Gateway Timeout whenever the- // JetStream result channel did not reply within- // `request_timeout` seconds. The SDK has no retry branch for 504,- // which meant a cold-start request that triggered a worker-side- // model load (worker NAKs + redelivers after load) would bubble- // up as a hard failure even though `wait_for_capacity=True` was- // set. We now map that timeout to 503 + MODEL_LOADING, which the- // SDK already retries under the same `provision_timeout_s`- // budget it uses for worker-emitted MODEL_LOADING responses.+ // A gateway-side result wait timeout is distinct from worker-emitted+ // MODEL_LOADING. Keep the signal explicit so load tests and dashboards do+ // not misread queue/head-of-line stalls as cold model loads.#[test]- fn test_build_model_loading_timeout_response_is_503_with_error_code() {- let resp = build_model_loading_timeout_response("BAAI/bge-m3", 30);- assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ fn test_build_queue_result_timeout_response_is_504() {+ let resp = build_queue_result_timeout_response("BAAI/bge-m3", 30.0);+ assert_eq!(resp.status(), StatusCode::GATEWAY_TIMEOUT);}#[test]- fn test_build_model_loading_timeout_response_sets_retry_after_and_version_headers() {- let resp = build_model_loading_timeout_response("BAAI/bge-m3", 30);+ fn test_build_queue_result_timeout_response_sets_retry_after_and_version_headers() {+ let resp = build_queue_result_timeout_response("BAAI/bge-m3", 30.0);let headers = resp.headers();assert_eq!(headers.get("retry-after").unwrap(),- MODEL_LOADING_RETRY_AFTER+ GATEWAY_TIMEOUT_RETRY_AFTER);assert!(headers.get("x-sie-version").is_some());assert!(headers.get("x-sie-server-version").is_some());}#[test]- fn test_build_model_loading_timeout_response_sets_error_code_header() {- // The documented contract (architecture-guide.md, README.md,- // docs/queue-based-routing.md) advertises `X-SIE-Error-Code:- // MODEL_LOADING` alongside the body field. External clients and- // observability middleware key off the header, so it must be- // set even though the SDK itself reads the body.- let resp = build_model_loading_timeout_response("BAAI/bge-m3", 30);+ fn test_build_queue_result_timeout_response_sets_error_code_header() {+ let resp = build_queue_result_timeout_response("BAAI/bge-m3", 30.0);assert_eq!(resp.headers().get("x-sie-error-code").unwrap(),- MODEL_LOADING_ERROR_CODE+ err_code::GATEWAY_TIMEOUT);}#[tokio::test]- async fn test_build_model_loading_timeout_response_body_matches_sdk_error_contract() {- // SDK parses `error.code` for the retry decision; body must- // include the MODEL_LOADING code and mention the model id.- let resp = build_model_loading_timeout_response("BAAI/bge-m3", 30);+ async fn test_build_queue_result_timeout_response_body_is_gateway_detail_contract() {+ let resp = build_queue_result_timeout_response("BAAI/bge-m3", 30.0);let body_bytes = axum::body::to_bytes(resp.into_body(), 64 * 1024).await.expect("read body");let body: serde_json::Value =serde_json::from_slice(&body_bytes).expect("response body is valid JSON");- assert_eq!(body["error"]["code"], MODEL_LOADING_ERROR_CODE);- let msg = body["error"]["message"].as_str().unwrap_or("");+ assert_eq!(body["detail"]["code"], err_code::GATEWAY_TIMEOUT);+ assert!(body.get("error").is_none());+ let msg = body["detail"]["message"].as_str().unwrap_or("");assert!(msg.contains("BAAI/bge-m3"),"message references the model id: {msg}"@@ -11803,6 +12089,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: false,}}@@ -11822,6 +12109,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: false,}}@@ -12008,6 +12296,33 @@ mod tests {assert!(!is_openai_embeddings_forwarded_header("x-sie-error-code"));}+ #[test]+ fn test_openai_embeddings_inner_request_forwards_trace_context() {+ // Auth/routing hints plus the W3C trace headers must reach the+ // internal /v1/encode request so the worker span continues the+ // client's trace (otherwise embeddings is the lone disconnected+ // path — every other endpoint injects queue trace context).+ for name in [+ "authorization",+ "x-sie-machine-profile",+ "x-sie-pool",+ "x-sie-engine",+ "x-sie-sdk-version",+ "traceparent",+ "tracestate",+ ] {+ assert!(+ is_openai_embeddings_inner_request_header(name),+ "{name} should be forwarded onto the internal /v1/encode request"+ );+ }+ assert!(is_openai_embeddings_inner_request_header("TraceParent"));+ assert!(!is_openai_embeddings_inner_request_header("cookie"));+ assert!(!is_openai_embeddings_inner_request_header(+ "x-sie-request-id"+ ));+ }+#[test]fn test_openai_embedding_value_base64_is_little_endian_f32() {let encoded = openai_embedding_value(vec![1.0, -2.0], "base64");@@ -12282,6 +12597,10 @@ mod tests {parse_engine_pin(&hdr(b"pytorch")),EnginePinParse::Some("pytorch".to_string()),);+ assert_eq!(+ parse_engine_pin(&hdr(b"candle")),+ EnginePinParse::Some("candle".to_string()),+ );}#[test]@@ -12300,11 +12619,9 @@ mod tests {#[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()),+ parse_engine_pin(&hdr(b"future-engine")),+ EnginePinParse::Unknown("future-engine".to_string()),);assert_eq!(parse_engine_pin(&hdr(b"jax")),@@ -12826,6 +13143,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: false,};let resp_body = result.result_msgpack.clone();assert_eq!(resp_body, payload);@@ -12861,6 +13179,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: false,},publisher::WorkResult {work_item_id: "r1.1".to_string(),@@ -12877,6 +13196,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: false,},];let items: Vec<serde_json::Value> = resultsdiff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rsindex f9a15f390..20eb5c95d 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -458,6 +458,10 @@ async fn run_sse_driver(args: SseDriverArgs) {// (`biased`) iteration would re-poll the now-consumed receiver and// panic on the request path. Disable the branch once it has fired.let mut outcome_done = false;+ // Latched when the terminal outcome resolves Ok (the generation completed+ // server-side). The Lagged arm uses it to skip a pointless worker cancel+ // for an already-completed request. #1602+ let mut stream_succeeded = false;// Helper: send an SSE event onto the mpsc channel. Returns false// if the receiver is closed (HTTP client disconnect), which is@@ -693,11 +697,14 @@ async fn run_sse_driver(args: SseDriverArgs) {publisher.drop_pending_stream(&request_id);return;}- // A success outcome resolved here means the- // terminal chunk was already forwarded through the- // tap (which fires the oneshot on the same- // terminal apply). The chunk arm's `is_terminal`- // branch owns the `[DONE]`; nothing more to do.+ // A success outcome resolved here means the terminal+ // chunk was already forwarded through the tap (which+ // fires the oneshot on the same terminal apply). The+ // chunk arm's `is_terminal` branch owns the `[DONE]`;+ // latch that the generation completed server-side so the+ // Lagged arm can skip a pointless cancel of an+ // already-finished request. See #1602.+ stream_succeeded = true;continue;}Err(_) => {@@ -727,10 +734,19 @@ async fn run_sse_driver(args: SseDriverArgs) {let chunk = match recv_result {Ok(c) => c,Err(broadcast::error::RecvError::Lagged(n)) => {+ // A lagged consumer means the sender overwrote `n` of the+ // oldest still-UNforwarded chunks in the bounded broadcast ring+ // before this driver read them, so the client's response is+ // genuinely INCOMPLETE — real content was dropped. (If all+ // content had been forwarded, the cursor would be caught up and+ // recv() would return the terminal in order, not `Lagged`.)+ // Always surface that: a bare `[DONE]` would present a+ // silently-truncated stream as a complete success. See #1602.warn!(request_id = %request_id,lagged = n,- "SSE consumer lagged behind chunk tap; surfacing as inter_chunk_timeout"+ succeeded = stream_succeeded,+ "SSE consumer lagged behind chunk tap; response is incomplete");send_error_chunk(&event_tx,@@ -740,12 +756,18 @@ async fn run_sse_driver(args: SseDriverArgs) {&model,&request_id,"inter_chunk_timeout",- "SSE consumer fell behind",+ "SSE consumer fell behind; response is incomplete",).await;send_done(&event_tx).await;cancel_guard.defuse();- publisher.publish_cancel(&request_id).await;+ // Only cancel the worker if the generation is still in flight.+ // A request whose terminal outcome already resolved Ok has+ // completed server-side — there is nothing to cancel, so the+ // publish_cancel would be a redundant wire op. See #1602.+ if !stream_succeeded {+ publisher.publish_cancel(&request_id).await;+ }publisher.drop_pending_stream(&request_id);return;}diff --git a/packages/sie_gateway/src/main.rs b/packages/sie_gateway/src/main.rsindex e1bead186..a70b6dba4 100644--- a/packages/sie_gateway/src/main.rs+++ b/packages/sie_gateway/src/main.rs@@ -129,6 +129,10 @@ async fn main() {bundles_dir,models_dir,} => {+ // Release images enable cloud-storage: object_store selects aws-lc-rs+ // while NATS/Kubernetes select ring. Pick one provider before TLS clients start.+ let _ = rustls::crypto::ring::default_provider().install_default();+// Load config from env varslet mut cfg = Config::load();diff --git a/packages/sie_gateway/src/metrics.rs b/packages/sie_gateway/src/metrics.rsindex 1cfcc531d..c97712957 100644--- a/packages/sie_gateway/src/metrics.rs+++ b/packages/sie_gateway/src/metrics.rs@@ -123,6 +123,8 @@ pub static REGISTRY: LazyLock<Registry> = LazyLock::new(|| {r.register(Box::new(QUEUE_ACK_FAILURES.clone())).unwrap();r.register(Box::new(GENERATION_STALE_ATTEMPT_CHUNKS.clone())).unwrap();+ r.register(Box::new(GENERATION_STALE_ATTEMPT_NAKS.clone()))+ .unwrap();r.register(Box::new(GENERATION_INVALID_CHUNKS.clone())).unwrap();r.register(Box::new(GENERATION_SEQ_GAP_CHUNKS.clone()))@@ -575,6 +577,25 @@ pub static GENERATION_STALE_ATTEMPT_CHUNKS: LazyLock<CounterVec> = LazyLock::new.unwrap()});+// sie_gateway_generation_stale_attempt_naks_total+//+// Counts NAKs dropped because their ``attempt_id`` does not match the+// latched attempt for the request. The canonical producer is a late NAK from+// an attempt already abandoned by a first-chunk-timeout/NAK republish: acting+// on it would tear down the healthy successor stream that re-latched a newer+// attempt (#1601). Mirrors ``GENERATION_STALE_ATTEMPT_CHUNKS`` on the chunk+// path.+pub static GENERATION_STALE_ATTEMPT_NAKS: LazyLock<CounterVec> = LazyLock::new(|| {+ CounterVec::new(+ Opts::new(+ "sie_gateway_generation_stale_attempt_naks_total",+ "NAKs dropped due to stale attempt_id",+ ),+ &["model", "pool"],+ )+ .unwrap()+});+// sie_gateway_generation_invalid_chunks_total//// Counts chunks rejected by ``StreamCollector::apply`` after deserialization@@ -1116,14 +1137,18 @@ pub fn record_rejected_request_for_pool(bundle: &str,reason: &str,) {- let effective_pool = if pool.is_empty() { "unknown" } else { pool };- let effective_profile = if machine_profile.is_empty() {- "unknown"- } else {- machine_profile- };+ // Route the caller-influenced labels through the canonical `sanitize_label`+ // (empty -> "unknown", over-length / junk-charset -> "invalid") rather than+ // an ad-hoc empty-check. This also normalizes `bundle` — previously passed+ // raw, so call sites compensated by hand-passing a literal "unknown" — and+ // gives the rejected-requests metric the same cardinality / charset bound+ // the rest of the label surface already has. `reason` is a fixed in-tree+ // literal, not caller-influenced, so it is left as-is.+ let pool = sanitize_label(pool);+ let machine_profile = sanitize_label(machine_profile);+ let bundle = sanitize_label(bundle);REJECTED_REQUESTS- .with_label_values(&[effective_pool, effective_profile, bundle, reason])+ .with_label_values(&[&pool, &machine_profile, &bundle, reason]).inc();}@@ -2189,6 +2214,35 @@ mod tests {assert!((after - before - 1.0).abs() < f64::EPSILON);}+ /// `record_rejected_request_for_pool` routes all three caller-influenced+ /// labels through `sanitize_label`, so empty pool/profile/**bundle** all+ /// normalize to "unknown" (bundle was previously passed raw). See #1573.+ #[test]+ fn test_record_rejected_normalizes_labels_via_sanitize() {+ let _guard = METRICS_TEST_LOCK.lock().unwrap();+ let reason = "test_normalizes_via_sanitize";+ let unknown_before = REJECTED_REQUESTS+ .with_label_values(&["unknown", "unknown", "unknown", reason])+ .get();++ record_rejected_request_for_pool("", "", "", reason);++ assert_eq!(+ REJECTED_REQUESTS+ .with_label_values(&["unknown", "unknown", "unknown", reason])+ .get(),+ unknown_before + 1.0,+ "empty labels must normalize to the 'unknown' series"+ );+ assert_eq!(+ REJECTED_REQUESTS+ .with_label_values(&["", "", "", reason])+ .get(),+ 0.0,+ "the raw empty-label series must never be touched (bundle included)"+ );+ }+/// Without `init_metric_families`, `*Vec` metrics with no/// observations are silently elided by Prometheus' text encoder,/// so a freshly booted gateway shows "no data" for the@@ -2286,6 +2340,9 @@ mod tests {GENERATION_STALE_ATTEMPT_CHUNKS.with_label_values(&["surface/model", "surface/pool"]).inc();+ GENERATION_STALE_ATTEMPT_NAKS+ .with_label_values(&["surface/model", "surface/pool"])+ .inc();GENERATION_TIMEOUTS.with_label_values(&["surface/model", "surface/pool", "first_chunk"]).inc();@@ -2306,6 +2363,7 @@ mod tests {"sie_gateway_generation_total_tokens","sie_gateway_routing_fallback_total","sie_gateway_generation_stale_attempt_chunks_total",+ "sie_gateway_generation_stale_attempt_naks_total","sie_gateway_routing_cache_hit_estimate","sie_gateway_kv_reservation_known","sie_gateway_generation_timeout_total",diff --git a/packages/sie_gateway/src/nats/manager.rs b/packages/sie_gateway/src/nats/manager.rsindex 87f94883f..d08421095 100644--- a/packages/sie_gateway/src/nats/manager.rs+++ b/packages/sie_gateway/src/nats/manager.rs@@ -61,6 +61,10 @@ pub struct ConfigNotification {pub model_config: String,#[serde(default)]pub affected_bundles: Vec<String>,+ #[serde(default)]+ pub pool: Option<String>,+ #[serde(default)]+ pub bundle_pool_config_hashes: HashMap<String, HashMap<String, String>>,}pub struct NatsManager {@@ -339,6 +343,11 @@ impl NatsManager {notification.bundle_config_hash.clone(),)]));}+ if !notification.bundle_pool_config_hashes.is_empty() {+ self.model_registry.install_bundle_pool_config_hashes(+ notification.bundle_pool_config_hashes.clone(),+ );+ }self.config_epoch.set_max(notification.epoch);metrics::CONFIG_DELTAS.with_label_values(&[kind, "applied"])@@ -376,6 +385,11 @@ mod tests {profiles_added: vec!["default".to_string(), "fast".to_string()],model_config: "name: bge-m3\nprofiles: {}\n".to_string(),affected_bundles: vec!["default".to_string(), "premium".to_string()],+ pool: Some("default".to_string()),+ bundle_pool_config_hashes: HashMap::from([(+ "default".to_string(),+ HashMap::from([("default".to_string(), "pool-hash".to_string())]),+ )]),};let json = serde_json::to_string(¬ification).unwrap();@@ -388,6 +402,15 @@ mod tests {assert_eq!(parsed.model_id, "BAAI/bge-m3");assert_eq!(parsed.profiles_added, vec!["default", "fast"]);assert_eq!(parsed.affected_bundles, vec!["default", "premium"]);+ assert_eq!(parsed.pool.as_deref(), Some("default"));+ assert_eq!(+ parsed+ .bundle_pool_config_hashes+ .get("default")+ .and_then(|hashes| hashes.get("default"))+ .map(String::as_str),+ Some("pool-hash")+ );}#[test]@@ -407,6 +430,8 @@ mod tests {assert!(parsed.profiles_added.is_empty());assert!(parsed.model_config.is_empty());assert!(parsed.affected_bundles.is_empty());+ assert!(parsed.pool.is_none());+ assert!(parsed.bundle_pool_config_hashes.is_empty());}#[test]@@ -566,6 +591,8 @@ mod tests {profiles_added: Vec::new(),model_config: String::new(),affected_bundles: Vec::new(),+ pool: None,+ bundle_pool_config_hashes: HashMap::new(),};manager.apply_notification(¬ification).await;assert_eq!(@@ -591,6 +618,8 @@ profiles:"#.to_string(),affected_bundles: vec!["default".to_string()],+ pool: None,+ bundle_pool_config_hashes: HashMap::new(),};manager.apply_notification(¬ification_with_body).await;assert_eq!(@@ -684,6 +713,11 @@ profiles:"#.to_string(),affected_bundles: vec!["default".to_string()],+ pool: None,+ bundle_pool_config_hashes: HashMap::from([(+ "default".to_string(),+ HashMap::from([("default".to_string(), "pool-hash3".to_string())]),+ )]),};manager.apply_notification(¬ification).await;@@ -692,6 +726,10 @@ profiles:profiles.sort();assert_eq!(profiles, vec!["default".to_string(), "fast".to_string()]);assert_eq!(registry.compute_bundle_config_hash("default"), "hash3");+ assert_eq!(+ registry.compute_bundle_config_hash_for_pool("default", "default"),+ "pool-hash3"+ );}#[tokio::test]@@ -728,6 +766,8 @@ profiles:profiles_added: vec![],model_config: " \n\t".to_string(),affected_bundles: vec![],+ pool: None,+ bundle_pool_config_hashes: HashMap::new(),};manager.apply_notification(¬ification).await;@@ -768,6 +808,8 @@ profiles:profiles_added: vec![],model_config: "::: not valid yaml :::".to_string(),affected_bundles: vec![],+ pool: None,+ bundle_pool_config_hashes: HashMap::new(),};manager.apply_notification(¬ification).await;@@ -827,6 +869,8 @@ profiles:profiles_added: vec![],model_config: String::new(),affected_bundles: vec![],+ pool: None,+ bundle_pool_config_hashes: HashMap::new(),};manager.apply_notification(¬ification).await;assert_eq!(epoch.get(), 42);@@ -878,6 +922,8 @@ profiles:profiles_added: vec![],model_config: "::: not yaml :::".to_string(),affected_bundles: vec!["default".to_string()],+ pool: None,+ bundle_pool_config_hashes: HashMap::new(),};manager.apply_notification(¬ification).await;assert_eq!(@@ -936,6 +982,8 @@ profiles:"#.to_string(),affected_bundles: vec!["default".to_string()],+ pool: None,+ bundle_pool_config_hashes: HashMap::new(),};manager.apply_notification(¬ification).await;assert_eq!(diff --git a/packages/sie_gateway/src/observability/propagation.rs b/packages/sie_gateway/src/observability/propagation.rsindex 57970575a..858b19b68 100644--- a/packages/sie_gateway/src/observability/propagation.rs+++ b/packages/sie_gateway/src/observability/propagation.rs@@ -97,7 +97,7 @@ mod tests {use axum::http::{HeaderName, HeaderValue};use opentelemetry::trace::{Span as _, TraceContextExt, Tracer, TracerProvider as _};use opentelemetry_sdk::propagation::TraceContextPropagator;- use opentelemetry_sdk::trace::TracerProvider;+ use opentelemetry_sdk::trace::SdkTracerProvider;/// Install the propagator once per test process. Each test path/// is independent; installing twice is harmless (the global@@ -120,7 +120,7 @@ mod tests {let cx = extract_context_from_headers(&headers);// Attach the context, create a child span; the child's parent// should match the extracted trace id.- let provider = TracerProvider::builder().build();+ let provider = SdkTracerProvider::builder().build();let tracer = provider.tracer("test");let span = tracer.start_with_context("child", &cx);let span_cx = span.span_context().clone();@@ -145,12 +145,11 @@ mod tests {#[test]fn inject_with_active_span_yields_w3c_traceparent() {install_propagator();- let provider = TracerProvider::builder().build();+ let provider = SdkTracerProvider::builder().build();let tracer = provider.tracer("test");let span = tracer.start("parent");- // `TraceContextExt::with_span` is the 0.24 API for building a- // context that carries a span; the older `current_with_span`- // free function was retired with 0.23.+ // `TraceContextExt::with_span` builds a context that carries+ // a span for propagation.let cx = Context::current().with_span(span);let (tp, _ts) = inject_context(&cx);let tp = tp.expect("active span should inject a traceparent");diff --git a/packages/sie_gateway/src/observability/tracing.rs b/packages/sie_gateway/src/observability/tracing.rsindex 0d0fa4ed6..bcf73d5c1 100644--- a/packages/sie_gateway/src/observability/tracing.rs+++ b/packages/sie_gateway/src/observability/tracing.rs@@ -1,24 +1,25 @@//! OpenTelemetry tracer-provider setup for the gateway.//!-//! All knobs are read from the standard OTel environment variables-//! (`OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_SERVICE_NAME`,-//! `OTEL_TRACES_SAMPLER`, …) — no SIE-specific env vars are-//! introduced. The W3C [`TraceContextPropagator`] is installed-//! globally even when no exporter is configured so that inbound-//! `traceparent` headers still propagate through to the worker via-//! the JetStream work envelope. Without an exporter the gateway-//! itself records no spans, but the IDs continue to flow.+//! The OTLP exporter is enabled only when `SIE_TRACING_ENABLED` is+//! truthy and an OTLP endpoint is configured via+//! `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`.+//! The W3C [`TraceContextPropagator`] is installed globally regardless+//! of that exporter gate so that inbound `traceparent` headers still+//! propagate through to the worker via the JetStream work envelope.+//! Without an exporter the gateway itself records no spans, but the IDs+//! continue to flow.//!//! [`TraceContextPropagator`]: opentelemetry_sdk::propagation::TraceContextPropagatoruse std::env;+use std::sync::OnceLock;+use std::time::Duration;use opentelemetry::global;use opentelemetry::trace::TracerProvider as _;-use opentelemetry::KeyValue;use opentelemetry_otlp::WithExportConfig;use opentelemetry_sdk::propagation::TraceContextPropagator;-use opentelemetry_sdk::trace::Tracer;+use opentelemetry_sdk::trace::{SdkTracerProvider, Tracer};use opentelemetry_sdk::Resource;use tracing_subscriber::layer::SubscriberExt;use tracing_subscriber::util::SubscriberInitExt;@@ -26,6 +27,15 @@ use tracing_subscriber::{EnvFilter, Layer};/// Service name used when `OTEL_SERVICE_NAME` is not set.const DEFAULT_SERVICE_NAME: &str = "sie-gateway";+static TRACER_PROVIDER: OnceLock<SdkTracerProvider> = OnceLock::new();++/// Bounded flush deadline (ms) so process exit can't stall on an unreachable collector.+const TRACING_SHUTDOWN_TIMEOUT_MS: u64 = 3_000;++/// True when the OTLP exporter/provider is installed (spans are recorded).+pub fn exporter_enabled() -> bool {+ TRACER_PROVIDER.get().is_some()+}/// Initialise OpenTelemetry + tracing-subscriber for the gateway.///@@ -35,14 +45,14 @@ const DEFAULT_SERVICE_NAME: &str = "sie-gateway";/// `opentelemetry::Context`. **Always runs**, even without/// an exporter — propagation is the load-bearing piece for/// worker-side correlation.-/// 2. If `OTEL_EXPORTER_OTLP_ENDPOINT` (or the trace-specific-/// `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) is set, build a-/// [`opentelemetry_sdk::trace::TracerProvider`] with the OTLP-/// gRPC exporter, attach a+/// 2. If `SIE_TRACING_ENABLED` is truthy and `OTEL_EXPORTER_OTLP_ENDPOINT`+/// (or the trace-specific `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) is+/// set, build a [`opentelemetry_sdk::trace::SdkTracerProvider`] with+/// the OTLP gRPC exporter, attach a/// [`tracing_opentelemetry::OpenTelemetryLayer`] so existing/// `tracing::*` spans become OTel spans, and set the provider-/// as global. If not set, only the tracing-subscriber fmt-/// layer is installed (legacy behaviour preserved).+/// as global. Otherwise, only the tracing-subscriber fmt layer is+/// installed while the propagator remains active.pub fn init_tracing(level: &str, json: bool) {// Idempotency guard. The subscriber's ``.init()`` panics on a// second call ("a global default trace dispatcher has already@@ -61,10 +71,12 @@ pub fn init_tracing(level: &str, json: bool) {// (which runs the heavy adapter call) can continue the trace.global::set_text_map_propagator(TraceContextPropagator::new());- let endpoint = env::var("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")- .or_else(|_| env::var("OTEL_EXPORTER_OTLP_ENDPOINT"))- .ok()- .filter(|s| !s.is_empty());+ let endpoint = if sie_tracing_enabled() {+ cleaned_env("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")+ .or_else(|| cleaned_env("OTEL_EXPORTER_OTLP_ENDPOINT"))+ } else {+ None+ };let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| {let level_str = match level.to_lowercase().as_str() {@@ -117,33 +129,49 @@ pub fn init_tracing(level: &str, json: bool) {tracing::info!(endpoint = %ep, "OpenTelemetry tracing initialized");} else {tracing::debug!(- "OTEL_EXPORTER_OTLP_ENDPOINT not set; W3C propagator installed (no exporter)"+ "SIE_TRACING_ENABLED not truthy or OTLP endpoint not set; W3C propagator installed (no exporter)");}}+fn tracing_flag_set(raw: Option<&str>) -> bool {+ raw.is_some_and(|value| {+ let value = value.trim();+ value.eq_ignore_ascii_case("true") || value == "1" || value.eq_ignore_ascii_case("yes")+ })+}++fn sie_tracing_enabled() -> bool {+ let raw = env::var("SIE_TRACING_ENABLED").ok();+ tracing_flag_set(raw.as_deref())+}++/// Read an env var, trimming surrounding whitespace and treating a+/// whitespace-only value as absent so it can't shadow a valid fallback.+fn cleaned_env(name: &str) -> Option<String> {+ env::var(name)+ .ok()+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+}+fn init_tracer(endpoint: &str) -> Result<Tracer, String> {let service_name =env::var("OTEL_SERVICE_NAME").unwrap_or_else(|_| DEFAULT_SERVICE_NAME.to_string());- let provider = opentelemetry_otlp::new_pipeline()- .tracing()- .with_trace_config(opentelemetry_sdk::trace::Config::default().with_resource(- Resource::new(vec![KeyValue::new("service.name", service_name)]),- ))- .with_exporter(- opentelemetry_otlp::new_exporter()- .tonic()- .with_endpoint(endpoint),- )- .install_batch(opentelemetry_sdk::runtime::Tokio)- .map_err(|e| format!("install OTLP batch pipeline: {e}"))?;+ let exporter = opentelemetry_otlp::SpanExporter::builder()+ .with_tonic()+ .with_endpoint(endpoint)+ .build()+ .map_err(|e| format!("build OTLP span exporter: {e}"))?;+ let provider = SdkTracerProvider::builder()+ .with_resource(Resource::builder().with_service_name(service_name).build())+ .with_batch_exporter(exporter)+ .build();let tracer = provider.tracer("sie-gateway");- // `install_batch` already sets the provider globally inside the- // 0.17 pipeline; ensure the *exact* provider we built is the one- // future `global::tracer(...)` calls see (no-op when identical).- global::set_tracer_provider(provider);+ global::set_tracer_provider(provider.clone());+ let _ = TRACER_PROVIDER.set(provider);Ok(tracer)}@@ -152,5 +180,31 @@ fn init_tracer(endpoint: &str) -> Result<Tracer, String> {/// Called from `main.rs` on the way out so the OTLP exporter has a/// chance to drain its batch before the process exits.pub fn shutdown_tracing() {- global::shutdown_tracer_provider();+ if let Some(provider) = TRACER_PROVIDER.get() {+ let _ = provider.shutdown_with_timeout(Duration::from_millis(TRACING_SHUTDOWN_TIMEOUT_MS));+ }+}++#[cfg(test)]+mod tests {+ use super::{exporter_enabled, tracing_flag_set};++ #[test]+ fn tracing_flag_set_accepts_only_positive_truthy_values() {+ assert!(tracing_flag_set(Some("true")));+ assert!(tracing_flag_set(Some("1")));+ assert!(tracing_flag_set(Some("yes")));+ assert!(tracing_flag_set(Some("TRUE")));+ assert!(tracing_flag_set(Some(" true ")));++ assert!(!tracing_flag_set(Some("false")));+ assert!(!tracing_flag_set(Some("")));+ assert!(!tracing_flag_set(Some(" ")));+ assert!(!tracing_flag_set(None));+ }++ #[test]+ fn exporter_enabled_is_false_before_exporter_init() {+ assert!(!exporter_enabled());+ }}diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 7d153913c..92f60f6dd 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -2142,6 +2142,7 @@ pub struct BundleConfigsResponse {#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct BundleConfigSummary {pub bundle_id: String,+ pub engine: String,pub priority: i32,pub adapter_count: usize,pub source: String,@@ -2151,6 +2152,7 @@ pub struct BundleConfigSummary {#[derive(Debug, Serialize, Deserialize, ToSchema)]pub struct BundleConfigDocument {pub name: String,+ pub engine: String,pub priority: i32,pub source: String,pub adapters: Vec<String>,@@ -2641,7 +2643,7 @@ mod tests {}#[test]- fn openapi_document_advertises_engine_header_on_inference_paths() {+ fn openapi_document_does_not_advertise_engine_header_on_inference_paths() {let spec = serde_json::to_value(openapi_document()).unwrap();for path in ["/v1/encode/{model}",@@ -2653,10 +2655,10 @@ mod tests {.as_array().unwrap_or_else(|| panic!("{path} must document parameters"));assert!(- parameters.iter().any(|p| p["name"]+ !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"+ "{path} must not advertise X-SIE-Engine; normal routing uses model profile variants");}}diff --git a/packages/sie_gateway/src/queue/payload_store.rs b/packages/sie_gateway/src/queue/payload_store.rsindex b80414291..61839a5c6 100644--- a/packages/sie_gateway/src/queue/payload_store.rs+++ b/packages/sie_gateway/src/queue/payload_store.rs@@ -5,6 +5,9 @@ use std::sync::Arc;use async_trait::async_trait;use tracing::debug;+#[cfg(feature = "cloud-storage")]+use object_store::ObjectStoreExt;+const OBJECT_STORE_SCHEMES: &[&str] = &["s3://", "gs://", "abfs://", "abfss://"];fn object_store_scheme(url: &str) -> Option<&'static str> {diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex 113496760..8775e65ad 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -67,17 +67,20 @@ struct TokenBucket {}impl TokenBucket {- fn new(rate_per_sec: f64, burst: f64) -> Self {+ /// `now` is injected rather than read from `Instant::now()` inside, so the+ /// refill / burst-cap logic is unit-testable by advancing a synthetic+ /// clock instead of `thread::sleep`. Production callers pass+ /// `Instant::now()`. First seam of the injectable-clock work in #1575.+ fn new(rate_per_sec: f64, burst: f64, now: Instant) -> Self {Self {tokens: burst,rate_per_sec,burst,- last_refill: Instant::now(),+ last_refill: now,}}- fn try_take(&mut self) -> bool {- let now = Instant::now();+ fn try_take(&mut self, now: Instant) -> bool {let elapsed = now.saturating_duration_since(self.last_refill).as_secs_f64();@@ -526,6 +529,8 @@ pub struct WorkResult {pub postprocessing_ms: Option<f64>,#[serde(default)]pub payload_fetch_ms: Option<f64>,+ #[serde(default)]+ pub worker_direct: bool,}struct CachedStreamInfo {@@ -671,26 +676,37 @@ struct ResultCollector {pool_label: String,model_label: String,pool_fallback_subject: Option<String>,+ direct_fallback_worker_id: Option<String>,+ direct_fallback_republished_indices: BTreeSet<usize>,direct_fallback_payloads: Vec<Option<Vec<u8>>>,direct_fallback_republished: bool,}struct PublishedWorkItem {index: usize,- ack: jetstream::context::PublishAckFuture,+ ack: Option<jetstream::context::PublishAckFuture>,encoded: Vec<u8>,}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum StoreResultOutcome {+ Stored,+ Duplicate,+ StaleDirectFallback,+ OutOfRange,+}+type DirectFallbackPayload = (usize, Vec<u8>);type DirectFallbackPayloads = Vec<DirectFallbackPayload>;fn take_direct_fallback_payloads(collector: &mut ResultCollector,-) -> Option<(String, DirectFallbackPayloads)> {+) -> Option<(String, Option<String>, DirectFallbackPayloads)> {if collector.direct_fallback_republished {return None;}let subject = collector.pool_fallback_subject.clone()?;+ let worker_id = collector.direct_fallback_worker_id.clone();let mut payloads = Vec::new();for (index, payload) in collector.direct_fallback_payloads.iter().enumerate() {let still_missing = collector.results.get(index).is_some_and(Option::is_none);@@ -704,7 +720,68 @@ fn take_direct_fallback_payloads(return None;}collector.direct_fallback_republished = true;- Some((subject, payloads))+ Some((subject, worker_id, payloads))+}++fn store_result_if_missing(+ collector: &mut ResultCollector,+ result: WorkResult,+) -> StoreResultOutcome {+ let idx = result.item_index as usize;+ if idx >= collector.results.len() {+ return StoreResultOutcome::OutOfRange;+ }+ if result.worker_direct && collector.direct_fallback_republished_indices.contains(&idx) {+ return StoreResultOutcome::StaleDirectFallback;+ }+ if collector.results[idx].is_some() {+ return StoreResultOutcome::Duplicate;+ }+ collector.results[idx] = Some(result);+ StoreResultOutcome::Stored+}++fn mark_direct_fallback_republished_indices(+ collector: &mut ResultCollector,+ indices: impl IntoIterator<Item = usize>,+) {+ collector+ .direct_fallback_republished_indices+ .extend(indices);+}++fn mark_direct_fallback_confirmed(+ collector: &mut ResultCollector,+ indices: impl IntoIterator<Item = usize>,+) {+ collector.direct_fallback_republished = true;+ mark_direct_fallback_republished_indices(collector, indices);+}++fn take_ack_futures(items: &mut [PublishedWorkItem]) -> Vec<jetstream::context::PublishAckFuture> {+ items+ .iter_mut()+ .filter_map(|item| item.ack.take())+ .collect()+}++async fn await_batch_direct_fallback_acks(+ request_id: &str,+ acks: Vec<jetstream::context::PublishAckFuture>,+) -> bool {+ let mut all_acked = true;+ for ack in acks {+ if let Err(e) = ack.await {+ warn!(+ request_id = %request_id,+ error = %e,+ "JetStream ack failed for batch direct fallback"+ );+ metrics::QUEUE_ACK_FAILURES.inc();+ all_acked = false;+ }+ }+ all_acked}fn stream_name(pool: &str) -> String {@@ -1183,9 +1260,11 @@ fn skip_msgpack_value(data: &[u8]) -> Option<&[u8]> {/// The legacy [`WorkPublisher::republish_to_pool`] wrapper collapses the/// non-`Republished` arms to `false`, but `handle_nak` needs to tell/// "already republished" apart from "no collector / no payload": a NAK-/// that arrives after the request already fell back to the pool means the-/// item has been retried as far as it can be, so the client should get a-/// 429 immediately rather than hang until the first-chunk timeout.+/// that arrives after the request already fell back to the pool needs a+/// second collector-state check: before a successor emits its first chunk,+/// a late NAK from the abandoned attempt is indistinguishable from a NAK+/// emitted by the successor. Once a current attempt has latched, the NAK can+/// be classified precisely.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum RepublishOutcome {/// The item was re-issued to the pool subject.@@ -1204,6 +1283,56 @@ enum RepublishOutcome {RateLimited,}+/// Whether a NAK must be ignored because it is from an ABANDONED attempt.+///+/// After a first-chunk-timeout (or earlier NAK) republishes a request to the+/// pool, a healthy successor worker relatches a newer `current_attempt_id` and+/// streams into the same collector. A late NAK from the abandoned attempt would+/// otherwise tear that live successor down. The NAK is stale iff it carries a+/// non-empty attempt id and either:+///+/// - the collector has latched a different `current_attempt_id`, or+/// - the collector is between republish and successor first chunk, and the NAK+/// matches an explicitly recorded abandoned attempt id.+///+/// When neither guard can identify the NAK as abandoned, this predicate returns+/// `false`; callers then decide whether the NAK is actionable or ambiguous for+/// their state. See #1601.+fn nak_is_stale(+ current_attempt_id: Option<&str>,+ abandoned_attempt_id: Option<&str>,+ nak_attempt_id: &str,+) -> bool {+ if nak_attempt_id.is_empty() {+ return false;+ }+ match current_attempt_id {+ Some(current) => current != nak_attempt_id,+ None => abandoned_attempt_id.is_some_and(|abandoned| abandoned == nak_attempt_id),+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum AlreadyRepublishedNakDecision {+ DropStale,+ WaitForSuccessor,+ Fail,+}++fn already_republished_nak_decision(+ current_attempt_id: Option<&str>,+ abandoned_attempt_id: Option<&str>,+ nak_attempt_id: &str,+) -> AlreadyRepublishedNakDecision {+ if nak_is_stale(current_attempt_id, abandoned_attempt_id, nak_attempt_id) {+ return AlreadyRepublishedNakDecision::DropStale;+ }+ if current_attempt_id.is_none() {+ return AlreadyRepublishedNakDecision::WaitForSuccessor;+ }+ AlreadyRepublishedNakDecision::Fail+}+impl WorkPublisher {pub fn new(jetstream: jetstream::Context,@@ -1246,6 +1375,7 @@ impl WorkPublisher {std::sync::Mutex::new(TokenBucket::new(self.fallback_rate_per_sec,self.fallback_burst,+ Instant::now(),))});// Lock is a plain (non-async) ``std::sync::Mutex``; the critical@@ -1257,7 +1387,7 @@ impl WorkPublisher {Ok(g) => g,Err(_) => return false,};- guard.try_take()+ guard.try_take(Instant::now())}#[allow(dead_code)]@@ -1488,12 +1618,17 @@ impl WorkPublisher {};let subject = target.subject();- let pool_fallback_subject = match (&target, endpoint) {- (PublishTarget::Worker { .. }, "generate") => None,- (PublishTarget::Worker { .. }, _) => Some(target.as_pool_fallback().subject()),- (PublishTarget::Pool { .. }, _) => None,+ let (pool_fallback_subject, direct_fallback_worker_id) = match (&target, endpoint) {+ (PublishTarget::Worker { .. }, "generate") | (PublishTarget::Pool { .. }, _) => {+ (None, None)+ }+ (PublishTarget::Worker { worker_id, .. }, _) => (+ Some(target.as_pool_fallback().subject()),+ Some(worker_id.clone()),+ ),};let direct_publish_fallback_subject = pool_fallback_subject.clone();+ let direct_publish_fallback_worker_id = direct_fallback_worker_id.clone();let direct_publish_retry_items = if direct_publish_fallback_subject.is_some() {Some(items.clone())} else {@@ -1514,6 +1649,8 @@ impl WorkPublisher {pool_label: pool.clone(),model_label: model.to_string(),pool_fallback_subject,+ direct_fallback_worker_id,+ direct_fallback_republished_indices: BTreeSet::new(),direct_fallback_payloads: vec![None; total_items as usize],direct_fallback_republished: false,},@@ -1525,9 +1662,11 @@ impl WorkPublisher {.unwrap_or_default().as_secs_f64();- // 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.+ // All recognized endpoints carry W3C trace context on the work+ // envelope so the worker span attaches to the gateway/client+ // trace (issue #1500). The endpoint classifier gates this and+ // fails closed for unknown labels; `inject_current_context()` is+ // a no-op when no context is active.let (traceparent, tracestate) = Self::trace_context_for_endpoint(endpoint);// Every work item in a request shares the same pool / model /@@ -1583,7 +1722,31 @@ impl WorkPublisher {).await{- Ok(items) => {+ Ok(mut items) => {+ let fallback_indices: Vec<usize> =+ items.iter().map(|item| item.index).collect();+ let fallback_acks = take_ack_futures(&mut items);+ let fallback_confirmed =+ await_batch_direct_fallback_acks(&request_id, fallback_acks).await;+ if fallback_confirmed {+ if let Some(mut entry) = self.pending_results.get_mut(&request_id) {+ mark_direct_fallback_confirmed(+ entry.value_mut(),+ fallback_indices,+ );+ }+ if let Some(worker_id) =+ direct_publish_fallback_worker_id.as_deref()+ {+ self.publish_batch_direct_cancel(worker_id, &request_id)+ .await;+ }+ } else {+ warn!(+ request_id = %request_id,+ "skipping batch direct-dispatch cancel because pool fallback was not durably acked"+ );+ }metrics::ROUTING_FALLBACK_TOTAL.with_label_values(&[&metrics::sanitize_model_label(model),@@ -1623,14 +1786,17 @@ impl WorkPublisher {}}}- for item in published_items {- ack_futures.push(item.ack);+ for mut item in published_items {+ if let Some(ack) = item.ack.take() {+ ack_futures.push(ack);+ }}// Fire-and-forget: spawn background task to monitor acks.// The request handler proceeds immediately to wait for inbox results.// JetStream acks confirm durability but our streams are ephemeral- // (memory, 60s TTL) — clients retry on timeout if messages are lost.+ // (memory + configured max_age) — clients retry on timeout if+ // messages are lost.if !ack_futures.is_empty() {tokio::spawn(async move {for ack in ack_futures {@@ -1677,7 +1843,7 @@ impl WorkPublisher {.map(|(ack, encoded)| {vec![PublishedWorkItem {index: 0,- ack,+ ack: Some(ack),encoded,}]})@@ -1687,7 +1853,7 @@ impl WorkPublisher {.map(|(ack, encoded)| {vec![PublishedWorkItem {index: 0,- ack,+ ack: Some(ack),encoded,}]})@@ -1705,7 +1871,7 @@ impl WorkPublisher {.await.map(|(ack, encoded)| PublishedWorkItem {index,- ack,+ ack: Some(ack),encoded,})}@@ -1721,8 +1887,9 @@ impl WorkPublisher {/// delivery budget. If that worker or its private consumer disappears/// after the gateway publishes, the worker-specific stream cannot fail/// over by itself. This timer republishes any still-missing items to the- /// lane's pool subject once; late duplicate results are harmless because- /// the result collector removes itself on first complete response.+ /// lane's pool subject once. After those fallback publishes are durably+ /// acked, it emits a worker-scoped batch cancel so the original sidecar+ /// can ACK queued worker-direct items that have not reached IPC yet.pub fn spawn_batch_direct_fallback(self: &Arc<Self>, request_id: String, delay: Duration) {let publisher = Arc::clone(self);tokio::spawn(async move {@@ -1745,19 +1912,22 @@ impl WorkPublisher {request_id: &str,reason: &'static str,) -> Result<bool, String> {- let (subject, payloads, operation, pool, model) = {+ let (subject, direct_worker_id, payloads, operation, pool, model) = {let Some(mut entry) = self.pending_results.get_mut(request_id) else {return Ok(false);};- let Some((subject, payloads)) = take_direct_fallback_payloads(entry.value_mut()) else {+ let Some((subject, direct_worker_id, payloads)) =+ take_direct_fallback_payloads(entry.value_mut())+ else {return Ok(false);};let operation = entry.operation.clone();let pool = entry.pool_label.clone();let model = entry.model_label.clone();- (subject, payloads, operation, pool, model)+ (subject, direct_worker_id, payloads, operation, pool, model)};+ let fallback_indices: Vec<usize> = payloads.iter().map(|(index, _)| *index).collect();let mut acks = Vec::with_capacity(payloads.len());for (index, payload) in payloads {let ack = self@@ -1773,6 +1943,22 @@ impl WorkPublisher {acks.push(ack);}+ let fallback_confirmed = await_batch_direct_fallback_acks(request_id, acks).await;+ if fallback_confirmed {+ if let Some(mut entry) = self.pending_results.get_mut(request_id) {+ mark_direct_fallback_confirmed(entry.value_mut(), fallback_indices);+ }+ if let Some(worker_id) = direct_worker_id.as_deref() {+ self.publish_batch_direct_cancel(worker_id, request_id)+ .await;+ }+ } else {+ warn!(+ request_id = %request_id,+ "skipping batch direct-dispatch cancel because pool fallback was not durably acked"+ );+ }+metrics::ROUTING_FALLBACK_TOTAL.with_label_values(&[&metrics::sanitize_model_label(&model),@@ -1785,20 +1971,10 @@ impl WorkPublisher {operation = %operation,subject = %subject,reason,+ fallback_confirmed,"republished non-streaming direct-dispatch work to pool fallback");- for ack in acks {- if let Err(e) = ack.await {- warn!(- request_id = %request_id,- error = %e,- "JetStream ack failed for batch direct fallback"- );- metrics::QUEUE_ACK_FAILURES.inc();- }- }-Ok(true)}@@ -2224,6 +2400,32 @@ impl WorkPublisher {}}+ /// Best-effort cancel for abandoned non-streaming worker-direct batch+ /// work. Unlike the generation gateway-request cancel signal, this is+ /// scoped to the original direct worker. Sidecars only drop items pulled+ /// from worker-direct subjects, so the pool fallback with the same request+ /// id remains eligible to run.+ pub async fn publish_batch_direct_cancel(&self, worker_id: &str, request_id: &str) {+ let client_opt = { self.nats_client.read().await.clone() };+ let Some(client) = client_opt else {+ return;+ };+ let subject = format!(+ "batch_cancel.{}.{}.{}",+ self.router_id,+ normalize_model_id(worker_id),+ request_id+ );+ if let Err(e) = client.publish(subject, Vec::new().into()).await {+ warn!(+ error = %e,+ request_id = %request_id,+ worker_id = %worker_id,+ "failed to publish batch direct-dispatch cancel signal"+ );+ }+ }+/// Returns ``true`` iff the streaming collector for ``request_id``/// has already observed at least one chunk — used to label/// cancellation metrics (`before_first_chunk` vs `mid_stream`).@@ -2406,6 +2608,16 @@ impl WorkPublisher {&self,request_id: &str,reason: &'static str,+ ) -> Result<RepublishOutcome, String> {+ self.republish_to_pool_outcome_with_abandoned_attempt(request_id, reason, None)+ .await+ }++ async fn republish_to_pool_outcome_with_abandoned_attempt(+ &self,+ request_id: &str,+ reason: &'static str,+ abandoned_attempt_id: Option<&str>,) -> Result<RepublishOutcome, String> {// Take a short lock to: check + flip `republished`, copy out// the encoded bytes + the pool subject, bump the attempt@@ -2448,6 +2660,9 @@ impl WorkPublisher {}entry.republished = true;let gen = entry.bump_attempt_generation();+ if let Some(attempt_id) = abandoned_attempt_id {+ entry.record_abandoned_attempt_id(attempt_id);+ }(subject,payload,@@ -2612,6 +2827,7 @@ impl WorkPublisher {/// Handle an incoming result message (called from inbox subscription).pub async fn handle_result(&self, result: WorkResult) {let request_id = result.request_id.clone();+ let item_index = result.item_index;// Insert result into collector (per-key lock via DashMap)let all_done = {@@ -2623,9 +2839,30 @@ impl WorkPublisher {}};let collector = entry.value_mut();- let idx = result.item_index as usize;- if idx < collector.results.len() {- collector.results[idx] = Some(result);+ match store_result_if_missing(collector, result) {+ StoreResultOutcome::Stored => {}+ StoreResultOutcome::Duplicate => {+ debug!(+ request_id = %request_id,+ item_index,+ "ignoring duplicate result for already-completed batch item"+ );+ }+ StoreResultOutcome::StaleDirectFallback => {+ debug!(+ request_id = %request_id,+ item_index,+ "ignoring stale worker-direct result for republished batch fallback item"+ );+ }+ StoreResultOutcome::OutOfRange => {+ warn!(+ request_id = %request_id,+ item_index,+ total_items = collector.results.len(),+ "received result with out-of-range item_index"+ );+ }}collector.results.iter().all(|r| r.is_some())};@@ -2759,6 +2996,59 @@ impl WorkPublisher {/// Unknown reasons fall through to the generic ``nak`` bucket so/// we never lose data on a forward-compat addition.async fn handle_nak(&self, nak: NakEnvelope) {+ // Attempt-isolation guard (mirrors the stale-chunk filter in+ // StreamCollector::apply, streaming.rs): a NAK from an ABANDONED+ // attempt must not act on the request. After a first-chunk-timeout (or+ // earlier NAK) republishes to the pool, a healthy successor worker+ // relatches a newer `current_attempt_id` and streams. A late NAK from+ // the abandoned attempt would otherwise reach the `AlreadyRepublished`+ // arm and `fail_pending_stream` the live successor with a spurious 429,+ // dropping its already-produced terminal. If the collector has either+ // latched a different current_attempt_id or recorded this NAK's attempt+ // id as abandoned during a prior republish, it is a stale leftover —+ // drop it. See #1601.+ // Capture the latched/abandoned attempt ids plus the bounded metric labels+ // (display_model/pool) in one lookup so the stale-drop path can record+ // a metric without a second DashMap probe. The `Ref` guard is dropped+ // at the end of the closure — nothing is held across the `.inc()`.+ let collector_state = self.pending_streams.get(&nak.request_id).map(|e| {+ let collector = e.value();+ (+ collector.current_attempt_id.clone(),+ collector.abandoned_attempt_id.clone(),+ collector.display_model.clone(),+ collector.pool.clone(),+ )+ });+ let latched_attempt = collector_state+ .as_ref()+ .and_then(|(current, ..)| current.clone());+ let abandoned_attempt = collector_state+ .as_ref()+ .and_then(|(_, abandoned, ..)| abandoned.clone());+ if nak_is_stale(+ latched_attempt.as_deref(),+ abandoned_attempt.as_deref(),+ &nak.attempt_id,+ ) {+ // Mirror the chunk-path stale-drop metric so an operator can see+ // abandoned-attempt NAKs being dropped (#1601).+ if let Some((_, _, model, pool)) = &collector_state {+ metrics::GENERATION_STALE_ATTEMPT_NAKS+ .with_label_values(&[+ &metrics::sanitize_model_label(model),+ &metrics::sanitize_label(pool),+ ])+ .inc();+ }+ debug!(+ request_id = %nak.request_id,+ nak_attempt_id = %nak.attempt_id,+ "dropping stale NAK from an abandoned attempt"+ );+ return;+ }+let reason: &'static str = match nak.reason.as_str() {"kv_budget" => "nak_kv_budget","model_not_loaded" => "nak_model_not_loaded",@@ -2781,7 +3071,11 @@ impl WorkPublisher {}};match self- .republish_to_pool_outcome(&nak.request_id, reason)+ .republish_to_pool_outcome_with_abandoned_attempt(+ &nak.request_id,+ reason,+ Some(nak.attempt_id.as_str()),+ ).await{Ok(RepublishOutcome::Republished) => debug!(@@ -2790,17 +3084,63 @@ impl WorkPublisher {"NAK observed, republished to pool"),Ok(RepublishOutcome::AlreadyRepublished) => {- // The request already fell back to the pool (via an- // earlier NAK or the first-chunk timeout) and is now- // being NAKed again. There is nothing further to retry,- // so don't leave the client hanging until the first-chunk- // timeout — surface a 429 immediately, mirroring the- // pool-republish-failed arm below.- let (display_model, pool) = self+ // Re-read under the collector lock before deciding. A+ // first-chunk-timeout fallback can set `republished` before+ // any worker attempt id has latched; in that window, a late+ // NAK from the abandoned direct attempt is indistinguishable+ // from a NAK emitted by the pool successor. Failing the+ // request here would recreate #1601's spurious 429. Once a+ // current attempt has latched, we can classify the NAK+ // precisely and keep the immediate 429 for a live attempt+ // that really NAKs after fallback.+ let Some((decision, display_model, pool)) = self.pending_streams- .get(&nak.request_id)- .map(|e| (e.value().display_model.clone(), e.value().pool.clone()))- .unwrap_or_else(|| ("unknown".to_string(), "unknown".to_string()));+ .get_mut(&nak.request_id)+ .map(|mut entry| {+ let decision = already_republished_nak_decision(+ entry.current_attempt_id.as_deref(),+ entry.abandoned_attempt_id.as_deref(),+ &nak.attempt_id,+ );+ if matches!(decision, AlreadyRepublishedNakDecision::WaitForSuccessor) {+ entry.record_abandoned_attempt_id(&nak.attempt_id);+ }+ (decision, entry.display_model.clone(), entry.pool.clone())+ })+ else {+ debug!(+ request_id = %nak.request_id,+ reason = %nak.reason,+ "NAK on already-republished request after collector completed"+ );+ return;+ };+ match decision {+ AlreadyRepublishedNakDecision::DropStale => {+ metrics::GENERATION_STALE_ATTEMPT_NAKS+ .with_label_values(&[+ &metrics::sanitize_model_label(&display_model),+ &metrics::sanitize_label(&pool),+ ])+ .inc();+ debug!(+ request_id = %nak.request_id,+ nak_attempt_id = %nak.attempt_id,+ "dropping stale NAK from an abandoned attempt"+ );+ return;+ }+ AlreadyRepublishedNakDecision::WaitForSuccessor => {+ debug!(+ request_id = %nak.request_id,+ nak_attempt_id = %nak.attempt_id,+ reason = %nak.reason,+ "ignoring ambiguous NAK on already-republished request before successor attempt latched"+ );+ return;+ }+ AlreadyRepublishedNakDecision::Fail => {}+ }metrics::RATE_LIMIT_TOTAL.with_label_values(&[&metrics::sanitize_model_label(&display_model),@@ -3502,6 +3842,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: false,}),None,],@@ -3512,18 +3853,133 @@ mod tests {pool_label: "default".into(),model_label: "BAAI/bge-m3".into(),pool_fallback_subject: Some("sie.work.default.l4.default.BAAI__bge-m3".into()),+ direct_fallback_worker_id: Some("worker-1".into()),+ direct_fallback_republished_indices: BTreeSet::new(),direct_fallback_payloads: vec![Some(vec![0]), Some(vec![1]), Some(vec![2])],direct_fallback_republished: false,};- let (subject, payloads) =+ let (subject, worker_id, payloads) =take_direct_fallback_payloads(&mut collector).expect("fallback payloads");assert_eq!(subject, "sie.work.default.l4.default.BAAI__bge-m3");+ assert_eq!(worker_id.as_deref(), Some("worker-1"));assert_eq!(payloads, vec![(0, vec![0]), (2, vec![2])]);assert!(collector.direct_fallback_republished);assert!(take_direct_fallback_payloads(&mut collector).is_none());}+ #[test]+ fn test_batch_result_collector_keeps_first_result_for_duplicate_item() {+ let (tx, _rx) = oneshot::channel();+ let mut collector = ResultCollector {+ _total_items: 1,+ results: vec![None],+ sender: Some(tx),+ deadline: Instant::now() + Duration::from_secs(30),+ operation: "encode".into(),+ published_at: Instant::now(),+ pool_label: "default".into(),+ model_label: "BAAI/bge-m3".into(),+ pool_fallback_subject: None,+ direct_fallback_worker_id: None,+ direct_fallback_republished_indices: BTreeSet::new(),+ direct_fallback_payloads: vec![None],+ direct_fallback_republished: false,+ };++ let first = WorkResult {+ work_item_id: "req.0".into(),+ request_id: "req".into(),+ item_index: 0,+ success: true,+ result_msgpack: vec![1],+ error: None,+ error_code: None,+ inference_ms: None,+ queue_ms: None,+ processing_ms: None,+ worker_id: Some("direct-worker".into()),+ tokenization_ms: None,+ postprocessing_ms: None,+ payload_fetch_ms: None,+ worker_direct: false,+ };+ let duplicate = WorkResult {+ result_msgpack: vec![2],+ worker_id: Some("pool-worker".into()),+ ..first.clone()+ };++ assert_eq!(+ store_result_if_missing(&mut collector, first),+ StoreResultOutcome::Stored+ );+ assert_eq!(+ store_result_if_missing(&mut collector, duplicate),+ StoreResultOutcome::Duplicate+ );+ let stored = collector.results[0].as_ref().expect("stored result");+ assert_eq!(stored.result_msgpack, vec![1]);+ assert_eq!(stored.worker_id.as_deref(), Some("direct-worker"));+ }++ #[test]+ fn test_batch_result_collector_ignores_stale_direct_after_fallback_confirmed() {+ let (tx, _rx) = oneshot::channel();+ let mut collector = ResultCollector {+ _total_items: 1,+ results: vec![None],+ sender: Some(tx),+ deadline: Instant::now() + Duration::from_secs(30),+ operation: "encode".into(),+ published_at: Instant::now(),+ pool_label: "default".into(),+ model_label: "BAAI/bge-m3".into(),+ pool_fallback_subject: Some("sie.work.default.l4.default.BAAI__bge-m3".into()),+ direct_fallback_worker_id: Some("direct-worker".into()),+ direct_fallback_republished_indices: BTreeSet::from([0]),+ direct_fallback_payloads: vec![Some(vec![0])],+ direct_fallback_republished: true,+ };++ let stale_direct = WorkResult {+ work_item_id: "req.0".into(),+ request_id: "req".into(),+ item_index: 0,+ success: true,+ result_msgpack: vec![1],+ error: None,+ error_code: None,+ inference_ms: None,+ queue_ms: None,+ processing_ms: None,+ worker_id: Some("direct-worker".into()),+ tokenization_ms: None,+ postprocessing_ms: None,+ payload_fetch_ms: None,+ worker_direct: true,+ };+ let pool_result = WorkResult {+ result_msgpack: vec![2],+ worker_id: Some("pool-worker".into()),+ worker_direct: false,+ ..stale_direct.clone()+ };++ assert_eq!(+ store_result_if_missing(&mut collector, stale_direct),+ StoreResultOutcome::StaleDirectFallback+ );+ assert!(collector.results[0].is_none());+ assert_eq!(+ store_result_if_missing(&mut collector, pool_result),+ StoreResultOutcome::Stored+ );+ let stored = collector.results[0].as_ref().expect("stored result");+ assert_eq!(stored.result_msgpack, vec![2]);+ assert_eq!(stored.worker_id.as_deref(), Some("pool-worker"));+ }+#[test]fn test_pending_generation_snapshot_groups_collectors() {let now = Instant::now();@@ -3868,6 +4324,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: true,};let encoded = rmp_serde::to_vec(&result).unwrap();@@ -3877,6 +4334,7 @@ mod tests {assert_eq!(decoded.item_index, 2);assert!(decoded.success);assert_eq!(decoded.result_msgpack, vec![5, 6, 7]);+ assert!(decoded.worker_direct);}#[test]@@ -3982,6 +4440,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: false,};let encoded = rmp_serde::to_vec(&result).unwrap();let extracted = extract_request_id_fast(&encoded);@@ -4005,6 +4464,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: false,};let encoded = rmp_serde::to_vec_named(&result).unwrap();let extracted = extract_request_id_fast(&encoded);@@ -4045,6 +4505,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: false,};let encoded = rmp_serde::to_vec(&result).unwrap();let extracted = extract_request_id_fast(&encoded);@@ -4574,10 +5035,10 @@ mod tests {use opentelemetry::trace::{TraceContextExt, Tracer, TracerProvider as _};use opentelemetry::Context;use opentelemetry_sdk::propagation::TraceContextPropagator;- use opentelemetry_sdk::trace::TracerProvider;+ use opentelemetry_sdk::trace::SdkTracerProvider;opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());- let provider = TracerProvider::builder().build();+ let provider = SdkTracerProvider::builder().build();let tracer = provider.tracer("gateway-test");let span = tracer.start("gateway.proxy_chat");let cx = Context::current().with_span(span);@@ -4592,28 +5053,36 @@ mod tests {}#[test]- fn test_queue_trace_context_stays_off_for_non_generation() {+ fn test_queue_trace_context_injects_for_non_generation() {use opentelemetry::trace::{TraceContextExt, Tracer, TracerProvider as _};use opentelemetry::Context;use opentelemetry_sdk::propagation::TraceContextPropagator;- use opentelemetry_sdk::trace::TracerProvider;+ use opentelemetry_sdk::trace::SdkTracerProvider;opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());- let provider = TracerProvider::builder().build();+ let provider = SdkTracerProvider::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();+ // Non-generation endpoints now inject the active W3C context into+ // the queue work-item envelope so the worker span attaches to the+ // gateway span (issue #1500). A real 4-part traceparent proves the+ // context was actually serialized, not just left non-None.for endpoint in InferenceEndpoint::NON_GENERATION_QUEUE_LABELS {assert!(- !WorkPublisher::should_propagate_queue_trace(endpoint),- "{endpoint} must keep the pre-generation queue hot path"+ WorkPublisher::should_propagate_queue_trace(endpoint),+ "{endpoint} must inject queue trace context");- 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(endpoint);+ let tp = tp.unwrap_or_else(|| panic!("{endpoint} should propagate traceparent"));+ let parts: Vec<&str> = tp.split('-').collect();+ assert_eq!(parts.len(), 4, "wire shape: version-trace-span-flags");+ assert_eq!(parts[1].len(), 32, "trace_id is 32 hex chars");+ assert_eq!(parts[2].len(), 16, "span_id is 16 hex chars");}+ // Unrecognized endpoints still fail closed (no envelope injection).let (tp, ts) = WorkPublisher::trace_context_for_endpoint("unknown");assert!(tp.is_none(),@@ -4626,14 +5095,14 @@ mod tests {}#[test]- fn test_queue_trace_context_is_generation_only() {+ fn test_queue_trace_context_propagates_for_generate() {use opentelemetry::trace::{TraceContextExt, Tracer, TracerProvider as _};use opentelemetry::Context;use opentelemetry_sdk::propagation::TraceContextPropagator;- use opentelemetry_sdk::trace::TracerProvider;+ use opentelemetry_sdk::trace::SdkTracerProvider;opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());- let provider = TracerProvider::builder().build();+ let provider = SdkTracerProvider::builder().build();let tracer = provider.tracer("gateway-test");let span = tracer.start("gateway.proxy_generate");let cx = Context::current().with_span(span);@@ -4646,25 +5115,388 @@ mod tests {assert_eq!(parts.len(), 4, "wire shape: version-trace-span-flags");}+ #[tokio::test]+ async fn test_inbound_context_continues_into_non_generation_envelope() {+ // End-to-end mechanism for #1500 on the non-generation path: the+ // gateway extracts the inbound client `traceparent`, scopes it+ // over the publish via `with_context` (no billed gateway span),+ // and the queue-publish injection re-emits it. The emitted+ // traceparent must CONTINUE the inbound trace — same trace_id and+ // parent == the inbound span_id — so the worker's run_batch span+ // attaches to the client trace instead of rooting a fresh one.+ use opentelemetry::trace::FutureExt;+ use opentelemetry_sdk::propagation::TraceContextPropagator;++ opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());++ let inbound_trace_id = "0af7651916cd43dd8448eb211c80319c";+ let inbound_span_id = "b7ad6b7169203331";+ let inbound_tp = format!("00-{inbound_trace_id}-{inbound_span_id}-01");+ let mut headers = axum::http::HeaderMap::new();+ headers.insert(+ axum::http::HeaderName::from_static("traceparent"),+ axum::http::HeaderValue::from_str(&inbound_tp).unwrap(),+ );+ let cx = crate::observability::propagation::extract_context_from_headers(&headers);++ // Mirror the gateway: the inbound context is current over the+ // publish future, then a non-generation endpoint injects it.+ let (tp, _ts) = async { WorkPublisher::trace_context_for_endpoint("encode") }+ .with_context(cx)+ .await;++ let tp = tp.expect("encode must inject the inbound trace context");+ let parts: Vec<&str> = tp.split('-').collect();+ assert_eq!(parts.len(), 4, "wire shape: version-trace-span-flags");+ assert_eq!(+ parts[1], inbound_trace_id,+ "must continue the inbound trace_id"+ );+ assert_eq!(+ parts[2], inbound_span_id,+ "worker's parent must be the inbound span"+ );+ }++ #[tokio::test]+ async fn test_gateway_publish_span_context_parents_non_generation_envelope() {+ use opentelemetry::trace::{FutureExt, TraceContextExt, TracerProvider as _};+ use opentelemetry_sdk::propagation::TraceContextPropagator;+ use opentelemetry_sdk::trace::SdkTracerProvider;+ use tracing::Instrument;+ use tracing_opentelemetry::OpenTelemetrySpanExt;+ use tracing_subscriber::layer::SubscriberExt;++ async fn publish_with_gateway_span(+ headers: axum::http::HeaderMap,+ ) -> (String, String, String) {+ let provider = SdkTracerProvider::builder().build();+ let tracer = provider.tracer("gateway-test");+ let subscriber = tracing_subscriber::registry()+ .with(tracing_opentelemetry::layer().with_tracer(tracer));+ let dispatch = tracing::Dispatch::new(subscriber);++ let publish_fut = tracing::dispatcher::with_default(&dispatch, || {+ let inbound_cx =+ crate::observability::propagation::extract_context_from_headers(&headers);+ let span = tracing::info_span!(+ "gateway.publish",+ otel.name = "gateway.publish",+ sie.endpoint = "encode",+ sie.model = "BAAI/bge-m3",+ sie.pool = "default",+ sie.publish_ms = tracing::field::Empty,+ );+ let _ = span.set_parent(inbound_cx);+ let publish_cx = span.context();+ let span_context = publish_cx.span().span_context().clone();+ let gateway_trace_id = span_context.trace_id().to_string();+ let gateway_span_id = span_context.span_id().to_string();++ async move {+ let (tp, _ts) = async { WorkPublisher::trace_context_for_endpoint("encode") }+ .with_context(publish_cx)+ .instrument(span)+ .await;+ (+ tp.expect("encode envelope must carry gateway.publish context"),+ gateway_trace_id,+ gateway_span_id,+ )+ }+ });++ publish_fut.await+ }++ opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());++ let inbound_trace_id = "0af7651916cd43dd8448eb211c80319c";+ let inbound_span_id = "b7ad6b7169203331";+ let inbound_tp = format!("00-{inbound_trace_id}-{inbound_span_id}-01");+ let mut headers = axum::http::HeaderMap::new();+ headers.insert(+ axum::http::HeaderName::from_static("traceparent"),+ axum::http::HeaderValue::from_str(&inbound_tp).unwrap(),+ );++ let (tp, gateway_trace_id, gateway_span_id) = publish_with_gateway_span(headers).await;+ let parts: Vec<&str> = tp.split('-').collect();+ assert_eq!(parts.len(), 4, "wire shape: version-trace-span-flags");+ assert_eq!(+ parts[1], inbound_trace_id,+ "gateway.publish must continue the inbound trace_id"+ );+ assert_eq!(parts[1], gateway_trace_id);+ assert_eq!(+ parts[2], gateway_span_id,+ "worker's parent must be gateway.publish"+ );+ assert_ne!(+ parts[2], inbound_span_id,+ "worker must not attach directly to the inbound client span"+ );+ assert_eq!(parts[3], "01", "gateway.publish span should be sampled");++ let (root_tp, root_gateway_trace_id, root_gateway_span_id) =+ publish_with_gateway_span(axum::http::HeaderMap::new()).await;+ let root_parts: Vec<&str> = root_tp.split('-').collect();+ assert_eq!(root_parts.len(), 4, "wire shape: version-trace-span-flags");+ assert_eq!(+ root_parts[1], root_gateway_trace_id,+ "gateway.publish must be the fresh trace root when no inbound context exists"+ );+ assert_eq!(+ root_parts[2], root_gateway_span_id,+ "worker's parent must be the root gateway.publish span"+ );+ assert_ne!(root_parts[1], "00000000000000000000000000000000");+ assert_ne!(root_parts[2], "0000000000000000");+ assert_eq!(+ root_parts[3], "01",+ "root gateway.publish span should be sampled"+ );+ }++ /// Integration test (issue #1500): drive a real `WorkPublisher` encode+ /// publish over a live NATS/JetStream broker, with the inbound trace+ /// context scoped over the publish via `with_context` exactly as+ /// `proxy_request` does, and assert the published work-item envelope+ /// (decoded off the wire) carries a `traceparent` that CONTINUES the+ /// inbound trace. Unlike the unit tests above this exercises the real+ /// JetStream publish, the real msgpack `WorkItemRef` serialization,+ /// and the context surviving the publish future's own `.await`s.+ ///+ /// NATS-gated, mirroring `tests/nak_republish.rs`: a no-op pass when+ /// `NATS_URL` is unset / unreachable so the hermetic `cargo test` run+ /// (and the gateway CI job, which runs no NATS sidecar) stays green;+ /// the full flow runs when `NATS_URL` points at a JetStream server.+ #[tokio::test]+ async fn test_encode_publish_continues_inbound_trace_over_nats() {+ use futures_util::StreamExt;+ use opentelemetry::trace::FutureExt;+ use opentelemetry_sdk::propagation::TraceContextPropagator;++ let Ok(url) = std::env::var("NATS_URL") else {+ eprintln!("skipping: NATS_URL not set");+ return;+ };+ let client =+ match tokio::time::timeout(Duration::from_secs(2), async_nats::connect(&url)).await {+ Ok(Ok(c)) => c,+ _ => {+ eprintln!("skipping: could not connect to NATS at {url}");+ return;+ }+ };++ opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());++ // Unique pool token so this run's JetStream stream + work subject+ // never collide with a parallel run on a shared broker.+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ let pool = format!("itpool{nanos}");+ let model = "BAAI__bge-m3";++ let publisher = WorkPublisher::new(+ async_nats::jetstream::new(client.clone()),+ "it-router".to_string(),+ Arc::new(crate::queue::payload_store::DisabledPayloadStore),+ Duration::from_secs(5),+ 1024,+ Duration::from_secs(300),+ );++ let target = PublishTarget::Pool {+ pool: pool.clone(),+ machine_profile: "l4".to_string(),+ bundle: "default".to_string(),+ model: model.to_string(),+ };+ let subject = target.subject();++ // Pre-create the work stream + a JetStream consumer so the+ // publisher sees a live consumer (`num_consumers > 0`), mirroring a+ // real worker bound to the pool. Without it `publish_work` fails+ // backpressure with "no consumers available for work stream". The+ // stream config matches `ensure_stream` so its later+ // `get_or_create_stream` is a no-op.+ let stream = async_nats::jetstream::new(client.clone())+ .get_or_create_stream(jetstream::stream::Config {+ name: stream_name(&pool),+ subjects: vec![format!("sie.work.{pool}.*.*.*")],+ retention: jetstream::stream::RetentionPolicy::WorkQueue,+ storage: jetstream::stream::StorageType::Memory,+ max_age: Duration::from_secs(300),+ max_messages: 100_000,+ ..Default::default()+ })+ .await+ .expect("create work stream");+ stream+ .create_consumer(jetstream::consumer::pull::Config {+ durable_name: Some("itworker".to_string()),+ filter_subject: subject.clone(),+ ..Default::default()+ })+ .await+ .expect("create work consumer");++ // Subscribe BEFORE publishing — a core subscriber also receives+ // JetStream-published messages on the subject.+ let mut sub = client.subscribe(subject.clone()).await.expect("subscribe");+ client.flush().await.expect("flush");++ // Inbound client trace context (as a `/v1/encode` caller sends).+ let inbound_trace_id = "0af7651916cd43dd8448eb211c80319c";+ let inbound_span_id = "b7ad6b7169203331";+ let inbound_tp = format!("00-{inbound_trace_id}-{inbound_span_id}-01");+ let mut headers = axum::http::HeaderMap::new();+ headers.insert(+ axum::http::HeaderName::from_static("traceparent"),+ axum::http::HeaderValue::from_str(&inbound_tp).unwrap(),+ );+ let cx = crate::observability::propagation::extract_context_from_headers(&headers);++ let params = WorkParams {+ output_types: None,+ instruction: None,+ is_query: false,+ options: None,+ labels: None,+ output_schema: None,+ query_item: None,+ generate: None,+ routing_key: None,+ prompt_cache_key: None,+ };+ let items = vec![rmpv::Value::Map(vec![(+ rmpv::Value::String("text".into()),+ rmpv::Value::String("hello".into()),+ )])];++ // Mirror the handler: scope the inbound context over the publish.+ let (_request_id, _rx) = publisher+ .publish_work(+ target, &pool, "encode", model, "pytorch", "", items, ¶ms,+ )+ .with_context(cx)+ .await+ .expect("publish_work");++ let msg = tokio::time::timeout(Duration::from_secs(5), sub.next())+ .await+ .expect("timed out waiting for the published work item")+ .expect("subscription closed before a message arrived");+ let work: WorkItem =+ rmp_serde::from_slice(&msg.payload).expect("decode work-item envelope");++ let tp = work+ .traceparent+ .expect("encode envelope must carry the inbound traceparent");+ let parts: Vec<&str> = tp.split('-').collect();+ assert_eq!(parts.len(), 4, "wire shape: version-trace-span-flags");+ assert_eq!(+ parts[1], inbound_trace_id,+ "must continue the inbound trace_id"+ );+ assert_eq!(+ parts[2], inbound_span_id,+ "worker's parent must be the inbound span"+ );++ // Best-effort cleanup so repeated local runs don't accumulate+ // per-run streams on a persistent broker.+ let _ = async_nats::jetstream::new(client.clone())+ .delete_stream(stream_name(&pool))+ .await;+ }+// ----- H9 — first-chunk-fallback rate limit ---------------------- /// The bucket admits exactly ``burst`` tokens immediately, then- /// refuses until the rate refills enough for the next whole token.- /// Refilling is driven by monotonic time so the test sleeps briefly- /// to advance the clock; the timing window is generous enough to- /// avoid flakes on a loaded CI runner.+ /// A NAK is dropped as stale only when the collector can identify it as an+ /// abandoned, non-empty attempt id — either by comparing with the latched+ /// current attempt, or with the abandoned attempt recorded during a+ /// NAK-driven republish before the successor's first chunk. See #1601.#[test]- fn test_token_bucket_burst_and_refill() {- let mut bucket = TokenBucket::new(10.0, 3.0); // 10/s, burst 3- // Burst exhausted in three takes.- assert!(bucket.try_take());- assert!(bucket.try_take());- assert!(bucket.try_take());- assert!(!bucket.try_take(), "burst exceeded — must refuse");+ fn test_nak_is_stale_for_latched_or_recorded_abandoned_attempt() {+ // Stale: collector latched gen1, NAK is from the abandoned gen0.+ assert!(nak_is_stale(Some("gen1"), None, "gen0"));+ // Not stale: NAK is from the currently-latched attempt.+ assert!(!nak_is_stale(Some("gen0"), None, "gen0"));+ // Stale: republish happened before any successor chunk latched, but the+ // NAK-driven republish recorded the abandoned attempt id.+ assert!(nak_is_stale(None, Some("gen0"), "gen0"));+ // Not stale by this predicate: before successor latch, a different NAK+ // may be from the live pool attempt. The already-republished handler+ // treats that state as ambiguous and waits instead of failing.+ assert!(!nak_is_stale(None, Some("gen0"), "gen1"));+ // Fail open — no attempt latched or recorded yet: act on the NAK.+ assert!(!nak_is_stale(None, None, "gen0"));+ // Fail open — NAK carries no attempt id: act on the NAK.+ assert!(!nak_is_stale(Some("gen1"), Some("gen0"), ""));+ assert!(!nak_is_stale(None, Some("gen0"), ""));+ assert!(!nak_is_stale(None, None, ""));+ }++ #[test]+ fn test_already_republished_nak_waits_before_successor_latches() {+ use AlreadyRepublishedNakDecision::{DropStale, Fail, WaitForSuccessor};++ // Timeout-driven fallback: no worker attempt id was known when the+ // request republished, so a later NAK before the pool worker's first+ // chunk is ambiguous. Do not synthesize the spurious 429 from #1601.+ assert_eq!(+ already_republished_nak_decision(None, None, "gen0"),+ WaitForSuccessor+ );+ // Even if a previous pre-latch NAK recorded an abandoned id, a+ // different pre-latch NAK is still ambiguous until a successor chunk+ // proves which attempt is live.+ assert_eq!(+ already_republished_nak_decision(None, Some("gen0"), "gen1"),+ WaitForSuccessor+ );+ // Exact abandoned-id matches are still stale drops.+ assert_eq!(+ already_republished_nak_decision(None, Some("gen0"), "gen0"),+ DropStale+ );+ assert_eq!(+ already_republished_nak_decision(Some("gen1"), Some("gen0"), "gen0"),+ DropStale+ );+ // Once an attempt has latched, a NAK from that same attempt is the live+ // retry failure and may surface immediately.+ assert_eq!(+ already_republished_nak_decision(Some("gen1"), Some("gen0"), "gen1"),+ Fail+ );+ }- // Sleep ~120ms — at 10/s that's >=1 token of refill.- std::thread::sleep(Duration::from_millis(150));- assert!(bucket.try_take(), "expected refill to permit one more take");+ /// The bucket admits exactly ``burst`` tokens immediately, then refuses+ /// until the rate refills enough for the next whole token. Time is+ /// injected, so the refill is exercised by advancing a synthetic clock —+ /// deterministic, no ``thread::sleep`` and no CI-timing window.+ #[test]+ fn test_token_bucket_burst_and_refill() {+ let t0 = Instant::now();+ let mut bucket = TokenBucket::new(10.0, 3.0, t0); // 10/s, burst 3+ // Burst exhausted in three takes at t0.+ assert!(bucket.try_take(t0));+ assert!(bucket.try_take(t0));+ assert!(bucket.try_take(t0));+ assert!(!bucket.try_take(t0), "burst exceeded — must refuse");++ // Advance 150ms — at 10/s that is >=1 token of refill.+ let t1 = t0 + Duration::from_millis(150);+ assert!(+ bucket.try_take(t1),+ "expected refill to permit one more take"+ );}/// Regression for the burst cap: the bucket must NOT accumulate@@ -4673,13 +5505,15 @@ mod tests {/// hours of accrued tokens at once.#[test]fn test_token_bucket_caps_at_burst() {- let mut bucket = TokenBucket::new(100.0, 2.0); // very fast refill, tiny burst- std::thread::sleep(Duration::from_millis(50)); // would refill 5 tokens uncapped- // Two takes succeed (burst), the third refuses (no overflow stored).- assert!(bucket.try_take());- assert!(bucket.try_take());+ let t0 = Instant::now();+ let mut bucket = TokenBucket::new(100.0, 2.0, t0); // very fast refill, tiny burst+ // 50ms at 100/s would refill 5 tokens uncapped; the cap must hold.+ let t1 = t0 + Duration::from_millis(50);+ // Two takes succeed (burst), the third refuses (no overflow stored).+ assert!(bucket.try_take(t1));+ assert!(bucket.try_take(t1));assert!(- !bucket.try_take(),+ !bucket.try_take(t1),"burst cap must be enforced even after a long idle window");}@@ -4690,10 +5524,12 @@ mod tests {/// permits and we want a deterministic, bounded number of republishes.#[test]fn test_token_bucket_drops_excess_attempts() {- let mut bucket = TokenBucket::new(5.0, 4.0); // 5/s, burst 4+ let t0 = Instant::now();+ let mut bucket = TokenBucket::new(5.0, 4.0, t0); // 5/s, burst 4let mut admitted = 0usize;+ // All attempts at the same instant — no refill, so exactly burst admit.for _ in 0..20 {- if bucket.try_take() {+ if bucket.try_take(t0) {admitted += 1;}}@@ -4722,19 +5558,24 @@ mod tests {burst: f64,model: &str,pool: &str,+ now: Instant,) -> bool {let key = format!("{}|{}", model, pool);let entry = buckets.entry(key)- .or_insert_with(|| std::sync::Mutex::new(TokenBucket::new(rate, burst)));- let admitted = entry.value().lock().unwrap().try_take();+ .or_insert_with(|| std::sync::Mutex::new(TokenBucket::new(rate, burst, now)));+ let admitted = entry.value().lock().unwrap().try_take(now);admitted}+ // All attempts at one instant — no refill, so each key admits exactly+ // burst-many before refusing.+ let t0 = Instant::now();+// Same key — admit exactly burst, then refuse.let mut admitted_a = 0usize;for _ in 0..30 {- if try_take(&buckets, rate, burst, "model-A", "pool-1") {+ if try_take(&buckets, rate, burst, "model-A", "pool-1", t0) {admitted_a += 1;}}@@ -4743,7 +5584,7 @@ mod tests {// Different model on same pool → independent bucket → full burst.let mut admitted_b = 0usize;for _ in 0..30 {- if try_take(&buckets, rate, burst, "model-B", "pool-1") {+ if try_take(&buckets, rate, burst, "model-B", "pool-1", t0) {admitted_b += 1;}}@@ -4752,7 +5593,7 @@ mod tests {// Different pool on same model → also independent.let mut admitted_c = 0usize;for _ in 0..30 {- if try_take(&buckets, rate, burst, "model-A", "pool-2") {+ if try_take(&buckets, rate, burst, "model-A", "pool-2", t0) {admitted_c += 1;}}diff --git a/packages/sie_gateway/src/queue/streaming.rs b/packages/sie_gateway/src/queue/streaming.rsindex 82b1951f5..6a6bd0c0e 100644--- a/packages/sie_gateway/src/queue/streaming.rs+++ b/packages/sie_gateway/src/queue/streaming.rs@@ -324,16 +324,17 @@ pub struct StreamCollector {/// requested. Snapshotted/cleared by the attempt-generation machinery/// exactly like ``chunks``.logprobs: Vec<serde_json::Value>,- /// Attempt id of the most recently abandoned attempt, set by- /// [`Self::bump_attempt_generation`] from the old- /// ``current_attempt_id``. While ``current_attempt_id`` is ``None``- /// (post-bump, pre-relatch), :meth:`apply` refuses to re-latch on- /// this id so a stale leftover chunk from the just-abandoned attempt- /// cannot hijack the latch and starve the genuinely-new attempt's- /// chunks (which would then be dropped as stale, hanging the- /// request). Cleared the moment a non-abandoned attempt latches.- /// uuid4 attempt ids are never reused, so an incoming chunk whose id- /// equals this is unambiguously from the abandoned attempt.+ /// Attempt id of the most recently abandoned attempt. Usually set by+ /// [`Self::bump_attempt_generation`] from the old ``current_attempt_id``;+ /// NAK-driven republish may also fill it from the NAK envelope when the+ /// abandoned attempt had not emitted a first chunk yet. While+ /// ``current_attempt_id`` is ``None`` (post-bump, pre-relatch),+ /// :meth:`apply` refuses to re-latch on this id so a stale leftover chunk+ /// from the just-abandoned attempt cannot hijack the latch and starve the+ /// genuinely-new attempt's chunks (which would then be dropped as stale,+ /// hanging the request). Cleared the moment a non-abandoned attempt+ /// latches. uuid4 attempt ids are never reused, so an incoming chunk whose+ /// id equals this is unambiguously from the abandoned attempt.pub abandoned_attempt_id: Option<String>,/// Snapshot of the per-attempt state cleared by/// [`Self::bump_attempt_generation`], consumed only by an@@ -474,6 +475,18 @@ impl StreamCollector {self.attempt_generation}+ /// Fill the abandoned-attempt guard from an inbox NAK that caused a+ /// republish before any chunk latched an attempt id.+ pub fn record_abandoned_attempt_id(&mut self, attempt_id: &str) {+ if attempt_id.is_empty()+ || self.current_attempt_id.is_some()+ || self.abandoned_attempt_id.is_some()+ {+ return;+ }+ self.abandoned_attempt_id = Some(attempt_id.to_string());+ }+/// Undo a [`Self::bump_attempt_generation`] that was followed by/// a publish failure. Used by `WorkPublisher::republish_to_pool` to/// keep the collector's `attempt_generation` consistent with what@@ -1393,6 +1406,26 @@ mod tests {assert_eq!(outcome.attempt_id, "att-B");}+ #[test]+ fn test_nak_recorded_abandoned_attempt_does_not_relatch_before_successor() {+ let (tx, _rx) = oneshot::channel();+ let mut c = StreamCollector::new(tx, "m".to_string(), "p".to_string());+ c.bump_attempt_generation();+ c.record_abandoned_attempt_id("att-A");++ assert_eq!(+ c.apply(_make_chunk("att-A", 0, "STALE", false)),+ ChunkApplied::Stale+ );+ assert!(c.current_attempt_id.is_none());++ let applied = c.apply(_make_chunk("att-B", 0, "fresh", true));+ assert_eq!(applied, ChunkApplied::Terminal);+ let outcome = c.build_outcome().expect("terminal");+ assert_eq!(outcome.text, "fresh");+ assert_eq!(outcome.attempt_id, "att-B");+ }+/// BUG B regression: a ``bump`` followed by a ``rewind`` (publish/// failed) must restore the accumulated chunks the bump cleared,/// rather than permanently dropping the abandoned attempt's partial@@ -1412,6 +1445,25 @@ mod tests {assert!(c.last_chunk_at.is_some());}+ #[test]+ fn test_rewind_clears_nak_recorded_abandoned_attempt() {+ let (tx, _rx) = oneshot::channel();+ let mut c = StreamCollector::new(tx, "m".to_string(), "p".to_string());+ c.bump_attempt_generation();+ c.record_abandoned_attempt_id("att-A");++ c.rewind_attempt_generation();++ assert!(c.abandoned_attempt_id.is_none());+ assert_eq!(+ c.apply(_make_chunk("att-A", 0, "restored", true)),+ ChunkApplied::Terminal+ );+ let outcome = c.build_outcome().expect("terminal");+ assert_eq!(outcome.text, "restored");+ assert_eq!(outcome.attempt_id, "att-A");+ }+/// BUG B regression: a successful new attempt (bump with NO rewind)/// must not resurrect the abandoned attempt's chunks — the snapshot/// is consumed only by a rewind.diff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rsindex a1488b043..a999f91ea 100644--- a/packages/sie_gateway/src/state/config_bootstrap.rs+++ b/packages/sie_gateway/src/state/config_bootstrap.rs@@ -89,6 +89,8 @@ struct ExportSnapshot {#[serde(default)]bundle_config_hashes: HashMap<String, String>,#[serde(default)]+ bundle_pool_config_hashes: HashMap<String, HashMap<String, String>>,+ #[serde(default)]models: Vec<ExportedModel>,}@@ -454,6 +456,7 @@ impl BootstrapClient {Ok(count) => {applied = count;registry.install_bundle_config_hashes(snapshot.bundle_config_hashes);+ registry.install_bundle_pool_config_hashes(snapshot.bundle_pool_config_hashes);}Err(e) => {warn!(error = %e, "failed to install authoritative config export");@@ -783,6 +786,7 @@ mod tests {"epoch": 42,"generated_at": "2026-04-17T00:00:00Z","bundle_config_hashes": {"default": "control-plane-hash"},+ "bundle_pool_config_hashes": {"default": {"default": "control-plane-pool-hash"}},"models": [{"model_id": "test/model",@@ -811,6 +815,10 @@ mod tests {registry.compute_bundle_config_hash("default"),"control-plane-hash");+ assert_eq!(+ registry.compute_bundle_config_hash_for_pool("default", "default"),+ "control-plane-pool-hash"+ );assert_eq!(registry.get_model_profile_names("test/model"),vec!["default".to_string()],@@ -1397,7 +1405,7 @@ mod tests {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",+ "name: bad-engine\npriority: 10\nengine: future-engine\nadapters:\n - sie_server.adapters.sentence_transformer\n",)).mount(&server).await;@@ -1408,7 +1416,7 @@ mod tests {BootstrapError::BadStatus { status, body, .. } => {assert_eq!(status, 200);assert!(body.contains("unknown bundle engine"));- assert!(body.contains("candle"));+ assert!(body.contains("future-engine"));}other => panic!("expected BadStatus, got {:?}", other),}diff --git a/packages/sie_gateway/src/state/k8s_pool_backend.rs b/packages/sie_gateway/src/state/k8s_pool_backend.rsindex a9a253e47..960b96c8c 100644--- a/packages/sie_gateway/src/state/k8s_pool_backend.rs+++ b/packages/sie_gateway/src/state/k8s_pool_backend.rs@@ -1,13 +1,13 @@use std::time::Duration;-use chrono::Utc;use k8s_openapi::api::coordination::v1::Lease as K8sLease;use k8s_openapi::api::coordination::v1::LeaseSpec;use k8s_openapi::api::core::v1::ConfigMap;use k8s_openapi::apimachinery::pkg::apis::meta::v1::{MicroTime, ObjectMeta};+use k8s_openapi::jiff::Timestamp;use kube::api::{Api, ListParams, Patch, PatchParams};use kube::Client;-use rand::Rng;+use rand::RngExt as _;use tracing::{debug, info, warn};use crate::types::pool::{Pool, PoolStatus};@@ -264,8 +264,8 @@ impl K8sPoolBackend {// Apply jitter: multiply delay by a random factor in [1 - jitter, 1 + jitter)let jitter_factor = {- let mut rng = rand::thread_rng();- rng.gen_range((1.0 - CAS_JITTER_FRACTION)..(1.0 + CAS_JITTER_FRACTION))+ let mut rng = rand::rng();+ rng.random_range((1.0 - CAS_JITTER_FRACTION)..(1.0 + CAS_JITTER_FRACTION))};let sleep_ms = delay_ms * jitter_factor;@@ -308,7 +308,7 @@ impl K8sPoolBackend {) -> Result<(), String> {let api = self.lease_api();let name = Self::lease_name(pool_name);- let now = MicroTime(Utc::now());+ let now = MicroTime(Timestamp::now());// Preserve the original acquireTime if the Lease already existslet acquire_time = match api.get(&name).await {@@ -350,7 +350,7 @@ impl K8sPoolBackend {pub async fn renew_lease(&self, pool_name: &str) -> Result<(), String> {let api = self.lease_api();let name = Self::lease_name(pool_name);- let now = MicroTime(Utc::now());+ let now = MicroTime(Timestamp::now());let labels = Self::pool_labels(pool_name);@@ -416,7 +416,7 @@ impl K8sPoolBackend {.await.map_err(|e| format!("list Leases: {}", e))?;- let now = Utc::now();+ let now = Timestamp::now();let mut expired = Vec::new();for lease in leases.items {@@ -450,7 +450,7 @@ impl K8sPoolBackend {None => continue,};- let elapsed = now.signed_duration_since(last_dt).num_seconds();+ let elapsed = now.as_second() - last_dt.as_second();if elapsed > duration_secs {debug!(pool = %pool_name,diff --git a/packages/sie_gateway/src/state/k8s_pool_watcher.rs b/packages/sie_gateway/src/state/k8s_pool_watcher.rsindex 3e2e0c457..aa93852cc 100644--- a/packages/sie_gateway/src/state/k8s_pool_watcher.rs+++ b/packages/sie_gateway/src/state/k8s_pool_watcher.rs@@ -6,7 +6,7 @@ use k8s_openapi::api::core::v1::ConfigMap;use kube::api::Api;use kube::runtime::watcher::{self, Event};use kube::Client;-use rand::prelude::*;+use rand::RngExt as _;use tracing::{debug, info, warn};use crate::state::k8s_pool_backend::{@@ -54,8 +54,8 @@ impl K8sPoolWatcher {// Add jitter (20%)let jitter_factor = {- let mut rng = rand::thread_rng();- rng.gen_range(0.8..1.2)+ let mut rng = rand::rng();+ rng.random_range(0.8..1.2)};let sleep_duration =Duration::from_secs_f64(backoff.as_secs_f64() * jitter_factor);diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex c0eb0d186..fb85ac006 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -1,4 +1,5 @@use std::collections::{BTreeMap, HashMap, HashSet};+use std::fmt::Write as _;use std::path::{Path, PathBuf};use std::sync::{Arc, Mutex};@@ -382,7 +383,11 @@ impl ModelRegistry {config: &ModelConfig,) -> Result<Vec<ModelEntry>, String> {let base_entry = Self::model_entry_from_config(config)?;- let mut entries = vec![base_entry.clone()];+ let mut entries = if base_entry.profile_names.contains("default") {+ vec![base_entry.clone()]+ } else {+ Vec::new()+ };let mut profile_names: Vec<String> = base_entry.profile_names.iter().cloned().collect();profile_names.sort();for profile_name in profile_names {@@ -392,6 +397,11 @@ impl ModelRegistry {Self::validate_profile_name(&profile_name)?;let profile_config =Self::resolved_profile_from_profiles(&config.profiles, &profile_name)?;+ let info_extras = Self::narrow_info_extras_to_profile(+ &base_entry.info_extras,+ &profile_name,+ &profile_config,+ );let mut variant_profile_names = HashSet::new();variant_profile_names.insert("default".to_string());let mut variant_profile_configs = HashMap::new();@@ -411,10 +421,7 @@ impl ModelRegistry {adapter_modules: variant_adapters,profile_names: variant_profile_names,profile_configs: variant_profile_configs,- info_extras: Self::narrow_info_extras_to_profile(- &base_entry.info_extras,- &profile_name,- ),+ info_extras,});}@@ -427,10 +434,13 @@ impl ModelRegistry {/// adapters configured for *its* profile. Without this narrowing,/// the variant inherits the union and the lora_adapter gate accepts/// adapters that are only configured on a sibling profile (M10 bug).- /// All other capability fields stay the same.+ /// Native Rust variants also narrow the advertised output surface to the+ /// adapter class (`dense` for embeddings, `score` for rerankers)+ /// because the base model may carry PyTorch-only capabilities.fn narrow_info_extras_to_profile(base: &ModelInfoExtras,profile_name: &str,+ profile_config: &CanonicalProfile,) -> ModelInfoExtras {let mut narrowed = base.clone();// Clear the per-variant routing hint. A variant entry IS a concrete@@ -460,31 +470,42 @@ impl ModelRegistry {narrowed.profile_lora_adapters = Some(single);}}+ Self::narrow_native_outputs_to_profile(&mut narrowed, profile_config);narrowed}+ fn narrow_native_outputs_to_profile(+ extras: &mut ModelInfoExtras,+ profile_config: &CanonicalProfile,+ ) {+ let Some(adapter_path) = profile_config.adapter_path.as_deref() else {+ return;+ };+ if !adapter_path.starts_with("sie_server_rust.adapters.candle") {+ return;+ }+ if !extras.outputs.iter().any(|name| name == "dense") {+ return;+ }+ extras.outputs = vec!["dense".to_string()];+ extras.dims.retain(|name, _| name == "dense");+ }+fn model_entry_from_config(config: &ModelConfig) -> Result<ModelEntry, String> {let info_extras = crate::types::model::ModelInfoExtras::from_model_config(config);let model_name = config.name.clone();let pool = Self::normalize_model_pool(config.pool.as_deref())?;- let mut adapter_modules: HashSet<String> = HashSet::new();let mut profile_names: HashSet<String> = HashSet::new();let mut profile_configs: HashMap<String, CanonicalProfile> = HashMap::new();for profile_name in config.profiles.keys() {profile_names.insert(profile_name.clone());- if let Some(adapter_path) =- Self::effective_adapter_path_from_profiles(&config.profiles, profile_name)- {- if let Some(module) = Self::adapter_module_from_path(adapter_path) {- adapter_modules.insert(module);- }- }profile_configs.insert(profile_name.clone(),Self::resolved_profile_from_profiles(&config.profiles, profile_name)?,);}+ let adapter_modules = Self::base_route_adapter_modules_from_profiles(&config.profiles);Ok(ModelEntry {name: model_name,@@ -525,7 +546,11 @@ impl ModelRegistry {fn expand_model_entry_into_profile_variants(base_entry: &ModelEntry,) -> Result<Vec<ModelEntry>, String> {- let mut entries = vec![base_entry.clone()];+ let mut entries = if base_entry.profile_names.contains("default") {+ vec![base_entry.clone()]+ } else {+ Vec::new()+ };let mut profile_names: Vec<String> = base_entry.profile_names.iter().cloned().collect();profile_names.sort();for profile_name in profile_names {@@ -545,6 +570,11 @@ impl ModelRegistry {else {return Err(Self::profile_resolution_error(&profile_name));};+ let info_extras = Self::narrow_info_extras_to_profile(+ &base_entry.info_extras,+ &profile_name,+ &profile_config,+ );let mut variant_profile_names = HashSet::new();variant_profile_names.insert("default".to_string());let mut variant_profile_configs = HashMap::new();@@ -564,10 +594,7 @@ impl ModelRegistry {adapter_modules: variant_adapters,profile_names: variant_profile_names,profile_configs: variant_profile_configs,- info_extras: Self::narrow_info_extras_to_profile(- &base_entry.info_extras,- &profile_name,- ),+ info_extras,});}@@ -626,9 +653,10 @@ impl ModelRegistry {if profile.compute_precision.is_some() {resolved.compute_precision = profile.compute_precision.clone();}- if profile.adapter_options.is_some() {- resolved.adapter_options = profile.adapter_options.clone();- }+ resolved.adapter_options = ModelRegistry::merge_adapter_options(+ resolved.adapter_options,+ profile.adapter_options.clone(),+ );resolved.extends = None;Some(resolved)}@@ -706,18 +734,60 @@ impl ModelRegistry {if profile.compute_precision.is_some() {resolved.compute_precision = profile.compute_precision.clone();}- if profile.adapter_options.is_some() {- resolved.adapter_options = profile.adapter_options.clone();- }+ resolved.adapter_options =+ Self::merge_adapter_options(resolved.adapter_options, profile.adapter_options.clone());Some(resolved)}- fn adapter_modules_from_entry_profiles(entry: &ModelEntry) -> HashSet<String> {- entry- .profile_names- .iter()- .filter_map(|profile_name| Self::effective_adapter_path_from_entry(entry, profile_name))- .filter_map(Self::adapter_module_from_path)+ fn merge_adapter_options(+ parent: Option<serde_json::Value>,+ child: Option<serde_json::Value>,+ ) -> Option<serde_json::Value> {+ let Some(child_value) = child else {+ return parent;+ };++ let serde_json::Value::Object(child_map) = child_value else {+ return Some(child_value);+ };++ let mut merged = match parent {+ Some(serde_json::Value::Object(parent_map)) => parent_map,+ Some(_) | None => serde_json::Map::new(),+ };++ for (key, value) in child_map {+ if matches!(key.as_str(), "loadtime" | "runtime") {+ if !matches!(&value, serde_json::Value::Object(map) if map.is_empty()) {+ merged.insert(key, value);+ }+ continue;+ }+ merged.insert(key, value);+ }++ Some(serde_json::Value::Object(merged))+ }++ fn base_route_adapter_modules_from_profiles(+ profiles: &HashMap<String, crate::types::model::ProfileConfig>,+ ) -> HashSet<String> {+ if !profiles.contains_key("default") {+ return HashSet::new();+ }+ Self::effective_adapter_path_from_profiles(profiles, "default")+ .and_then(Self::adapter_module_from_path)+ .into_iter()+ .collect()+ }++ fn base_route_adapter_modules_from_entry(entry: &ModelEntry) -> HashSet<String> {+ if !entry.profile_names.contains("default") {+ return HashSet::new();+ }+ Self::effective_adapter_path_from_entry(entry, "default")+ .and_then(Self::adapter_module_from_path)+ .into_iter().collect()}@@ -795,10 +865,9 @@ impl ModelRegistry {/// 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.+ /// `X-SIE-Engine` header at the proxy layer. This remains an+ /// operator/debug override; normal routing should select the bundle+ /// through model/profile compatibility.////// `engine_filter = None` is the back-compat path used by callers/// that don't care about engine selection.@@ -1131,6 +1200,38 @@ impl ModelRegistry {self.snapshot.store(Arc::new(snap));}+ pub fn install_bundle_pool_config_hashes(+ &self,+ hashes: HashMap<String, 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, pool_hashes) in hashes {+ if !snap.bundles.contains_key(&bundle_name) {+ continue;+ }+ for (pool_name, hash) in pool_hashes {+ let pool_name = pool_name.trim().to_lowercase();+ let pool_name = if pool_name.is_empty() {+ DEFAULT_MODEL_POOL.to_string()+ } else {+ pool_name+ };+ let key = (bundle_name.clone(), pool_name);+ if hash.is_empty() {+ snap.bundle_pool_config_hashes.remove(&key);+ } else {+ snap.bundle_pool_config_hashes.insert(key, 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(@@ -1169,10 +1270,7 @@ impl ModelRegistry {models: &HashMap<String, ModelEntry>,) -> HashMap<(String, String), String> {let mut pools_by_bundle: HashMap<String, HashSet<String>> = HashMap::new();- for (model_name, entry) in models {- if Self::is_synthetic_profile_variant(model_name, models) {- continue;- }+ for entry in models.values() {let pool = Self::entry_pool_name(entry).to_string();for bundle in &entry.bundles {pools_by_bundle@@ -1225,8 +1323,17 @@ impl ModelRegistry {model_names.sort();for model_name in model_names {- if Self::is_synthetic_profile_variant(model_name, models) {- continue;+ let synthetic_variant = Self::synthetic_profile_variant_parts(model_name, models);+ if let Some((base_name, _)) = synthetic_variant {+ if models+ .get(base_name)+ .is_some_and(|base_entry| base_entry.bundles.iter().any(|b| b == bundle_id))+ {+ // The base entry already carries all profiles compatible with this+ // bundle. Only hash synthetic variants when they are the sole+ // routing identity for this bundle, e.g. `model:candle`.+ continue;+ }}let model_entry = &models[model_name];@@ -1236,6 +1343,13 @@ impl ModelRegistry {{continue;}++ let (hash_model_name, variant_profile_name) =+ if let Some((base_name, profile_name)) = synthetic_variant {+ (base_name, Some(profile_name))+ } else {+ (model_name.as_str(), None)+ };if !model_entry.bundles.contains(&bundle_id.to_string()) {continue;}@@ -1284,14 +1398,28 @@ impl ModelRegistry {let mut profile = BTreeMap::new();profile.insert("config", serde_json::to_value(config).unwrap());- profile.insert("name", serde_json::Value::String(pname.clone()));+ let profile_name_for_hash = if pname == "default" {+ variant_profile_name.unwrap_or(pname.as_str())+ } else {+ pname.as_str()+ };+ profile.insert(+ "name",+ serde_json::Value::String(profile_name_for_hash.to_string()),+ );profiles_for_hash.push(profile);}}+ if profiles_for_hash.is_empty() {+ continue;+ }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()));+ item.insert(+ "sie_id",+ serde_json::Value::String(hash_model_name.to_string()),+ );items.push(serde_json::to_value(item).unwrap());}@@ -1302,17 +1430,22 @@ impl ModelRegistry {let serialized = serde_json::to_string(&items).unwrap_or_default();let mut hasher = Sha256::new();hasher.update(serialized.as_bytes());- format!("{:x}", hasher.finalize())+ let digest = hasher.finalize();+ let mut hex = String::with_capacity(64);+ for byte in digest {+ write!(&mut hex, "{byte:02x}").expect("write to String cannot fail");+ }+ hex}- fn is_synthetic_profile_variant(- model_name: &str,+ fn synthetic_profile_variant_parts<'a>(+ model_name: &'a str,models: &HashMap<String, ModelEntry>,- ) -> bool {+ ) -> Option<(&'a str, &'a str)> {model_name.rsplit_once(':')- .is_some_and(|(base_model_name, profile_name)| {- !profile_name.is_empty() && models.contains_key(base_model_name)+ .filter(|(base_model_name, profile_name)| {+ !profile_name.is_empty() && models.contains_key(*base_model_name)})}@@ -1577,7 +1710,7 @@ impl ModelRegistry {Self::resolved_profile_from_profiles(&merged_profiles, pname)?,);}- existing.adapter_modules = Self::adapter_modules_from_entry_profiles(existing);+ existing.adapter_modules = Self::base_route_adapter_modules_from_entry(existing);Self::merge_model_info_extras(&mut existing.info_extras, &config, &merged_profiles);} else {// New model@@ -1601,7 +1734,9 @@ impl ModelRegistry {name: sie_id.clone(),pool: incoming_pool,bundles: Vec::new(),- adapter_modules: new_adapter_modules,+ adapter_modules: Self::base_route_adapter_modules_from_profiles(+ &config.profiles,+ ),profile_names,profile_configs,info_extras,@@ -1630,6 +1765,10 @@ impl ModelRegistry {snap.models.remove(&name);snap.model_names_lower.remove(&name.to_lowercase());}+ if !base_entry.profile_names.contains("default") {+ snap.models.remove(sie_id);+ snap.model_names_lower.remove(&sie_id.to_lowercase());+ }for mut entry in Self::expand_model_entry_into_profile_variants(&base_entry)? {Self::assign_bundles(&mut entry, &snap.bundles);@@ -2050,9 +2189,17 @@ profiles:default:adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdaptermax_batch_tokens: 8192+ adapter_options:+ loadtime:+ trust_remote_code: false+ runtime:+ normalize: falsea100-40gb:extends: defaultmax_batch_tokens: 32768+ adapter_options:+ runtime:+ normalize: true"#,).unwrap();@@ -2083,6 +2230,104 @@ profiles:Some("sie_server.adapters.sglang.generation:SGLangGenerationAdapter"));assert_eq!(default_profile.max_batch_tokens, Some(32768));+ assert_eq!(+ default_profile.adapter_options,+ Some(serde_json::json!({+ "loadtime": {"trust_remote_code": false},+ "runtime": {"normalize": true},+ }))+ );+ }++ #[test]+ fn test_reload_profile_only_model_exposes_variant_without_base_route() {+ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("candle.yaml"),+ "name: candle\npriority: 20\nadapters:\n - sie_server_rust.adapters.candle\n",+ )+ .unwrap();+ fs::write(+ models_dir.join("org__profile-only.yaml"),+ r#"+sie_id: org/profile-only+profiles:+ experimental:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ max_batch_tokens: 8192+"#,+ )+ .unwrap();++ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);++ assert!(!registry.model_exists("org/profile-only"));+ assert!(registry.model_exists("org/profile-only:experimental"));+ assert_eq!(+ registry.list_models(),+ vec!["org/profile-only:experimental".to_string()]+ );+ assert!(registry.resolve_bundle("org/profile-only", None).is_err());+ assert_eq!(+ registry+ .resolve_bundle("org/profile-only:experimental", None)+ .unwrap(),+ "candle"+ );+ }++ #[test]+ fn test_add_profile_only_model_exposes_variant_without_base_route() {+ use crate::types::model::{ModelConfig, ProfileConfig};+ use std::collections::HashMap as StdHashMap;++ let (_dir, bundles_dir, models_dir) = create_test_dirs();+ fs::write(+ bundles_dir.join("candle.yaml"),+ "name: candle\npriority: 20\nadapters:\n - sie_server_rust.adapters.candle\n",+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);++ let mut profiles = StdHashMap::new();+ profiles.insert(+ "experimental".to_string(),+ ProfileConfig {+ adapter_path: Some(+ "sie_server_rust.adapters.candle:CandleEmbeddingAdapter".to_string(),+ ),+ max_batch_tokens: Some(8192),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ registry+ .add_model_config(ModelConfig {+ name: "org/profile-only".to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ tasks: None,+ max_sequence_length: None,+ })+ .unwrap();++ assert!(!registry.model_exists("org/profile-only"));+ assert!(registry.model_exists("org/profile-only:experimental"));+ assert_eq!(+ registry.list_models(),+ vec!["org/profile-only:experimental".to_string()]+ );+ assert!(registry.resolve_bundle("org/profile-only", None).is_err());+ assert_eq!(+ registry+ .resolve_bundle("org/profile-only:experimental", None)+ .unwrap(),+ "candle"+ );}#[test]@@ -2156,6 +2401,79 @@ profiles:.unwrap_or(false));}+ #[test]+ fn test_candle_profile_variant_narrows_outputs_to_dense() {+ 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.rope_flash\n",+ )+ .unwrap();+ fs::write(+ bundles_dir.join("candle.yaml"),+ "name: candle\npriority: 30\nengine: candle\nadapters:\n - sie_server_rust.adapters.candle\n",+ )+ .unwrap();+ fs::write(+ models_dir.join("acme__hybrid.yaml"),+ r#"+sie_id: acme/hybrid+tasks:+ encode:+ dense:+ dim: 768+ sparse:+ dim: 30522+ multivector:+ dim: 128+ score: {}+profiles:+ default:+ adapter_path: sie_server.adapters.rope_flash:RoPEFlashAdapter+ max_batch_tokens: 8192+ candle:+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ max_batch_tokens: 8192+"#,+ )+ .unwrap();++ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ let base = registry.get_model_info("acme/hybrid").unwrap();+ assert_eq!(+ base.bundles,+ vec!["default".to_string()],+ "base model routes through the default profile adapter"+ );+ assert_eq!(+ base.info_extras.outputs,+ vec![+ "dense".to_string(),+ "sparse".to_string(),+ "multivector".to_string(),+ "score".to_string(),+ ],+ "base entry preserves the full model-level capability surface"+ );++ let variant = registry.get_model_info("acme/hybrid:candle").unwrap();+ assert_eq!(variant.info_extras.outputs, vec!["dense".to_string()]);+ assert_eq!(variant.info_extras.dims.get("dense"), Some(&768));+ assert!(!variant.info_extras.dims.contains_key("sparse"));+ assert!(!variant.info_extras.dims.contains_key("multivector"));+ assert_eq!(+ registry.resolve_bundle("acme/hybrid:candle", None).unwrap(),+ "candle",+ "profile variant routes through its own adapter without X-SIE-Engine"+ );+ assert_eq!(+ registry+ .resolve_bundle_with_engine("acme/hybrid:candle", None, Some("candle"))+ .unwrap(),+ "candle"+ );+ }+#[test]fn test_reload_rejects_model_with_missing_profile_parent() {let (_dir, bundles_dir, models_dir) = create_test_dirs();@@ -3285,6 +3603,62 @@ profiles:);}+ #[test]+ fn test_compute_bundle_config_hash_includes_candle_profile_variant() {+ 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(+ bundles_dir.join("candle.yaml"),+ r#"+name: candle+priority: 30+engine: candle+adapters:+ - sie_server_rust.adapters.candle+"#,+ )+ .unwrap();++ fs::write(+ models_dir.join("bge-m3.yaml"),+ r#"+name: BAAI/bge-m3+profiles:+ default:+ adapter_path: "sie_server.adapters.bert_flash:BertFlashAdapter"+ max_batch_tokens: 4096+ candle:+ adapter_path: "sie_server_rust.adapters.candle:CandleEmbeddingAdapter"+ max_batch_tokens: 2048+ adapter_options:+ runtime:+ pooling: cls+ normalize: true+"#,+ )+ .unwrap();++ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);+ let candle_hash = registry.compute_bundle_config_hash("candle");+ let candle_pool_hash = registry.compute_bundle_config_hash_for_pool("candle", "default");++ assert!(registry.model_exists("BAAI/bge-m3:candle"));+ assert!(!candle_hash.is_empty());+ assert_eq!(candle_hash.len(), 64);+ assert_eq!(candle_pool_hash, candle_hash);+ assert_ne!(candle_hash, registry.compute_bundle_config_hash("default"));+ }+#[test]fn test_install_bundle_config_hashes_overrides_local_hash() {let (_dir, bundles_dir, models_dir) = create_test_dirs();@@ -3441,7 +3815,6 @@ profiles:// ---------------------------------------------------------------// 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]@@ -3487,13 +3860,7 @@ profiles:}#[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.+ fn test_resolve_bundle_with_engine_filter_selects_matching_engine() {let (_dir, bundles_dir, models_dir) = create_test_dirs();fs::write(bundles_dir.join("default.yaml"),@@ -3502,6 +3869,17 @@ name: defaultpriority: 10adapters:- sie_server.adapters.bert_flash+"#,+ )+ .unwrap();+ fs::write(+ bundles_dir.join("candle.yaml"),+ r#"+name: candle+priority: 30+engine: candle+adapters:+ - sie_server_rust.adapters.candle"#,).unwrap();@@ -3512,6 +3890,8 @@ name: example/bertprofiles:default:adapter_path: "sie_server.adapters.bert_flash:Adapter"+ candle:+ adapter_path: "sie_server_rust.adapters.candle:CandleEmbeddingAdapter""#,).unwrap();@@ -3525,6 +3905,23 @@ profiles:.resolve_bundle_with_engine("example/bert", None, Some("pytorch")).unwrap();assert_eq!(filtered, "default");++ assert!(+ registry+ .resolve_bundle_with_engine("example/bert", None, Some("candle"))+ .is_err(),+ "base model routing should follow the default profile, not the engine override"+ );++ let candle = registry+ .resolve_bundle("example/bert:candle", None)+ .unwrap();+ assert_eq!(candle, "candle");++ let candle_with_engine = registry+ .resolve_bundle_with_engine("example/bert:candle", None, Some("candle"))+ .unwrap();+ assert_eq!(candle_with_engine, "candle");}#[test]diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rsindex 8f27233c8..9c0f27a65 100644--- a/packages/sie_gateway/src/state/worker_registry.rs+++ b/packages/sie_gateway/src/state/worker_registry.rs@@ -374,7 +374,17 @@ impl WorkerRegistry {admitted_worker_names: Option<&HashSet<String>>,) -> Vec<WorkerState> {let snap = self.snapshot.load();- snap.all_healthy+ // Narrow to the lane's bundle via the `by_bundle` index (O(N_bundle))+ // instead of scanning the whole-cluster `all_healthy` list+ // (O(N_cluster)) — mirroring `lazy_lane_workers_for_matching`, which+ // already does this on the same request. Every worker in the bucket+ // already has this bundle, so the `w.bundle` predicate is dropped.+ // See #1607.+ let bundle_lower = bundle.to_lowercase();+ let Some(candidates) = snap.by_bundle.get(&bundle_lower) else {+ return Vec::new();+ };+ candidates.iter().filter(|w| {!w.saturated@@ -382,7 +392,6 @@ impl WorkerRegistry {&& !w.machine_profile.is_empty()&& w.pool_name.eq_ignore_ascii_case(pool)&& w.machine_profile.eq_ignore_ascii_case(machine_profile)- && w.bundle.eq_ignore_ascii_case(bundle)&& bundle_config_hash_matches(&w.bundle_config_hash, bundle_config_hash)&& w.models.iter().any(|m| m.eq_ignore_ascii_case(model))})@@ -1304,6 +1313,40 @@ mod tests {.is_empty());}+ #[tokio::test]+ async fn test_dispatch_workers_for_scopes_by_bundle() {+ // Two workers, same model/pool/profile but DIFFERENT bundles. The+ // by_bundle-indexed lookup (#1607) must stay equivalent to the old+ // `w.bundle` predicate: dispatch for one bundle returns only that+ // bundle's worker, and an empty bundle bucket returns nothing.+ let reg = registry();++ let mut a = make_msg(true);+ a.name = "wa".into();+ a.pool_name = "default".into();+ a.bundle = "bundle-a".into();+ reg.update_worker("http://wa:8080", a).await;++ let mut b = make_msg(true);+ b.name = "wb".into();+ b.pool_name = "default".into();+ b.bundle = "bundle-b".into();+ reg.update_worker("http://wb:8080", b).await;++ let a_only = reg.dispatch_workers_for("BAAI/bge-m3", "default", "l4-spot", "bundle-a", "");+ assert_eq!(a_only.len(), 1);+ assert_eq!(a_only[0].name, "wa");++ let b_only = reg.dispatch_workers_for("BAAI/bge-m3", "default", "l4-spot", "bundle-b", "");+ assert_eq!(b_only.len(), 1);+ assert_eq!(b_only[0].name, "wb");++ // A bundle with no workers hits the by_bundle miss path → empty.+ assert!(reg+ .dispatch_workers_for("BAAI/bge-m3", "default", "l4-spot", "bundle-c", "")+ .is_empty());+ }+// ── ring_snapshot_for dedup ────────────────────────────────────#[tokio::test]diff --git a/packages/sie_gateway/src/types/bundle.rs b/packages/sie_gateway/src/types/bundle.rsindex 94ece1699..73fc35b8b 100644--- a/packages/sie_gateway/src/types/bundle.rs+++ b/packages/sie_gateway/src/types/bundle.rs@@ -2,21 +2,19 @@ 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.+/// `pytorch` is the Python ``sie_server`` adapter image. `candle` is+/// the Rust ``sie-server-rust`` worker process backed by native Candle+/// execution.////// 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"];+pub const KNOWN_ENGINES: &[&str] = &["pytorch", "candle"];/// 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.+/// Python worker path. Kept as a separate constant so the asymmetric+/// "default vs known" contract reads cleanly as more native engines+/// land.pub const DEFAULT_ENGINE: &str = "pytorch";#[allow(dead_code)]@@ -30,7 +28,7 @@ pub struct BundleConfig {#[serde(default)]pub default: bool,/// Execution engine the bundle's worker image speaks. Today- /// only ``"pytorch"`` (the Python adapter image) is recognised;+ /// ``"pytorch"`` and ``"candle"`` are recognised;/// see ``KNOWN_ENGINES`` for the load-time check. Defaults to/// ``"pytorch"`` for back-compat with pre-engine bundle YAMLs.#[serde(default = "default_engine")]@@ -74,8 +72,7 @@ pub struct BundleInfo {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``).+ /// can verify they speak the right engine.#[allow(dead_code)]pub engine: String,}@@ -95,6 +92,7 @@ pub struct BundleInfo {pub fn engine_adapter_prefixes(engine: &str) -> &'static [&'static str] {match engine {"pytorch" => &["sie_server.adapters."],+ "candle" => &["sie_server_rust.adapters.candle"],_ => &[],}}@@ -137,18 +135,20 @@ default: trueengine_adapter_prefixes("pytorch"),&["sie_server.adapters."]);+ assert_eq!(+ engine_adapter_prefixes("candle"),+ &["sie_server_rust.adapters.candle"]+ );// 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("future-engine").is_empty());assert!(engine_adapter_prefixes("unknown").is_empty());}#[test]- fn test_known_engines_only_pytorch() {+ fn test_known_engines_include_candle() {// 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"]);+ assert_eq!(KNOWN_ENGINES, &["pytorch", "candle"]);}#[test]diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex 0fd8471aa..b6e9201ec 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -453,8 +453,14 @@ impl CanonicalProfile {/// (null, `false`, `0`, `0.0`, `""`, empty array, empty object). Otherwise/// returns `Some(opts)` unchanged.fn canonicalize_adapter_options(opts: serde_json::Value) -> Option<serde_json::Value> {- if let serde_json::Value::Object(ref map) = opts {- let all_falsy = map.values().all(|v| match v {+ if let serde_json::Value::Object(map) = opts {+ let compact: serde_json::Map<String, serde_json::Value> = map+ .into_iter()+ .filter(+ |(_, value)| !matches!(value, serde_json::Value::Object(inner) if inner.is_empty()),+ )+ .collect();+ let all_falsy = compact.values().all(|v| match v {serde_json::Value::Null => true,serde_json::Value::Bool(b) => !*b,serde_json::Value::Number(n) => {@@ -469,6 +475,7 @@ fn canonicalize_adapter_options(opts: serde_json::Value) -> Option<serde_json::Vif all_falsy {return None;}+ return Some(serde_json::Value::Object(compact));}Some(opts)}@@ -534,35 +541,96 @@ mod tests {}#[test]- fn test_canonical_profile_python_falsy_parity() {- // Config service uses Python `not any(values)` which treats 0,- // 0.0, "", [], {}, None, False as empty. Gateway must match or- // `compute_bundle_config_hash` diverges and every worker in the- // affected bundle sits in `pending_workers` forever. Regression- // for the bug where gateway-side canonicalization only stripped- // null/false.- let cases = vec![- serde_json::json!({"x": 0}),- serde_json::json!({"x": 0.0}),- serde_json::json!({"x": ""}),- serde_json::json!({"x": []}),- serde_json::json!({"x": {}}),- serde_json::json!({"x": null, "y": false, "z": 0}),- ];- for opts in cases {- let profile = ProfileConfig {+ fn test_canonical_profile_drops_empty_nested_option_maps() {+ let profile = ProfileConfig {+ adapter_path: Some("mod:A".into()),+ max_batch_tokens: None,+ compute_precision: None,+ adapter_options: Some(serde_json::json!({+ "loadtime": {},+ "runtime": {"pooling": "cls"}+ })),+ extends: None,+ };+ let canonical = CanonicalProfile::from_profile(&profile);+ assert_eq!(+ canonical.adapter_options,+ Some(serde_json::json!({"runtime": {"pooling": "cls"}}))+ );+ }++ #[test]+ fn test_canonical_profile_conformance_vectors() {+ // Generic flat canonicalizer: strip an options map to None when every+ // value is falsy (0, 0.0, "", [], {}, None, False) and drop empty nested+ // maps. The config service must match or `compute_bundle_config_hash`+ // diverges and every worker in the affected bundle sits in+ // `pending_workers` forever. These vectors are shared with the sie_config+ // and sie_server Python suites — see+ // `conformance/bundle_config_hash/canonical_profile_falsy_vectors.json`+ // — so all three implementations stay in lockstep (#1542). The+ // `transform` cases pin the loadtime/runtime compaction that real+ // profiles use, which the worker's structured canonicalizer also honors.+ let raw = include_str!(+ "../../../../conformance/bundle_config_hash/canonical_profile_falsy_vectors.json"+ );+ let vectors: serde_json::Value = serde_json::from_str(raw).expect("valid conformance JSON");++ let canonicalize = |opts: &serde_json::Value| {+ CanonicalProfile::from_profile(&ProfileConfig {adapter_path: Some("mod:A".into()),max_batch_tokens: None,compute_precision: None,adapter_options: Some(opts.clone()),extends: None,- };- let canonical = CanonicalProfile::from_profile(&profile);+ })+ .adapter_options+ };++ for case in vectors["strip_to_none"]+ .as_array()+ .expect("strip_to_none array")+ {+ let opts = &case["adapter_options"];+ let name = case["name"].as_str().unwrap_or("?");assert!(- canonical.adapter_options.is_none(),- "Expected falsy-only options {opts:?} to be stripped to None for Python parity"+ canonicalize(opts).is_none(),+ "case {name}: expected falsy-only options {opts:?} to strip to None");}++ for case in vectors["keep_unchanged"]+ .as_array()+ .expect("keep_unchanged array")+ {+ let opts = &case["adapter_options"];+ let name = case["name"].as_str().unwrap_or("?");+ let got = canonicalize(opts);+ assert_eq!(+ got.as_ref(),+ Some(opts),+ "case {name}: expected meaningful options to be kept unchanged"+ );+ }++ for case in vectors["transform"].as_array().expect("transform array") {+ let opts = &case["adapter_options"];+ let name = case["name"].as_str().unwrap_or("?");+ let expected = &case["expected"];+ let got = canonicalize(opts);+ if expected.is_null() {+ assert!(+ got.is_none(),+ "case {name}: expected {opts:?} to canonicalize to None"+ );+ } else {+ assert_eq!(+ got.as_ref(),+ Some(expected),+ "case {name}: unexpected canonicalization of {opts:?}"+ );+ }+ }}#[test]diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex 97c088ec8..c5a5ab9c8 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.6.14"+version = "0.6.15"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_sdk/src/sie_sdk/bundle_utils.py b/packages/sie_sdk/src/sie_sdk/bundle_utils.pyindex 1cf67dff3..8c9915929 100644--- a/packages/sie_sdk/src/sie_sdk/bundle_utils.py+++ b/packages/sie_sdk/src/sie_sdk/bundle_utils.py@@ -8,15 +8,51 @@ import yamllogger = logging.getLogger(__name__)+def _adapter_module_from_path(adapter_path: object) -> str | None:+ if not isinstance(adapter_path, str) or not adapter_path:+ return None+ module_path = adapter_path.split(":", maxsplit=1)[0]+ return module_path or None+++def _effective_adapter_path(profiles: dict, profile_name: str) -> str | None:+ current: str | None = profile_name+ seen: set[str] = set()+ while current:+ if current in seen:+ return None+ seen.add(current)+ profile = profiles.get(current)+ if not isinstance(profile, dict):+ return None+ adapter_path = profile.get("adapter_path")+ if isinstance(adapter_path, str) and adapter_path:+ return adapter_path+ parent = profile.get("extends")+ current = parent if isinstance(parent, str) and parent else None+ return None+++def _profile_adapter_modules(profiles: dict, profile_name: str) -> set[str]:+ module_path = _adapter_module_from_path(_effective_adapter_path(profiles, profile_name))+ return {module_path} if module_path else set()+++def _base_route_adapter_modules(profiles: dict) -> set[str]:+ if "default" not in profiles:+ return set()+ return _profile_adapter_modules(profiles, "default")++def _scan_model_adapters(models_dir: Path) -> dict[str, tuple[set[str], str | None]]:- """Scan model config YAMLs and return adapter modules per model.+ """Scan model config YAMLs and return adapter modules per route identity.Args:models_dir: Path to the models directory containing *.yaml configs.Returns:- Dict mapping model name to ``(modules, pool)`` where ``modules`` is- the set of adapter module paths declared by the model profiles and+ Dict mapping model/profile route name to ``(modules, pool)`` where+ ``modules`` is the set of effective adapter module paths for that route and``pool`` is the optional configured pool name."""result: dict[str, tuple[set[str], str | None]] = {}@@ -30,16 +66,24 @@ def _scan_model_adapters(models_dir: Path) -> dict[str, tuple[set[str], str | Nologger.exception("Failed to parse model config %s", model_path.name)continuemodel_name = model_data.get("sie_id", model_path.stem.replace("__", "/"))- modules: set[str] = set()- for profile in model_data.get("profiles", {}).values():- adapter_path = profile.get("adapter_path", "")- module_path = adapter_path.split(":", maxsplit=1)[0]- if module_path:- modules.add(module_path)- if modules:- raw_pool = model_data.get("pool")- pool = raw_pool.strip().lower() if isinstance(raw_pool, str) else None- result[model_name] = (modules, pool or None)+ profiles = model_data.get("profiles", {})+ if not isinstance(profiles, dict):+ continue++ raw_pool = model_data.get("pool")+ pool = raw_pool.strip().lower() if isinstance(raw_pool, str) else None+ route_pool = pool or None++ base_modules = _base_route_adapter_modules(profiles)+ if base_modules:+ result[model_name] = (base_modules, route_pool)++ for profile_name in sorted(profiles):+ if profile_name == "default":+ continue+ modules = _profile_adapter_modules(profiles, str(profile_name))+ if modules:+ result[f"{model_name}:{profile_name}"] = (modules, route_pool)return resultdiff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.pyindex 72e7f1a93..9973c96d5 100644--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py@@ -872,6 +872,43 @@ def parse_encode_results(items: list[dict[str, Any]]) -> list[EncodeResult]:return results+def validate_encode_result_count(results: list[EncodeResult], expected: int, model: str) -> None:+ """Guard the encode contract: exactly one result per input item.++ Encode is positional — callers rely on a 1:1 input↔output correspondence:+ ``encode()`` returns ``results[0]`` for a single-item request, and batch+ callers (e.g. the eval harness ``SIEEncoderWrapper``) reassemble embeddings+ by index. The contract can break with an HTTP 200 whose ``items`` list is+ *shorter* than the request: the gateway returns mixed-success batches as+ ``200`` carrying only the successful items (a per-item server-side failure —+ e.g. an input exceeding the model's ``max_sequence_length`` — is dropped from+ the body, not surfaced as an error envelope). Without this check, that short+ list flows into a positional access and raises a context-free+ ``IndexError: list index out of range`` deep in a caller (issue #1526).++ Raising a typed, actionable :class:`ServerError` here keeps the failure+ legible — it names the model and the expected vs. returned counts instead of+ a bare ``IndexError``. A common trigger is an input that exceeds the model's+ ``max_sequence_length``.++ Args:+ results: Parsed encode results from the server response.+ expected: Number of input items in the request.+ model: Model name, for the error message.++ Raises:+ ServerError: If ``len(results) != expected``.+ """+ if len(results) != expected:+ msg = (+ f"Encode response desync for model {model!r}: server returned "+ f"{len(results)} embedding(s) for {expected} input item(s); expected "+ f"exactly one per input. An input may have failed server-side "+ f"(e.g. exceeding the model's max_sequence_length) and been dropped from the batch."+ )+ raise ServerError(msg, code="ENCODE_RESULT_COUNT_MISMATCH")++def parse_score_result(data: dict[str, Any]) -> ScoreResult:"""Parse score response into ScoreResult TypedDict."""result: ScoreResult = {diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.pyindex dab03c047..a7787e83d 100644--- a/packages/sie_sdk/src/sie_sdk/client/async_.py+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py@@ -101,6 +101,7 @@ from ._shared import (retry_after_or_default,sse_chunk_error,sse_headers,+ validate_encode_result_count,)from ._sse import aiter_sse_payloadsfrom .errors import (@@ -1285,13 +1286,10 @@ class SIEAsyncClient:)continue- # Handle 504 (gateway timeout) — defense-in-depth for older- # gateways that don't yet map an upstream timeout to- # 503 + MODEL_LOADING. A cold-start request that triggers a- # worker-side on-demand model load will typically exceed the- # gateway's per-request timeout on the first call; treat that- # the same as MODEL_LOADING and retry under the existing- # provision_timeout_s budget.+ # Handle 504 (gateway timeout): queued work was published, but the+ # gateway did not receive a worker result before its deadline.+ # Encode/score/extract are idempotent, so callers that opted into+ # wait_for_capacity can retry within provision_timeout_s.if response.status_code == HTTP_GATEWAY_TIMEOUT and wait_for_capacity:elapsed = time.monotonic() - start_timeif elapsed < timeout:@@ -1325,6 +1323,10 @@ class SIEAsyncClient:# Parse results and inject timing into eachresults = parse_encode_results(response_data["items"])+ # Guard the 1:1 input↔output contract before any positional access+ # (``results[0]`` below, or batch reassembly in callers). A desynced+ # count otherwise surfaces as a context-free ``IndexError`` (#1526).+ validate_encode_result_count(results, len(items_list), model)if timing:for result in results:result["timing"] = timing@@ -1695,9 +1697,7 @@ class SIEAsyncClient:)continue- # Handle 504 (gateway timeout) — defense-in-depth for older- # gateways that don't yet map an upstream timeout to- # 503 + MODEL_LOADING. See encode() above for rationale.+ # Handle 504 (gateway timeout). See encode() above for rationale.if response.status_code == HTTP_GATEWAY_TIMEOUT and wait_for_capacity:elapsed = time.monotonic() - start_timeif elapsed < timeout:@@ -2455,9 +2455,7 @@ class SIEAsyncClient:)continue- # Handle 504 (gateway timeout) — defense-in-depth for older- # gateways that don't yet map an upstream timeout to- # 503 + MODEL_LOADING. See encode() above for rationale.+ # Handle 504 (gateway timeout). See encode() above for rationale.if response.status_code == HTTP_GATEWAY_TIMEOUT and wait_for_capacity:elapsed = time.monotonic() - start_timeif elapsed < timeout:diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.pyindex 402e85234..8e9bfb257 100644--- a/packages/sie_sdk/src/sie_sdk/client/sync.py+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py@@ -108,6 +108,7 @@ from ._shared import (retry_after_or_default,sse_chunk_error,sse_headers,+ validate_encode_result_count,)from ._sse import iter_sse_payloadsfrom .errors import (@@ -961,8 +962,7 @@ class SIEClient:wait_for_capacity: When True (default), auto-retry transient "notenough capacity yet" responses under ``provision_timeout_s`` —``503 PROVISIONING`` (scale-from-zero provisioning);- ``504`` (defense-in-depth for older gateways that haven't yet- mapped upstream timeouts to ``503 MODEL_LOADING``); local+ ``504`` gateway result timeouts for idempotent queue paths; local``httpx`` read/connect/pool timeouts; and transientmid-flight transport errors (``RemoteProtocolError``,``ReadError``, ``WriteError`` — peer severed the connection@@ -1237,13 +1237,10 @@ class SIEClient:)continue- # Handle 504 (gateway timeout) — defense-in-depth for older- # gateways that don't yet map an upstream timeout to- # 503 + MODEL_LOADING. A cold-start request that triggers a- # worker-side on-demand model load will typically exceed the- # gateway's per-request timeout on the first call; treat that- # the same as MODEL_LOADING and retry under the existing- # provision_timeout_s budget.+ # Handle 504 (gateway timeout): queued work was published, but the+ # gateway did not receive a worker result before its deadline.+ # Encode/score/extract are idempotent, so callers that opted into+ # wait_for_capacity can retry within provision_timeout_s.if response.status_code == HTTP_GATEWAY_TIMEOUT and wait_for_capacity:elapsed = time.monotonic() - start_timeif elapsed < timeout:@@ -1277,6 +1274,10 @@ class SIEClient:# Parse results and inject timing into eachresults = parse_encode_results(response_data["items"])+ # Guard the 1:1 input↔output contract before any positional access+ # (``results[0]`` below, or batch reassembly in callers). A desynced+ # count otherwise surfaces as a context-free ``IndexError`` (#1526).+ validate_encode_result_count(results, len(items_list), model)if timing:for result in results:result["timing"] = timing@@ -1630,8 +1631,7 @@ class SIEClient:wait_for_capacity: When True (default), auto-retry transient "notenough capacity yet" responses under ``provision_timeout_s`` —``503 PROVISIONING`` (scale-from-zero provisioning);- ``504`` (defense-in-depth for older gateways that haven't yet- mapped upstream timeouts to ``503 MODEL_LOADING``); local+ ``504`` gateway result timeouts for idempotent queue paths; local``httpx`` read/connect/pool timeouts; and transientmid-flight transport errors (``RemoteProtocolError``,``ReadError``, ``WriteError`` — peer severed the connection@@ -1822,13 +1822,10 @@ class SIEClient:)continue- # Handle 504 (gateway timeout) — defense-in-depth for older- # gateways that don't yet map an upstream timeout to- # 503 + MODEL_LOADING. A cold-start request that triggers a- # worker-side on-demand model load will typically exceed the- # gateway's per-request timeout on the first call; treat that- # the same as MODEL_LOADING and retry under the existing- # provision_timeout_s budget.+ # Handle 504 (gateway timeout): queued work was published, but the+ # gateway did not receive a worker result before its deadline.+ # Encode/score/extract are idempotent, so callers that opted into+ # wait_for_capacity can retry within provision_timeout_s.if response.status_code == HTTP_GATEWAY_TIMEOUT and wait_for_capacity:elapsed = time.monotonic() - start_timeif elapsed < timeout:@@ -2461,8 +2458,7 @@ class SIEClient:wait_for_capacity: When True (default), auto-retry transient "notenough capacity yet" responses under ``provision_timeout_s`` —``503 PROVISIONING`` (scale-from-zero provisioning);- ``504`` (defense-in-depth for older gateways that haven't yet- mapped upstream timeouts to ``503 MODEL_LOADING``); local+ ``504`` gateway result timeouts for idempotent queue paths; local``httpx`` read/connect/pool timeouts; and transientmid-flight transport errors (``RemoteProtocolError``,``ReadError``, ``WriteError`` — peer severed the connection@@ -2687,13 +2683,10 @@ class SIEClient:)continue- # Handle 504 (gateway timeout) — defense-in-depth for older- # gateways that don't yet map an upstream timeout to- # 503 + MODEL_LOADING. A cold-start request that triggers a- # worker-side on-demand model load will typically exceed the- # gateway's per-request timeout on the first call; treat that- # the same as MODEL_LOADING and retry under the existing- # provision_timeout_s budget.+ # Handle 504 (gateway timeout): queued work was published, but the+ # gateway did not receive a worker result before its deadline.+ # Encode/score/extract are idempotent, so callers that opted into+ # wait_for_capacity can retry within provision_timeout_s.if response.status_code == HTTP_GATEWAY_TIMEOUT and wait_for_capacity:elapsed = time.monotonic() - start_timeif elapsed < timeout:diff --git a/packages/sie_sdk/src/sie_sdk/queue_types.py b/packages/sie_sdk/src/sie_sdk/queue_types.pyindex 17061bc7f..51214b927 100644--- a/packages/sie_sdk/src/sie_sdk/queue_types.py+++ b/packages/sie_sdk/src/sie_sdk/queue_types.py@@ -354,8 +354,7 @@ def work_worker_subject(machine_profile: Hardware lane (e.g., ``"rtx6000"``).bundle_id: Runtime/image bundle identifier (e.g., ``"sglang"``).model_id: Model identifier (e.g., ``"BAAI/bge-m3"``).- worker_id: Stable worker identity (matches- :attr:`sie_server.nats_pull_loop.NatsPullLoop.worker_id`).+ worker_id: Stable worker identity advertised by the worker-sidecar.Returns:NATS subject likediff --git a/packages/sie_sdk/tests/client/test_async.py b/packages/sie_sdk/tests/client/test_async.pyindex 2d81da313..39ea69467 100644--- a/packages/sie_sdk/tests/client/test_async.py+++ b/packages/sie_sdk/tests/client/test_async.py@@ -259,6 +259,37 @@ class TestAsyncEncode:assert len(results) == 2await client.close()+ @pytest.mark.asyncio+ async def test_encode_single_item_empty_items_raises_server_error(self) -> None:+ """Empty ``items`` for a single input raises ``ServerError`` not ``IndexError`` (#1526)."""+ resp = _make_msgpack_response({"model": "e5-mistral", "items": []})++ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(return_value=resp) # type: ignore+ with pytest.raises(ServerError) as excinfo:+ await client.encode("e5-mistral", {"text": "a very long document"})+ assert "e5-mistral" in str(excinfo.value)+ assert "0 embedding(s) for 1 input item(s)" in str(excinfo.value)+ assert excinfo.value.code == "ENCODE_RESULT_COUNT_MISMATCH"+ await client.close()++ @pytest.mark.asyncio+ async def test_encode_batch_short_items_raises_server_error(self) -> None:+ """A batch response that drops an item raises ``ServerError`` with counts (#1526)."""+ resp = _make_msgpack_response(+ {+ "model": "e5-mistral",+ "items": [{"dense": {"dims": 4, "dtype": "float32", "values": np.array([1.0, 2.0, 3.0, 4.0])}}],+ }+ )++ client = SIEAsyncClient("http://localhost:8080")+ client._post = AsyncMock(return_value=resp) # type: ignore+ with pytest.raises(ServerError) as excinfo:+ await client.encode("e5-mistral", [{"text": "short"}, {"text": "over-length doc"}])+ assert "1 embedding(s) for 2 input item(s)" in str(excinfo.value)+ await client.close()+class TestAsyncListModels:"""Tests for async list_models() method."""diff --git a/packages/sie_sdk/tests/client/test_gateway_timeout_retry.py b/packages/sie_sdk/tests/client/test_gateway_timeout_retry.pyindex 6d8fada9a..e9eac590e 100644--- a/packages/sie_sdk/tests/client/test_gateway_timeout_retry.py+++ b/packages/sie_sdk/tests/client/test_gateway_timeout_retry.py@@ -1,11 +1,9 @@# Tests for the 504 Gateway Timeout retry branch.#-# The SDK already retries on 503 + X-SIE-Error-Code: MODEL_LOADING. The-# gateway also maps upstream timeouts (e.g. a worker cold-loading a-# model on demand) to that contract in the current release, but the-# SDK adds a defense-in-depth 504 retry so older gateways (or any path-# that still returns plain 504) don't surface as a hard failure to a-# caller who opted into wait_for_capacity=True.+# The SDK already retries on 503 + X-SIE-Error-Code: MODEL_LOADING when a+# worker explicitly reports an in-progress model load. Gateway-owned queue+# result timeouts are distinct 504 GATEWAY_TIMEOUT responses; idempotent encode+# retries them when the caller opted into wait_for_capacity=True.## Covers: sync + async clients, encode (representative path; the score# and extract paths share the same retry block by construction).@@ -25,7 +23,7 @@ def _mock_response_504() -> MagicMock:resp = MagicMock()resp.status_code = 504resp.headers = {"Retry-After": "0.01", "content-type": "application/json"}- resp.json.return_value = {"error": {"code": "MODEL_LOADING", "message": "Timeout waiting for queue result"}}+ resp.json.return_value = {"detail": {"code": "GATEWAY_TIMEOUT", "message": "Timeout waiting for queue result"}}return resp@@ -42,7 +40,7 @@ def _async_response_504() -> object:return _AioResponse(504,- json.dumps({"error": {"code": "MODEL_LOADING", "message": "Timeout waiting for queue result"}}).encode(),+ json.dumps({"detail": {"code": "GATEWAY_TIMEOUT", "message": "Timeout waiting for queue result"}}).encode(),{"Retry-After": "0.01", "content-type": "application/json"},)diff --git a/packages/sie_sdk/tests/client/test_generate.py b/packages/sie_sdk/tests/client/test_generate.pyindex 70eb01537..a7096165c 100644--- a/packages/sie_sdk/tests/client/test_generate.py+++ b/packages/sie_sdk/tests/client/test_generate.py@@ -29,12 +29,12 @@ def _ok_response(payload: dict) -> MagicMock:def _resp_504() -> MagicMock:- # A 504 carrying MODEL_LOADING is what the idempotent paths retry on;- # generate() must NOT retry it (post-publish, non-idempotent).+ # A gateway-owned queue result timeout is retryable for idempotent encode+ # paths; generate() must NOT retry it (post-publish, non-idempotent).response = MagicMock()response.status_code = 504response.headers = {"Retry-After": "0.01", "content-type": "application/json"}- response.json.return_value = {"error": {"code": "MODEL_LOADING", "message": "Timeout waiting for queue result"}}+ response.json.return_value = {"detail": {"code": "GATEWAY_TIMEOUT", "message": "Timeout waiting for queue result"}}response.content = json.dumps(response.json.return_value).encode("utf-8")return responsediff --git a/packages/sie_sdk/tests/client/test_no_engine_surface.py b/packages/sie_sdk/tests/client/test_no_engine_surface.pynew file mode 100644index 000000000..c896bb85b--- /dev/null+++ b/packages/sie_sdk/tests/client/test_no_engine_surface.py@@ -0,0 +1,23 @@+from __future__ import annotations++import inspect++from sie_sdk import SIEAsyncClient, SIEClient++PUBLIC_INFERENCE_METHODS = (+ "encode",+ "score",+ "extract",+ "generate",+ "chat_completions",+)+++def test_public_inference_methods_do_not_expose_engine_parameter() -> None:+ for client_cls in (SIEClient, SIEAsyncClient):+ for method_name in PUBLIC_INFERENCE_METHODS:+ signature = inspect.signature(getattr(client_cls, method_name))+ assert "engine" not in signature.parameters, (+ f"{client_cls.__name__}.{method_name} must route alternate runtimes "+ "through model profile variants, not a public engine parameter"+ )diff --git a/packages/sie_sdk/tests/client/test_sync.py b/packages/sie_sdk/tests/client/test_sync.pyindex 617a3145e..6afe766bb 100644--- a/packages/sie_sdk/tests/client/test_sync.py+++ b/packages/sie_sdk/tests/client/test_sync.py@@ -288,6 +288,48 @@ class TestEncode:assert result["multivector"].shape == (3, 128)client.close()+ def test_encode_single_item_empty_items_raises_server_error(self) -> None:+ """An empty ``items`` list for a single input must raise an actionable+ ``ServerError`` rather than a bare ``IndexError`` from ``results[0]`` (#1526).+ """+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.content = msgpack.packb({"model": "e5-mistral", "items": []}, use_bin_type=True)++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = mock_response+ client = SIEClient("http://localhost:8080")+ with pytest.raises(ServerError) as excinfo:+ client.encode("e5-mistral", {"text": "a very long document"})+ # Actionable: names the model and the expected vs. returned counts.+ assert "e5-mistral" in str(excinfo.value)+ assert "0 embedding(s) for 1 input item(s)" in str(excinfo.value)+ assert excinfo.value.code == "ENCODE_RESULT_COUNT_MISMATCH"+ client.close()++ def test_encode_batch_short_items_raises_server_error(self) -> None:+ """A batch whose response drops an item (desync) raises ``ServerError`` with+ counts instead of silently returning fewer embeddings than inputs (#1526).+ """+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.content = msgpack.packb(+ {+ "model": "e5-mistral",+ # Two inputs sent, one embedding returned.+ "items": [{"dense": {"dims": 4, "dtype": "float32", "values": np.array([1.0, 2.0, 3.0, 4.0])}}],+ },+ use_bin_type=True,+ )++ with patch("sie_sdk.client.sync.httpx.Client") as mock_client:+ mock_client.return_value.post.return_value = mock_response+ client = SIEClient("http://localhost:8080")+ with pytest.raises(ServerError) as excinfo:+ client.encode("e5-mistral", [{"text": "short"}, {"text": "over-length doc"}])+ assert "1 embedding(s) for 2 input item(s)" in str(excinfo.value)+ client.close()+class TestErrorHandling:"""Tests for error handling."""diff --git a/packages/sie_sdk/tests/test_bundle_utils.py b/packages/sie_sdk/tests/test_bundle_utils.pyindex bb3b1659a..d212ffd9d 100644--- a/packages/sie_sdk/tests/test_bundle_utils.py+++ b/packages/sie_sdk/tests/test_bundle_utils.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom pathlib import Path-from sie_sdk.bundle_utils import match_bundle_models+from sie_sdk.bundle_utils import find_bundle_for_models, match_bundle_modelsdef _write_model(models_dir: Path, name: str, *, pool: str | None = None) -> None:@@ -30,3 +30,53 @@ def test_match_bundle_models_filters_by_pool(tmp_path: Path) -> None:assert match_bundle_models(bundle_path, models_dir, pool_name="default") == ["org/generation"]assert match_bundle_models(bundle_path, models_dir, pool_name="sglang-embedding") == ["org/embedding"]assert match_bundle_models(bundle_path, models_dir, pool_name="SGLANG-EMBEDDING") == ["org/embedding"]+++def test_match_bundle_models_routes_profile_variants_by_effective_adapter(tmp_path: Path) -> None:+ bundles_dir = tmp_path / "bundles"+ bundles_dir.mkdir()+ default_bundle = bundles_dir / "default.yaml"+ default_bundle.write_text("adapters:\n - pkg.adapters.pytorch\n")+ candle_bundle = bundles_dir / "candle.yaml"+ candle_bundle.write_text("adapters:\n - pkg.adapters.candle\n")++ models_dir = tmp_path / "models"+ models_dir.mkdir()+ (models_dir / "org__embedding.yaml").write_text(+ """+sie_id: org/embedding+profiles:+ default:+ adapter_path: pkg.adapters.pytorch:Adapter+ candle:+ extends: default+ adapter_path: pkg.adapters.candle:Adapter+""".lstrip()+ )++ assert match_bundle_models(default_bundle, models_dir) == ["org/embedding"]+ assert match_bundle_models(candle_bundle, models_dir) == ["org/embedding:candle"]+ assert find_bundle_for_models(["org/embedding"], bundles_dir, models_dir) == "default"+ assert find_bundle_for_models(["org/embedding:candle"], bundles_dir, models_dir) == "candle"+++def test_match_bundle_models_omits_bare_model_without_default_profile(tmp_path: Path) -> None:+ bundles_dir = tmp_path / "bundles"+ bundles_dir.mkdir()+ candle_bundle = bundles_dir / "candle.yaml"+ candle_bundle.write_text("adapters:\n - pkg.adapters.candle\n")++ models_dir = tmp_path / "models"+ models_dir.mkdir()+ (models_dir / "org__candle-only.yaml").write_text(+ """+sie_id: org/candle-only+profiles:+ candle:+ adapter_path: pkg.adapters.candle:Adapter+""".lstrip()+ )++ assert match_bundle_models(candle_bundle, models_dir) == ["org/candle-only:candle"]+ assert find_bundle_for_models(["org/candle-only"], bundles_dir, models_dir) is None+ assert find_bundle_for_models(["org/candle-only:candle"], bundles_dir, models_dir) == "candle"diff --git a/packages/sie_sdk/tests/test_worker_id_normalization.py b/packages/sie_sdk/tests/test_worker_id_normalization.pyindex e782fe9dc..60b360f8c 100644--- a/packages/sie_sdk/tests/test_worker_id_normalization.py+++ b/packages/sie_sdk/tests/test_worker_id_normalization.py@@ -4,8 +4,8 @@ The gateway (Rust) publishes direct-dispatch work items to``sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`` andapplies its ``normalize_model_id`` to the worker_id before publishing. The Python SDKhelpers (``work_worker_subject``, ``work_worker_stream_subjects``,-``work_worker_stream_name``, ``work_worker_consumer_name``) and the worker-init (``NatsPullLoop.__init__``) now route worker IDs through+``work_worker_stream_name``, ``work_worker_consumer_name``) and the worker-sidecar+startup path now route worker IDs through:func:`sie_sdk.queue_types.normalize_worker_id`, which delegates to``normalize_model_id`` for byte-identical output.@@ -73,9 +73,8 @@ def test_normalize_worker_id_rejects_empty(raw: str) -> None:The previous helper silently substituted the literal string``"worker"`` for an empty input, which collided durable JetStreamconsumers across processes when env vars were missing. Empty input- is now a hard error — :class:`NatsPullLoop.__init__` falls back to- ``uuid4().hex`` and logs the failure explicitly rather than letting- a silent substitution propagate.+ is now a hard error; worker startup must choose an explicit fallback+ identity rather than letting a silent substitution propagate."""with pytest.raises(ValueError, match="empty"):normalize_worker_id(raw)diff --git a/packages/sie_server/bundles/candle.yaml b/packages/sie_server/bundles/candle.yamlnew file mode 100644index 000000000..77b210702--- /dev/null+++ b/packages/sie_server/bundles/candle.yaml@@ -0,0 +1,6 @@+name: candle+priority: 30+engine: candle+adapters:+- sie_server_rust.adapters.candle+deps: {}diff --git a/packages/sie_server/bundles/sglang.yaml b/packages/sie_server/bundles/sglang.yamlindex 8975d6cc6..3053ad603 100644--- a/packages/sie_server/bundles/sglang.yaml+++ b/packages/sie_server/bundles/sglang.yaml@@ -28,7 +28,9 @@ deps:# * grammar backends: ``xgrammar`` / ``outlines`` / ``llguidance`` / ``none``# * ``sgl_kernel`` covers SM_80 / SM_89 / SM_90 / SM_100 via gencode.# * torch==2.9.1 (CUDA 12.9 wheels); ``cuda-python==12.9``.- sglang: '==0.5.10.post1'+ sglang:+ version: '==0.5.10.post1'+ marker: sys_platform == 'linux'## Grammar backend deps — pinned to exactly what SGLang 0.5.10 imports# internally to prevent silent pip resolution drift.@@ -37,7 +39,9 @@ deps:# ``xgrammar==0.1.32`` exactly. That release also brought the# structured-output VRAM-leak fix (PR #20697) and grammar-error# propagation (PR #20467). Kept available as the fallback backend.- xgrammar: '==0.1.32'+ xgrammar:+ version: '==0.1.32'+ marker: sys_platform == 'linux'## ``outlines==0.1.11`` is a hard transitive dep of sglang==0.5.10.post1. We# declare it explicitly at bundle level so the surface is visible.@@ -58,9 +62,22 @@ deps:# ``OutlinesGrammarBackend`` does internally), so the mismatch is gone# for json_schema/regex; ebnf is forwarded straight to SGLang. See# ``processors/grammar_compile.py`` ("Tokenizer adapter").- outlines: '==0.1.11'+ outlines:+ version: '==0.1.11'+ marker: sys_platform == 'linux'## llguidance is the third grammar backend (regex / json_schema / ebnf).# Pinned to SGLang 0.5.10's compatible range. Kept available as the# fallback if a future model regresses on xgrammar.- llguidance: '>=0.7.11,<0.8.0'+ llguidance:+ version: '>=0.7.11,<0.8.0'+ marker: sys_platform == 'linux'+ # Apple Silicon (Metal) generation. SGLang is CUDA-only, so on macOS the+ # SGLangGenerationAdapter.create_for_device swap serves generation via Apple's+ # MLX (mlx_lm.server) instead — this makes the same bundle resolve correctly on+ # both platforms (CUDA -> SGLang, Darwin -> MLX). mlx-lm pulls transformers>=5,+ # which the MLX path needs and which is darwin-only here so it never perturbs+ # the Linux resolve.+ mlx-lm:+ version: '>=0.30.7'+ marker: sys_platform == 'darwin'diff --git a/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-1.5B-instruct.yaml b/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-1.5B-instruct.yamlindex 8e14c24f8..a09763498 100644--- a/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-1.5B-instruct.yaml+++ b/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-1.5B-instruct.yaml@@ -18,10 +18,22 @@ profiles:default:max_batch_tokens: 16384compute_precision: bfloat16- adapter_path: sie_server.adapters.qwen2_flash:Qwen2FlashAdapter+ # gte-Qwen2 is a decoder converted to BIDIRECTIONAL attention (config+ # is_causal=false) with last-token pooling, served via its custom+ # trust_remote_code modeling. The qwen2_flash adapter reimplements the+ # forward with flash attention and cannot reproduce that recipe, collapsing+ # retrieval to near-random (#1593). Use the sentence_transformer adapter,+ # which runs the model's own forward + pooling (the official recipe).+ adapter_path: sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapteradapter_options:loadtime:- uses_legacy_transformers_cache: true+ trust_remote_code: true+ # gte-Qwen2's custom modeling uses the legacy (<4.54) transformers cache+ # API (DynamicCache.get_usable_length), removed in the bundle's newer+ # transformers. Disabling the KV cache skips that path (embeddings need+ # no cache); mirrors the old uses_legacy_transformers_cache workaround.+ config_kwargs:+ use_cache: falseruntime:pooling: lastnormalize: truediff --git a/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-7B-instruct.yaml b/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-7B-instruct.yamlindex 8919a5e73..1d7219213 100644--- a/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-7B-instruct.yaml+++ b/packages/sie_server/models/Alibaba-NLP__gte-Qwen2-7B-instruct.yaml@@ -22,6 +22,13 @@ profiles:adapter_options:loadtime:mem_fraction_static: 0.85+ # The model's remote-code tokenizer only re-exports the stock Qwen2+ # tokenizer through a hardcoded transformers submodule import that is+ # fragile across transformers versions. sglang serves the weights with+ # its own native Qwen2 implementation (the config's remote auto_map is+ # only for HF AutoModel), so disable remote code and load the stock+ # tokenizer — functionally identical and version-robust.+ trust_remote_code: falseruntime:pooling: last_tokennormalize: truediff --git a/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yaml b/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yamlindex 6b5104c38..b938dd42e 100644--- a/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yaml+++ b/packages/sie_server/models/Alibaba-NLP__gte-modernbert-base.yaml@@ -24,3 +24,10 @@ profiles:runtime:pooling: clsnormalize: true+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: truediff --git a/packages/sie_server/models/BAAI__bge-base-en-v1.5.yaml b/packages/sie_server/models/BAAI__bge-base-en-v1.5.yamlnew file mode 100644index 000000000..1a3233357--- /dev/null+++ b/packages/sie_server/models/BAAI__bge-base-en-v1.5.yaml@@ -0,0 +1,27 @@+sie_id: BAAI/bge-base-en-v1.5+hf_id: BAAI/bge-base-en-v1.5+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 512+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: true+ query_template: 'Represent this sentence for searching relevant passages: {text}'+ doc_template: '{text}'diff --git a/packages/sie_server/models/BAAI__bge-large-en-v1.5.yaml b/packages/sie_server/models/BAAI__bge-large-en-v1.5.yamlnew file mode 100644index 000000000..cde71e1e3--- /dev/null+++ b/packages/sie_server/models/BAAI__bge-large-en-v1.5.yaml@@ -0,0 +1,27 @@+sie_id: BAAI/bge-large-en-v1.5+hf_id: BAAI/bge-large-en-v1.5+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 1024+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 512+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: true+ query_template: 'Represent this sentence for searching relevant passages: {text}'+ doc_template: '{text}'diff --git a/packages/sie_server/models/BAAI__bge-m3.yaml b/packages/sie_server/models/BAAI__bge-m3.yamlindex 8b33028ce..a176e4f26 100644--- a/packages/sie_server/models/BAAI__bge-m3.yaml+++ b/packages/sie_server/models/BAAI__bge-m3.yaml@@ -50,6 +50,13 @@ profiles:normalize: trueoutput_types:- multivector+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: truebanking:extends: defaultadapter_options:diff --git a/packages/sie_server/models/BAAI__bge-reranker-v2-m3.yaml b/packages/sie_server/models/BAAI__bge-reranker-v2-m3.yamlindex f34f63780..7dfd7e7f7 100644--- a/packages/sie_server/models/BAAI__bge-reranker-v2-m3.yaml+++ b/packages/sie_server/models/BAAI__bge-reranker-v2-m3.yaml@@ -13,7 +13,11 @@ max_sequence_length: 8192profiles:default:max_batch_tokens: 16384- compute_precision: null+ # fp16 is explicit (not null) so the Mac torch-MPS fallback runs fp16+ # (≈1.24 GB vs 3.21 GB fp32, Pearson 0.9997 vs CPU-fp32 — benchmarked). On+ # CUDA this is unchanged: the engine default is already fp16, so null+ # resolved to fp16 there anyway. On CPU the cross-encoder ignores it (fp32).+ compute_precision: float16adapter_path: sie_server.adapters.bert_flash_cross_encoder:BertFlashCrossEncoderAdapteradapter_options:loadtime: {}diff --git a/packages/sie_server/models/BAAI__bge-small-en-v1.5.yaml b/packages/sie_server/models/BAAI__bge-small-en-v1.5.yamlnew file mode 100644index 000000000..221b8ae10--- /dev/null+++ b/packages/sie_server/models/BAAI__bge-small-en-v1.5.yaml@@ -0,0 +1,27 @@+sie_id: BAAI/bge-small-en-v1.5+hf_id: BAAI/bge-small-en-v1.5+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 384+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 512+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: true+ query_template: 'Represent this sentence for searching relevant passages: {text}'+ doc_template: '{text}'diff --git a/packages/sie_server/models/BAAI__bge-small-zh-v1.5.yaml b/packages/sie_server/models/BAAI__bge-small-zh-v1.5.yamlnew file mode 100644index 000000000..ae811a06f--- /dev/null+++ b/packages/sie_server/models/BAAI__bge-small-zh-v1.5.yaml@@ -0,0 +1,27 @@+sie_id: BAAI/bge-small-zh-v1.5+hf_id: BAAI/bge-small-zh-v1.5+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 512+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 512+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: true+ query_template: '为这个句子生成表示以用于检索相关文章:{text}'+ doc_template: '{text}'diff --git a/packages/sie_server/models/Linq-AI-Research__Linq-Embed-Mistral.yaml b/packages/sie_server/models/Linq-AI-Research__Linq-Embed-Mistral.yamlindex 01585aa2b..8614d2e48 100644--- a/packages/sie_server/models/Linq-AI-Research__Linq-Embed-Mistral.yaml+++ b/packages/sie_server/models/Linq-AI-Research__Linq-Embed-Mistral.yaml@@ -22,6 +22,10 @@ profiles:adapter_options:loadtime:mem_fraction_static: 0.85+ # Mistral-family last-token embedder: SGLang does not auto-append EOS for+ # this architecture, so last-token pooling reads the wrong position and+ # retrieval collapses (#1489). Append the model's own EOS at encode time.+ append_eos: trueruntime:pooling: last_tokennormalize: truediff --git a/packages/sie_server/models/NovaSearch__stella_en_1.5B_v5.yaml b/packages/sie_server/models/NovaSearch__stella_en_1.5B_v5.yamlindex c981992f6..2479713c4 100644--- a/packages/sie_server/models/NovaSearch__stella_en_1.5B_v5.yaml+++ b/packages/sie_server/models/NovaSearch__stella_en_1.5B_v5.yaml@@ -32,5 +32,6 @@ profiles:pooling: meannormalize: truequery_template: |-- Instruct: Given a web search query, retrieve relevant passages that answer the query.+ Instruct: {instruction}Query: {text}+ default_instruction: Given a web search query, retrieve relevant passages that answer the query.diff --git a/packages/sie_server/models/NovaSearch__stella_en_400M_v5.yaml b/packages/sie_server/models/NovaSearch__stella_en_400M_v5.yamlindex 0f4c73e6a..9e05ca332 100644--- a/packages/sie_server/models/NovaSearch__stella_en_400M_v5.yaml+++ b/packages/sie_server/models/NovaSearch__stella_en_400M_v5.yaml@@ -29,5 +29,6 @@ profiles:pooling: meannormalize: truequery_template: |-- Instruct: Given a web search query, retrieve relevant passages that answer the query.+ Instruct: {instruction}Query: {text}+ default_instruction: Given a web search query, retrieve relevant passages that answer the query.diff --git a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml b/packages/sie_server/models/Qwen__Qwen3.5-4B.yamlindex 292cd439e..aeddd4d67 100644--- a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml@@ -123,6 +123,11 @@ profiles:kv_budget_tokens: 7168adapter_options:loadtime:+ # Apple-Silicon (MLX) repo served by the MLX subprocess backend. On+ # non-CUDA devices SGLangGenerationAdapter.create_for_device swaps to+ # MLXGenerationAdapter, which reads this. Ignored on CUDA (SGLang+ # swallows it via **kwargs). 4-bit MLX quant ≈ 120 tok/s on M-series.+ mlx_repo: mlx-community/Qwen3.5-4B-4bit# Empirical floor on L4 — anything lower OOMs at model load.mem_fraction_static: 0.90served_model_name: Qwen/Qwen3.5-4Bdiff --git a/packages/sie_server/models/Salesforce__SFR-Embedding-2_R.yaml b/packages/sie_server/models/Salesforce__SFR-Embedding-2_R.yamlindex 465675d83..379d57247 100644--- a/packages/sie_server/models/Salesforce__SFR-Embedding-2_R.yaml+++ b/packages/sie_server/models/Salesforce__SFR-Embedding-2_R.yaml@@ -22,6 +22,10 @@ profiles:adapter_options:loadtime:mem_fraction_static: 0.85+ # Mistral-family last-token embedder: SGLang does not auto-append EOS for+ # this architecture, so last-token pooling reads the wrong position and+ # retrieval collapses (#1489). Append the model's own EOS at encode time.+ append_eos: trueruntime:pooling: last_tokennormalize: truediff --git a/packages/sie_server/models/Salesforce__SFR-Embedding-Mistral.yaml b/packages/sie_server/models/Salesforce__SFR-Embedding-Mistral.yamlindex 3c57b72cd..8f9b74c4d 100644--- a/packages/sie_server/models/Salesforce__SFR-Embedding-Mistral.yaml+++ b/packages/sie_server/models/Salesforce__SFR-Embedding-Mistral.yaml@@ -22,6 +22,10 @@ profiles:adapter_options:loadtime:mem_fraction_static: 0.85+ # Mistral-family last-token embedder: SGLang does not auto-append EOS for+ # this architecture, so last-token pooling reads the wrong position and+ # retrieval collapses (#1489). Append the model's own EOS at encode time.+ append_eos: trueruntime:pooling: last_tokennormalize: truediff --git a/packages/sie_server/models/Snowflake__snowflake-arctic-embed-l-v2.0.yaml b/packages/sie_server/models/Snowflake__snowflake-arctic-embed-l-v2.0.yamlindex 23d998e2d..82cab4c0e 100644--- a/packages/sie_server/models/Snowflake__snowflake-arctic-embed-l-v2.0.yaml+++ b/packages/sie_server/models/Snowflake__snowflake-arctic-embed-l-v2.0.yaml@@ -26,3 +26,12 @@ profiles:normalize: truequery_template: 'query: {text}'doc_template: '{text}'+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: true+ query_template: 'query: {text}'+ doc_template: '{text}'diff --git a/packages/sie_server/models/WhereIsAI__UAE-Large-V1.yaml b/packages/sie_server/models/WhereIsAI__UAE-Large-V1.yamlnew file mode 100644index 000000000..8a7b844fb--- /dev/null+++ b/packages/sie_server/models/WhereIsAI__UAE-Large-V1.yaml@@ -0,0 +1,25 @@+sie_id: WhereIsAI/UAE-Large-V1+hf_id: WhereIsAI/UAE-Large-V1+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 1024+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 512+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/models/answerdotai__ModernBERT-base.yaml b/packages/sie_server/models/answerdotai__ModernBERT-base.yamlindex 256b29ea8..d0f523b90 100644--- a/packages/sie_server/models/answerdotai__ModernBERT-base.yaml+++ b/packages/sie_server/models/answerdotai__ModernBERT-base.yaml@@ -24,6 +24,13 @@ profiles:runtime:pooling: clsnormalize: true+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: trueus-regulatory:extends: defaultadapter_options:diff --git a/packages/sie_server/models/answerdotai__ModernBERT-large.yaml b/packages/sie_server/models/answerdotai__ModernBERT-large.yamlnew file mode 100644index 000000000..fd623e013--- /dev/null+++ b/packages/sie_server/models/answerdotai__ModernBERT-large.yaml@@ -0,0 +1,25 @@+sie_id: answerdotai/ModernBERT-large+hf_id: answerdotai/ModernBERT-large+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 1024+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 8192+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: truediff --git a/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yaml b/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yamlindex 9aac172ce..9b869f6fd 100644--- a/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yaml+++ b/packages/sie_server/models/answerdotai__answerai-colbert-small-v1.yaml@@ -22,9 +22,15 @@ profiles:adapter_options:loadtime:muvera_config:- num_repetitions: 20+ num_repetitions: 40num_simhash_projections: 6projection_dim: 8+ final_projection_dim: null+ # answerai tokens carry a dominant shared DC component (mean-token norm+ # ~0.93) that tips SimHash into collapse on Blackwell (@muvera nDCG 0.0+ # while @default MaxSim is healthy 0.57). Centering removes it and also+ # improves FDE on healthy hardware (MPS 0.287 -> 0.379). See #1528.+ center_tokens: truetoken_dim: 96normalize: truequery_max_length: 32diff --git a/packages/sie_server/models/colbert-ir__colbertv2.0.yaml b/packages/sie_server/models/colbert-ir__colbertv2.0.yamlindex 35ed494ee..d660a936c 100644--- a/packages/sie_server/models/colbert-ir__colbertv2.0.yaml+++ b/packages/sie_server/models/colbert-ir__colbertv2.0.yaml@@ -24,8 +24,8 @@ profiles:muvera_config:num_repetitions: 40num_simhash_projections: 6- projection_dim: null- final_projection_dim: 10240+ projection_dim: 8+ final_projection_dim: nulltoken_dim: 128normalize: truequery_max_length: 32diff --git a/packages/sie_server/models/google__embeddinggemma-300m.yaml b/packages/sie_server/models/google__embeddinggemma-300m.yamlindex 89e26f638..633528933 100644--- a/packages/sie_server/models/google__embeddinggemma-300m.yaml+++ b/packages/sie_server/models/google__embeddinggemma-300m.yaml@@ -32,18 +32,11 @@ max_sequence_length: 2048profiles:default:max_batch_tokens: 16384- # bfloat16 on CUDA matches the captured reference embedding in- # ``test_all_models.py``. On CPU the adapter falls back to fp32- # automatically (see pytorch_embedding adapter); the loaded model- # still works, but numerical-equivalence tests should be gated on- # CUDA availability if drift becomes an issue.- compute_precision: bfloat16- adapter_path: sie_server.adapters.pytorch_embedding:PyTorchEmbeddingAdapter- adapter_options:- loadtime:- attn_implementation: sdpa- runtime:- pooling: mean- normalize: true- query_template: 'task: search result | query: {text}'- doc_template: 'title: none | text: {text}'+ # EmbeddingGemma carries trained Dense projection layers on top of the+ # transformer (Transformer -> mean Pooling -> Dense -> Dense -> Normalize),+ # so it is served through the sentence-transformers pipeline; a plain+ # transformers.AutoModel path would expose only the backbone without the+ # projection head. Pooling and normalization are owned by the pipeline, and+ # query/document prompts come from the model's own prompt set selected by+ # is_query, so none are configured here.+ adapter_path: sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapterdiff --git a/packages/sie_server/models/ibm-granite__granite-embedding-english-r2.yaml b/packages/sie_server/models/ibm-granite__granite-embedding-english-r2.yamlindex ac2395911..e9e4c4b21 100644--- a/packages/sie_server/models/ibm-granite__granite-embedding-english-r2.yaml+++ b/packages/sie_server/models/ibm-granite__granite-embedding-english-r2.yaml@@ -24,3 +24,10 @@ profiles:runtime:pooling: clsnormalize: true+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: truediff --git a/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yaml b/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yamlindex e50ddb812..664366eaf 100644--- a/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yaml+++ b/packages/sie_server/models/ibm-granite__granite-embedding-small-english-r2.yaml@@ -24,3 +24,10 @@ profiles:runtime:pooling: clsnormalize: true+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: truediff --git a/packages/sie_server/models/intfloat__e5-base-v2.yaml b/packages/sie_server/models/intfloat__e5-base-v2.yamlindex 7d721af56..1ed3f208b 100644--- a/packages/sie_server/models/intfloat__e5-base-v2.yaml+++ b/packages/sie_server/models/intfloat__e5-base-v2.yaml@@ -26,3 +26,12 @@ profiles:normalize: truequery_template: 'query: {text}'doc_template: 'passage: {text}'+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: true+ query_template: 'query: {text}'+ doc_template: 'passage: {text}'diff --git a/packages/sie_server/models/intfloat__e5-large-v2.yaml b/packages/sie_server/models/intfloat__e5-large-v2.yamlindex 42a99c646..194e366d8 100644--- a/packages/sie_server/models/intfloat__e5-large-v2.yaml+++ b/packages/sie_server/models/intfloat__e5-large-v2.yaml@@ -26,3 +26,12 @@ profiles:normalize: truequery_template: 'query: {text}'doc_template: 'passage: {text}'+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: true+ query_template: 'query: {text}'+ doc_template: 'passage: {text}'diff --git a/packages/sie_server/models/intfloat__e5-mistral-7b-instruct.yaml b/packages/sie_server/models/intfloat__e5-mistral-7b-instruct.yamlindex 55dd4eb9f..7d9d32f5b 100644--- a/packages/sie_server/models/intfloat__e5-mistral-7b-instruct.yaml+++ b/packages/sie_server/models/intfloat__e5-mistral-7b-instruct.yaml@@ -22,6 +22,10 @@ profiles:adapter_options:loadtime:mem_fraction_static: 0.85+ # Mistral-family last-token embedder: SGLang does not auto-append EOS for+ # this architecture, so last-token pooling reads the wrong position and+ # retrieval collapses (#1489). Append the model's own EOS at encode time.+ append_eos: trueruntime:pooling: last_tokennormalize: truediff --git a/packages/sie_server/models/intfloat__e5-small-v2.yaml b/packages/sie_server/models/intfloat__e5-small-v2.yamlindex 8e4c6a314..52e64f3c9 100644--- a/packages/sie_server/models/intfloat__e5-small-v2.yaml+++ b/packages/sie_server/models/intfloat__e5-small-v2.yaml@@ -26,3 +26,12 @@ profiles:normalize: truequery_template: 'query: {text}'doc_template: 'passage: {text}'+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: true+ query_template: 'query: {text}'+ doc_template: 'passage: {text}'diff --git a/packages/sie_server/models/intfloat__multilingual-e5-large-instruct.yaml b/packages/sie_server/models/intfloat__multilingual-e5-large-instruct.yamlindex 52eae1133..a424c3865 100644--- a/packages/sie_server/models/intfloat__multilingual-e5-large-instruct.yaml+++ b/packages/sie_server/models/intfloat__multilingual-e5-large-instruct.yaml@@ -27,3 +27,13 @@ profiles:query_template: 'Instruct: {instruction}\nQuery: {text}'instruction: 'Given a web search query, retrieve relevant passages that answer the query'doc_template: '{text}'+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: true+ query_template: 'Instruct: {instruction}\nQuery: {text}'+ instruction: 'Given a web search query, retrieve relevant passages that answer the query'+ doc_template: '{text}'diff --git a/packages/sie_server/models/intfloat__multilingual-e5-large.yaml b/packages/sie_server/models/intfloat__multilingual-e5-large.yamlindex 7d9dee06f..e49daabdd 100644--- a/packages/sie_server/models/intfloat__multilingual-e5-large.yaml+++ b/packages/sie_server/models/intfloat__multilingual-e5-large.yaml@@ -35,3 +35,12 @@ profiles:runtime:pooling: meannormalize: true+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: true+ query_template: 'query: {text}'+ doc_template: 'passage: {text}'diff --git a/packages/sie_server/models/jinaai__jina-colbert-v2.yaml b/packages/sie_server/models/jinaai__jina-colbert-v2.yamlindex 911e298d3..043c578da 100644--- a/packages/sie_server/models/jinaai__jina-colbert-v2.yaml+++ b/packages/sie_server/models/jinaai__jina-colbert-v2.yaml@@ -22,9 +22,10 @@ profiles:adapter_options:loadtime:muvera_config:- num_repetitions: 20+ num_repetitions: 40num_simhash_projections: 6projection_dim: 8+ final_projection_dim: nulltoken_dim: 128normalize: truequery_max_length: 32diff --git a/packages/sie_server/models/jinaai__jina-embeddings-v2-base-code.yaml b/packages/sie_server/models/jinaai__jina-embeddings-v2-base-code.yamlnew file mode 100644index 000000000..ca60323b2--- /dev/null+++ b/packages/sie_server/models/jinaai__jina-embeddings-v2-base-code.yaml@@ -0,0 +1,25 @@+sie_id: jinaai/jina-embeddings-v2-base-code+hf_id: jinaai/jina-embeddings-v2-base-code+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 8192+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/models/jinaai__jina-embeddings-v2-base-de.yaml b/packages/sie_server/models/jinaai__jina-embeddings-v2-base-de.yamlnew file mode 100644index 000000000..fc8b6a361--- /dev/null+++ b/packages/sie_server/models/jinaai__jina-embeddings-v2-base-de.yaml@@ -0,0 +1,25 @@+sie_id: jinaai/jina-embeddings-v2-base-de+hf_id: jinaai/jina-embeddings-v2-base-de+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 8192+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/models/jinaai__jina-embeddings-v2-base-en.yaml b/packages/sie_server/models/jinaai__jina-embeddings-v2-base-en.yamlnew file mode 100644index 000000000..b5ae08133--- /dev/null+++ b/packages/sie_server/models/jinaai__jina-embeddings-v2-base-en.yaml@@ -0,0 +1,25 @@+sie_id: jinaai/jina-embeddings-v2-base-en+hf_id: jinaai/jina-embeddings-v2-base-en+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 8192+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/models/jinaai__jina-embeddings-v2-base-es.yaml b/packages/sie_server/models/jinaai__jina-embeddings-v2-base-es.yamlnew file mode 100644index 000000000..d40e40d8e--- /dev/null+++ b/packages/sie_server/models/jinaai__jina-embeddings-v2-base-es.yaml@@ -0,0 +1,25 @@+sie_id: jinaai/jina-embeddings-v2-base-es+hf_id: jinaai/jina-embeddings-v2-base-es+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 8192+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/models/jinaai__jina-embeddings-v2-base-zh.yaml b/packages/sie_server/models/jinaai__jina-embeddings-v2-base-zh.yamlnew file mode 100644index 000000000..0cc68ef52--- /dev/null+++ b/packages/sie_server/models/jinaai__jina-embeddings-v2-base-zh.yaml@@ -0,0 +1,25 @@+sie_id: jinaai/jina-embeddings-v2-base-zh+hf_id: jinaai/jina-embeddings-v2-base-zh+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 8192+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/models/jinaai__jina-embeddings-v2-small-en.yaml b/packages/sie_server/models/jinaai__jina-embeddings-v2-small-en.yamlnew file mode 100644index 000000000..114435788--- /dev/null+++ b/packages/sie_server/models/jinaai__jina-embeddings-v2-small-en.yaml@@ -0,0 +1,25 @@+sie_id: jinaai/jina-embeddings-v2-small-en+hf_id: jinaai/jina-embeddings-v2-small-en+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 512+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 8192+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml b/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yamlindex e51b375b5..05b479f11 100644--- a/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml+++ b/packages/sie_server/models/lightonai__GTE-ModernColBERT-v1.yaml@@ -24,8 +24,8 @@ profiles:muvera_config:num_repetitions: 40num_simhash_projections: 6- projection_dim: null- final_projection_dim: 10240+ projection_dim: 8+ final_projection_dim: nulltoken_dim: 128normalize: truequery_max_length: 32diff --git a/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml b/packages/sie_server/models/lightonai__Reason-ModernColBERT.yamlindex b1404a971..9e0ddf5fc 100644--- a/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml+++ b/packages/sie_server/models/lightonai__Reason-ModernColBERT.yaml@@ -24,8 +24,8 @@ profiles:muvera_config:num_repetitions: 40num_simhash_projections: 6- projection_dim: null- final_projection_dim: 10240+ projection_dim: 8+ final_projection_dim: nulltoken_dim: 128normalize: truequery_max_length: 32diff --git a/packages/sie_server/models/mixedbread-ai__mxbai-colbert-large-v1.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-colbert-large-v1.yamlindex de40017d8..1e1c793d1 100644--- a/packages/sie_server/models/mixedbread-ai__mxbai-colbert-large-v1.yaml+++ b/packages/sie_server/models/mixedbread-ai__mxbai-colbert-large-v1.yaml@@ -22,9 +22,10 @@ profiles:adapter_options:loadtime:muvera_config:- num_repetitions: 20+ num_repetitions: 40num_simhash_projections: 6projection_dim: 8+ final_projection_dim: nulltoken_dim: 128normalize: truequery_max_length: 128diff --git a/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yamlindex 2789262dc..f3ab578ec 100644--- a/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml+++ b/packages/sie_server/models/mixedbread-ai__mxbai-edge-colbert-v0-32m.yaml@@ -22,9 +22,10 @@ profiles:adapter_options:loadtime:muvera_config:- num_repetitions: 20+ num_repetitions: 40num_simhash_projections: 6projection_dim: 8+ final_projection_dim: nulltoken_dim: 64normalize: truequery_max_length: 32diff --git a/packages/sie_server/models/mixedbread-ai__mxbai-embed-large-v1.yaml b/packages/sie_server/models/mixedbread-ai__mxbai-embed-large-v1.yamlindex d944e305b..0dd6b844f 100644--- a/packages/sie_server/models/mixedbread-ai__mxbai-embed-large-v1.yaml+++ b/packages/sie_server/models/mixedbread-ai__mxbai-embed-large-v1.yaml@@ -26,3 +26,12 @@ profiles:normalize: truequery_template: 'Represent this sentence for searching relevant passages: {text}'doc_template: '{text}'+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: cls+ normalize: true+ query_template: 'Represent this sentence for searching relevant passages: {text}'+ doc_template: '{text}'diff --git a/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml b/packages/sie_server/models/nomic-ai__modernbert-embed-base.yamlindex 3f25f989e..ae008b82d 100644--- a/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml+++ b/packages/sie_server/models/nomic-ai__modernbert-embed-base.yaml@@ -26,3 +26,12 @@ profiles:normalize: truequery_template: 'search_query: {text}'doc_template: 'search_document: {text}'+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: true+ query_template: 'search_query: {text}'+ doc_template: 'search_document: {text}'diff --git a/packages/sie_server/models/nomic-ai__nomic-embed-text-v1.5.yaml b/packages/sie_server/models/nomic-ai__nomic-embed-text-v1.5.yamlnew file mode 100644index 000000000..ccb599130--- /dev/null+++ b/packages/sie_server/models/nomic-ai__nomic-embed-text-v1.5.yaml@@ -0,0 +1,27 @@+sie_id: nomic-ai/nomic-embed-text-v1.5+hf_id: nomic-ai/nomic-embed-text-v1.5+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 8192+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: true+ query_template: 'search_query: {text}'+ doc_template: 'search_document: {text}'diff --git a/packages/sie_server/models/sentence-transformers__all-MiniLM-L6-v2.yaml b/packages/sie_server/models/sentence-transformers__all-MiniLM-L6-v2.yamlindex ccb897d29..c4f1864f7 100644--- a/packages/sie_server/models/sentence-transformers__all-MiniLM-L6-v2.yaml+++ b/packages/sie_server/models/sentence-transformers__all-MiniLM-L6-v2.yaml@@ -25,3 +25,10 @@ profiles:runtime:pooling: meannormalize: true+ candle:+ extends: default+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/models/thenlper__gte-base.yaml b/packages/sie_server/models/thenlper__gte-base.yamlnew file mode 100644index 000000000..5b10d4a33--- /dev/null+++ b/packages/sie_server/models/thenlper__gte-base.yaml@@ -0,0 +1,25 @@+sie_id: thenlper/gte-base+hf_id: thenlper/gte-base+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 768+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 512+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/models/thenlper__gte-large.yaml b/packages/sie_server/models/thenlper__gte-large.yamlnew file mode 100644index 000000000..0efe1a220--- /dev/null+++ b/packages/sie_server/models/thenlper__gte-large.yaml@@ -0,0 +1,25 @@+sie_id: thenlper/gte-large+hf_id: thenlper/gte-large+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 1024+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 512+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/models/thenlper__gte-small.yaml b/packages/sie_server/models/thenlper__gte-small.yamlnew file mode 100644index 000000000..4097bd4d9--- /dev/null+++ b/packages/sie_server/models/thenlper__gte-small.yaml@@ -0,0 +1,25 @@+sie_id: thenlper/gte-small+hf_id: thenlper/gte-small+inputs:+ text: true+ image: false+ audio: false+ video: false+tasks:+ encode:+ dense:+ dim: 384+ sparse: null+ multivector: null+ score: null+ extract: null+max_sequence_length: 512+profiles:+ candle:+ max_batch_tokens: 16384+ compute_precision: null+ adapter_path: sie_server_rust.adapters.candle:CandleEmbeddingAdapter+ adapter_options:+ runtime:+ pooling: mean+ normalize: truediff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex c496a3bf7..275a1cc60 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -3,7 +3,7 @@"info": {"title": "SIE Server","description": "Search Inference Engine - GPU inference server for search workloads",- "version": "0.6.14"+ "version": "0.6.15"},"paths": {"/": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex 05141d296..e13e65ce7 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.6.14"+version = "0.6.15"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }@@ -13,6 +13,7 @@ dependencies = [# Serialization"msgpack>=1.1,<2","msgpack-numpy>=0.4,<1",+ "orjson>=3.10,<4",# ML / Inference# torch 2.9.x required - flash-attn prebuilt wheels are version-specific"torch>=2.9,<2.10",@@ -83,6 +84,21 @@ xformers = ["xformers>=0.0.30,<0.1 ; sys_platform == 'linux'"]gpu-metrics = ["nvidia-ml-py>=13.5,<14"]# TUI dependenciestop = ["textual>=3.0,<4"]+# Local embeddings + reranking on Apple Silicon / CPU (no Docker/mise). The torch /+# sentence-transformers / FlagEmbedding stack is already in the base deps; the base+# leaves transformers at >=4.57,<6 so the transformers-5 bundle overlays resolve.+# This extra tightens it to <5 — the version the embed/rerank adapters need — for a+# bare install with no bundle overlay:+# uv tool install "sie-server[local]" && sie-server serve+#+# Generation is deliberately NOT a locked extra. mlx-lm requires transformers>=5; as+# a workspace extra it would drag the base resolution toward 5.x (which breaks+# embed/rerank on a bare install). Instead overlay it per-invocation, mirroring the+# bundle's `uv run --with-requirements` — keeps generation deps out of the base lock:+# uvx --with "mlx-lm>=0.30.7" --from sie-server sie-server serve -b sglang -p 8081+# (Linux/CUDA generation uses the Docker image: SGLang pins timm==1.0.16, which+# conflicts with the embed/rerank stack's timm<1.0, so it can't share a pip env.)+local = ["transformers>=4.57,<5"][project.scripts]sie-server = "sie_server.cli:app"diff --git a/packages/sie_server/src/sie_server/adapter_call_loop.py b/packages/sie_server/src/sie_server/adapter_call_loop.pyindex 7dc0788bc..6d053a8dd 100644--- a/packages/sie_server/src/sie_server/adapter_call_loop.py+++ b/packages/sie_server/src/sie_server/adapter_call_loop.py@@ -14,16 +14,16 @@ 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.+ IPC execution path. They prepare adapter-coupled inputs and call+ ``ModelWorker.submit_preformed*`` so Rust-owned batches do not re-enter+ Python's local ``BatchFormer``.* ``adapter_call_loop`` is a **strict subset** of what those threemethods do: it accepts an already-formed batch (no batching, nocoalesce, no adaptive control — those live in Rust now) and fanseach ``RunBatchItem`` into the same per-op handlers the executoralready calls. All the adapter-side logic (``handlers.make_config_key``,- ``EncodePipeline.run_encode``, ``ModelWorker.submit``, ``_group_by_inference_config``,- ``_complete_requests``) is reused verbatim.+ ``EncodePipeline.run_encode``, ``ModelWorker.submit_preformed``,+ ``_group_by_inference_config``, ``_complete_requests``) is reused.* Keeping the dispatch thin here lets the Rust side own the onlybehaviourally-novel piece (batch formation + FCFS across LoRAs + PIloop) without duplicating the Python handler vocabulary.@@ -34,17 +34,14 @@ LoRA plumbing (single source of truth for the wire-boundary contract):batch — items inside the batch are guaranteed homogeneous by theupstream 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.+ before fanning out to the per-op handler. From there the pre-formed+ ``ModelWorker`` entrypoint picks it up via ``options.get("lora")`` and+ sets the adapter's active LoRA immediately 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 mustapply the same normalisation.-* Score is base-only — Python's ``ModelWorker.submit_score`` documents+* Score is base-only — Python's ``ModelWorker.submit_score_preformed`` documentsthis as "Score operations use base model batcher (no LoRA supportfor reranking)". When ``RunBatch`` arrives with ``op="score"`` and anon-empty ``lora_key`` we **log** and serve the base path rather@@ -83,6 +80,9 @@ from __future__ import annotationsimport loggingfrom typing import TYPE_CHECKING, Any+from opentelemetry import propagate, trace+from opentelemetry.context import Context+from sie_server.ipc_types import (BatchOutcome,EncodeBatchItem,@@ -91,6 +91,7 @@ from sie_server.ipc_types import (ProcessEncodeBatchRequest,ProcessExtractBatchRequest,ProcessScoreBatchRequest,+ RunBatchItem,RunBatchRequest,)@@ -120,7 +121,7 @@ def _merge_lora_into_options() -> dict[str, Any] | None:"""Return an options dict with ``options["lora"] = lora_key`` set.- Matches the legacy ``ModelWorker.submit`` contract where the+ Matches the ``ModelWorker.submit_preformed`` contract where thebatcher selection is sourced from ``options.get("lora")``. Returns``existing`` unchanged when ``lora_key`` is empty (the base-modelcase — leaving ``options["lora"]`` unset rather than setting it to@@ -205,20 +206,91 @@ async def handle_run_batch()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}")+ # W3C Trace Context propagation (mirrors the streaming path in+ # ``processors/streaming.py``). The gateway serialises its span into+ # each work item's ``traceparent`` / ``tracestate``; the Rust+ # scheduler copies those onto the wire items. We re-extract them here+ # so ``worker.run_batch`` attaches to the gateway span instead of+ # rooting a fresh trace. A batch can fan in items from several+ # requests (each with its own trace) — we parent the span to the+ # first distinct context and add OTel links to the rest.+ parent_ctx, links = _extract_batch_trace_context(req.items)+ tracer = trace.get_tracer("sie_server.adapter_call_loop")+ with tracer.start_as_current_span(+ "worker.run_batch",+ context=parent_ctx,+ links=links,+ attributes={+ "sie.model": req.model_id,+ "sie.batch_id": req.batch_id,+ "sie.op": op,+ "sie.adapter": "run_batch",+ "sie.batch_size": len(req.items),+ },+ ):+ 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}")+++def _extract_batch_trace_context(+ items: list[RunBatchItem],+) -> tuple[Context, list[trace.Link]]:+ """Resolve the parent context + span links for a ``worker.run_batch`` span.++ A run_batch holds N items, each potentially from a different request+ with its own ``traceparent`` / ``tracestate``. We:++ * collect the DISTINCT ``(traceparent, tracestate)`` pairs, preserving+ first-seen order;+ * :func:`opentelemetry.propagate.extract` each into a parent+ :class:`~opentelemetry.context.Context` and keep only the ones that+ carry a *valid* span context;+ * return the FIRST valid context as the parent and OTel+ :class:`~opentelemetry.trace.Link` s to the remaining valid ones so+ the fan-in is visible in the trace graph.++ When no item carries a valid trace context, the empty context from+ ``propagate.extract({})`` is returned (a safe no-op) so the caller+ opens a root span.+ """+ distinct: list[tuple[str | None, str | None]] = []+ for item in items:+ key = (item.traceparent, item.tracestate)+ if key not in distinct:+ distinct.append(key)++ valid_ctxs: list[Context] = []+ for traceparent, tracestate in distinct:+ carrier: dict[str, str] = {}+ if traceparent is not None:+ carrier["traceparent"] = traceparent+ if tracestate is not None:+ carrier["tracestate"] = tracestate+ ctx = propagate.extract(carrier)+ if trace.get_current_span(ctx).get_span_context().is_valid:+ valid_ctxs.append(ctx)++ if not valid_ctxs:+ # No valid parent — open a root span. ``propagate.extract({})``+ # yields an empty context that ``start_as_current_span`` treats+ # as "no parent" (root).+ return propagate.extract({}), []++ parent_ctx = valid_ctxs[0]+ links = [trace.Link(trace.get_current_span(ctx).get_span_context()) for ctx in valid_ctxs[1:]]+ return parent_ctx, links# --------------------------------------------------------------------@@ -250,10 +322,8 @@ async def _dispatch_encode()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.+ # ``ModelWorker.submit_preformed`` sets the adapter's active LoRA+ # immediately before the forward pass.merged_options = _merge_lora_into_options(ri.encode.options,req.lora_key,@@ -282,14 +352,14 @@ 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+ # Score is base-only: ``ModelWorker.submit_score_preformed`` ignores+ # LoRA. 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), "+ "score has no LoRA support (ModelWorker.submit_score_preformed), ""serving base weights for batch_id=%d",req.model_id,req.lora_key,@@ -337,9 +407,8 @@ async def _dispatch_extract()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).+ # lora_key into ``options["lora"]`` so the pre-formed ModelWorker+ # path selects the right LoRA for this IPC batch.merged_options = _merge_lora_into_options(ri.extract.options,req.lora_key,diff --git a/packages/sie_server/src/sie_server/adapters/_flash_pack.py b/packages/sie_server/src/sie_server/adapters/_flash_pack.pynew file mode 100644index 000000000..cc01464ec--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/_flash_pack.py@@ -0,0 +1,40 @@+"""Shared variable-length packing helpers for flash-attention adapters.++Flash-attention encoders pack a batch of sequences into one flat token stream+and drive attention with cumulative sequence lengths (``cu_seqlens``). Each+packed sequence needs position ids restarting at the model's base offset.++Historically every ``*_flash`` adapter reimplemented this with a per-sequence+``torch.arange`` loop (with a ``.item()`` CUDA sync per sequence). This module+is the single deep implementation those adapters delegate to. See issue #1538.+"""++from __future__ import annotations++import torch+++def build_position_ids(cu_seqlens: torch.Tensor, *, offset: int = 0) -> torch.Tensor:+ """Position ids for a varlen-packed batch, restarting per sequence.++ Given ``cu_seqlens`` (cumulative token counts, shape ``[num_seqs + 1]``),+ return a flat ``int64`` tensor where packed sequence ``i`` carries+ ``[offset, offset + 1, ..., offset + len_i - 1]``.++ Fully vectorized — no per-sequence ``.item()`` CUDA sync — and bit-identical+ to the per-sequence ``torch.arange`` loops it replaces. The result is placed+ on ``cu_seqlens.device``.++ Args:+ cu_seqlens: Cumulative sequence lengths, shape ``[num_seqs + 1]``.+ offset: Base position of each sequence. ``0`` for most encoders;+ ``padding_idx + 1`` for XLM-RoBERTa-style position ids.++ Returns:+ A 1-D ``int64`` tensor of length ``cu_seqlens[-1]`` on ``cu_seqlens.device``.+ """+ total_tokens = int(cu_seqlens[-1].item())+ positions = torch.arange(total_tokens, device=cu_seqlens.device)+ seq_starts = torch.repeat_interleave(cu_seqlens[:-1], cu_seqlens[1:] - cu_seqlens[:-1])+ positions = positions - seq_starts+ return positions + offset if offset else positionsdiff --git a/packages/sie_server/src/sie_server/adapters/_multivector.py b/packages/sie_server/src/sie_server/adapters/_multivector.pynew file mode 100644index 000000000..96225f3f6--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/_multivector.py@@ -0,0 +1,84 @@+"""Shared multivector (late-interaction) MaxSim scoring for ColBERT-style adapters.++ColBERT / ColPali / ColQwen-style adapters score a query against documents with+MaxSim: for each query token take the max dot product over the document's+tokens, then sum over query tokens. Historically every multivector adapter+reimplemented this. This module is the single deep implementation. See #1539.++Token embeddings are assumed L2-normalized by the caller (the adapters normalize+at encode time), so the dot product is cosine similarity. Both functions place+no device of their own — the result follows ``query.device``.+"""++from __future__ import annotations++import torch+++def maxsim_scores(query: torch.Tensor, docs: list[torch.Tensor]) -> list[float]:+ """MaxSim score of each document against ``query`` (pairwise).++ For each document, sum over query tokens of the max over document tokens of+ the dot product.++ Args:+ query: Query token embeddings, shape ``[num_query_tokens, dim]``.+ docs: Per-document token embeddings, each ``[num_doc_tokens, dim]``,+ on the same device/dtype as ``query``.++ Returns:+ One score per document, in input order.+ """+ scores: list[float] = []+ for doc in docs:+ if doc.shape[0] == 0:+ # No document tokens: MaxSim is -inf (consistent with the batched path).+ scores.append(float("-inf"))+ continue+ sim = torch.matmul(query, doc.T)+ scores.append(sim.max(dim=-1).values.sum().item())+ return scores+++def maxsim_scores_batched(query: torch.Tensor, docs: list[torch.Tensor]) -> list[float]:+ """MaxSim scores via a single padded, masked batched matmul.++ Equivalent to :func:`maxsim_scores` but pads the documents to a uniform+ length and runs one batched matmul — faster when reranking many documents.+ Padded positions are masked with ``-inf`` so they never win the per-query+ token max.++ Args:+ query: Query token embeddings, shape ``[num_query_tokens, dim]``.+ docs: Per-document token embeddings, each ``[num_doc_tokens, dim]``,+ on the same device/dtype as ``query``.++ Returns:+ One score per document, in input order.+ """+ if not docs:+ return []+ device = query.device+ doc_lengths = [d.shape[0] for d in docs]+ max_doc_tokens = max(doc_lengths)+ if max_doc_tokens == 0:+ # Every document is empty (e.g. punctuation-only docs after special-token+ # stripping). A zero-length doc dimension would make sim.max(dim=-1) raise;+ # MaxSim over zero doc tokens is -inf for each, matching the per-doc mask.+ return [float("-inf")] * len(docs)+ dim = query.shape[1]++ docs_padded = torch.zeros((len(docs), max_doc_tokens, dim), dtype=query.dtype, device=device)+ for i, doc in enumerate(docs):+ docs_padded[i, : doc.shape[0]] = doc++ # Batched sim: [Q, D] @ [N, D, T] -> [N, Q, T]+ sim = torch.matmul(query, docs_padded.transpose(1, 2))++ # Mask padded positions so they cannot win the per-query-token max.+ lengths_t = torch.tensor(doc_lengths, device=device)+ mask = torch.arange(max_doc_tokens, device=device).unsqueeze(0) < lengths_t.unsqueeze(1)+ sim.masked_fill_(~mask.unsqueeze(1), float("-inf"))++ # MaxSim: max over doc tokens, sum over query tokens -> [N].+ return sim.max(dim=-1).values.sum(dim=-1).tolist()diff --git a/packages/sie_server/src/sie_server/adapters/base.py b/packages/sie_server/src/sie_server/adapters/base.pyindex 25da18384..ddeff2f93 100644--- a/packages/sie_server/src/sie_server/adapters/base.py+++ b/packages/sie_server/src/sie_server/adapters/base.py@@ -73,6 +73,12 @@ class ModelAdapter(ABC):wrapping it in the generic Python wait_for timeout, which cannot killthe underlying thread.+ Adapter-Owned Load Headroom:+ Adapters that reserve device memory during load can override+ load_required_memory_bytes() to tell the registry how much free memory+ should be available before load() starts. The registry may use that+ engine-agnostic estimate to evict non-pinned LRU models before loading.+Device-Aware Factory Method:Adapters can override create_for_device() to return different adapterimplementations based on device compatibility. Flash adapters inherit@@ -203,6 +209,25 @@ class ModelAdapter(ABC):return 0+ def load_required_memory_bytes(self, *, device_type: str, device_total_bytes: int) -> int | None:+ """Return minimum free device memory recommended before ``load()``.++ This is an optional load-staging hook for adapters whose startup+ reserves memory outside the parent process or whose footprint cannot be+ inferred from ``memory_footprint()`` before load. ``None`` means the+ registry should fall back to pressure-only eviction.++ Args:+ device_type: Memory tracker device type, such as ``"cuda"``.+ device_total_bytes: Total bytes reported for the target device.++ Returns:+ Minimum free bytes preferred before load, or ``None`` if the+ adapter has no additional load-headroom requirement.+ """+ _ = (device_type, device_total_bytes)+ return None+def encode(self,items: list[Item],diff --git a/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.py b/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.pyindex b1d1285f5..f7b3e3560 100644--- a/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/bge_m3/__init__.py@@ -66,7 +66,7 @@ class BGEM3Adapter(BGEM3ScoreMixin, BaseAdapter):*,normalize: bool = True,max_seq_length: int = 8192,- compute_precision: ComputePrecision = "bfloat16",+ compute_precision: ComputePrecision | None = None,**kwargs: Any, # Accept extra args from loader (e.g., pooling)) -> None:"""Initialize the adapter.@@ -75,7 +75,9 @@ class BGEM3Adapter(BGEM3ScoreMixin, BaseAdapter):model_name_or_path: HuggingFace model ID or local path.normalize: Whether to L2-normalize dense embeddings.max_seq_length: Maximum sequence length (default 8192).- compute_precision: Compute precision (bfloat16 recommended).+ compute_precision: Compute precision. None (default) selects fp32 off-CUDA+ (safe on MPS) and bfloat16 on CUDA; set explicitly to override (e.g.+ float16 to opt a curated model into fp16 on MPS).**kwargs: Additional arguments (ignored, for compatibility)."""_ = kwargs # Unused, but accepted for loader compatibility@@ -135,17 +137,21 @@ class BGEM3Adapter(BGEM3ScoreMixin, BaseAdapter):Returns:Tuple of (torch.dtype, attention_implementation string)."""- # CPU should use FP32- if not device.startswith("cuda"):- return torch.float32, "sdpa"-# Map precision to dtypedtype_map = {"float16": torch.float16,"bfloat16": torch.bfloat16,"float32": torch.float32,}- dtype = dtype_map.get(self._compute_precision, torch.bfloat16)+ # Default fp32 off-CUDA (safe on CPU/MPS); honor an explicit compute_precision+ # everywhere so curated Mac models can opt into fp16 on MPS. CUDA keeps bf16.+ precision = self._compute_precision+ if precision is None:+ precision = "bfloat16" if device.startswith("cuda") else "float32"+ # NOTE: bf16 is coerced to fp16 on MPS at the loader (MPS bf16 is incomplete+ # in torch and hangs XLM-RoBERTa load), so ``precision`` is never bf16 here on+ # MPS via the serving path. See core/loader.load_adapter.+ dtype = dtype_map.get(precision, torch.float32)# XLMRoberta (BGE-M3) does not support Flash Attention 2, always use SDPAreturn dtype, "sdpa"diff --git a/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.pyindex 0b72ab8d1..a855e86d8 100644--- a/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/bge_m3_flash/__init__.py@@ -11,6 +11,7 @@ from torch import nnfrom torch.nn import functionalfrom sie_server.adapters._flash_base import FlashBaseAdapter+from sie_server.adapters._flash_pack import build_position_idsfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecisionfrom sie_server.adapters._utils import validate_output_types@@ -236,23 +237,8 @@ class BGEM3FlashAdapter(BGEM3ScoreMixin, PEFTLoRAMixin, FlashBaseAdapter):# score() and score_pairs() are provided by BGEM3ScoreMixin.def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:- """Build XLMRoberta-style position IDs for packed sequences.-- XLMRoberta uses position IDs starting at padding_idx + 1, not 0.- This is critical for matching the padded model's output.- """- pos_list = []- for i in range(num_seqs):- seq_len = cu_seqlens[i + 1].item() - cu_seqlens[i].item()- # XLMRoberta positions: [padding_idx+1, padding_idx+2, ..., padding_idx+seq_len]- pos_list.append(- torch.arange(- self._padding_idx + 1,- self._padding_idx + 1 + seq_len,- device=self._device,- )- )- return torch.cat(pos_list)+ """Build XLMRoberta-style position IDs (each restarts at padding_idx + 1)."""+ return build_position_ids(cu_seqlens, offset=self._padding_idx + 1)def _run_embeddings(self, input_ids: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor:"""Compute embeddings for packed input."""@@ -332,15 +318,17 @@ class BGEM3FlashAdapter(BGEM3ScoreMixin, PEFTLoRAMixin, FlashBaseAdapter):"""Compute requested embeddings from the model output."""normalize = normalize if normalize is not None else self._normalizeresults: dict[str, Any] = {}- num_seqs = len(seq_lengths)if "dense" in output_types:- # Extract CLS token from each sequence- cls_embeddings = []- for i in range(num_seqs):- start = cu_seqlens[i].item()- cls_embeddings.append(hidden[start])- dense_vecs = torch.stack(cls_embeddings)+ # Extract the CLS token (first token) of each packed sequence in a+ # single vectorized gather. The CLS positions are exactly the+ # per-sequence start offsets, i.e. ``cu_seqlens[:-1]``. The previous+ # per-sequence ``cu_seqlens[i].item()`` loop forced one+ # cudaStreamSynchronize per sequence (N device round-trips per+ # encode) that serialized the otherwise-pipelined batch; this gathers+ # the same rows with zero syncs. Mirrors qwen2_flash's CLS gather.+ # See #1605.+ dense_vecs = hidden[cu_seqlens[:-1].long()]if normalize:dense_vecs = functional.normalize(dense_vecs, p=2, dim=-1)results["dense"] = dense_vecsdiff --git a/packages/sie_server/src/sie_server/adapters/colbert/__init__.py b/packages/sie_server/src/sie_server/adapters/colbert/__init__.pyindex 5e8824fc4..953d41e5f 100644--- a/packages/sie_server/src/sie_server/adapters/colbert/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colbert/__init__.py@@ -33,6 +33,8 @@ import torchfrom torch.nn import functionalfrom sie_server.adapters._base_adapter import BaseAdapter+from sie_server.adapters._flash_pack import build_position_ids+from sie_server.adapters._multivector import maxsim_scores_batchedfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecisionfrom sie_server.adapters._utils import grouped_score_pairs@@ -397,7 +399,15 @@ class ColBERTAdapter(BaseAdapter):return Nonedef _resolve_dtype(self) -> torch.dtype:- """Resolve compute dtype."""+ """Resolve compute dtype.++ Off-CUDA (CPU/MPS) ALWAYS uses fp32 for numerical safety — ColBERT is not+ validated for fp16 on MPS, so unlike ``bge_m3``/``pytorch_embedding`` (which+ honor an explicit precision off-CUDA for benchmarked models) it ignores+ ``compute_precision`` off-CUDA. fp16/bf16 are only used on CUDA.+ """+ if not self._device or not str(self._device).startswith("cuda"):+ return torch.float32dtype_map = {"float16": torch.float16,"bfloat16": torch.bfloat16,@@ -833,35 +843,11 @@ class ColBERTAdapter(BaseAdapter):is_query=False,)- # Compute MaxSim for all documents in a single batched operation+ # MaxSim over all documents in one padded, masked batched matmul.query_tensor = torch.from_numpy(query_vecs).to(self._device)-assert doc_output.multivector is not None- doc_list = doc_output.multivector- doc_lengths = [d.shape[0] for d in doc_list]- max_doc_tokens = max(doc_lengths)- dim = query_vecs.shape[1]-- # Pad documents to uniform length and transfer once- docs_padded = torch.zeros(- (len(doc_list), max_doc_tokens, dim),- dtype=query_tensor.dtype,- device=self._device,- )- for i, doc_vecs in enumerate(doc_list):- t = torch.from_numpy(doc_vecs).to(self._device)- docs_padded[i, : t.shape[0]] = t-- # Batched sim: [Q, D] @ [N, D, T]^T -> [N, Q, T]- sim = torch.matmul(query_tensor, docs_padded.transpose(1, 2))-- # Mask padded positions- lengths_t = torch.tensor(doc_lengths, device=self._device)- mask = torch.arange(max_doc_tokens, device=self._device).unsqueeze(0) < lengths_t.unsqueeze(1)- sim.masked_fill_(~mask.unsqueeze(1), float("-inf"))-- # MaxSim: max over doc tokens, sum over query tokens -> [N]- return sim.max(dim=-1).values.sum(dim=-1).tolist()+ doc_tensors = [torch.from_numpy(d).to(self._device) for d in doc_output.multivector]+ return maxsim_scores_batched(query_tensor, doc_tensors)def score_pairs(self,@@ -884,11 +870,7 @@ class ColBERTAdapter(BaseAdapter):def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:"""Build position IDs for packed sequences."""- pos_list = []- for i in range(num_seqs):- seq_len = int(cu_seqlens[i + 1].item() - cu_seqlens[i].item())- pos_list.append(torch.arange(0, seq_len, device=self._device, dtype=torch.long))- return torch.cat(pos_list)+ return build_position_ids(cu_seqlens)def _run_embeddings(self, input_ids: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor:"""Compute embeddings for packed input.diff --git a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.pyindex 58f9d723a..1b159f295 100644--- a/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colbert_modernbert_flash/__init__.py@@ -7,6 +7,8 @@ import torchfrom torch.nn import functionalfrom sie_server.adapters._flash_base import FlashBaseAdapter+from sie_server.adapters._flash_pack import build_position_ids+from sie_server.adapters._multivector import maxsim_scores_batchedfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecisionfrom sie_server.adapters._utils import apply_rotary_pos_emb, grouped_score_pairs, validate_output_types@@ -269,30 +271,10 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):is_query=False,)- # Compute MaxSim for all documents in a single batched operation+ # MaxSim over all documents in one padded, masked batched matmul.query_tensor = torch.from_numpy(query_vecs).to(self._device)-- doc_list = doc_output.multivector- doc_lengths = [d.shape[0] for d in doc_list]- max_doc_tokens = max(doc_lengths)- dim = query_vecs.shape[1]-- docs_padded = torch.zeros(- (len(doc_list), max_doc_tokens, dim),- dtype=query_tensor.dtype,- device=self._device,- )- for i, doc_vecs in enumerate(doc_list):- t = torch.from_numpy(doc_vecs).to(self._device)- docs_padded[i, : t.shape[0]] = t-- sim = torch.matmul(query_tensor, docs_padded.transpose(1, 2))-- lengths_t = torch.tensor(doc_lengths, device=self._device)- mask = torch.arange(max_doc_tokens, device=self._device).unsqueeze(0) < lengths_t.unsqueeze(1)- sim.masked_fill_(~mask.unsqueeze(1), float("-inf"))-- return sim.max(dim=-1).values.sum(dim=-1).tolist()+ doc_tensors = [torch.from_numpy(d).to(self._device) for d in doc_output.multivector]+ return maxsim_scores_batched(query_tensor, doc_tensors)def score_pairs(self,@@ -314,11 +296,7 @@ class ColBERTModernBERTFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:"""Build position IDs for packed sequences."""- pos_list = []- for i in range(num_seqs):- seq_len = int(cu_seqlens[i + 1].item() - cu_seqlens[i].item())- pos_list.append(torch.arange(0, seq_len, device=self._device, dtype=torch.long))- return torch.cat(pos_list)+ return build_position_ids(cu_seqlens)def _compute_rope(self, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:"""Compute RoPE cos/sin values for packed positions.diff --git a/packages/sie_server/src/sie_server/adapters/colbert_rotary_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/colbert_rotary_flash/__init__.pyindex cc0da1448..210dcff09 100644--- a/packages/sie_server/src/sie_server/adapters/colbert_rotary_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colbert_rotary_flash/__init__.py@@ -7,6 +7,7 @@ import torchfrom torch.nn import functionalfrom sie_server.adapters._flash_base import FlashBaseAdapter+from sie_server.adapters._multivector import maxsim_scores_batchedfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecisionfrom sie_server.adapters._utils import apply_rotary_pos_emb, grouped_score_pairs, validate_output_types@@ -401,30 +402,10 @@ class ColBERTRotaryFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):is_query=False,)- # Compute MaxSim for all documents in a single batched operation+ # MaxSim over all documents in one padded, masked batched matmul.query_tensor = torch.from_numpy(query_vecs).to(self._device)-- doc_list = doc_output.multivector- doc_lengths = [d.shape[0] for d in doc_list]- max_doc_tokens = max(doc_lengths)- dim = query_vecs.shape[1]-- docs_padded = torch.zeros(- (len(doc_list), max_doc_tokens, dim),- dtype=query_tensor.dtype,- device=self._device,- )- for i, doc_vecs in enumerate(doc_list):- t = torch.from_numpy(doc_vecs).to(self._device)- docs_padded[i, : t.shape[0]] = t-- sim = torch.matmul(query_tensor, docs_padded.transpose(1, 2))-- lengths_t = torch.tensor(doc_lengths, device=self._device)- mask = torch.arange(max_doc_tokens, device=self._device).unsqueeze(0) < lengths_t.unsqueeze(1)- sim.masked_fill_(~mask.unsqueeze(1), float("-inf"))-- return sim.max(dim=-1).values.sum(dim=-1).tolist()+ doc_tensors = [torch.from_numpy(d).to(self._device) for d in doc_output.multivector]+ return maxsim_scores_batched(query_tensor, doc_tensors)def score_pairs(self,diff --git a/packages/sie_server/src/sie_server/adapters/colpali/__init__.py b/packages/sie_server/src/sie_server/adapters/colpali/__init__.pyindex 7565e5a03..150d4f8f4 100644--- a/packages/sie_server/src/sie_server/adapters/colpali/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colpali/__init__.py@@ -27,6 +27,7 @@ import numpy as npimport torchfrom sie_server.adapters._base_adapter import BaseAdapter+from sie_server.adapters._multivector import maxsim_scoresfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecisionfrom sie_server.core.inference_output import EncodeOutput@@ -550,20 +551,11 @@ class ColPaliAdapter(BaseAdapter):is_query=False,)- # Compute MaxSim for each document- scores = []+ # MaxSim: per query token, max over doc patches, summed over query tokens.query_tensor = torch.from_numpy(query_vecs).to(self._device)-assert doc_output.multivector is not None- for doc_vecs in doc_output.multivector:- doc_tensor = torch.from_numpy(doc_vecs).to(self._device)-- # MaxSim: for each query token, find max similarity with any doc patch- sim = torch.matmul(query_tensor, doc_tensor.T)- maxsim_score = sim.max(dim=-1).values.sum().item()- scores.append(maxsim_score)-- return scores+ doc_tensors = [torch.from_numpy(d).to(self._device) for d in doc_output.multivector]+ return maxsim_scores(query_tensor, doc_tensors)def _validate_output_types(self, output_types: list[str]) -> None:"""Validate that output types are supported."""diff --git a/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py b/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.pyindex ad3074a9f..a9708e86a 100644--- a/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py@@ -31,6 +31,7 @@ import torchfrom torch import nnfrom sie_server.adapters._base_adapter import BaseAdapter+from sie_server.adapters._multivector import maxsim_scoresfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecisionfrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embed@@ -454,13 +455,9 @@ class ColQwen2Adapter(BaseAdapter):if doc_output.multivector is None:raise RuntimeError("Failed to encode documents: no multivector output")- scores = []query_tensor = torch.from_numpy(query_vecs).to(self._device)- for doc_vecs in doc_output.multivector:- doc_tensor = torch.from_numpy(doc_vecs).to(self._device)- sim = torch.matmul(query_tensor, doc_tensor.T)- scores.append(sim.max(dim=-1).values.sum().item())- return scores+ doc_tensors = [torch.from_numpy(d).to(self._device) for d in doc_output.multivector]+ return maxsim_scores(query_tensor, doc_tensors)def _validate_output_types(self, output_types: list[str]) -> None:unsupported = set(output_types) - {"multivector"}diff --git a/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.pyindex 3751202f9..39cd506a3 100644--- a/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py@@ -10,6 +10,7 @@ import torchfrom torch.nn import functional as Ffrom sie_server.adapters._base_adapter import BaseAdapter+from sie_server.adapters._multivector import maxsim_scoresfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecisionfrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embed@@ -352,13 +353,9 @@ class ColQwen3Adapter(BaseAdapter):if doc_output.multivector is None:raise RuntimeError("Failed to encode documents: no multivector output")- scores: list[float] = []query_tensor = torch.from_numpy(query_vecs).to(self._device)- for doc_vecs in doc_output.multivector:- doc_tensor = torch.from_numpy(doc_vecs).to(self._device)- sim = torch.matmul(query_tensor, doc_tensor.T)- scores.append(sim.max(dim=-1).values.sum().item())- return scores+ doc_tensors = [torch.from_numpy(d).to(self._device) for d in doc_output.multivector]+ return maxsim_scores(query_tensor, doc_tensors)# ------------------------------------------------------------------# Helpersdiff --git a/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py b/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.pyindex da65c4f26..1fcf74cde 100644--- a/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/cross_encoder/__init__.py@@ -58,7 +58,7 @@ class CrossEncoderAdapter(BaseAdapter):*,trust_remote_code: bool = False,max_length: int | None = None,- compute_precision: ComputePrecision = "float16",+ compute_precision: ComputePrecision | None = None,attn_implementation: AttnImplementation = "sdpa",**kwargs: Any, # Accept extra args from loader (e.g., pooling)) -> None:@@ -68,7 +68,9 @@ class CrossEncoderAdapter(BaseAdapter):model_name_or_path: HuggingFace model ID or local path.trust_remote_code: Whether to trust remote code in model files.max_length: Override default max sequence length for query+document.- compute_precision: Compute precision for inference (float16, bfloat16, float32).+ compute_precision: Compute precision for inference. None (default) selects+ fp32 off-CUDA (safe on MPS) and fp16 on CUDA; set explicitly to override+ (e.g. float16 to opt a curated model into fp16 on MPS).attn_implementation: Attention implementation ("sdpa" for optimized, "eager" for baseline).**kwargs: Additional arguments (ignored, for compatibility)."""@@ -93,16 +95,29 @@ class CrossEncoderAdapter(BaseAdapter):# Build model_kwargs for performance optimizationsmodel_kwargs: dict[str, Any] = {}- # Use SDPA for efficient attention on GPU+ # Use SDPA for efficient attention on acceleratorsif device.startswith("cuda") or device == "mps":- model_kwargs["attn_implementation"] = self._attn_implementation-- # Use FP16/BF16 for faster inference- if self._compute_precision == "float16":+ # FA2 is CUDA-only; off-CUDA (MPS) coerce anything but "eager" to "sdpa"+ # (mirrors PyTorchEmbeddingAdapter._resolve_dtype_and_attn) so a reranker+ # profile requesting flash_attention_2 still loads on Metal.+ if device.startswith("cuda") or self._attn_implementation == "eager":+ model_kwargs["attn_implementation"] = self._attn_implementation+ else:+ model_kwargs["attn_implementation"] = "sdpa"++ # Resolve precision. Default to fp32 off-CUDA (numerically safe on MPS);+ # honor an explicit compute_precision everywhere so curated Mac models can+ # opt into fp16 on MPS. CUDA keeps the historical fp16 default.+ precision = self._compute_precision+ if precision is None:+ precision = "float16" if device.startswith("cuda") else "float32"+ # NOTE: bf16 is coerced to fp16 on MPS at the loader (MPS bf16 is incomplete+ # in torch and can hang load). See core/loader.load_adapter.+ if precision == "float16":model_kwargs["dtype"] = torch.float16- elif self._compute_precision == "bfloat16":+ elif precision == "bfloat16":model_kwargs["dtype"] = torch.bfloat16- # float32 is the default, no need to specify+ # float32 -> CrossEncoder default, no dtype kwarg neededself._model = CrossEncoder(self._model_name_or_path,diff --git a/packages/sie_server/src/sie_server/adapters/mlx/__init__.py b/packages/sie_server/src/sie_server/adapters/mlx/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/packages/sie_server/src/sie_server/adapters/mlx/_server.py b/packages/sie_server/src/sie_server/adapters/mlx/_server.pynew file mode 100644index 000000000..9e0100dff--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/mlx/_server.py@@ -0,0 +1,286 @@+"""Shared MLX server subprocess plumbing.++Used by the MLX generation adapter (``generation.py``). Mirrors the SGLang+``_server.py`` patterns (port allocation, subprocess supervision,+health-polling, termination); it launches an ``mlx_lm.server`` child using the+**parent interpreter's own environment**.++No isolated env is needed: generation is served by the device-agnostic+``sglang`` bundle, which installs ``mlx-lm`` (and the ``transformers>=5`` it+requires) into the server's environment on Apple Silicon+(``mlx-lm ; sys_platform == 'darwin'``) — and that bundle carries no+``transformers<5`` embed/rerank stack to conflict with. So the child runs with+``sys.executable``'s ``mlx_lm.server`` console script directly. (On CUDA the+same bundle installs SGLang instead and this adapter is never selected.)++This module deliberately contains no model-specific logic; it just owns the+lifecycle of a single ``mlx_lm.server`` HTTP child process.+"""++from __future__ import annotations++import importlib.util+import logging+import math+import os+import random+import signal+import socket+import subprocess+import sys+import tempfile+import threading+import time+from pathlib import Path++import requests++logger = logging.getLogger(__name__)++# In-process record of ports already handed out by ``find_free_port`` but not+# yet bound by their MLX child — mirrors the SGLang TOCTOU mitigation. Uses a+# port range distinct from SGLang's (30000-30099) so the two never collide+# even if both somehow ran in one process.+_RESERVED_PORTS: set[int] = set()+# Loads run on the registry's load-executor thread pool, so two concurrent MLX+# loads could otherwise probe-and-hand-out the same port (TOCTOU). Guard the+# reserved-set scan with a lock, mirroring sglang/_server.py.+_RESERVED_PORTS_LOCK = threading.Lock()+BASE_PORT = 30200++# Model download (Qwen3.5-4B-4bit is ~2.5 GB) plus the first Metal load can take+# minutes on a cold cache. Generous default; override via the env vars below.+DEFAULT_STARTUP_TIMEOUT_S = 900.0+STARTUP_TIMEOUT_ENV_VARS = (+ "SIE_MLX_STARTUP_TIMEOUT_S",+ "SIE_MODEL_READY_TIMEOUT_S",+ "SIE_ADAPTER_STARTUP_TIMEOUT_S",+ "SIE_SERVER_STARTUP_TIMEOUT_S",+)+HEALTH_CHECK_INTERVAL_S = 2.0++ERR_SERVER_STARTUP = "MLX server failed to start within timeout"+ERR_WARMUP_FAILED = "MLX server started but the model failed to warm up (could not serve a test completion)"+++def mlx_lm_available() -> bool:+ """True if ``mlx-lm`` is importable in the current (parent) environment.++ The ``sglang`` generation bundle installs it on Apple Silicon; this lets+ :meth:`MLXGenerationAdapter.load` fail with a clear, actionable message+ instead of an opaque "command not found" from the child launch.+ """+ return importlib.util.find_spec("mlx_lm") is not None+++def resolve_startup_timeout(timeout_s: float | None = None) -> float:+ """Resolve the MLX startup-health timeout.++ Precedence: explicit value -> env vars in ``STARTUP_TIMEOUT_ENV_VARS`` order+ -> ``DEFAULT_STARTUP_TIMEOUT_S``.+ """+ if timeout_s is not None:+ try:+ value = float(timeout_s)+ except (TypeError, ValueError):+ value = 0.0+ if math.isfinite(value) and value > 0:+ return value+ logger.warning("Ignoring invalid MLX startup timeout override: %r (must be finite > 0)", timeout_s)++ for name in STARTUP_TIMEOUT_ENV_VARS:+ raw = os.environ.get(name)+ if raw is None or raw.strip() == "":+ continue+ try:+ value = float(raw)+ except ValueError:+ logger.warning("Ignoring invalid %s=%r; expected seconds", name, raw)+ continue+ if math.isfinite(value) and value > 0:+ return value+ logger.warning("Ignoring invalid %s=%r; expected finite seconds > 0", name, raw)++ return DEFAULT_STARTUP_TIMEOUT_S+++def find_free_port(start_port: int = BASE_PORT) -> int:+ """Find a free port in ``[start_port, start_port + 100)`` (TOCTOU-mitigated)."""+ span = 100+ offset = random.randrange(span) # noqa: S311 — port selection, not crypto+ with _RESERVED_PORTS_LOCK:+ for i in range(span):+ port = start_port + ((offset + i) % span)+ if port in _RESERVED_PORTS:+ continue+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:+ try:+ s.bind(("127.0.0.1", port))+ except OSError:+ continue+ _RESERVED_PORTS.add(port)+ return port+ msg = f"Could not find free port in range {start_port}-{start_port + span - 1}"+ raise RuntimeError(msg)+++def open_output_log(prefix: str = "mlx_") -> tempfile._TemporaryFileWrapper:+ """Open a named temp file for capturing subprocess stdout/stderr."""+ return tempfile.NamedTemporaryFile(mode="w", prefix=prefix, suffix=".log", delete=False)+++def build_launch_command(*, mlx_repo: str, port: int, host: str = "127.0.0.1") -> list[str]:+ """Build the argv that serves ``mlx_repo`` via ``mlx_lm.server`` in the parent env.++ The ``sglang`` (generation) bundle installs ``mlx-lm`` into the server's own+ environment on Apple Silicon, so the child launches with this interpreter's+ ``mlx_lm.server`` console script — no isolated/uv env. Falls back to+ ``python -m mlx_lm server`` if the console script is not on the interpreter's+ ``bin`` path (e.g. an unusual install layout).+ """+ server_bin = Path(sys.executable).parent / "mlx_lm.server"+ launcher = [str(server_bin)] if server_bin.exists() else [sys.executable, "-m", "mlx_lm", "server"]+ return [+ *launcher,+ "--model",+ mlx_repo,+ "--port",+ str(port),+ "--host",+ host,+ "--log-level",+ "INFO",+ ]+++def launch_mlx_server(+ cmd: list[str],+ *,+ output_file: tempfile._TemporaryFileWrapper,+ extra_env: dict[str, str] | None = None,+) -> subprocess.Popen[bytes]:+ """Launch an ``mlx_lm.server`` subprocess in a new process group.++ Args:+ cmd: Full argv (from :func:`build_launch_command`).+ output_file: Temp file open for write — child stdout/stderr is redirected+ here for diagnostics.+ extra_env: Additional environment variables for the subprocess.++ Returns:+ The ``Popen`` handle. ``start_new_session=True`` puts the child in its+ own process group so the whole group can be signalled on shutdown.+ """+ env = os.environ.copy()+ # hf-xet hangs on Apple Silicon (ignores HF download timeouts); force reliable+ # HTTPS for the multi-GB MLX weight download. See cli.py for the parent-process default.+ env.setdefault("HF_HUB_DISABLE_XET", "1")+ if extra_env:+ env.update(extra_env)+ logger.info("MLX subprocess output will be logged to: %s", output_file.name)+ return subprocess.Popen( # noqa: S603 — intentional subprocess call+ cmd,+ env=env,+ stdout=output_file,+ stderr=subprocess.STDOUT,+ start_new_session=True,+ )+++def wait_for_server(+ server_url: str,+ process: subprocess.Popen[bytes],+ *,+ output_file: tempfile._TemporaryFileWrapper | None = None,+ timeout_s: float | None = None,+) -> bool:+ """Poll the MLX ``/health`` endpoint until the server is ready.++ Returns True if the server reports healthy before the timeout; False if the+ timeout elapses or the subprocess dies. Note: ``mlx_lm.server`` binds the+ HTTP port and answers ``/health`` as soon as httpd is up — the model may+ still be loading. Callers warm the model up with a real request after this+ returns (see :meth:`MLXGenerationAdapter.load`).+ """+ timeout_s = resolve_startup_timeout(timeout_s)+ health_url = f"{server_url}/health"+ start_time = time.monotonic()++ while time.monotonic() - start_time < timeout_s:+ if process.poll() is not None:+ logger.error("MLX server exited prematurely with code %s", process.returncode)+ _log_subprocess_output(output_file)+ return False+ try:+ response = requests.get(health_url, timeout=5)+ if response.status_code == 200:+ return True+ except requests.RequestException:+ pass # Not up yet — keep polling.+ time.sleep(HEALTH_CHECK_INTERVAL_S)++ logger.error("MLX server startup timeout after %gs", timeout_s)+ _log_subprocess_output(output_file)+ return False+++def warmup_model(server_url: str, model: str, *, timeout_s: float) -> bool:+ """Force the model load by issuing one tiny non-streaming completion.++ ``mlx_lm.server`` answers ``/health`` as soon as the HTTP server binds — the+ model may still be downloading/loading. A 1-token request blocks until the+ model is actually ready, so :meth:`MLXGenerationAdapter.load` returns only+ once generation works (deterministic readiness; the user's first real+ request is then fast).++ Returns True if the test completion succeeded (the model genuinely serves),+ False otherwise. The caller treats False as a load failure so a child that+ bound the port but cannot serve the model is not reported as "ready".+ """+ try:+ response = requests.post(+ f"{server_url}/v1/completions",+ json={"model": model, "prompt": "ok", "max_tokens": 1, "temperature": 0.0, "stream": False},+ timeout=timeout_s,+ )+ except requests.RequestException as exc:+ logger.warning("MLX warmup request failed: %s", exc)+ return False+ if response.status_code != 200:+ logger.warning("MLX warmup returned HTTP %d: %s", response.status_code, response.text[:300])+ return False+ logger.info("MLX model %s warmed up and ready", model)+ return True+++def _log_subprocess_output(output_file: tempfile._TemporaryFileWrapper | None) -> None:+ if output_file is None:+ return+ try:+ output_file.flush()+ except Exception: # noqa: BLE001+ return+ try:+ with Path(output_file.name).open() as f:+ output = f.read()+ logger.error("MLX subprocess output from %s:\n%s", output_file.name, output[-5000:])+ except OSError as e:+ logger.error("Failed to read MLX log: %s", e)+++def terminate_process(process: subprocess.Popen[bytes] | None) -> None:+ """Terminate the subprocess group: SIGTERM, wait, SIGKILL fallback."""+ if process is None:+ return+ try:+ os.killpg(os.getpgid(process.pid), signal.SIGTERM)+ process.wait(timeout=10)+ except (ProcessLookupError, subprocess.TimeoutExpired):+ try:+ os.killpg(os.getpgid(process.pid), signal.SIGKILL)+ process.wait(timeout=5)+ except (ProcessLookupError, subprocess.TimeoutExpired):+ # Best-effort: the group is already gone (ProcessLookupError) or+ # outlived even SIGKILL within the grace window (TimeoutExpired).+ # Nothing more to do — the OS reaps it. Logged for post-mortem.+ logger.debug("MLX subprocess group (pid %s) not confirmed dead after SIGKILL", process.pid)diff --git a/packages/sie_server/src/sie_server/adapters/mlx/generation.py b/packages/sie_server/src/sie_server/adapters/mlx/generation.pynew file mode 100644index 000000000..d2f74cd9b--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/mlx/generation.py@@ -0,0 +1,435 @@+"""MLX adapter for autoregressive text generation on Apple Silicon.++The Mac-native generation backend. Generation runs in a managed+``mlx_lm.server`` subprocess (Apple's MLX framework, Metal-native) that this+adapter spawns and proxies — launched from the server's own environment (the+device-agnostic ``sglang`` bundle installs ``mlx-lm`` on Apple Silicon; see+:mod:`sie_server.adapters.mlx._server`). A subprocess rather than in-process+because ``mlx_lm.server`` already exposes the OpenAI ``/v1/completions`` server+this adapter proxies, and its own process gives clean single-tenant lifecycle ++Metal-memory isolation.++Selection is automatic: :meth:`SGLangGenerationAdapter.create_for_device`+swaps to this adapter on any non-CUDA device, so unsuffixed generation models+"just work" on a Mac (served via ``mise run serve -b sglang``).++Streaming async-iterator contract (same as the SGLang adapter). The adapter+opens an HTTP streaming connection to the child's OpenAI-compatible+``/v1/completions`` endpoint (``stream: true`` + ``stream_options.include_usage``),+parses the SSE, and yields :class:`GenerationChunk` objects. The terminal+chunk carries ``finish_reason`` plus prompt/completion token counts.++Cancellation: dropping the async iterator (``aclose()``) exits the+``httpx.stream`` context, closing the upstream connection — which the+single-tenant ``mlx_lm.server`` treats as a stop signal.+"""++from __future__ import annotations++import asyncio+import contextlib+import json+import logging+import os+import subprocess+import tempfile+import time+from collections.abc import AsyncIterator+from pathlib import Path+from typing import Any, cast++import httpx++from sie_server.adapters._generation_base import (+ FinishReason,+ GenerationAdapter,+ GenerationChunk,+)+from sie_server.adapters._spec import AdapterSpec+from sie_server.adapters._types import ERR_NOT_LOADED+from sie_server.adapters.mlx import _server+from sie_server.types.inputs import ImageInput++logger = logging.getLogger(__name__)++# Inter-chunk read timeout. Unlike the SGLang path (which sits behind the worker /+# gateway with its own deadline + abort), the MLX ``generate()`` is invoked DIRECTLY+# by the /v1/generate and /v1/chat/completions routes, so it must bound itself — a+# wedged child (Metal stall, paused decode) must not hang the request forever. The+# default is generous (300s between tokens is "truly stuck", not "slow"); override+# via ``SIE_MLX_READ_TIMEOUT_S``.+_CONNECT_TIMEOUT_S = 10.0+_WRITE_TIMEOUT_S = 10.0+_POOL_TIMEOUT_S = 10.0+try:+ _READ_TIMEOUT_S = float(os.environ.get("SIE_MLX_READ_TIMEOUT_S", "300"))+except ValueError:+ # Invalid override must degrade gracefully, not crash adapter import+ # (mirrors _server.resolve_startup_timeout).+ logger.warning(+ "Invalid SIE_MLX_READ_TIMEOUT_S=%r; falling back to 300s",+ os.environ.get("SIE_MLX_READ_TIMEOUT_S"),+ )+ _READ_TIMEOUT_S = 300.0++# Finish reasons mlx_lm.server emits, mapped to the SIE contract. Anything else+# falls back to "stop".+_FINISH_REASONS: frozenset[str] = frozenset({"stop", "length"})++# default_sampling keys mlx_lm.server's /v1/completions actually understands. The+# curated generation profiles also set SGLang/OpenAI-only knobs (presence_penalty,+# frequency_penalty) for the CUDA path; those are filtered out here rather than+# forwarded to the MLX child, which does not use them (and may reject unknown fields+# on some versions) — keeping this adapter's "those are unsupported" contract honest.+_MLX_SAMPLING_KEYS: frozenset[str] = frozenset(+ {"temperature", "top_p", "top_k", "min_p", "repetition_penalty", "max_tokens", "seed", "stop"}+)+++class MLXGenerationAdapter(GenerationAdapter):+ """Streaming MLX generation adapter (Apple-Silicon, ``mlx_lm.server`` subprocess).++ Lifecycle mirrors :class:`SGLangGenerationAdapter`: one subprocess per+ model, started in :meth:`load`, terminated in :meth:`unload`. Inference is+ an HTTP POST to ``{server_url}/v1/completions`` with ``stream: true``.+ """++ spec = AdapterSpec(+ inputs=("text",),+ outputs=("tokens",),+ unload_fields=("_process", "_server_url"),+ )++ # The mlx_lm.server child owns its own signal handling; the parent load must+ # not block the uvicorn event loop while polling child readiness.+ requires_main_thread: bool = False+ manages_own_load_timeout: bool = True++ def __init__(+ self,+ model_name_or_path: str,+ *,+ mlx_repo: str | None = None,+ max_seq_length: int = 32768,+ default_sampling: dict[str, Any] | None = None,+ stop_tokens: list[str] | None = None,+ served_model_name: str | None = None,+ trust_remote_code: bool = False,+ startup_timeout_s: float | None = None,+ **kwargs: Any, # accept (and drop) CUDA/SGLang-only kwargs from the swap+ ) -> None:+ _ = kwargs+ self._model_name_or_path = str(model_name_or_path)+ # The MLX-quantized repo to serve (e.g. ``mlx-community/Qwen3.5-4B-4bit``), from+ # the model YAML's ``adapter_options.loadtime.mlx_repo``. REQUIRED for the Mac+ # generation path — load() fails fast if it is missing rather than letting+ # mlx_lm download a multi-GB full-precision HF model that then OOMs on Metal+ # (e.g. a non-curated generation model matched into the `sglang` bundle).+ self._mlx_repo = mlx_repo+ self._max_seq_length = max_seq_length+ self._default_sampling = default_sampling or {}+ self._stop_tokens = stop_tokens or []+ self._served_model_name = served_model_name or self._model_name_or_path+ self._trust_remote_code = trust_remote_code+ self._startup_timeout_s = startup_timeout_s++ self._process: subprocess.Popen[bytes] | None = None+ self._server_url: str | None = None+ self._device: str | None = None+ self._output_file: tempfile._TemporaryFileWrapper | None = None+ # Single-flight lock: mlx_lm.server is single-tenant and the cancellation+ # contract assumes one in-flight generation. Bound to the running loop on+ # first acquire (Python 3.10+), so safe to construct off-loop here.+ self._gen_lock = asyncio.Semaphore(1)++ # -- Lifecycle -----------------------------------------------------------++ @property+ def server_url(self) -> str | None:+ """The child ``mlx_lm.server`` base URL (used by the local chat-completions proxy)."""+ return self._server_url++ @property+ def mlx_repo(self) -> str | None:+ """The MLX repo / model id the child serves (the OpenAI ``model`` field).++ ``None`` until set by config; a loaded adapter always has it (load() guards).+ """+ return self._mlx_repo++ def generation_slot(self) -> asyncio.Semaphore:+ """Single-flight lock for this model's MLX child.++ ``generate()`` holds it for its whole stream; the chat-completions proxy+ acquires the same lock so the single-tenant child only ever serves one+ generation at a time.+ """+ return self._gen_lock++ def load(self, device: str) -> None:+ # Fail fast (before any download/subprocess) if the model has no MLX repo. This+ # guards non-curated generation models that match the `sglang` bundle by adapter+ # module but lack adapter_options.loadtime.mlx_repo — without this, mlx_lm would+ # download the full-precision HF weights (e.g. a 27B model) and OOM on Metal.+ if not self._mlx_repo:+ raise RuntimeError(+ f"Generation model '{self._model_name_or_path}' has no mlx_repo set; the Mac MLX "+ "backend requires an MLX-quantized repo. Add adapter_options.loadtime.mlx_repo "+ "to the model YAML (e.g. 'mlx-community/<model>-4bit'), or serve a curated Mac model "+ "(Qwen/Qwen3.5-4B)."+ )+ mlx_repo = self._mlx_repo # narrowed to str for the calls below+ # mlx-lm is installed by the device-agnostic ``sglang`` bundle on Apple Silicon.+ # If it is missing, the child launch would fail with an opaque error — surface+ # the actionable fix instead.+ if not _server.mlx_lm_available():+ raise RuntimeError(+ "mlx-lm is not installed in this environment; the Apple-Silicon generation "+ "backend requires it. Serve generation with the 'sglang' bundle "+ "(`mise run serve -b sglang`), which installs mlx-lm on macOS."+ )+ # Defensive: a prior load that left a live subprocess would be orphaned (it+ # survives in its own session, holding its port + Metal memory). Tear it down+ # first so a double-load (e.g. a retry) is idempotent rather than leaking.+ if self._process is not None:+ self.unload()+ self._device = device+ port = _server.find_free_port()+ self._server_url = f"http://127.0.0.1:{port}"++ cmd = _server.build_launch_command(mlx_repo=mlx_repo, port=port)+ logger.info(+ "Starting MLX generation server for %s (repo=%s) on device=%s at port %d",+ self._model_name_or_path,+ self._mlx_repo,+ device,+ port,+ )+ logger.info("Loading model %s via MLX (first run downloads weights — this can take minutes)…", self._mlx_repo)++ self._output_file = _server.open_output_log()+ self._process = _server.launch_mlx_server(cmd, output_file=self._output_file)++ # One budget covers BOTH health-readiness and the model-load warmup below, so a+ # slow health bind can't let warmup tack on a second full timeout.+ budget = _server.resolve_startup_timeout(self._startup_timeout_s)+ started = time.monotonic()+ if not _server.wait_for_server(+ self._server_url,+ self._process,+ output_file=self._output_file,+ timeout_s=budget,+ ):+ self._abort_failed_load()+ raise RuntimeError(_server.ERR_SERVER_STARTUP)++ # mlx_lm.server answers /health as soon as httpd is up, possibly before the model+ # finishes loading. Warm it up with a 1-token request so the cold model load+ # completes inside load() (deterministic readiness) and the user's first real request+ # is fast. Use the REMAINING budget so wait+warmup stay within one timeout. A failed+ # warmup means the child bound the port but cannot serve the model, so treat it as a+ # load failure rather than reporting "ready" and handing the error to the first request.+ warmup_budget = max(30.0, budget - (time.monotonic() - started))+ if not _server.warmup_model(self._server_url, mlx_repo, timeout_s=warmup_budget):+ self._abort_failed_load()+ raise RuntimeError(_server.ERR_WARMUP_FAILED)++ logger.info("MLX generation server ready: %s at %s", self._model_name_or_path, self._server_url)++ def _abort_failed_load(self) -> None:+ """Tear down a partially-started child + reset state after a failed load.++ The registry does not call unload() on a failed load, so this mirrors unload():+ terminate the child, drop the temp log, and clear _server_url/_device so the adapter+ does not look "loaded" (_check_loaded() gates only on _server_url).+ """+ _server.terminate_process(self._process)+ self._process = None+ self._server_url = None+ self._device = None+ self._cleanup_output_log()++ def unload(self) -> None:+ if self._process is not None:+ logger.info("Shutting down MLX generation server for %s", self._model_name_or_path)+ _server.terminate_process(self._process)+ self._process = None+ self._server_url = None+ self._device = None+ self._cleanup_output_log()++ def _cleanup_output_log(self) -> None:+ """Close + delete the subprocess stdout/stderr log (best-effort, idempotent).++ Without this, one ``mlx_*.log`` (holding the child's HF download URLs) leaks+ into /tmp per load — unbounded under idle-eviction / hot-reload churn — and the+ open fd is held for the subprocess lifetime.+ """+ if self._output_file is not None:+ with contextlib.suppress(OSError):+ self._output_file.close()+ with contextlib.suppress(OSError):+ Path(self._output_file.name).unlink()+ self._output_file = None++ def memory_footprint(self) -> int:+ # The model lives in the MLX subprocess (Metal-direct), invisible to the+ # parent torch-MPS tracker; let the registry treat it as 0 like SGLang.+ return 0++ # -- Inference -----------------------------------------------------------++ def _check_loaded(self) -> None:+ if self._server_url is None:+ raise RuntimeError(ERR_NOT_LOADED)++ def _build_sampling_body(+ self,+ prompt: str,+ *,+ max_new_tokens: int,+ temperature: float,+ top_p: float,+ top_k: int | None,+ stop: list[str] | None,+ seed: int | None,+ ) -> dict[str, Any]:+ body: dict[str, Any] = {+ "model": self._mlx_repo,+ "prompt": prompt,+ "max_tokens": max_new_tokens,+ "temperature": temperature,+ "top_p": top_p,+ "stream": True,+ "stream_options": {"include_usage": True},+ }+ if top_k is not None:+ body["top_k"] = top_k+ if seed is not None:+ body["seed"] = seed+ stop_list = list(stop or [])+ stop_list.extend(s for s in self._stop_tokens if s not in stop_list)+ if stop_list:+ body["stop"] = stop_list+ # Merge model-config default sampling — but only keys mlx_lm.server supports+ # (drop presence_penalty / frequency_penalty etc. that the curated profile sets+ # for the CUDA path). Explicit request fields set above win (setdefault only+ # fills omitted keys).+ for key, value in self._default_sampling.items():+ if key in _MLX_SAMPLING_KEYS:+ body.setdefault(key, value)+ return body++ async def generate(+ self,+ prompt: str,+ *,+ max_new_tokens: int,+ temperature: float = 1.0,+ top_p: float = 1.0,+ stop: list[str] | None = None,+ frequency_penalty: float | None = None,+ presence_penalty: float | None = None,+ top_k: int | None = None,+ repetition_penalty: float | None = None,+ seed: int | None = None,+ logit_bias: dict[str, float] | None = None,+ logprobs: bool = False,+ top_logprobs: int | None = None,+ images: list[ImageInput] | None = None,+ **kwargs: Any, # tolerate SGLang-only kwargs (grammar, n, best_of, stream, …)+ ) -> AsyncIterator[GenerationChunk]:+ self._check_loaded()+ # Vision is deferred on the Mac MLX path (mlx-vlm would need its own+ # transformers>=5.5 process — see the implementation plan §9). Fail loud+ # rather than silently dropping the images and returning a wrong answer.+ if images:+ raise ValueError("vision input is not supported on the Mac MLX generation path yet (see plan §9)")+ # Unused on the MLX path today (kept to satisfy the streaming contract):+ # mlx_lm.server's /v1/completions does not expose these knobs uniformly.+ _ = (frequency_penalty, presence_penalty, repetition_penalty, logit_bias, logprobs, top_logprobs, kwargs)++ body = self._build_sampling_body(+ prompt,+ max_new_tokens=max_new_tokens,+ temperature=temperature,+ top_p=top_p,+ top_k=top_k,+ stop=stop,+ seed=seed,+ )++ finish_reason: FinishReason = "stop"+ prompt_tokens: int | None = None+ completion_tokens: int | None = None+ counted_completion = 0+ first_yield_done = False+ timeout = httpx.Timeout(+ connect=_CONNECT_TIMEOUT_S, read=_READ_TIMEOUT_S, write=_WRITE_TIMEOUT_S, pool=_POOL_TIMEOUT_S+ )++ # Serialize generations: mlx_lm.server is single-tenant, and the "drop the+ # iterator to stop" cancellation contract is only safe with one generation in+ # flight. The lock is held for the whole stream lifetime (released on+ # completion, cancellation, or error). The chat-completions proxy acquires the+ # same lock via generation_slot().+ async with self._gen_lock:+ async with (+ httpx.AsyncClient(timeout=timeout) as client,+ client.stream("POST", f"{self._server_url}/v1/completions", json=body) as response,+ ):+ if response.status_code != 200:+ preview = await response.aread()+ logger.error("MLX /v1/completions error %d: %s", response.status_code, preview[:500])+ response.raise_for_status()++ async for raw_line in response.aiter_lines():+ line = raw_line.strip()+ # Skip SSE comments (": keepalive N/M") and blanks.+ if not line or line.startswith(":"):+ continue+ if line.startswith("data:"):+ line = line[len("data:") :].strip()+ if not line or line == "[DONE]":+ continue+ try:+ event = json.loads(line)+ except json.JSONDecodeError:+ logger.warning("MLX stream: skipping non-JSON line: %s", line[:200])+ continue++ # Usage-only event (choices empty) carries the token counts; it+ # arrives after the terminal choice event.+ usage = event.get("usage")+ if isinstance(usage, dict):+ if isinstance(usage.get("prompt_tokens"), int):+ prompt_tokens = usage["prompt_tokens"]+ if isinstance(usage.get("completion_tokens"), int):+ completion_tokens = usage["completion_tokens"]++ choices = event.get("choices")+ if not choices:+ continue+ choice = choices[0]+ delta = choice.get("text") or ""+ fr = choice.get("finish_reason")+ if fr is not None:+ finish_reason = cast("FinishReason", fr if fr in _FINISH_REASONS else "stop")+ if delta:+ counted_completion += 1+ is_first = not first_yield_done+ first_yield_done = True+ yield GenerationChunk(text_delta=delta, done=False, is_first=is_first)++ # Single terminal chunk carrying finish_reason + usage. mlx_lm.server emits a+ # ``stream_options.include_usage`` usage event (the authoritative token count).+ # The fallback counts SSE delta CHUNKS, which approximates — but may undercount —+ # completion tokens if a future/older mlx-lm omits the usage event or batches+ # multiple tokens per chunk.+ yield GenerationChunk(+ text_delta="",+ done=True,+ finish_reason=finish_reason,+ prompt_tokens=prompt_tokens,+ completion_tokens=completion_tokens if completion_tokens is not None else counted_completion,+ )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__.pyindex 6bafccadd..b38d02448 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@@ -34,6 +34,7 @@ import numpy as npimport torchfrom sie_server.adapters._base_adapter import BaseAdapter+from sie_server.adapters._multivector import maxsim_scoresfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecisionfrom sie_server.adapters._vision_patch_embed import rebind_vision_patch_embed@@ -677,13 +678,8 @@ class NemoColEmbedAdapter(BaseAdapter):scores_matrix = self._model.get_scores([query_emb], doc_embs)return scores_matrix[0].cpu().tolist()- # Fallback: compute MaxSim manually- scores = []- for doc_emb in doc_embs:- sim = torch.matmul(query_emb, doc_emb.T)- maxsim_score = sim.max(dim=-1).values.sum().item()- scores.append(maxsim_score)- return scores+ # Fallback: compute MaxSim manually.+ return maxsim_scores(query_emb, doc_embs)def _validate_output_types(self, output_types: list[str]) -> None:"""Validate that output types are supported."""diff --git a/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.pyindex 50ea938df..56a5bea19 100644--- a/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/nomic_flash/__init__.py@@ -9,6 +9,7 @@ import torch.nn.functional as Ffrom torch import nnfrom sie_server.adapters._flash_base import FlashBaseAdapter+from sie_server.adapters._flash_pack import build_position_idsfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision, PoolingStrategyfrom sie_server.adapters._utils import apply_rotary_pos_emb, extract_texts, validate_output_types@@ -303,11 +304,7 @@ class NomicFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:"""Build position IDs for packed sequences (starting from 0 for each)."""- pos_list = []- for i in range(num_seqs):- seq_len = cu_seqlens[i + 1].item() - cu_seqlens[i].item()- pos_list.append(torch.arange(0, seq_len, device=self._device))- return torch.cat(pos_list)+ return build_position_ids(cu_seqlens)def _compute_rope(self, position_ids: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:"""Compute RoPE cos/sin values for packed positions.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__.pyindex 742235fa9..1d92efcc8 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@@ -88,7 +88,7 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):pooling: PoolingStrategy = "last_token",normalize: bool = True,max_seq_length: int = 8192,- compute_precision: ComputePrecision = "bfloat16",+ compute_precision: ComputePrecision | None = None,attn_implementation: AttnImplementation = "sdpa",trust_remote_code: bool = True,revision: str | None = None,@@ -109,7 +109,9 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):- "mean": Mean of all non-padding tokensnormalize: Whether to L2-normalize embeddings.max_seq_length: Maximum sequence length.- compute_precision: Compute precision (bfloat16 recommended for CUDA).+ compute_precision: Compute precision. None (default) selects fp32 off-CUDA+ (safe on MPS) and bfloat16 on CUDA; set explicitly to override (e.g.+ float16 to opt a curated model into fp16 on MPS).attn_implementation: Attention implementation. Default "sdpa".Use "flash_attention_2" only if inputs are consistently >512 tokens.Use "eager" for models that don't support SDPA (e.g., Stella).@@ -226,17 +228,25 @@ class PyTorchEmbeddingAdapter(PEFTLoRAMixin, BaseAdapter):Returns:Tuple of (torch.dtype, attention_implementation string)."""- # CPU should use FP32; respect explicit eager but default to SDPA- if not device.startswith("cuda"):- return torch.float32, self._attn_implementation if self._attn_implementation == "eager" else "sdpa"-# Map precision to dtypedtype_map = {"float16": torch.float16,"bfloat16": torch.bfloat16,"float32": torch.float32,}- dtype = dtype_map.get(self._compute_precision, torch.bfloat16)+ # Default fp32 off-CUDA (safe on CPU/MPS); honor an explicit compute_precision+ # everywhere so curated Mac models can opt into fp16 on MPS. CUDA keeps bf16.+ precision = self._compute_precision+ if precision is None:+ precision = "bfloat16" if device.startswith("cuda") else "float32"+ # NOTE: bf16 is coerced to fp16 on MPS at the loader (MPS bf16 is incomplete in+ # torch and can hang model load). See core/loader.load_adapter.+ dtype = dtype_map.get(precision, torch.float32)++ if not device.startswith("cuda"):+ # Off-CUDA: respect an explicit eager request but default to SDPA.+ attn = self._attn_implementation if self._attn_implementation == "eager" else "sdpa"+ return dtype, attn# Use configured attention implementation directlyreturn dtype, self._attn_implementationdiff --git a/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.pyindex de9d075e3..67492311c 100644--- a/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/qwen2_flash/__init__.py@@ -9,6 +9,7 @@ import torchfrom torch.nn import functionalfrom sie_server.adapters._flash_base import FlashBaseAdapter+from sie_server.adapters._flash_pack import build_position_idsfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision, PoolingStrategyfrom sie_server.adapters._utils import apply_rotary_pos_emb, extract_texts, validate_output_types@@ -314,18 +315,8 @@ class Qwen2FlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):)def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:- """Build position IDs for packed sequences.-- Each sequence has positions starting from 0. Fully vectorized- to avoid per-sequence .item() CUDA sync points.- """- total_tokens = cu_seqlens[-1].item()- positions = torch.arange(total_tokens, device=self._device)- seq_starts = torch.repeat_interleave(- cu_seqlens[:-1],- cu_seqlens[1:] - cu_seqlens[:-1],- )- return positions - seq_starts+ """Build position IDs for packed sequences (each restarts at 0)."""+ return build_position_ids(cu_seqlens)def _compute_rope(self,diff --git a/packages/sie_server/src/sie_server/adapters/sglang/_server.py b/packages/sie_server/src/sie_server/adapters/sglang/_server.pyindex 1697a89f5..0e651b077 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/_server.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/_server.py@@ -26,6 +26,8 @@ from pathlib import Pathimport requests+from sie_server.core.oom import is_oom_error+logger = logging.getLogger(__name__)# In-process record of ports already handed out by ``find_free_port`` but@@ -57,6 +59,8 @@ HEALTH_CHECK_INTERVAL_S = 2.0BASE_PORT = 30000 # Starting port for SGLang serversERR_SERVER_STARTUP = "SGLang server failed to start within timeout"+STARTUP_LOG_TAIL_CHARS = 5000+LOAD_HEADROOM_BYTES = 1024**3def _resolve_liveness_budget() -> float | None:@@ -251,18 +255,51 @@ def wait_for_server(def _log_subprocess_output(output_file: tempfile._TemporaryFileWrapper | None) -> None:+ output = read_subprocess_output_tail(output_file)+ if output:+ log_path = getattr(output_file, "name", "<unknown>")+ logger.error("SGLang subprocess output from %s:\n%s", log_path, output)+++def read_subprocess_output_tail(output_file: tempfile._TemporaryFileWrapper | None) -> str:if output_file is None:- return+ return ""try:output_file.flush()except Exception: # noqa: BLE001- return+ return ""try:- with Path(output_file.name).open() as f:+ with Path(output_file.name).open(encoding="utf-8", errors="replace") as f:output = f.read()- logger.error("SGLang subprocess output from %s:\n%s", output_file.name, output[-5000:])- except OSError as e:- logger.error("Failed to read SGLang log: %s", e)+ return output[-STARTUP_LOG_TAIL_CHARS:]+ except OSError as exc:+ return f"<failed to read SGLang log: {exc}>"+++def startup_failure_error(output_file: tempfile._TemporaryFileWrapper | None) -> RuntimeError:+ output = read_subprocess_output_tail(output_file).strip()+ if output:+ if is_oom_error(RuntimeError(output)):+ return RuntimeError(f"{ERR_SERVER_STARTUP}: out of memory detected in startup log")+ return RuntimeError(ERR_SERVER_STARTUP)+++def estimate_load_required_memory_bytes(+ *,+ device_type: str,+ device_total_bytes: int,+ mem_fraction_static: float,+) -> int | None:+ """Estimate free memory needed before launching a SGLang server."""+ if device_type != "cuda" or device_total_bytes <= 0:+ return None+ if isinstance(mem_fraction_static, bool) or not isinstance(mem_fraction_static, int | float):+ return None+ fraction = float(mem_fraction_static)+ if not 0.0 < fraction <= 1.0:+ return None+ required = int(device_total_bytes * fraction) + LOAD_HEADROOM_BYTES+ return min(required, device_total_bytes)def terminate_process(process: subprocess.Popen[bytes] | None) -> None:diff --git a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py b/packages/sie_server/src/sie_server/adapters/sglang/embedding.pyindex 84bb241cb..c4c8767bb 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py@@ -31,6 +31,7 @@ from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ERR_REQUIRES_TEXT, ComputePrecisionfrom sie_server.adapters.sglang import _serverfrom sie_server.core.inference_output import EncodeOutput+from sie_server.core.tokenizer import load_tokenizerif TYPE_CHECKING:from sie_server.types.inputs import Item@@ -86,6 +87,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):query_template: str | None = None,doc_template: str | None = None,default_instruction: str | None = None,+ append_eos: bool = False,pooling_method: str | None = None,lora_paths: dict[str, str] | None = None,max_loras_per_batch: int = 8,@@ -108,6 +110,16 @@ class SGLangEmbeddingAdapter(BaseAdapter):doc_template: Template for formatting documents. Use {text} placeholder.default_instruction: Default instruction when query_template uses{instruction} but none is provided.+ append_eos: When True, append the model's EOS token to every text+ sent to SGLang (after template formatting). Required for+ last-token-pooled LLM embedders whose tokenizer does NOT add an+ EOS automatically (e.g. the Mistral-family embedders+ e5-mistral-7b-instruct / SFR-Embedding / Linq-Embed-Mistral):+ without the trailing EOS, last-token pooling reads the wrong+ position and retrieval collapses (#1489). The EOS string is read+ from the model's own tokenizer at load time (see ``load``), so it+ is never hardcoded. Leave False for models SGLang already handles+ (e.g. Qwen3-Embedding).pooling_method: Pooling method for embeddings. Options: "cls", "lasttoken","max", "mean", "mean_sqrt_len_tokens", "weightedmean". If None, usesSGLang's default (usually lasttoken for LLM models).@@ -129,6 +141,8 @@ class SGLangEmbeddingAdapter(BaseAdapter):self._query_template = query_templateself._doc_template = doc_templateself._default_instruction = default_instruction+ self._append_eos = append_eos+ self._eos_token = "" # Resolved from the model tokenizer in load() when append_eosself._pooling_method = pooling_methodself._lora_paths = lora_paths or {}self._max_loras_per_batch = max_loras_per_batch@@ -167,6 +181,9 @@ class SGLangEmbeddingAdapter(BaseAdapter):"""self._device = device+ if self._append_eos:+ self._eos_token = self._resolve_eos_token()+device_index = _server.parse_device_index(device)port = _server.find_free_port()self._server_url = f"http://localhost:{port}"@@ -231,7 +248,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):):_server.terminate_process(self._process)self._process = None- raise RuntimeError(_server.ERR_SERVER_STARTUP)+ raise _server.startup_failure_error(self._output_file)logger.info("SGLang server ready: %s at %s",@@ -258,6 +275,14 @@ class SGLangEmbeddingAdapter(BaseAdapter):"""return 0+ def load_required_memory_bytes(self, *, device_type: str, device_total_bytes: int) -> int | None:+ """Return SGLang's startup reservation requirement for load staging."""+ return _server.estimate_load_required_memory_bytes(+ device_type=device_type,+ device_total_bytes=device_total_bytes,+ mem_fraction_static=self._mem_fraction_static,+ )+def encode(self,items: list[Item],@@ -411,6 +436,38 @@ class SGLangEmbeddingAdapter(BaseAdapter):msg = f"Unsupported output types: {unsupported}. SGLang adapter only supports 'dense'."raise ValueError(msg)+ def _resolve_eos_token(self) -> str:+ """Read the model's EOS token string from its own tokenizer.++ Reuses the shared ``core.tokenizer.load_tokenizer`` helper (the same path+ ``PyTorchEmbeddingAdapter`` uses) rather than hardcoding an EOS string, so+ the value always matches the served model. Only invoked when+ ``append_eos`` is set, so models that don't opt in never load a tokenizer+ in-process. A resolution failure degrades to "no EOS appended" (logged)+ rather than failing the whole model load.+ """+ try:+ tokenizer = load_tokenizer(self._model_name_or_path, trust_remote_code=self._trust_remote_code)+ except Exception: # noqa: BLE001 - tokenizer load must never take the model down+ logger.warning(+ "append_eos: could not load tokenizer for %s to resolve EOS; last-token pooling may be degraded",+ self._model_name_or_path,+ exc_info=True,+ )+ return ""++ eos = tokenizer.eos_token+ if not eos and tokenizer.eos_token_id is not None:+ eos = tokenizer.decode([tokenizer.eos_token_id]).strip()+ if not eos:+ logger.warning(+ "append_eos: model %s exposes no EOS token; last-token pooling may be degraded",+ self._model_name_or_path,+ )+ return ""+ logger.info("append_eos enabled for %s: appending EOS %r", self._model_name_or_path, eos)+ return eos+def _format_texts(self,items: list[Item],@@ -447,6 +504,13 @@ class SGLangEmbeddingAdapter(BaseAdapter):# Fallback: prepend instruction if provided but no templatetext = f"{instruction} {text}"+ # Append the model's EOS so last-token pooling reads the trained+ # summary position (queries and documents alike). Skip empty /+ # whitespace text so it still takes the zero-vector fallback in+ # encode() instead of becoming an EOS-only input.+ if self._append_eos and self._eos_token and text.strip():+ text = f"{text}{self._eos_token}"+texts.append(text)return textsdiff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex c0250facc..a05eb42c2 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -166,6 +166,37 @@ def _tail_file(path: str, *, max_lines: int = 200) -> str:return "".join(lines[-max_lines:])+# Kwargs the MLX adapter understands. The non-CUDA swap (``create_for_device``)+# projects the SGLang constructor kwargs onto this set and DROPS everything else+# — the CUDA/SGLang-only flags (mem_fraction_static, speculative, attention_backend,+# grammar_backend, reasoning_parser, tool_call_parser, lora_paths, disable_cuda_graph,+# extra_launch_args, extra_env, guard, compute_precision, …) that the MLX backend+# has no concept of.+_MLX_PASSTHROUGH_KWARGS = frozenset(+ {+ "model_name_or_path",+ "mlx_repo",+ "max_seq_length",+ "default_sampling",+ "stop_tokens",+ "served_model_name",+ "trust_remote_code",+ "startup_timeout_s",+ }+)+++def _translate_to_mlx_kwargs(kwargs: dict[str, Any]) -> dict[str, Any]:+ """Project SGLang adapter kwargs onto the MLX adapter's constructor.++ Keeps only the engine-agnostic knobs the MLX backend uses; drops the+ CUDA/SGLang-only flags (which the MLX adapter would otherwise silently+ swallow via ``**kwargs``). ``mlx_repo`` comes from the model YAML's+ ``adapter_options.loadtime`` and selects the MLX-quantized repo to serve.+ """+ return {k: v for k, v in kwargs.items() if k in _MLX_PASSTHROUGH_KWARGS}++class SGLangGenerationAdapter(GenerationAdapter):"""Streaming SGLang generation adapter.@@ -345,6 +376,27 @@ class SGLangGenerationAdapter(GenerationAdapter):# -- Lifecycle -----------------------------------------------------------+ @classmethod+ def create_for_device(cls, device: str, **kwargs: Any) -> GenerationAdapter:+ """Device-aware factory: SGLang on CUDA, MLX (Apple Silicon) elsewhere.++ SGLang is CUDA-only, so on a non-CUDA device (a Mac's ``mps``/``cpu``)+ the generation path is served by the MLX subprocess adapter instead.+ Unsuffixed generation models therefore "just work" on a Mac without+ ``:mac`` profile variants. Importing this module on a Mac is safe —+ ``sglang`` is only ever invoked as a subprocess, never imported at+ module top level — so this swap runs without sglang installed.+ """+ if device.startswith("cuda"):+ return cls(**kwargs)+ from sie_server.adapters.mlx.generation import MLXGenerationAdapter++ logger.info(+ "Non-CUDA device %r: serving generation via the MLX (Apple-Silicon) backend instead of SGLang",+ device,+ )+ return MLXGenerationAdapter(**_translate_to_mlx_kwargs(kwargs))+def load(self, device: str) -> None:self._device = devicedevice_index = _server.parse_device_index(device)@@ -466,7 +518,7 @@ class SGLangGenerationAdapter(GenerationAdapter):logger.error("SGLang startup log tail:\n%s", _tail_file(str(log_path)))_server.terminate_process(self._process)self._process = None- raise RuntimeError(_server.ERR_SERVER_STARTUP)+ raise _server.startup_failure_error(self._output_file)# Best-effort runtime verification that the# ``--grammar-backend`` flag actually took effect. SGLang's@@ -779,6 +831,14 @@ class SGLangGenerationAdapter(GenerationAdapter):# SGLang pre-allocates in the subprocess; let the registry measure GPU.return 0+ def load_required_memory_bytes(self, *, device_type: str, device_total_bytes: int) -> int | None:+ """Return SGLang's startup reservation requirement for load staging."""+ return _server.estimate_load_required_memory_bytes(+ device_type=device_type,+ device_total_bytes=device_total_bytes,+ mem_fraction_static=self._mem_fraction_static,+ )+# -- Inference -----------------------------------------------------------def _check_loaded(self) -> None:diff --git a/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.py b/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.pyindex 0c426754c..0f73773f9 100644--- a/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/xlm_roberta_flash/__init__.py@@ -10,6 +10,7 @@ import torchfrom torch.nn import functionalfrom sie_server.adapters._flash_base import FlashBaseAdapter+from sie_server.adapters._flash_pack import build_position_idsfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision, PoolingStrategyfrom sie_server.adapters._utils import extract_texts, validate_output_types@@ -233,23 +234,8 @@ class XLMRobertaFlashAdapter(PEFTLoRAMixin, FlashBaseAdapter):)def _build_position_ids(self, cu_seqlens: torch.Tensor, num_seqs: int) -> torch.Tensor:- """Build XLMRoberta-style position IDs for packed sequences.-- XLMRoberta uses position IDs starting at padding_idx + 1, not 0.- This is critical for matching the padded model's output.- """- pos_list = []- for i in range(num_seqs):- seq_len = cu_seqlens[i + 1].item() - cu_seqlens[i].item()- # XLMRoberta positions: [padding_idx+1, padding_idx+2, ..., padding_idx+seq_len]- pos_list.append(- torch.arange(- self._padding_idx + 1,- self._padding_idx + 1 + seq_len,- device=self._device,- )- )- return torch.cat(pos_list)+ """Build XLMRoberta-style position IDs (each restarts at padding_idx + 1)."""+ return build_position_ids(cu_seqlens, offset=self._padding_idx + 1)def _run_embeddings(self, input_ids: torch.Tensor, position_ids: torch.Tensor) -> torch.Tensor:"""Compute embeddings for packed input."""diff --git a/packages/sie_server/src/sie_server/api/generate.py b/packages/sie_server/src/sie_server/api/generate.pyindex 7a7ea08e4..a11821080 100644--- a/packages/sie_server/src/sie_server/api/generate.py+++ b/packages/sie_server/src/sie_server/api/generate.py@@ -42,10 +42,13 @@ import jsonimport loggingimport mathimport os+import time+import uuid+from collections.abc import AsyncIteratorfrom typing import Annotated, Anyfrom fastapi import APIRouter, Header, HTTPException, Request, status-from fastapi.responses import JSONResponse+from fastapi.responses import JSONResponse, StreamingResponsefrom sie_sdk.queue_types import denormalize_model_idfrom sie_server.adapters._generation_base import GenerationAdapter, collect_generation@@ -94,6 +97,7 @@ _SUPPORTED_FIELDS = {"temperature","top_p","stop",+ "stream","grammar","frequency_penalty","presence_penalty",@@ -295,6 +299,99 @@ def _payload_too_large(message: str, *, param: str | None = None) -> HTTPExceptireturn HTTPException(status_code=status.HTTP_413_CONTENT_TOO_LARGE, detail=detail)+async def _stream_generate_events(+ adapter: GenerationAdapter,+ *,+ prompt: str,+ max_new_tokens: int,+ temperature: float,+ top_p: float,+ stop: list[str] | None,+ seed: int | None,+ logit_bias: dict[str, float] | None,+) -> AsyncIterator[str]:+ """Yield SIE-native ``GenerateChunk`` SSE lines for ``SIEClient.stream_generate``.++ Wire shape mirrors the gateway's ``build_generate_chunk_event``+ (``sie_gateway/src/handlers/sse.rs``) and the ``GenerateChunk`` TypedDict in+ ``sie_sdk.types``: incremental ``text_delta`` chunks, a terminal ``done:+ true`` chunk carrying ``finish_reason`` / ``usage`` / ``ttft_ms``, then the+ literal ``[DONE]`` terminator the SDK's SSE reader honours. A mid-stream+ failure is surfaced as a terminal chunk with ``finish_reason: "error"`` ++ ``error`` so the SDK raises ``ServerError`` instead of truncating silently.+ """+ request_id = uuid.uuid4().hex+ seq = 0+ t0 = time.perf_counter()+ ttft_ms: float | None = None+ finish_reason = "stop"+ prompt_tokens = 0+ completion_tokens = 0+ try:+ async for chunk in adapter.generate(+ prompt=prompt,+ max_new_tokens=max_new_tokens,+ temperature=temperature,+ top_p=top_p,+ stop=stop,+ seed=seed,+ logit_bias=logit_bias,+ ):+ if chunk.done:+ finish_reason = chunk.finish_reason or "stop"+ if chunk.prompt_tokens is not None:+ prompt_tokens = chunk.prompt_tokens+ if chunk.completion_tokens is not None:+ completion_tokens = chunk.completion_tokens+ # The contract allows a terminal chunk to also carry final text; emit it as a+ # delta so it isn't dropped (MLX's terminal text is always empty, but SGLang+ # and future adapters may pack final tokens here).+ if chunk.text_delta:+ if ttft_ms is None:+ ttft_ms = (time.perf_counter() - t0) * 1000.0+ yield f"data: {json.dumps({'request_id': request_id, 'seq': seq, 'text_delta': chunk.text_delta})}\n\n"+ seq += 1+ continue+ if chunk.text_delta:+ if ttft_ms is None:+ ttft_ms = (time.perf_counter() - t0) * 1000.0+ event = {"request_id": request_id, "seq": seq, "text_delta": chunk.text_delta}+ seq += 1+ yield f"data: {json.dumps(event)}\n\n"+ except Exception: # noqa: BLE001 — surface as a terminal error chunk, never 500 mid-stream+ logger.warning("stream_generate failed mid-stream", exc_info=True)+ err = {+ "request_id": request_id,+ "seq": seq,+ "text_delta": "",+ "done": True,+ "finish_reason": "error",+ # Generic client message — the exception detail is logged server-side+ # (above, with exc_info) and must not leak to the client (CodeQL).+ "error": {"code": "inference_error", "message": "internal error during generation"},+ }+ yield f"data: {json.dumps(err)}\n\n"+ yield "data: [DONE]\n\n"+ return++ terminal: dict[str, Any] = {+ "request_id": request_id,+ "seq": seq,+ "text_delta": "",+ "done": True,+ "finish_reason": finish_reason,+ "usage": {+ "prompt_tokens": prompt_tokens,+ "completion_tokens": completion_tokens,+ "total_tokens": prompt_tokens + completion_tokens,+ },+ }+ if ttft_ms is not None:+ terminal["ttft_ms"] = ttft_ms+ yield f"data: {json.dumps(terminal)}\n\n"+ yield "data: [DONE]\n\n"++@router.post("/generate/{model:path}",response_model=None,@@ -309,7 +406,7 @@ async def generate(model: str,http_request: Request,x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,-) -> JSONResponse:+) -> JSONResponse | StreamingResponse:"""Generate text from a prompt using the named model.The ``model`` path segment uses the **SIE-safe** id (double-underscore@@ -410,6 +507,7 @@ async def generate()adapter = registry.get(registry_key)+ registry.touch_lru(registry_key)if not isinstance(adapter, GenerationAdapter):raise _bad_request(f"Model '{model}' adapter does not support generate (not a GenerationAdapter)",@@ -440,7 +538,7 @@ async def generate(# the same here.if stop_raw is not None and any(s == "" for s in stop_raw):raise _bad_request("'stop' must not contain empty strings", param="stop")- stop = list(stop_raw) if stop_raw else None+ stop = [str(s) for s in stop_raw] if stop_raw else None# ``frequency_penalty`` / ``presence_penalty`` / ``grammar`` are# whitelisted (so a schema-compliant body still 200s) but the@@ -463,6 +561,27 @@ async def generate(logit_bias = _validate_logit_bias(body.get("logit_bias"))_validate_logprobs(body.get("logprobs"), body.get("top_logprobs"))+ # Streaming path: emit SIE-native GenerateChunk SSE (drives+ # SIEClient.stream_generate). The blocking JSON path below is unchanged.+ stream_raw = body.get("stream", False)+ if stream_raw is not None and not isinstance(stream_raw, bool):+ raise _bad_request("'stream' must be a boolean", param="stream")+ if stream_raw:+ return StreamingResponse(+ _stream_generate_events(+ adapter,+ prompt=prompt,+ max_new_tokens=max_new_tokens,+ temperature=temperature,+ top_p=top_p,+ stop=stop,+ seed=seed,+ logit_bias=logit_bias,+ ),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ )+try:# ``adapter.generate`` is an async iterator. The# local-dev route keeps the walking-skeleton's blocking response shapediff --git a/packages/sie_server/src/sie_server/api/openai_compat.py b/packages/sie_server/src/sie_server/api/openai_compat.pyindex 6859e377d..5e6312010 100644--- a/packages/sie_server/src/sie_server/api/openai_compat.py+++ b/packages/sie_server/src/sie_server/api/openai_compat.py@@ -21,13 +21,15 @@ import numpy as npfrom fastapi import APIRouter, Header, HTTPException, Request, statusfrom pydantic import BaseModel, ConfigDict, Field-from sie_server.api.helpers import extract_request_context+from sie_server.api.helpers import extract_request_context, oom_retry_after_from_registryfrom sie_server.api.validation import validate_machine_profile_headerfrom sie_server.core.encode_pipeline import EncodePipeline+from sie_server.core.oom import is_oom_errorfrom sie_server.core.worker import QueueFullErrorfrom sie_server.observability.metrics import record_requestfrom sie_server.observability.tracing import tracerfrom sie_server.types.inputs import Item+from sie_server.types.responses import ErrorCodelogger = logging.getLogger(__name__)@@ -415,6 +417,33 @@ async def create_embeddings(},) from eexcept Exception as e:+ if is_oom_error(e):+ # Transient memory pressure (worker ResourceExhaustedError after+ # recovery is exhausted, or a raw CUDA/MPS OOM). Mirror the+ # native endpoints' 503 RESOURCE_EXHAUSTED + Retry-After — in the+ # OpenAI envelope — so the SDK auto-retries instead of treating+ # it as a terminal 500. See #1604.+ logger.warning("Embeddings OOM for model %s, returning 503 RESOURCE_EXHAUSTED: %s", model, e)+ span.set_attribute("error", "resource_exhausted")+ record_request(+ model=model,+ endpoint="embeddings",+ status="error",+ request_id=ctx.request_id,+ api_key=ctx.api_key,+ queue_depth=ctx.queue_depth,+ )+ raise HTTPException(+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,+ detail={+ "error": {+ "code": ErrorCode.RESOURCE_EXHAUSTED.value,+ "message": f"Embeddings temporarily unavailable due to resource pressure: {e}",+ "type": "server_error",+ }+ },+ headers={"Retry-After": str(oom_retry_after_from_registry(registry))},+ ) from elogger.exception("Inference error for model %s", model)span.set_attribute("error", "inference_error")record_request(diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pynew file mode 100644index 000000000..bf25b830b--- /dev/null+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -0,0 +1,352 @@+"""Mac-local OpenAI-compatible surfaces: ``/v1/chat/completions`` + ``/v1/rerank``.++These complete the local OpenAI surface for Apple-Silicon serving (alongside the+existing ``/v1/embeddings``), so any OpenAI/Cohere client or tool can hit the+local endpoint.++- ``/v1/chat/completions`` proxies the managed MLX generation subprocess+ (``mlx_lm.server``). Chat templating, streaming, and structured output come+ free from the child; we just resolve the model, ensure it is loaded, and+ stream-proxy. Only available where generation runs via MLX (Apple Silicon) —+ elsewhere it returns 501 (the production ingress is the Rust gateway).+- ``/v1/rerank`` wraps the in-process score adapter in the Cohere/OpenAI rerank+ shape (``{query, documents, top_n}`` -> ``{results: [{index, relevance_score}]}``).++These routes are mounted on the worker's own FastAPI app and are a local-dev /+single-node convenience, mirroring the existing direct ``/v1/generate`` and+``/v1/embeddings`` routes — no traffic reaches them in a real cluster.+"""++from __future__ import annotations++import json+import logging+import os+from typing import Annotated, Any++import httpx+from fastapi import APIRouter, Header, HTTPException, Request, status+from fastapi.responses import JSONResponse, Response, StreamingResponse+from sie_sdk.queue_types import denormalize_model_id++from sie_server.adapters.mlx.generation import MLXGenerationAdapter+from sie_server.api.helpers import ModelStateChecker+from sie_server.api.options import resolve_runtime_options+from sie_server.api.validation import validate_machine_profile_header+from sie_server.core.inference_output import ScoreOutput+from sie_server.core.score_cost import build_score_prepared_items+from sie_server.core.timing import RequestTiming+from sie_server.observability.tracing import tracer+from sie_server.types.inputs import Item+from sie_server.types.responses import ErrorCode++logger = logging.getLogger(__name__)++router = APIRouter(prefix="/v1", tags=["openai-compat"])++# Inter-chunk read timeout — bounded so a wedged child can't hang the request forever+# (this proxy is the direct ingress on Mac; there is no worker/abort layer behind it).+# Override via SIE_MLX_READ_TIMEOUT_S. Connect/write/pool stay short.+_PROXY_READ_TIMEOUT_S = float(os.environ.get("SIE_MLX_READ_TIMEOUT_S", "300"))+_PROXY_TIMEOUT = httpx.Timeout(connect=10.0, read=_PROXY_READ_TIMEOUT_S, write=10.0, pool=10.0)+# Cap the request body so a huge messages/documents array can't be buffered/forwarded+# unbounded (the gateway caps prod ingress; these local routes must cap themselves).+_MAX_BODY_BYTES = int(os.environ.get("SIE_CHAT_MAX_BODY_BYTES", str(8 * 1024 * 1024)))+# Ceiling on rerank candidates so a single request can't push an unbounded batch+# through the score worker.+_MAX_RERANK_DOCS = int(os.environ.get("SIE_RERANK_MAX_DOCS", "1000"))+++def _bad_request(message: str, *, param: str | None = None, code: str | None = None) -> HTTPException:+ detail: dict[str, Any] = {"code": code or ErrorCode.INVALID_INPUT.value, "message": message}+ if param is not None:+ detail["param"] = param+ return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=detail)+++async def _read_json_body(http_request: Request) -> dict[str, Any]:+ """Size-cap + parse the request body as a JSON object.++ These routes are direct local ingress (no gateway in front), so they bound the+ buffered body themselves: reject early on Content-Length, then on the real read.+ """+ clen = http_request.headers.get("content-length")+ if clen is not None and clen.isdigit() and int(clen) > _MAX_BODY_BYTES:+ raise HTTPException(+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,+ detail={"code": ErrorCode.INPUT_TOO_LONG.value, "message": "request body too large"},+ )+ raw = await http_request.body()+ if len(raw) > _MAX_BODY_BYTES:+ raise HTTPException(+ status_code=status.HTTP_413_CONTENT_TOO_LARGE,+ detail={"code": ErrorCode.INPUT_TOO_LONG.value, "message": "request body too large"},+ )+ try:+ body = json.loads(raw)+ except (ValueError, TypeError) as exc:+ raise _bad_request("request body must be a JSON object") from exc+ if not isinstance(body, dict):+ raise _bad_request("request body must be a JSON object")+ return body+++def _unsupported_chat(model: str) -> HTTPException:+ return HTTPException(+ status_code=status.HTTP_501_NOT_IMPLEMENTED,+ detail={+ "code": "unsupported_operation",+ "message": (+ f"/v1/chat/completions for '{model}' is only served by the local MLX "+ "generation backend (Apple Silicon). Use the Rust gateway in a cluster."+ ),+ },+ )+++# -- /v1/chat/completions (proxy to the MLX subprocess) ----------------------++[email protected]("/chat/completions", response_model=None)+async def chat_completions(+ http_request: Request,+ x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,+) -> Response | StreamingResponse:+ """OpenAI-compatible chat completions, proxied to the local MLX subprocess.++ Resolves the requested model, ensures it is loaded, then forwards the body+ to the child ``mlx_lm.server``'s ``/v1/chat/completions`` (rewriting the+ ``model`` field to the child's served MLX repo so it does not try to hot-swap+ models). Supports both streaming (SSE pass-through) and non-streaming.+ """+ validate_machine_profile_header(x_machine_profile)++ body = await _read_json_body(http_request)++ model = body.get("model")+ if not isinstance(model, str) or not model:+ raise _bad_request("'model' must be a non-empty string", param="model")+ if not isinstance(body.get("messages"), list) or not body["messages"]:+ raise _bad_request("'messages' must be a non-empty array", param="messages")+ # Validate the fields this route interprets locally (the rest pass through to+ # mlx_lm.server, which validates them) — reject rather than coerce, matching the gateway+ # parser. `bool("false")` is True, so an unvalidated `stream` would silently stream; an+ # invalid `max_tokens` must 400 rather than be silently clamped to the model cap.+ stream_opt = body.get("stream")+ if stream_opt is not None and not isinstance(stream_opt, bool):+ raise _bad_request("'stream' must be a boolean", param="stream")+ max_tokens_opt = body.get("max_tokens")+ if max_tokens_opt is not None and (+ isinstance(max_tokens_opt, bool) or not isinstance(max_tokens_opt, int) or max_tokens_opt <= 0+ ):+ raise _bad_request("'max_tokens' must be a positive integer", param="max_tokens")++ registry = http_request.app.state.registry+ device = registry.device+ registry_key = denormalize_model_id(model)++ with tracer.start_as_current_span("chat_completions") as span:+ span.set_attribute("model", model)+ checker = ModelStateChecker(registry, registry_key, span)+ checker.check_exists()++ # Validate generation capability + backend BEFORE loading: a chat request for an+ # embedding/reranker model (or on a non-MLX/CUDA device) must fail fast instead of+ # kicking off a real model load/download that only 501s afterwards. Mirrors the+ # rerank route's tasks.score gate.+ config = registry.get_config(registry_key)+ gen_task = getattr(config.tasks, "generate", None)+ if gen_task is None:+ raise _bad_request(+ f"Model '{model}' does not support generation (no generate task). Use a generation model."+ )+ if str(device).startswith("cuda"):+ raise _unsupported_chat(model)++ checker.check_not_failed()+ checker.check_not_unloading()+ checker.check_not_loading()+ await checker.ensure_loaded(device)++ adapter = registry.get(registry_key)+ server_url = getattr(adapter, "server_url", None)+ if not isinstance(adapter, MLXGenerationAdapter) or server_url is None:+ # Defensive backstop — the capability/device gates above catch the common cases.+ raise _unsupported_chat(model)++ # Rewrite the model to the child's served repo so mlx_lm.server does not attempt to+ # load a different model per request, and clamp max_tokens to the model's output cap+ # so a huge value can't drive an unbounded generation / OOM (gen_task is non-None here).+ proxied = dict(body)+ proxied["model"] = adapter.mlx_repo+ cap = gen_task.max_output_tokens+ # max_tokens_opt is a positive int or None (validated above). Make the per-model cap+ # authoritative: clamp a valid value, and fill the cap in when omitted so the child's+ # own (large) default can't bypass it.+ proxied["max_tokens"] = min(max_tokens_opt, cap) if max_tokens_opt is not None else cap+ url = f"{server_url}/v1/chat/completions"+ stream = bool(stream_opt) # validated above (bool or None)+ # Single-flight: the child is single-tenant; serialize with /v1/generate.+ slot = adapter.generation_slot()++ if stream:++ async def _proxy_sse() -> Any:+ async with slot:+ try:+ async with (+ httpx.AsyncClient(timeout=_PROXY_TIMEOUT) as client,+ client.stream("POST", url, json=proxied) as resp,+ ):+ if resp.status_code != status.HTTP_200_OK:+ # The 200 text/event-stream status is already committed, so+ # surface the child error as a terminal SSE event. Do NOT call+ # aiter_raw() after aread() (raises httpx.StreamConsumed).+ preview = (await resp.aread())[:500]+ logger.error("MLX chat proxy error %d: %s", resp.status_code, preview)+ err = json.dumps(+ {+ "error": {+ "code": "upstream_error",+ "message": preview.decode("utf-8", "replace"),+ "status": resp.status_code,+ }+ }+ )+ yield f"data: {err}\n\n".encode()+ yield b"data: [DONE]\n\n"+ return+ async for chunk in resp.aiter_raw():+ yield chunk+ except httpx.HTTPError as exc:+ # Child died / connection reset mid-stream — emit a terminal error+ # event so the client doesn't get a silently-truncated body.+ logger.warning("MLX chat proxy stream error: %s", exc)+ # Generic client message — detail is logged above; don't leak+ # the exception text to the client (CodeQL info-exposure).+ err = json.dumps({"error": {"code": "upstream_error", "message": "upstream stream error"}})+ yield f"data: {err}\n\n".encode()+ yield b"data: [DONE]\n\n"++ return StreamingResponse(+ _proxy_sse(),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},+ )++ async with slot, httpx.AsyncClient(timeout=_PROXY_TIMEOUT) as client:+ resp = await client.post(url, json=proxied)+ return Response(+ content=resp.content,+ status_code=resp.status_code,+ media_type=resp.headers.get("content-type", "application/json"),+ )+++# -- /v1/rerank (Cohere/OpenAI shape over the score adapter) -----------------++[email protected]("/rerank", response_model=None)+async def rerank(+ http_request: Request,+ x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,+) -> JSONResponse:+ """Cohere/OpenAI-style reranking backed by the in-process score adapter.++ Request: ``{model, query, documents: [str], top_n?, return_documents?}``.+ Response: ``{model, results: [{index, relevance_score, document?}], usage}``+ sorted by descending relevance.+ """+ validate_machine_profile_header(x_machine_profile)++ body = await _read_json_body(http_request)++ model = body.get("model")+ if not isinstance(model, str) or not model:+ raise _bad_request("'model' must be a non-empty string", param="model")+ query = body.get("query")+ if not isinstance(query, str) or not query:+ raise _bad_request("'query' must be a non-empty string", param="query")+ documents = body.get("documents")+ if not isinstance(documents, list) or not documents or not all(isinstance(d, str) for d in documents):+ raise _bad_request("'documents' must be a non-empty array of strings", param="documents")+ if len(documents) > _MAX_RERANK_DOCS:+ raise _bad_request(f"'documents' exceeds the maximum of {_MAX_RERANK_DOCS} per request", param="documents")+ top_n = body.get("top_n")+ if top_n is not None and (isinstance(top_n, bool) or not isinstance(top_n, int) or top_n <= 0):+ raise _bad_request("'top_n' must be a positive integer", param="top_n")+ return_documents = body.get("return_documents", False)+ if not isinstance(return_documents, bool):+ raise _bad_request("'return_documents' must be a boolean", param="return_documents")++ registry = http_request.app.state.registry+ device = registry.device+ registry_key = denormalize_model_id(model)++ with tracer.start_as_current_span("rerank") as span:+ span.set_attribute("model", model)+ span.set_attribute("batch_size", len(documents))+ checker = ModelStateChecker(registry, registry_key, span)+ checker.check_exists()++ config = registry.get_config(registry_key)+ if config.tasks.score is None:+ raise _bad_request(+ f"Model '{model}' does not support reranking (no score task). Use a reranker model.",+ )++ checker.check_not_failed()+ checker.check_not_unloading()+ checker.check_not_loading()+ await checker.ensure_loaded(device)++ query_item = Item(text=query)+ doc_items = [Item(id=str(i), text=str(doc)) for i, doc in enumerate(documents)]+ options_raw = body.get("options")+ if options_raw is not None and not isinstance(options_raw, dict):+ raise _bad_request("'options' must be an object", param="options")+ options = resolve_runtime_options(config, options_raw, span)+ instruction = options.get("instruction")++ timing = RequestTiming()+ timing.start_tokenization()+ prepared_items = build_score_prepared_items(query_item, doc_items)+ timing.end_tokenization()+ worker = await registry.start_worker(registry_key)+ future = await worker.submit_score(+ prepared_items=prepared_items,+ query=query_item,+ items=doc_items,+ instruction=instruction,+ options=options,+ timing=timing,+ )+ try:+ worker_result = await future+ except Exception as exc:+ logger.warning("rerank failed for %s", model, exc_info=True)+ raise HTTPException(+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,+ detail={"code": "inference_error", "message": str(exc)},+ ) from exc++ score_output: ScoreOutput = worker_result.output+ scores = [float(score_output.scores[i]) for i in range(score_output.batch_size)]++ ranked = sorted(enumerate(scores), key=lambda pair: pair[1], reverse=True)+ if top_n is not None:+ ranked = ranked[:top_n]+ results: list[dict[str, Any]] = []+ for index, score in ranked:+ entry: dict[str, Any] = {"index": index, "relevance_score": score}+ if return_documents:+ entry["document"] = {"text": documents[index]}+ results.append(entry)++ return JSONResponse(+ content={+ "model": getattr(config, "name", None) or registry_key,+ "results": results,+ "usage": {"total_tokens": sum(len(d) // 4 + 1 for d in documents)},+ }+ )diff --git a/packages/sie_server/src/sie_server/api/options.py b/packages/sie_server/src/sie_server/api/options.pyindex 4a0a0e1b1..4ee4fc32e 100644--- a/packages/sie_server/src/sie_server/api/options.py+++ b/packages/sie_server/src/sie_server/api/options.py@@ -3,6 +3,7 @@ from typing import Anyfrom fastapi import HTTPException, statusfrom sie_server.config.model import ModelConfig+from sie_server.core.runtime_options import merge_runtime_optionsfrom sie_server.types.overflow_policy import VALID_OVERFLOW_POLICIESfrom sie_server.types.responses import ErrorCode@@ -29,10 +30,10 @@ def resolve_runtime_options(Raises:HTTPException: 400 if profile name is invalid."""- profile_name = request_options.get("profile") if request_options else None-+ # Shared with the cluster queue worker (queue_executor) so both ingress+ # paths produce the same effective options; see core.runtime_options.try:- resolved = config.resolve_profile(profile_name or "default")+ merged = merge_runtime_options(config, request_options)except ValueError as e:span.set_attribute("error", "invalid_profile")raise HTTPException(@@ -43,13 +44,6 @@ def resolve_runtime_options(},) from e- # Start with profile runtime options- merged = dict(resolved.runtime)-- # Merge request-level overrides (excluding the "profile" key itself)- if request_options:- merged |= {k: v for k, v in request_options.items() if k != "profile"}-overflow_policy = merged.get("overflow_policy")if overflow_policy is not None and overflow_policy not in VALID_OVERFLOW_POLICIES:span.set_attribute("error", "invalid_overflow_policy")diff --git a/packages/sie_server/src/sie_server/api/ws.py b/packages/sie_server/src/sie_server/api/ws.pyindex c4db6d017..4c043b849 100644--- a/packages/sie_server/src/sie_server/api/ws.py+++ b/packages/sie_server/src/sie_server/api/ws.py@@ -4,14 +4,15 @@ import asyncioimport functoolsimport getpassimport hashlib-import jsonimport loggingimport osimport timeimport weakref+from collections.abc import Mappingfrom pathlib import Path-from typing import TYPE_CHECKING, Any, Protocol+from typing import TYPE_CHECKING, Any, Protocol, cast+import orjsonimport yamlfrom fastapi import APIRouter, WebSocket, WebSocketDisconnectfrom sie_sdk.types import (@@ -25,7 +26,6 @@ from sie_sdk.types import (ModelConfig as SDKModelConfig,)-from sie_server.config.model import ModelConfig as ServerModelConfigfrom sie_server.core.batcher import BatchConfigfrom sie_server.core.gpu_health import gpu_is_healthy_asyncfrom sie_server.core.readiness import is_ready@@ -33,10 +33,11 @@ from sie_server.observability.gpu import get_gpu_metricsfrom sie_server.observability.prometheus import collect_prometheus_metricsif TYPE_CHECKING:+ from sie_server.config.model import ModelConfig as ServerModelConfigfrom sie_server.core.registry import ModelRegistry-class StatusPullLoop(Protocol):+class StatusQueueRuntime(Protocol):worker_id: strdef update_saturation(self) -> bool:@@ -194,67 +195,108 @@ def _bundle_adapter_modules(bundle_id: str) -> frozenset[str]:return frozenset(str(adapter) for adapter in adapters if adapter)-def _is_hash_falsy(value: object) -> bool:- if value is None:- return True- if value is False:- return True- if isinstance(value, int | float) and value == 0:- return True- return isinstance(value, str | list | tuple | dict) and len(value) == 0+def _adapter_module(adapter_path: str | None) -> str | None:+ if not adapter_path:+ return None+ return adapter_path.split(":", maxsplit=1)[0]-def _canonical_adapter_options_for_hash(adapter_options: dict[str, Any] | None) -> dict[str, Any] | None:- if isinstance(adapter_options, dict) and not any(not _is_hash_falsy(value) for value in adapter_options.values()):- return None- return adapter_options+def _profile_value(profile: object, field: str, default: Any = None) -> Any:+ if isinstance(profile, dict):+ return cast("dict[str, Any]", profile).get(field, default)+ return getattr(profile, field, default)-def _profile_adapter_options_for_hash(profile: Any) -> dict[str, Any] | None:- if "adapter_options" not in getattr(profile, "model_fields_set", set()):- return None- adapter_options = profile.adapter_options- option_fields = getattr(adapter_options, "model_fields_set", set())- raw: dict[str, Any] = {}- if "loadtime" in option_fields:- raw["loadtime"] = dict(adapter_options.loadtime)- if "runtime" in option_fields:- raw["runtime"] = dict(adapter_options.runtime)- return _canonical_adapter_options_for_hash(raw)---def _resolved_profile_for_hash(config: ServerModelConfig, profile_name: str) -> dict[str, Any]:- def resolve(name: str, seen: set[str]) -> dict[str, Any]:- if name in seen:- msg = f"Profile '{name}' has an inheritance cycle"- raise ValueError(msg)- seen.add(name)+def _copy_mapping(value: object) -> dict[str, Any]:+ if isinstance(value, Mapping):+ return {str(key): item for key, item in cast("Mapping[object, Any]", value).items()}+ return {}+++def _profile_adapter_options_parts(profile: object) -> tuple[dict[str, Any], dict[str, Any]]:+ adapter_options = _profile_value(profile, "adapter_options")+ if adapter_options is None:+ return {}, {}+ if isinstance(adapter_options, dict):+ options = cast("dict[str, Any]", adapter_options)+ return (+ _copy_mapping(options.get("loadtime")),+ _copy_mapping(options.get("runtime")),+ )+ return (+ _copy_mapping(getattr(adapter_options, "loadtime", None)),+ _copy_mapping(getattr(adapter_options, "runtime", None)),+ )- profile = config.profiles.get(name)- if profile is None:- msg = f"Profile '{name}' referenced via extends does not exist"++def _compact_adapter_options_for_hash(+ loadtime: dict[str, Any],+ runtime: dict[str, Any],+) -> dict[str, dict[str, Any]] | None:+ adapter_options: dict[str, dict[str, Any]] = {}+ if loadtime:+ adapter_options["loadtime"] = loadtime+ if runtime:+ adapter_options["runtime"] = runtime+ return adapter_options or None+++def _resolved_profile_for_hash(config: object, profile_name: str, seen: set[str] | None = None) -> dict[str, object]:+ """Resolve one profile into the canonical fields used by bundle_config_hash."""+ profiles_raw = _profile_value(config, "profiles")+ if not isinstance(profiles_raw, dict):+ msg = "Model config profiles must be a mapping"+ raise ValueError(msg)+ profiles = cast("dict[str, object]", profiles_raw)++ if profile_name not in profiles:+ msg = f"Profile '{profile_name}' referenced via extends does not exist"+ raise ValueError(msg)++ if seen is None:+ seen = set()+ if profile_name in seen:+ msg = f"Profile '{profile_name}' has cyclic extends references"+ raise ValueError(msg)+ seen.add(profile_name)++ profile = profiles[profile_name]+ parent_name = _profile_value(profile, "extends")+ if isinstance(parent_name, str) and parent_name:+ if parent_name not in profiles:+ msg = f"Profile '{parent_name}' referenced via extends does not exist"raise ValueError(msg)- if profile.extends:- resolved = resolve(profile.extends, seen)+ resolved = _resolved_profile_for_hash(config, parent_name, seen)+ inherited_options = resolved.get("adapter_options")+ if isinstance(inherited_options, dict):+ options = cast("dict[str, Any]", inherited_options)+ loadtime = _copy_mapping(options.get("loadtime"))+ runtime = _copy_mapping(options.get("runtime"))else:- resolved = {- "adapter_path": None,- "max_batch_tokens": None,- "compute_precision": None,- "adapter_options": None,- }-- if profile.adapter_path is not None:- resolved["adapter_path"] = profile.adapter_path- if profile.max_batch_tokens is not None:- resolved["max_batch_tokens"] = profile.max_batch_tokens- if profile.compute_precision is not None:- resolved["compute_precision"] = profile.compute_precision- if "adapter_options" in getattr(profile, "model_fields_set", set()):- resolved["adapter_options"] = _profile_adapter_options_for_hash(profile)- return resolved-- return resolve(profile_name, set())+ loadtime = {}+ runtime = {}+ else:+ resolved = {+ "adapter_path": None,+ "max_batch_tokens": None,+ "compute_precision": None,+ "adapter_options": None,+ }+ loadtime = {}+ runtime = {}++ for field in ("adapter_path", "max_batch_tokens", "compute_precision"):+ value = _profile_value(profile, field)+ if value is not None:+ resolved[field] = value++ child_loadtime, child_runtime = _profile_adapter_options_parts(profile)+ if child_loadtime:+ loadtime = child_loadtime+ if child_runtime:+ runtime = child_runtime+ resolved["adapter_options"] = _compact_adapter_options_for_hash(loadtime, runtime)+ return resolveddef _is_synthetic_profile_variant(config: ServerModelConfig, configs: dict[str, ServerModelConfig]) -> bool:@@ -265,6 +307,27 @@ def _is_synthetic_profile_variant(config: ServerModelConfig, configs: dict[str,return bool(base_model in configs and profile and config.sie_id == f"{base_model}:{profile}")+def _model_has_bundle_adapter(config: ServerModelConfig, bundle_adapters: frozenset[str]) -> bool:+ return any(+ (module := _adapter_module(config.resolve_profile(profile_name).adapter_path)) is not None+ and module in bundle_adapters+ for profile_name in config.profiles+ )+++def _profile_matches_bundle(+ config: ServerModelConfig,+ profile_name: str,+ bundle_adapters: frozenset[str],+) -> bool:+ module = _adapter_module(config.resolve_profile(profile_name).adapter_path)+ return module is not None and module in bundle_adapters+++def _profile_config_for_hash(config: ServerModelConfig, profile_name: str) -> dict[str, object | None]:+ return _resolved_profile_for_hash(config, profile_name)++def _compute_bundle_config_hash(registry: ModelRegistry, bundle_id: str) -> str:"""Compute SHA-256 hash of model configs assigned to this worker's bundle.@@ -287,31 +350,39 @@ def _compute_bundle_config_hash(registry: ModelRegistry, bundle_id: str) -> str:# both sides hash [{"sie_id": name, "profiles": [{name, config}]}]# where config contains resolved routable fields: adapter_path,# max_batch_tokens, compute_precision, adapter_options.- items = []- bundle_adapter_set = _bundle_adapter_modules(bundle_id)+ bundle_adapters = _bundle_adapter_modules(bundle_id)+ items_by_model: dict[str, dict[str, dict[str, object | None]]] = {}for config in sorted(configs.values(), key=lambda c: c.sie_id):if _is_synthetic_profile_variant(config, configs):continue+ if not _model_has_bundle_adapter(config, bundle_adapters):+ continue++ base_id = config.sie_id+ profile_name_map = {pname: pname for pname in config.profiles}+ if config.synthetic_profile_variant_source is not None:+ base_id, variant_profile = config.synthetic_profile_variant_source+ profile_name_map = {"default": variant_profile}++ profiles_for_model = items_by_model.setdefault(base_id, {})+ for pname in sorted(profile_name_map):+ if not _profile_matches_bundle(config, pname, bundle_adapters):+ continue+ profiles_for_model[profile_name_map[pname]] = _profile_config_for_hash(config, pname)++ items = []+ for model_id in sorted(items_by_model):+ profiles = items_by_model[model_id]+ if not profiles:+ continue+ profiles_for_hash = [{"name": pname, "config": profiles[pname]} for pname in sorted(profiles)]+ items.append({"sie_id": model_id, "profiles": profiles_for_hash})++ if not items:+ return ""- profiles_for_hash = []- for pname in sorted(config.profiles.keys()):- profile_dict = _resolved_profile_for_hash(config, pname)- adapter_path = profile_dict.get("adapter_path")- if adapter_path:- module_path = str(adapter_path).split(":", maxsplit=1)[0]- if module_path not in bundle_adapter_set:- continue- profile_dict = {- "adapter_path": profile_dict.get("adapter_path"),- "max_batch_tokens": profile_dict.get("max_batch_tokens"),- "compute_precision": profile_dict.get("compute_precision"),- "adapter_options": profile_dict.get("adapter_options"),- }- profiles_for_hash.append({"name": pname, "config": profile_dict})- items.append({"sie_id": config.sie_id, "profiles": profiles_for_hash})-- serialized = json.dumps(items, sort_keys=True, separators=(",", ":"))- return hashlib.sha256(serialized.encode()).hexdigest()+ serialized = orjson.dumps(items, option=orjson.OPT_SORT_KEYS)+ return hashlib.sha256(serialized).hexdigest()# Cache of bundle config hashes. Populated by _compute_bundle_config_hash@@ -350,7 +421,7 @@ def compute_bundle_config_hash_cached(registry: ModelRegistry, bundle_id: str) -async def build_status_message(registry: ModelRegistry,- pull_loop: StatusPullLoop | None = None,+ queue_runtime: StatusQueueRuntime | None = None,) -> WorkerStatusMessage:"""Build the complete status message.@@ -407,16 +478,14 @@ async def build_status_message(# Worker name (== worker_id used by direct-dispatch routing).#- # The pull loop owns the canonical resolution- # (``SIE_WORKER_ID > HOSTNAME > POD_NAME > uuid4``); we mirror that- # value here so the gateway's WorkerRegistry keys its dispatch+ # The queue runtime owns the canonical worker identity; we mirror that+ # value here so the gateway's WorkerRegistry keys its direct-dispatch# subject (``sie.work.{pool}.{machine_profile}.{bundle}.{model}.{name}``)- # on the *same*- # identifier the worker is subscribed to. Falling back to the- # legacy ``HOSTNAME``/``POD_NAME`` lookup when the pull loop is- # absent keeps the non-queue path working unchanged.- if pull_loop is not None and hasattr(pull_loop, "worker_id"):- worker_name = pull_loop.worker_id+ # on the same identifier the worker is subscribed to. Falling back to the+ # env lookup when the queue runtime is absent keeps standalone/direct+ # server status working unchanged.+ if queue_runtime is not None and hasattr(queue_runtime, "worker_id"):+ worker_name = queue_runtime.worker_idelse:worker_name = os.environ.get("SIE_WORKER_ID") or os.environ.get("HOSTNAME") or os.environ.get("POD_NAME", "")@@ -434,12 +503,11 @@ async def build_status_message(else:max_batch_requests = BatchConfig().max_batch_requests- # Ask the pull loop for its latched saturation flag. The- # pull loop owns the SaturationGate state machine; we drive an- # update here so the WS-emitted snapshot matches whatever the- # optional NATS health publisher sees on the same tick. Falls- # back to False when the pull loop is not present (eg. tests- # using `build_status_message` standalone).+ # Ask the optional queue runtime for its latched saturation flag when+ # it exposes one. After the Python pull-loop deletion, the app wires+ # the IPC server here primarily for canonical worker identity; that+ # object has no local view of Rust queue pressure, so saturation falls+ # back to False unless a richer runtime supplies update_saturation().## Admission-control note: the underlying ratio changed semantics. On# generation pools (where a ``kv_budget_tokens`` is configured)@@ -448,10 +516,9 @@ async def build_status_message(# it still reads ``in_flight / aggregate_max_batch_requests``.# The boolean ``saturated`` is unchanged for consumers, but# downstream alerts that previously assumed the pre-admission fraction- # should be aware of the switch — see- # :meth:`NatsPullLoop.update_saturation`.- if pull_loop is not None and hasattr(pull_loop, "update_saturation"):- saturated = bool(pull_loop.update_saturation())+ # should be aware of the switch.+ if queue_runtime is not None and hasattr(queue_runtime, "update_saturation"):+ saturated = bool(queue_runtime.update_saturation())else:saturated = False@@ -496,15 +563,15 @@ async def websocket_status(websocket: WebSocket) -> None:# Get registry from app stateregistry: ModelRegistry = websocket.app.state.registry- # Feed `build_status_message` the pull loop so it can- # populate the `saturated` flag. May be absent in stripped-down- # test apps; the helper handles `None` defensively.- pull_loop = getattr(websocket.app.state, "nats_pull_loop", None)+ # Feed `build_status_message` the optional queue runtime so it can+ # populate the `saturated` flag. May be absent in stripped-down test apps;+ # the helper handles `None` defensively.+ queue_runtime = getattr(websocket.app.state, "queue_runtime", None)try:while True:# Build and send status- status = await build_status_message(registry, pull_loop=pull_loop)+ status = await build_status_message(registry, queue_runtime=queue_runtime)await websocket.send_json(status)# Wait 200ms before next updatediff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.pyindex 671ecf5bd..ed4086ef1 100644--- a/packages/sie_server/src/sie_server/app/app_factory.py+++ b/packages/sie_server/src/sie_server/app/app_factory.py@@ -15,6 +15,7 @@ from sie_server.api.health import router as health_routerfrom sie_server.api.metrics import router as metrics_routerfrom sie_server.api.models import router as models_routerfrom sie_server.api.openai_compat import router as openai_router+from sie_server.api.openai_local import router as openai_local_routerfrom sie_server.api.openapi import setup_custom_openapi_schemafrom sie_server.api.root import router as root_routerfrom sie_server.api.score import router as score_router@@ -29,7 +30,7 @@ from sie_server.core.shutdown import ShutdownMiddleware, ShutdownState, setup_sifrom sie_server.ipc_server import IpcServerfrom sie_server.observability.gpu import _init_nvml, shutdown_nvmlfrom sie_server.observability.telemetry import telemetry_sender-from sie_server.observability.tracing import setup_tracing+from sie_server.observability.tracing import setup_tracing, shutdown_tracingfrom sie_server.queue_executor import QueueExecutorlogger = logging.getLogger(__name__)@@ -76,7 +77,7 @@ class AppFactory:# Add graceful shutdown middleware (for spot instance preemption)app.add_middleware(ShutdownMiddleware, shutdown_state=shutdown_state)- # Setup OpenTelemetry tracing (no-op if SIE_TRACING_ENABLED is not set)+ # Setup OpenTelemetry tracing (no-op unless the flag and endpoint are set)setup_tracing(app)# Queue is the only supported routing mode: the worker-sidecar@@ -102,6 +103,9 @@ class AppFactory:app.include_router(score_router)app.include_router(models_router)app.include_router(openai_router) # OpenAI-compatible /v1/embeddings+ # Local-only convenience (single-node/dev); intentionally NOT in the published+ # openapi.json — see cli.openapi_export. The Rust gateway is the prod API authority.+ app.include_router(openai_local_router) # local /v1/chat/completions + /v1/reranksetup_custom_openapi_schema(app)return app@@ -124,6 +128,9 @@ class AppFactory:cls._configure_torch_threads()cls._configure_cuda_defaults()async with (+ # First to enter → last to tear down, so spans emitted during+ # other stages' shutdown (model unload, drain) are still flushed.+ _timed_stage("tracing", cls._tracing()),_timed_stage("nvml", cls._nvml()),_timed_stage("telemetry", telemetry_sender()),_timed_stage("model_registry", cls._model_registry(config)) as registry,@@ -133,6 +140,10 @@ class AppFactory:):app.state.registry = registryapp.state.ipc_server = ipc_server+ # /ws/status reads queue_runtime for the canonical worker_id.+ # The Python NATS pull loop is gone, so the IPC server is the+ # remaining Python object that mirrors the sidecar identity.+ app.state.queue_runtime = ipc_serveryieldreturn lifespan@@ -221,6 +232,20 @@ class AppFactory:register_liveness_probe(None)await server.stop()+ @classmethod+ @asynccontextmanager+ async def _tracing(cls) -> AsyncGenerator[None, None]:+ """Bounded tracing flush on shutdown.++ Setup happens in ``build_app`` (``setup_tracing``); this stage only owns+ the deterministic, bounded shutdown so exit can't stall on an unreachable+ OTLP collector.+ """+ try:+ yield+ finally:+ shutdown_tracing()+@classmethod@asynccontextmanagerasync def _nvml(cls) -> AsyncGenerator[None, None]:diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.pyindex 24c1be1cf..8ad9d4f0c 100644--- a/packages/sie_server/src/sie_server/cli.py+++ b/packages/sie_server/src/sie_server/cli.py@@ -9,10 +9,20 @@ from __future__ import annotations# defaults before our overrides land. Keep these two ``setdefault`` lines# as the very first executable statements after ``__future__``.import os+import sysos.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "60")os.environ.setdefault("HF_HUB_ETAG_TIMEOUT", "30")+# hf-xet (HuggingFace's Xet download protocol) can hang indefinitely on Apple+# Silicon — it does NOT honour HF_HUB_DOWNLOAD_TIMEOUT, so a stuck ``xet_get``+# wedges model loads with no recovery (verified: bge-m3 load blocked forever in+# ``huggingface_hub.file_download.xet_get`` on macOS). Disable Xet on macOS so+# downloads use reliable HTTPS. CUDA/Linux keep Xet (faster, works there).+# Override by exporting HF_HUB_DISABLE_XET=0.+if sys.platform == "darwin":+ os.environ.setdefault("HF_HUB_DISABLE_XET", "1")+import hashlibimport loggingfrom pathlib import Path@@ -192,8 +202,12 @@ def openapi_export(from sie_server.api.score import router as score_routerfrom sie_server.api.ws import router as ws_router- # Build a lightweight FastAPI app with all routers but no lifespan- # (no GPU init, no model registry, no telemetry, no NATS)+ # Build a lightweight FastAPI app for the PUBLISHED API surface — no lifespan (no GPU+ # init, model registry, telemetry, or NATS). NOTE: the local-only convenience routes are+ # intentionally excluded from the committed openapi.json — the native ``generate`` router+ # and the ``openai_local`` router (/v1/chat/completions + /v1/rerank) are a single-node/dev+ # surface mounted on the worker's own app, not part of the cluster API (the Rust gateway is+ # the production OpenAPI authority). They still appear at runtime /docs on a local server.app_ = FastAPI(title="SIE Server",description="Search Inference Engine - GPU inference server for search workloads",@@ -361,6 +375,17 @@ def serve(typer.echo(f"Models directory: {models_dir_resolved}")typer.echo(f"Device: {resolved_device}")+ if resolved_device == "mps":+ # Apple-Silicon banner: surface the one-command local OpenAI endpoint so the+ # first-run experience points at the playground / docs / OpenAI base URL.+ typer.echo("")+ typer.echo(" Apple Silicon (Metal) — one local OpenAI-compatible endpoint:")+ typer.echo(f" → Playground http://localhost:{port}/")+ typer.echo(f" → API docs http://localhost:{port}/docs")+ typer.echo(+ f" → OpenAI base http://localhost:{port}/v1 (embeddings · rerank; chat/completions with -b sglang)"+ )+ typer.echo("")if cluster_cache:typer.echo(f"Cluster cache: {cluster_cache}")if not hf_fallback:diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.pyindex 217cadcd5..73bf4e7ba 100644--- a/packages/sie_server/src/sie_server/config/model.py+++ b/packages/sie_server/src/sie_server/config/model.py@@ -488,8 +488,8 @@ class ModelConfig(BaseModel):@model_validator(mode="after")def validate_profiles(self) -> "ModelConfig":- if "default" not in self.profiles:- msg = "'default' key must exist in profiles"+ if not self.profiles:+ msg = "'profiles' must contain at least one profile"raise ValueError(msg)# ``grammar_profile`` must name a real profile (it becomes thediff --git a/packages/sie_server/src/sie_server/core/adaptive_batching.py b/packages/sie_server/src/sie_server/core/adaptive_batching.pyindex 6a28d6fe5..56e3f5157 100644--- a/packages/sie_server/src/sie_server/core/adaptive_batching.py+++ b/packages/sie_server/src/sie_server/core/adaptive_batching.py@@ -4,10 +4,23 @@ import loggingimport timefrom collections import dequefrom dataclasses import dataclass, field+from typing import Protocollogger = logging.getLogger(__name__)+class AdaptiveBatchTarget(Protocol):+ """The mutable batch limits the controller drives.++ ``BatchConfig`` satisfies this structurally; declaring it here lets the+ controller own its write-back without importing the concrete config+ (which would couple this leaf module to ``batcher`` and risk a cycle).+ """++ max_batch_wait_ms: float+ max_batch_cost: int++@dataclass(slots=True)class LatencyTracker:"""Rolling percentile tracker for request latencies.@@ -402,6 +415,29 @@ class AdaptiveBatchController:return self._current_wait_ms, self._current_batch_cost+ def apply_step(+ self,+ target: AdaptiveBatchTarget,+ observed_p50_ms: float | None,+ fill_ratio: float | None,+ *,+ batch_size: int | None = None,+ ) -> tuple[float, int]:+ """Advance the controller and write the new limits into ``target``.++ Single owner of the controller-output → batch-config write-back that+ previously lived inline in ``ModelWorker._process_loop``. Returns+ ``(max_batch_wait_ms, max_batch_cost)`` for the caller's metrics.++ Synchronous (no ``await``): both assignments happen together on the+ event-loop thread, so the in-place mutation stays safe against+ ``BatchFormer``'s async lock, which cannot interleave with this block.+ """+ new_wait, new_cost = self.step(observed_p50_ms, fill_ratio, batch_size=batch_size)+ target.max_batch_wait_ms = new_wait+ target.max_batch_cost = new_cost+ return new_wait, new_cost+# ------------------------------------------------------------------# Starvation detector helpers# ------------------------------------------------------------------diff --git a/packages/sie_server/src/sie_server/core/batcher.py b/packages/sie_server/src/sie_server/core/batcher.pyindex 8abe3048e..fe45f76dd 100644--- a/packages/sie_server/src/sie_server/core/batcher.py+++ b/packages/sie_server/src/sie_server/core/batcher.py@@ -18,10 +18,16 @@ The key optimization is cost-sorted sub-batching:- Each sub-batch contains similar-cost items- This minimizes padding waste within each sub-batch-Cost semantics vary by modality:+Cost semantics vary by modality (modality-native units):- Text: cost = token count- Images: cost = 1 per image (fixed dimensions)+- Vision (tiled): cost = tile count (1-N per image)- Audio: cost = sample_count / chunk_size++These units are NOT commensurable across modalities, so ``total_cost`` is only+meaningful within a single modality (the common case — a model's batch is+single-modality). See docs/adr/0004 for why cost is kept modality-native+rather than unified onto a canonical unit."""from __future__ import annotations@@ -367,7 +373,7 @@ class BatchFormer[I: HasCost, T]:effective_ms = min(batch_remaining_ms, coalesce_remaining_ms)return effective_ms / 1000 # Convert to seconds- def _extract_batch(self) -> FormattedBatch[I, T]:+ def _extract_batch(self, max_items: int | None = None) -> FormattedBatch[I, T]:"""Extract an optimal sub-batch from pending requests.Algorithm:@@ -376,6 +382,13 @@ class BatchFormer[I: HasCost, T]:3. Keep remaining requests for next get_batch() callThis minimizes padding waste by grouping similar-cost sequences.++ Args:+ max_items: Optional hard cap on the number of items taken, on top of+ the cost/request limits. Used by ``try_drain`` to bound a+ continuous-batch drain to a caller-held snapshot budget so+ post-snapshot arrivals are not swept in ahead of the next FCFS+ selection. See #1606."""# Track why batch was triggered (must check BEFORE extracting items)was_full = self._batch_is_full()@@ -396,6 +409,10 @@ class BatchFormer[I: HasCost, T]:hit_request_limit = Falsefor request in self._pending:+ # Respect an explicit per-extract item cap (a drain-fairness bound)+ # before anything else, so post-snapshot arrivals stay queued.+ if max_items is not None and take_count >= max_items:+ break# Would this item push us over the cost limit?# Always take at least one item (handles single large requests)if batch_cost + request.item.cost > self._config.max_batch_cost:@@ -455,7 +472,7 @@ class BatchFormer[I: HasCost, T]:return self._extract_batch()return None- async def try_drain(self) -> FormattedBatch[I, T] | None:+ async def try_drain(self, max_items: int | None = None) -> FormattedBatch[I, T] | None:"""Drain accumulated items immediately, bypassing batch timeout.Used by the process loop after inference completes to immediately@@ -463,13 +480,18 @@ class BatchFormer[I: HasCost, T]:"continuous batching" optimization — items that waited duringinference don't need to wait an additional batch formation window.+ Args:+ max_items: Optional cap on how many items this drain may take, so a+ caller draining a snapshot backlog does not sweep in items that+ arrived mid-drain. See #1606.+Returns:FormattedBatch if items were pending, None otherwise."""async with self._lock:if not self._pending:return None- return self._extract_batch()+ return self._extract_batch(max_items=max_items)def collate_batch(diff --git a/packages/sie_server/src/sie_server/core/encode_pipeline.py b/packages/sie_server/src/sie_server/core/encode_pipeline.pyindex 2da0fec13..ddffbb50e 100644--- a/packages/sie_server/src/sie_server/core/encode_pipeline.py+++ b/packages/sie_server/src/sie_server/core/encode_pipeline.py@@ -30,6 +30,7 @@ class EncodePipeline:options: dict[str, Any],prepared_tokens_per_item: list[PreparedTokens | None] | None = None,response_output_types: list[str] | None = None,+ preformed_batch: bool = False,) -> tuple[list[dict[str, Any]], RequestTiming]:"""Main entry point: preprocess then execute encoding.@@ -46,6 +47,11 @@ class EncodePipeline:(e.g. muvera asks the adapter for ``multivector`` while the postprocessoradds ``dense``); the response must then be filtered by the user-requestedtypes, not the translated adapter types. Defaults to ``output_types``.++ ``preformed_batch=True`` is the worker-sidecar IPC path: Rust has+ already formed the batch, so the Python worker must execute it directly+ rather than submit it to the local BatchFormer again. Direct HTTP leaves+ this false and keeps Python-side batching for single-instance serving."""timing = RequestTiming()@@ -62,7 +68,8 @@ class EncodePipeline:if prepared_batch is not None:# Batched worker pathworker = await registry.start_worker(model)- future = await worker.submit(+ submit = worker.submit_preformed if preformed_batch else worker.submit+ future = await submit(prepared_items=prepared_batch.items,items=items,output_types=output_types,@@ -77,6 +84,7 @@ class EncodePipeline:# Direct adapter call (no batching) - run in thread to avoid blocking event loopencode_handler = EncodeHandler(model, registry.postprocessor_registry)adapter = registry.get(model)+ registry.touch_lru(model)timing.start_inference()encode_output = await asyncio.to_thread(encode_handler.encode,diff --git a/packages/sie_server/src/sie_server/core/hot_reload.py b/packages/sie_server/src/sie_server/core/hot_reload.pyindex fc4da0cd2..68ca5c4b4 100644--- a/packages/sie_server/src/sie_server/core/hot_reload.py+++ b/packages/sie_server/src/sie_server/core/hot_reload.py@@ -388,11 +388,8 @@ class HotReloader:# Drain in-flight requestsawait self._drain_requests(model_name)- # Stop worker if running- await self._registry.stop_worker(model_name)-- # Unload the model- self._registry.unload(model_name)+ # Unload the model through the registry's async load lock.+ await self._registry.unload_async(model_name)# Clear custom adapter from module cacheself._clear_custom_adapter_cache(model_name)@@ -418,7 +415,7 @@ class HotReloader:# Reload model if it was loaded beforeif was_loaded and model_name in new_configs:try:- self._registry.load(model_name, self._device)+ await self._registry.load_async(model_name, self._device)await self._registry.start_worker(model_name)logger.info("Reloaded model: %s", model_name)except (RuntimeError, OSError, ValueError) as e:@@ -464,11 +461,8 @@ class HotReloader:# Drain in-flight requestsawait self._drain_requests(model_name)- # Stop worker if running- await self._registry.stop_worker(model_name)-- # Unload the model- self._registry.unload(model_name)+ # Unload the model through the registry's async load lock.+ await self._registry.unload_async(model_name)finally:self._reloading.discard(model_name)diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.pyindex 82c32d628..0c63c4545 100644--- a/packages/sie_server/src/sie_server/core/loader.py+++ b/packages/sie_server/src/sie_server/core/loader.py@@ -114,11 +114,16 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:For each model config, non-default profiles become separate model entriesnamed '{sie_id}:{profile_name}'. The variant entry is a copy of the base- config with the variant profile promoted to 'default'.+ config with the variant profile promoted to 'default'. If a config omits+ a default profile, the bare base model id is removed after variant expansion+ so only explicit profile identities are routable."""variants: dict[str, ModelConfig] = {}+ remove_base_names: list[str] = []for base_name, config in configs.items():+ if "default" not in config.profiles:+ remove_base_names.append(base_name)for profile_name, profile in config.profiles.items():if profile_name == "default":continue@@ -176,6 +181,9 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:variants[variant_id] = variant_configlogger.info("Expanded profile '%s' as variant: %s", profile_name, variant_id)+ for base_name in remove_base_names:+ configs.pop(base_name, None)+configs.update(variants)@@ -316,8 +324,26 @@ def load_adapter(# Custom adapter: load from file pathadapter_class = _import_custom_adapter(Path(module_path), class_name)- # Instantiate with config values- adapter_kwargs = _build_adapter_kwargs(config, default_compute_precision)+ # Instantiate with config values. The engine-level default compute precision+ # is fp32 off-CUDA (numerically safe on CPU/MPS for models we have not verified+ # at lower precision); a model profile's explicit compute_precision still wins+ # (e.g. curated Mac models opt into fp16 on MPS). On CUDA the engine default+ # (typically fp16) is used unchanged. See adapters' dtype resolution for the+ # matching honor-explicit-precision logic.+ effective_default_precision: ComputePrecision = (+ default_compute_precision if device.startswith("cuda") else "float32"+ )+ adapter_kwargs = _build_adapter_kwargs(config, effective_default_precision)++ # MPS bfloat16 support is incomplete in torch and can HANG model load (verified:+ # bge-m3 bf16 load wedges at ~1% CPU on Apple Silicon). fp16 is the MPS-verified+ # path (parity 1.0 vs CPU-fp32 in benchmarks), so coerce any resolved bf16 -> fp16+ # on MPS for every adapter. CUDA/CPU are untouched.+ if device == "mps" and adapter_kwargs.get("compute_precision") == "bfloat16":+ logger.info(+ "Coercing compute_precision bfloat16 -> float16 for '%s' on MPS (MPS bf16 is unreliable)", config.name+ )+ adapter_kwargs["compute_precision"] = "float16"# Apply engine-level attention backend only when adapter supports itif attention_backend != "auto" and "attn_implementation" not in adapter_kwargs:diff --git a/packages/sie_server/src/sie_server/core/memory.py b/packages/sie_server/src/sie_server/core/memory.pyindex c44816fa5..6f0a913ca 100644--- a/packages/sie_server/src/sie_server/core/memory.py+++ b/packages/sie_server/src/sie_server/core/memory.py@@ -3,7 +3,8 @@Device-agnostic memory monitoring and LRU tracking for CUDA, MPS, and CPU.Memory management behavior:-- Reactive LRU eviction without static VRAM budgets+- Proactive and reactive LRU eviction without static VRAM budgets+- Before load, evict when current pressure or requested load headroom requires it- Try to load model → If OOM, evict LRU model and retry- After each batch, check memory usage; evict if above threshold"""@@ -129,15 +130,25 @@ class MPSMemoryTracker(DeviceMemoryTracker):# Get current allocated memory on MPSused = torch.mps.current_allocated_memory()- # MPS uses unified memory - get system memory as total- # Note: This is the full system memory, not a dedicated GPU budget- try:- import psutil-- total = psutil.virtual_memory().total- except ImportError:- # Fallback: assume 32GB if psutil not available- total = 32 * (1024**3)+ # MPS uses unified memory. Prefer Metal's recommended working-set size as the+ # budget so LRU eviction can actually fire (using full system RAM as `total`+ # means the 0.95 threshold is almost never crossed on unified memory). Fall+ # back to system RAM, then a fixed 32GB, if the API is unavailable.+ total = 0+ recommended = getattr(torch.mps, "recommended_max_memory", None)+ if callable(recommended):+ try:+ total = int(recommended())+ except (RuntimeError, ValueError):+ total = 0+ if not total:+ try:+ import psutil++ total = psutil.virtual_memory().total+ except ImportError:+ # Fallback: assume 32GB if psutil not available+ total = 32 * (1024**3)return MemoryStats(used_bytes=used, total_bytes=total, device_type="mps")diff --git a/packages/sie_server/src/sie_server/core/postprocessor.py b/packages/sie_server/src/sie_server/core/postprocessor.pyindex abcc345bc..14cd62992 100644--- a/packages/sie_server/src/sie_server/core/postprocessor.py+++ b/packages/sie_server/src/sie_server/core/postprocessor.py@@ -16,6 +16,7 @@ Paper: https://arxiv.org/abs/2405.19504from __future__ import annotations+import loggingfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Literal, Protocol@@ -24,6 +25,8 @@ import numpy as npif TYPE_CHECKING:from sie_server.core.inference_output import EncodeOutput+logger = logging.getLogger(__name__)+class Postprocessor(Protocol):"""Protocol for output postprocessors.@@ -143,11 +146,11 @@ class MuveraConfig:This gives: 40 * 64 * 128 = 327,680 intermediate dims -> 10,240 final- Alternative (memory-efficient but lower quality):+ Alternative (memory-efficient; the text ColBERT models use this — #1493):- projection_dim: 8 (AMS sketch per-token compression)- - final_projection_dim: None (no final compression)+ - final_projection_dim: None (no final Count Sketch — it is harmful here)- This gives: 20 * 64 * 8 = 10,240 directly+ This gives: 40 * 64 * 8 = 20,480 directlyReferences:- Paper: https://arxiv.org/abs/2405.19504@@ -162,10 +165,18 @@ class MuveraConfig:Set to None for identity projection (paper's approach).Set to small value (e.g., 8) for AMS sketch (lower quality).final_projection_dim: If set, apply Count Sketch to compress the- concatenated FDE to this dimension. Paper uses 10240.+ concatenated FDE to this dimension. Paper uses 10240. A value+ ``>= intermediate_dim`` is ignored (the sketch is skipped), since+ a same-or-larger Count Sketch can only destroy information (#1493).seed: Random seed for reproducibility. Default: 42.normalize: Whether to L2 normalize FDE vectors. Default: False.Set True for cosine similarity, False for inner product.+ center_tokens: If True, subtract the per-multivector mean token before+ SimHash partitioning. A dominant shared DC component otherwise makes+ SimHash bucket all tokens together (near-tied FDEs that collapse+ ranking, while MaxSim stays healthy); centering partitions on the+ discriminative residual. Improves FDE quality for near-collinear+ models. Default: False (#1528)."""num_repetitions: int = 40 # Paper uses 40@@ -174,12 +185,27 @@ class MuveraConfig:final_projection_dim: int | None = 10240 # Count Sketch to this dim (paper uses 10240)seed: int = 42normalize: bool = False # True for cosine, False for inner product+ center_tokens: bool = False # subtract per-multivector mean before SimHash (#1528)@propertydef num_partitions(self) -> int:"""Number of partitions per repetition."""return 2**self.num_simhash_projections+ def _effective_final_dim(self, token_dim: int) -> int | None:+ """Final Count-Sketch target dim, or None when no sketch should run.++ A Count-Sketch is only ever a *reduction*. When the configured+ final_projection_dim is >= the intermediate dim it can only destroy+ information (same-dim destructive hashing, see #1493), so it is+ skipped and the intermediate FDE is returned unprojected.+ """+ if self.final_projection_dim is None:+ return None+ if self.final_projection_dim >= self.intermediate_dim(token_dim):+ return None+ return self.final_projection_dim+def fde_dim(self, token_dim: int) -> int:"""Calculate FDE output dimension.@@ -189,12 +215,8 @@ class MuveraConfig:Returns:Total FDE dimension (after final projection if configured)."""- proj_dim = self.projection_dim or token_dim- intermediate_dim = self.num_repetitions * self.num_partitions * proj_dim-- if self.final_projection_dim is not None:- return self.final_projection_dim- return intermediate_dim+ final = self._effective_final_dim(token_dim)+ return final if final is not None else self.intermediate_dim(token_dim)def intermediate_dim(self, token_dim: int) -> int:"""Calculate intermediate FDE dimension before final projection.@@ -252,10 +274,29 @@ class MuveraPostprocessor:self._proj_dim = self.config.projection_dim or token_dimself._use_identity = self.config.projection_dim is None- # Calculate dimensions+ # Calculate dimensions. ``_final_dim`` is the effective Count-Sketch+ # target dim (None = skip the sketch); ``target_dim`` stays consistent+ # with it via ``fde_dim`` (both route through ``_effective_final_dim``).self._intermediate_dim = self.config.intermediate_dim(token_dim)+ self._final_dim = self.config._effective_final_dim(token_dim)self.target_dim = self.config.fde_dim(token_dim)+ # Warn once (at construction) when a configured final_projection_dim is+ # ignored because it would not reduce the FDE (#1493 footgun guard).+ if (+ self.config.final_projection_dim is not None+ and self.config.final_projection_dim >= self.config.intermediate_dim(token_dim)+ ):+ logger.warning(+ "MUVERA final Count-Sketch skipped: final_projection_dim=%d >= intermediate_dim=%d "+ "(token_dim=%d) — a same-or-larger sketch only destroys information; "+ "returning unprojected %d-dim FDE (#1493).",+ self.config.final_projection_dim,+ self.config.intermediate_dim(token_dim),+ token_dim,+ self.target_dim,+ )+# Pre-compute Gray code lookup table for fast partition index conversion# Gray code: adjacent indices differ by 1 bit (preserves LSH locality)self._gray_lut = self._build_gray_lut(self.config.num_simhash_projections)@@ -323,6 +364,13 @@ class MuveraPostprocessor:if num_tokens == 0:return np.zeros(self.target_dim, dtype=np.float32)+ # Subtract the per-multivector mean token before partitioning/projection.+ # A dominant shared DC component makes SimHash bucket all tokens together+ # (near-tied FDEs -> collapsed ranking), so centering partitions on the+ # discriminative residual. MaxSim is DC-shift-tolerant and unaffected (#1528).+ if self.config.center_tokens:+ token_embeddings = token_embeddings - token_embeddings.mean(axis=0, keepdims=True)+num_partitions = self.config.num_partitionsproj_dim = self._proj_dimrep_block_size = num_partitions * proj_dim@@ -358,9 +406,10 @@ class MuveraPostprocessor:rep_start = rep_num * rep_block_sizeintermediate_fde[rep_start : rep_start + rep_block_size] = rep_fde- # Step 6: Apply final Count Sketch projection if configured- if self.config.final_projection_dim is not None:- return _apply_count_sketch(intermediate_fde, self.config.final_projection_dim, self.config.seed)+ # Step 6: Apply final Count Sketch projection if it would reduce the+ # FDE. ``_final_dim`` is None when the sketch is skipped (#1493 guard).+ if self._final_dim is not None:+ return _apply_count_sketch(intermediate_fde, self._final_dim, self.config.seed)return intermediate_fdediff --git a/packages/sie_server/src/sie_server/core/prepared.py b/packages/sie_server/src/sie_server/core/prepared.pyindex 80ca49905..6c3a95f3d 100644--- a/packages/sie_server/src/sie_server/core/prepared.py+++ b/packages/sie_server/src/sie_server/core/prepared.py@@ -70,7 +70,10 @@ class PreparedItem[T: Payload]:Attributes:payload: Modality-specific preprocessed data.- cost: Batching budget consumed (tokens for text, 1 for images).+ cost: Per-modality batching budget in modality-native units (text =+ token count, image = 1, tiled vision = tile count). NOT comparable+ across modalities; the BatchFormer sum is only meaningful within+ one modality. See docs/adr/0004.original_index: Position in original request for result reordering."""diff --git a/packages/sie_server/src/sie_server/core/preprocessor/vision.py b/packages/sie_server/src/sie_server/core/preprocessor/vision.pyindex eea85cd77..dfb8751ae 100644--- a/packages/sie_server/src/sie_server/core/preprocessor/vision.py+++ b/packages/sie_server/src/sie_server/core/preprocessor/vision.py@@ -29,6 +29,8 @@ from sie_server.core.preprocessor.base import get_image_executorfrom sie_server.types.inputs import media_bytesif TYPE_CHECKING:+ from PIL import Image as PILImage+from sie_server.config.model import ModelConfigfrom sie_server.types.inputs import Item@@ -39,6 +41,22 @@ _SIGLIP_MEAN = (0.5, 0.5, 0.5)_SIGLIP_STD = (0.5, 0.5, 0.5)+def _load_rgb(media: object) -> PILImage.Image:+ """Decode a wire image input into an RGB PIL image.++ Centralizes the ``PILImage.open(io.BytesIO(media_bytes(...)))`` + RGB-convert+ idiom that every vision preprocessor repeated. ``media_bytes`` raises+ ``InvalidMediaError`` (-> 400 INVALID_INPUT) on a non-bytes payload rather+ than hitting a raw ``TypeError`` deep in the decode. See issue #1540.+ """+ from PIL import Image as PILImage # deferred: PIL is an optional dependency++ img = PILImage.open(io.BytesIO(media_bytes(media, kind="image")))+ if img.mode != "RGB":+ img = img.convert("RGB")+ return img++def _find_closest_aspect_ratio(aspect_ratio: float,target_ratios: list[tuple[int, int]],@@ -231,7 +249,6 @@ class NemoColEmbedPreprocessor:PreparedBatch with NemoColEmbedPayload items."""import torch- from PIL import Image as PILImageprepared_items: list[PreparedItem[NemoColEmbedPayload]] = []total_cost = 0@@ -243,13 +260,9 @@ class NemoColEmbedPreprocessor:# Load image from bytesimg_input = item.images[0]- pil_img = PILImage.open(io.BytesIO(media_bytes(img_input, kind="image")))+ pil_img = _load_rgb(img_input)original_size = pil_img.size- # Convert to RGB if needed- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")-# Dynamic tilingimage_tiles = _dynamic_preprocess(pil_img,@@ -518,21 +531,15 @@ class Florence2Preprocessor:Returns:PreparedItem or None if item has no images."""- from PIL import Image as PILImage-if not item.images:logger.warning("Florence2Preprocessor: item %d has no images", index)return None# Load image from bytes - PIL releases GIL during decodeimg_input = item.images[0]- pil_img = PILImage.open(io.BytesIO(media_bytes(img_input, kind="image")))+ pil_img = _load_rgb(img_input)original_size = (pil_img.width, pil_img.height)- # Convert to RGB if needed- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")-# Process through Florence-2 processor (CPU-bound, releases GIL)inputs = self._processor(text=prompt,@@ -712,21 +719,15 @@ class DonutPreprocessor:Returns:PreparedItem or None if item has no images."""- from PIL import Image as PILImage-if not item.images:logger.warning("DonutPreprocessor: item %d has no images", index)return None# Load image from bytes - PIL releases GIL during decodeimg_input = item.images[0]- pil_img = PILImage.open(io.BytesIO(media_bytes(img_input, kind="image")))+ pil_img = _load_rgb(img_input)original_size = (pil_img.width, pil_img.height)- # Convert to RGB if needed- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")-# Process image through Donut processor (CPU-bound, releases GIL)pixel_values = self._processor(pil_img, return_tensors="pt").pixel_values.squeeze(0)@@ -924,19 +925,14 @@ class LightOnOCRPreprocessor:Returns:PreparedItem or None if item has no images."""- from PIL import Image as PILImage-if not item.images:logger.warning("LightOnOCRPreprocessor: item %d has no images", index)return Noneimg_input = item.images[0]- pil_img = PILImage.open(io.BytesIO(media_bytes(img_input, kind="image")))+ pil_img = _load_rgb(img_input)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],@@ -1105,19 +1101,14 @@ class GlmOcrPreprocessor:Returns:PreparedItem or None if item has no images."""- from PIL import Image as PILImage-if not item.images:logger.warning("GlmOcrPreprocessor: item %d has no images", index)return Noneimg_input = item.images[0]- pil_img = PILImage.open(io.BytesIO(media_bytes(img_input, kind="image")))+ pil_img = _load_rgb(img_input)original_size = (pil_img.width, pil_img.height)- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")-text = instruction or self._user_textmessages = [{@@ -1283,8 +1274,6 @@ class DetectionPreprocessor:Returns:PreparedItem or None if item has no images."""- from PIL import Image as PILImage-if not item.images:logger.warning("DetectionPreprocessor: item %d has no images", index)return None@@ -1293,13 +1282,9 @@ class DetectionPreprocessor:# Load image from bytes - PIL releases GIL during decode. media_bytes# raises InvalidMediaError (-> 400 INVALID_INPUT) on a non-bytes payload# rather than silently dropping the item or hitting a raw TypeError.- pil_img = PILImage.open(io.BytesIO(media_bytes(img, kind="image")))+ pil_img = _load_rgb(img)original_size = (pil_img.width, pil_img.height)- # Convert to RGB if needed- if pil_img.mode != "RGB":- pil_img = pil_img.convert("RGB")-# Run image_processor to produce tensor (resize, normalize)# This is the expensive part (~23ms, 94% of preprocessing)processed = self._image_processor(images=pil_img, return_tensors="pt")@@ -1464,19 +1449,15 @@ class PaddleOCRVLPreprocessor:index: int,text: str,) -> PreparedItem[PaddleOCRVLPayload] | None:- from PIL import Image as PILImageif not item.images:logger.warning("PaddleOCRVLPreprocessor: item %d has no images", index)return Noneimg_input = item.images[0]- pil_img = PILImage.open(io.BytesIO(media_bytes(img_input, kind="image")))+ pil_img = _load_rgb(img_input)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],@@ -1637,19 +1618,15 @@ class MinerUVLPreprocessor:index: int,text: str,) -> PreparedItem[MinerUVLPayload] | None:- from PIL import Image as PILImageif not item.images:logger.warning("MinerUVLPreprocessor: item %d has no images", index)return Noneimg_input = item.images[0]- pil_img = PILImage.open(io.BytesIO(media_bytes(img_input, kind="image")))+ pil_img = _load_rgb(img_input)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],diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex e8635f7a2..1616c2175 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -43,6 +43,7 @@ from sie_server.core.pool_isolation import ()from sie_server.core.postprocessor_registry import PostprocessorRegistryfrom sie_server.core.preprocessor_registry import PreprocessorRegistry+from sie_server.core.residency import EvictionResultfrom sie_server.core.worker import ModelWorkerfrom sie_server.core.worker.types import AdaptiveBatchingParamsfrom sie_server.observability.metrics import record_idle_eviction@@ -108,6 +109,29 @@ def _model_configs_semantically_equal(left: ModelConfig | None, right: ModelConfreturn left is not None and _model_config_semantic_hash(left) == _model_config_semantic_hash(right)+def _is_python_runtime_adapter(adapter_path: str) -> bool:+ return not adapter_path.startswith("sie_server_rust.")+++def _adapter_load_required_bytes(adapter: ModelAdapter, memory_manager: MemoryManager) -> int | None:+ """Return an adapter-provided load-headroom estimate, if any."""+ stats = memory_manager.get_stats()+ if stats.total_bytes <= 0:+ return None++ try:+ required = adapter.load_required_memory_bytes(+ device_type=stats.device_type,+ device_total_bytes=stats.total_bytes,+ )+ except Exception:+ logger.exception("adapter.load_required_memory_bytes() raised; falling back to pressure-only eviction")+ return None+ if isinstance(required, bool) or not isinstance(required, int) or required <= 0:+ return None+ return min(required, stats.total_bytes)++class ModelRegistry:"""Registry for managing model configs and loaded models.@@ -407,17 +431,16 @@ class ModelRegistry:else:self._configs = all_configs- if self._pool_name is not None:- before_count = len(self._configs)- self._configs = {name: config for name, config in self._configs.items() if self.accepts_config_pool(config)}- filtered_count = before_count - len(self._configs)- if filtered_count:- logger.info(- "Pool filter applied for SIE_POOL=%s: %d/%d models available",- self._pool_name,- len(self._configs),- before_count,- )+ before_count = len(self._configs)+ self._configs = {name: config for name, config in self._configs.items() if self.accepts_config_pool(config)}+ filtered_count = before_count - len(self._configs)+ if filtered_count:+ logger.info(+ "Model config filter applied for SIE_POOL=%s: %d/%d models available",+ self._pool_name or "<unset>",+ len(self._configs),+ before_count,+ )# Pool isolation. With the post-filter set in hand,# reject mixed generation/non-generation pools loudly. The@@ -677,11 +700,20 @@ class ModelRegistry:msg = _ERR_MODEL_NOT_LOADED.format(name=name)raise KeyError(msg)- # Update LRU tracking - this model was recently used- self._memory_manager.touch(name)-+ # ``get`` is a pure read: it does not update LRU. Request hot paths call+ # ``touch_lru`` explicitly after obtaining the adapter (see #1541).return self._loaded[name].adapter+ def touch_lru(self, name: str) -> None:+ """Mark a loaded model as recently used for LRU eviction.++ :meth:`get` is a pure read and does not update LRU; request hot paths+ call this explicitly after obtaining the adapter so the model is+ protected from eviction. No-op for a model that is not loaded.+ """+ if name in self._loaded:+ self._memory_manager.touch(name)+def load(self, name: str, device: str) -> ModelAdapter:"""Load a model onto a device.@@ -717,6 +749,25 @@ class ModelRegistry:# Instantiate the adapter with device-aware fallback selectionadapter = self._loader.instantiate_adapter(name, config, model_dir, device)+ required_load_bytes = _adapter_load_required_bytes(adapter, self._memory_manager)+ while self._memory_manager.should_evict_for_load(required_load_bytes):+ lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)+ if lru_model is None:+ break++ stats = self._memory_manager.get_stats()+ logger.info(+ "Pre-load eviction: %.2f GB free, %.2f GB required, %.1f%% used "+ "(threshold %.1f%%); evicting '%s' before loading '%s'",+ stats.available_gb,+ (required_load_bytes or 0) / (1024**3),+ stats.usage_ratio * 100,+ self._memory_manager.pressure_threshold_pct,+ lru_model,+ name,+ )+ self.unload(lru_model)+# Try to load onto device, with OOM retrytry:loaded = self._loader.load_and_register(name, device, adapter, config)@@ -758,7 +809,7 @@ class ModelRegistry:This method:- Serializes all load/unload operations via an async lock- - Proactively evicts LRU models if memory pressure is high before loading+ - Proactively evicts LRU models if memory pressure or load headroom requires it- Runs the blocking load in a thread pool to avoid blocking the event loop- Falls back to OOM-triggered eviction if load still fails (fragmentation)- On-demand config discovery: rescans models_dir if model not found@@ -791,28 +842,13 @@ class ModelRegistry:msg = f"Model '{name}' is currently being unloaded"raise RuntimeError(msg)- # Pre-load eviction: evict LRU non-pinned models until below pressure threshold- while self._memory_manager.check_pressure():- lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)- if lru_model is None:- break # No non-pinned models to evict, proceed with load attempt-- stats = self._memory_manager.get_stats()- logger.info(- "Pre-load eviction: memory %.1f%% > %.1f%% threshold, evicting '%s' before loading '%s'",- stats.usage_ratio * 100,- self._memory_manager.pressure_threshold_pct,- lru_model,- name,- )- await self._do_unload(lru_model)+ config = self._configs[name]# Mark as loading before starting (visible to WebSocket status)self._loading.add(name)load_start = time.monotonic()try:- config = self._configs[name]model_dir = self._model_dirs.get(name, Path())# Ensure weights are cached BEFORE instantiation. This@@ -825,6 +861,41 @@ class ModelRegistry:# Instantiate adapter (in thread pool, post-download timeout applies)adapter = await self._loader.instantiate_adapter_async(name, config, model_dir, device)+ required_load_bytes = _adapter_load_required_bytes(adapter, self._memory_manager)++ # Pre-load eviction: evict LRU non-pinned models until current pressure+ # and any adapter-provided load headroom requirement are satisfied.+ while self._memory_manager.should_evict_for_load(required_load_bytes):+ lru_model = self._memory_manager.get_lru_model(exclude=self._pinned_models)+ if lru_model is None:+ break # No non-pinned models to evict, proceed with load attempt++ if lru_model not in self._loaded:+ # Belt-and-braces: a MemoryManager entry with no matching+ # ``_loaded`` model is a ghost (see #1600). ``_do_unload``+ # would no-op on it, so drop the stale accounting entry and+ # re-evaluate rather than spin. The ``_do_unload`` finally+ # normally prevents ghosts; this guards any other source.+ logger.warning(+ "Evictor found ghost '%s' (in memory manager, not loaded); dropping stale entry",+ lru_model,+ )+ self._memory_manager.unregister_model(lru_model)+ continue++ stats = self._memory_manager.get_stats()+ logger.info(+ "Pre-load eviction: %.2f GB free, %.2f GB required, %.1f%% used "+ "(threshold %.1f%%); evicting '%s' before loading '%s'",+ stats.available_gb,+ (required_load_bytes or 0) / (1024**3),+ stats.usage_ratio * 100,+ self._memory_manager.pressure_threshold_pct,+ lru_model,+ name,+ )+ await self._do_unload(lru_model)+try:# Load onto device (loader handles main thread vs executor)loaded = await self._loader.load_and_register_async(name, device, adapter, config)@@ -1092,30 +1163,42 @@ class ModelRegistry:del self._loaded[name]device = loaded.device- # Some adapters (e.g. the SGLang generation adapter) hold an- # async HTTP client to a subprocess. ``unload()`` is sync and- # can only fire-and-forget the client close, which races the- # subprocess termination on the next line — the close could be- # cut off before its connections drain, leaking fds / wedging- # on a half-open socket. When the adapter exposes an awaitable- # ``aclose_client``, drive it to completion HERE (we're on the- # event loop) so the client is fully closed against the still-- # live subprocess before ``unload()`` terminates it.- aclose_client = getattr(loaded.adapter, "aclose_client", None)- if aclose_client is not None:+ # Once removed from ``_loaded`` above, the model is committed-gone+ # from the registry's view, so its MemoryManager entry MUST be+ # dropped even if adapter teardown below raises. Otherwise the+ # model becomes a "ghost" — absent from ``_loaded`` but still+ # counted in ``_models`` — that ``get_lru_model`` keeps+ # re-selecting while ``_do_unload`` no-ops on it: a no-yield spin+ # under ``_load_lock`` that starves the whole event loop. See #1600.+ try:+ # Some adapters (e.g. the SGLang generation adapter) hold an+ # async HTTP client to a subprocess. ``unload()`` is sync and+ # can only fire-and-forget the client close, which races the+ # subprocess termination on the next line — the close could be+ # cut off before its connections drain, leaking fds / wedging+ # on a half-open socket. When the adapter exposes an awaitable+ # ``aclose_client``, drive it to completion HERE (we're on the+ # event loop) so the client is fully closed against the still-+ # live subprocess before ``unload()`` terminates it.+ aclose_client = getattr(loaded.adapter, "aclose_client", None)+ if aclose_client is not None:+ try:+ await aclose_client()+ except Exception: # noqa: BLE001 - close is best-effort+ logger.warning("aclose_client() failed during unload of '%s'", name, exc_info=True)++ # Adapter.unload() handles gc.collect + empty_cache+ loaded.adapter.unload()+ finally:+ # Always run, even if adapter teardown above raised, so a+ # failed unload can never leave a ghost behind (#1600).try:- await aclose_client()- except Exception: # noqa: BLE001 - close is best-effort- logger.warning("aclose_client() failed during unload of '%s'", name, exc_info=True)-- # Adapter.unload() handles gc.collect + empty_cache- loaded.adapter.unload()-- # Unregister tokenizer, preprocessor, and clear metrics- self._loader.unregister(name, device)-- # Unregister from memory manager- self._memory_manager.unregister_model(name)+ # Unregister tokenizer, preprocessor, and clear metrics+ self._loader.unregister(name, device)+ except Exception: # noqa: BLE001 - best-effort; must not skip below+ logger.warning("loader.unregister failed during unload of '%s'", name, exc_info=True)+ # Unregister from memory manager (a plain dict-pop; never raises)+ self._memory_manager.unregister_model(name)# Freeing memory makes any prior OOM-class load failure on a# *sibling* model retryable; clear those records so the next@@ -1236,8 +1319,7 @@ class ModelRegistry:removed = ", ".join(sorted(removed_ids))msg = f"cannot synchronously remove model config(s): {removed}; use add_config_async"raise RuntimeError(msg)- for expanded_config in expanded.values():- self._apply_config_entry(expanded_config, model_dir)+ self._apply_config_entry(config, model_dir)self._loader.update_configs(self._configs)return updated_ids | removed_ids@@ -1254,15 +1336,17 @@ class ModelRegistry:if model_id in self._loaded:await self._do_unload(model_id)self._drop_config_entry(model_id)- for expanded_config in expanded.values():- self._apply_config_entry(expanded_config, model_dir)+ self._apply_config_entry(config, model_dir)self._loader.update_configs(self._configs)return updated_ids | removed_idsdef _prepare_config_update(self, config: ModelConfig) -> tuple[dict[str, ModelConfig], set[str], set[str]]:expanded = expand_profile_variants([config])updated_ids = set(expanded)- removed_ids = self._synthetic_profile_variant_ids_for_base(config.sie_id) - updated_ids+ previously_materialized = self._synthetic_profile_variant_ids_for_base(config.sie_id)+ if config.sie_id in self._configs:+ previously_materialized.add(config.sie_id)+ removed_ids = previously_materialized - updated_idsreturn expanded, updated_ids, removed_idsdef _preflight_config_update(@@ -1300,14 +1384,9 @@ class ModelRegistry:self._config_version += 1def _add_config_entry(self, config: ModelConfig, model_dir: Path | None = None) -> None:- if not self.accepts_config_pool(config):- if config.sie_id in self._configs:- del self._configs[config.sie_id]- self._loader.update_configs(self._configs)- self._failed.pop(config.sie_id, None)- self._config_version += 1- return- self._validate_config_entry(config, self._configs)+ for expanded_config in expand_profile_variants([config]).values():+ if self.accepts_config_pool(expanded_config):+ self._validate_config_entry(expanded_config, self._configs)self._apply_config_entry(config, model_dir)def _validate_config_entry(self, config: ModelConfig, existing_configs: dict[str, ModelConfig]) -> None:@@ -1329,25 +1408,42 @@ class ModelRegistry:validate_no_legacy_scalar_lora_id(name=config.sie_id, config=config)def _apply_config_entry(self, config: ModelConfig, model_dir: Path | None = None) -> None:- if not self.accepts_config_pool(config):- if config.sie_id in self._configs:- self._drop_config_entry(config.sie_id)+ base_id = (+ config.synthetic_profile_variant_source[0]+ if config.synthetic_profile_variant_source is not None+ else config.sie_id+ )+ expanded_configs = {+ name: expanded_config+ for name, expanded_config in expand_profile_variants([config]).items()+ if self.accepts_config_pool(expanded_config)+ }+ if not expanded_configs:+ stale_ids = {base_id} | self._synthetic_profile_variant_ids_for_base(base_id)+ for stale_id in sorted(stale_ids):+ self._drop_config_entry(stale_id)return- self._configs[config.sie_id] = config+ stale_ids = ({base_id} | self._synthetic_profile_variant_ids_for_base(base_id)) - set(expanded_configs)+ for stale_id in sorted(stale_ids):+ self._drop_config_entry(stale_id)+ self._configs.update(expanded_configs)if self._model_filter is not None:- self._model_filter.add(config.sie_id)+ self._model_filter.update(expanded_configs)if model_dir is not None:- self._model_dirs[config.sie_id] = model_dir+ for name in expanded_configs:+ self._model_dirs[name] = model_dir# A config update is operator intent that may have fixed the# underlying issue (e.g. pinned a working revision, dropped a# broken adapter option). Clear any sticky failure so the next# request retries with the new config.- self._failed.pop(config.sie_id, None)+ for name in expanded_configs:+ self._failed.pop(name, None)self._config_version += 1# The config for an already-pinned model may have just arrived at runtime# (default Helm workers receive configs via the sidecar after a pin was# recorded). Eager-load it now so the pin actually keeps it resident.- self._maybe_schedule_pinned_load(config.sie_id)+ for name in expanded_configs:+ self._maybe_schedule_pinned_load(name)async def replace_configs_async(self,@@ -1424,9 +1520,13 @@ class ModelRegistry:def accepts_config_pool(self, config: ModelConfig) -> bool:if self._pool_name is None:- return True- config_pool = (config.pool or "default").strip().lower()- return config_pool == self._pool_name+ pool_matches = True+ else:+ config_pool = (config.pool or "default").strip().lower()+ pool_matches = config_pool == self._pool_name+ if not pool_matches:+ return False+ return _is_python_runtime_adapter(config.resolve_profile("default").adapter_path)def get_model_info(self, name: str) -> dict[str, Any]:"""Get information about a model.@@ -1557,7 +1657,7 @@ class ModelRegistry:"""return is_oom_error(error)- async def evict_lru_excluding(self, exclude_name: str, *, timeout_s: float = 5.0) -> bool:+ async def evict_lru_excluding(self, exclude_name: str, *, timeout_s: float = 5.0) -> EvictionResult:"""Evict the LRU model that is not ``exclude_name``.Used by the per-worker OOM recovery executor to free GPU memory by@@ -1585,9 +1685,10 @@ class ModelRegistry:giving up.Returns:- True if a sibling model was actually unloaded; False if there- was no eligible candidate, the lock could not be acquired in- time, or the eviction itself failed.+ An :class:`EvictionResult` reporting which outcome occurred —+ ``EVICTED`` when a sibling was unloaded, or ``NO_CANDIDATE`` /+ ``LOCK_TIMEOUT`` / ``UNLOAD_FAILED`` for the three formerly+ conflated failure modes."""lock = self._get_load_lock()try:@@ -1598,7 +1699,7 @@ class ModelRegistry:timeout_s,exclude_name,)- return False+ return EvictionResult.LOCK_TIMEOUTtry:# Walk LRU order and pick the first that is not ``exclude_name``,@@ -1622,9 +1723,9 @@ class ModelRegistry:await self._do_unload(candidate)except Exception:logger.exception("OOM recovery: failed to evict '%s'", candidate)- return False- return True- return False+ return EvictionResult.UNLOAD_FAILED+ return EvictionResult.EVICTED+ return EvictionResult.NO_CANDIDATEfinally:lock.release()@@ -1843,6 +1944,17 @@ class ModelRegistry:)break+ if lru_model not in self._loaded:+ # Belt-and-braces ghost guard (see #1600): drop a+ # stale MemoryManager entry with no ``_loaded``+ # model instead of spinning on a no-op _do_unload.+ logger.warning(+ "Memory monitor found ghost '%s' (not loaded); dropping stale entry",+ lru_model,+ )+ self._memory_manager.unregister_model(lru_model)+ continue+stats = self._memory_manager.get_stats()logger.info("Memory monitor: pressure %.1f%% > %.1f%% threshold, evicting LRU model '%s'",diff --git a/packages/sie_server/src/sie_server/core/residency.py b/packages/sie_server/src/sie_server/core/residency.pynew file mode 100644index 000000000..49278a10d--- /dev/null+++ b/packages/sie_server/src/sie_server/core/residency.py@@ -0,0 +1,42 @@+"""Model-residency policy types.++This module is the first seam of the planned ResidencyPolicy (issue #1569),+which will eventually own the eviction decision, the LRU order, and the+OOM-recovery cooldown that are today spread across ``core/registry.py``,+``core/memory.py`` and ``core/worker/oom_recovery.py``.++It deliberately holds only leaf types so both the registry and the worker's+OOM-recovery executor can import it without a cycle (the worker must not+import the registry).+"""++from __future__ import annotations++from enum import Enum+++class EvictionResult(Enum):+ """Typed outcome of a single LRU eviction attempt.++ Replaces the bool that ``evict_lru_excluding`` used to return, which+ collapsed three distinct non-eviction outcomes into ``False`` — so the+ caller (the worker's OOM recovery) could not tell "nothing eligible to+ evict" from "the registry was too busy to acquire the lock in time". The+ eviction *decision* now reports why, which the recovery path logs and a+ later ResidencyPolicy slice can act on.+ """++ EVICTED = "evicted"+ """A sibling model was unloaded and its GPU memory freed."""++ NO_CANDIDATE = "no_candidate"+ """No eligible sibling to evict (all pinned, already unloading, not+ loaded, or the only resident model is the caller itself)."""++ LOCK_TIMEOUT = "lock_timeout"+ """The registry load-lock could not be acquired within the soft timeout;+ another residency operation (load/unload/drain) held it. Transient —+ the caller may retry."""++ UNLOAD_FAILED = "unload_failed"+ """A candidate was selected but its unload raised."""diff --git a/packages/sie_server/src/sie_server/core/runtime_options.py b/packages/sie_server/src/sie_server/core/runtime_options.pynew file mode 100644index 000000000..477db86cb--- /dev/null+++ b/packages/sie_server/src/sie_server/core/runtime_options.py@@ -0,0 +1,60 @@+"""Single source of truth for turning a request's raw options into the+effective options an adapter sees.++A model profile declares ``adapter_options.runtime`` defaults (e.g. an+embedding model's ``query_template`` / ``default_instruction`` / ``pooling`` /+``normalize``). Those defaults must be merged under the per-request options so+the adapter receives them at encode/score time.++There are two ingress paths and they MUST agree:++* Single-server HTTP (``api.options.resolve_runtime_options`` →+ ``api.encode``) — used by ``mise run serve`` and local SDK calls.+* Cluster queue worker (``queue_executor.process_encode_batch``) — the Rust+ gateway publishes only the raw SDK options to the queue, so the worker has to+ perform the same merge itself.++Historically only the HTTP path merged profile runtime defaults; the cluster+path forwarded the raw SDK options verbatim, silently dropping+``query_template`` / ``default_instruction`` / ``pooling`` / ``normalize`` for+every queued request (issue #1489). Routing both paths through this helper+keeps them in lockstep.+"""++from __future__ import annotations++from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from sie_server.config.model import ModelConfig+++def merge_runtime_options(+ config: ModelConfig,+ request_options: dict[str, Any] | None,+) -> dict[str, Any]:+ """Resolve the selected profile and overlay request options on its runtime defaults.++ The ``"profile"`` key in ``request_options`` selects the profile and is+ consumed (not forwarded). Request-supplied values win over profile runtime+ defaults so per-request overrides still work.++ Args:+ config: The model configuration (carries the profiles).+ request_options: Raw options from the request (may be ``None`` or carry+ a ``"profile"`` key).++ Returns:+ The merged options dict ready to hand to the adapter.++ Raises:+ ValueError: If ``request_options`` names a profile that does not exist+ (propagated from ``config.resolve_profile``).+ """+ profile_name = request_options.get("profile") if request_options else None+ resolved = config.resolve_profile(profile_name or "default")++ merged: dict[str, Any] = dict(resolved.runtime)+ if request_options:+ merged |= {k: v for k, v in request_options.items() if k != "profile"}+ return mergeddiff --git a/packages/sie_server/src/sie_server/core/worker/model_worker.py b/packages/sie_server/src/sie_server/core/worker/model_worker.pyindex d54cf7a5a..bb1f37a85 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@@ -22,6 +22,7 @@ import osimport timefrom collections.abc import Sequencefrom concurrent.futures import ThreadPoolExecutor+from dataclasses import dataclassfrom typing import TYPE_CHECKING, Anyfrom sie_server.core.adaptive_batching import (@@ -134,6 +135,29 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)+@dataclass(frozen=True, slots=True)+class PreformedExtractRequest:+ prepared_items: Sequence[HasCost]+ 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+ request_id: str | None = None+ timing: RequestTiming | None = None+++@dataclass(frozen=True, slots=True)+class PreformedScoreRequest:+ prepared_items: Sequence[HasCost]+ query: Item+ items: list[Item]+ instruction: str | None = None+ options: dict[str, Any] | None = None+ request_id: str | None = None+ timing: RequestTiming | None = None++class ModelWorker:"""Worker that batches and processes inference requests for a single model.@@ -190,22 +214,12 @@ class ModelWorker:self._postprocessor_registry = postprocessor_registryself._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()+ # Protect adapter-global state, especially active LoRA selection,+ # across the direct HTTP batcher and the sidecar IPC pre-formed batch+ # entrypoints. The inference executor serialises GPU work, but LoRA+ # selection happens on the event-loop thread immediately before+ # dispatch, so the set_lora -> forward pair must be atomic.+ self._adapter_dispatch_lock = asyncio.Lock()# Initialize operation handlers (dependency injection point)if handlers is not None:@@ -226,15 +240,13 @@ class ModelWorker: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. 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]] = {}- if not self._passthrough_mode:- self._batchers[None] = BatchFormer(self._batch_config) # Base model batcher+ # Per-LoRA batchers: None = base model, "lora-name" = specific LoRA.+ # Each LoRA gets its own batcher for FCFS fairness on the direct+ # Python HTTP path. Sidecar IPC uses submit_preformed* below and+ # bypasses these batchers explicitly.+ self._batchers: dict[str | None, BatchFormer[HasCost, RequestMetadata]] = {+ None: BatchFormer(self._batch_config)+ }# Thread pool for running inference (doesn't block event loop)self._inference_executor = ThreadPoolExecutor(@@ -242,13 +254,12 @@ class ModelWorker:thread_name_prefix="inference",)- # 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.+ # Adaptive batching controller (optional, off by default). It belongs+ # to the direct Python HTTP path; sidecar IPC bypasses the process+ # loop through submit_preformed* and therefore never steps this+ # controller.ab = self._config.adaptive_batching- if ab.enabled and not self._passthrough_mode:+ if ab.enabled:self._latency_tracker: LatencyTracker | None = LatencyTracker(window_size=ab.window_size,)@@ -357,10 +368,14 @@ class ModelWorker:# =========================================================================async def start(self) -> None:- """Start the background processing task.+ """Mark the worker ready to accept requests.Should be called before submitting requests.Set SIE_INSTRUMENTATION=1 to enable detailed batch statistics.++ The direct HTTP batching loop starts lazily on the first normal+ ``submit*`` call. Sidecar IPC calls use ``submit_preformed*`` and do+ not need a Python batch loop."""if self._running:return@@ -372,22 +387,6 @@ 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",- )if self._adaptive_controller is not None:target_str = (f"{self._adaptive_controller.target_p50_ms:.0f}ms"@@ -593,6 +592,163 @@ class ModelWorker:# Score operations use base model batcher (no LoRA support for reranking)return await self._submit_to_batcher(prepared_items, metadata, None)+ async def submit_preformed(+ self,+ prepared_items: Sequence[HasCost],+ items: list[Item],+ output_types: list[str],+ *,+ instruction: str | None = None,+ is_query: bool = False,+ options: dict[str, Any] | None = None,+ request_id: str | None = None,+ timing: RequestTiming | None = None,+ ) -> asyncio.Future[WorkerResult]:+ """Run a caller-formed encode batch directly.++ Used by the worker-sidecar IPC path after Rust has already handled+ queue pull, scheduling, batching, and adaptive control. Direct HTTP+ callers should continue to use :meth:`submit` so local single-instance+ serving retains Python batching.+ """+ self._check_running()++ future, request_timing = self._create_future_and_timing(timing)+ metadata = RequestMetadata(+ future=future,+ items=items,+ output_types=output_types,+ timing=request_timing,+ instruction=instruction,+ is_query=is_query,+ options=options,+ request_id=request_id,+ )+ lora = options.get("lora") if options else None+ return await self._submit_preformed_batch(prepared_items, metadata, lora)++ async def submit_extract_preformed(+ self,+ prepared_items: Sequence[HasCost],+ 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,+ request_id: str | None = None,+ timing: RequestTiming | None = None,+ ) -> asyncio.Future[WorkerResult]:+ """Run a caller-formed extract batch directly for sidecar IPC."""+ self._check_running()++ future, request_timing = self._create_future_and_timing(timing)+ metadata = RequestMetadata(+ future=future,+ items=items,+ timing=request_timing,+ request_id=request_id,+ operation="extract",+ labels=labels,+ output_schema=output_schema,+ instruction=instruction,+ options=options,+ )+ lora = options.get("lora") if options else None+ return await self._submit_preformed_batch(prepared_items, metadata, lora)++ async def submit_extract_preformed_batch(+ self,+ requests: Sequence[PreformedExtractRequest],+ *,+ lora: str | None,+ ) -> list[asyncio.Future[WorkerResult]]:+ """Run caller-formed extract requests as one sidecar IPC batch.++ The caller has already decided the queue batch. We preserve that+ grouping and let ``_process_batch`` split only on adapter config.+ ``lora`` is explicit because adapter LoRA state is global for the+ forward pass and must be homogeneous for the synthetic batch.+ """+ self._check_running()++ entries: list[tuple[Sequence[HasCost], RequestMetadata]] = []+ for req in requests:+ future, request_timing = self._create_future_and_timing(req.timing)+ entries.append(+ (+ req.prepared_items,+ RequestMetadata(+ future=future,+ items=req.items,+ timing=request_timing,+ request_id=req.request_id,+ operation="extract",+ labels=req.labels,+ output_schema=req.output_schema,+ instruction=req.instruction,+ options=req.options,+ ),+ )+ )++ return await self._submit_preformed_metadata_batch(entries, lora)++ async def submit_score_preformed(+ self,+ prepared_items: Sequence[HasCost],+ query: Item,+ items: list[Item],+ *,+ instruction: str | None = None,+ options: dict[str, Any] | None = None,+ request_id: str | None = None,+ timing: RequestTiming | None = None,+ ) -> asyncio.Future[WorkerResult]:+ """Run a caller-formed score batch directly for sidecar IPC."""+ self._check_running()++ future, request_timing = self._create_future_and_timing(timing)+ metadata = RequestMetadata(+ future=future,+ items=items,+ timing=request_timing,+ request_id=request_id,+ operation="score",+ query=query,+ instruction=instruction,+ options=options,+ )+ return await self._submit_preformed_batch(prepared_items, metadata, None)++ async def submit_score_preformed_batch(+ self,+ requests: Sequence[PreformedScoreRequest],+ ) -> list[asyncio.Future[WorkerResult]]:+ """Run caller-formed score requests as one sidecar IPC batch."""+ self._check_running()++ entries: list[tuple[Sequence[HasCost], RequestMetadata]] = []+ for req in requests:+ future, request_timing = self._create_future_and_timing(req.timing)+ entries.append(+ (+ req.prepared_items,+ RequestMetadata(+ future=future,+ items=req.items,+ timing=request_timing,+ request_id=req.request_id,+ operation="score",+ query=req.query,+ instruction=req.instruction,+ options=req.options,+ ),+ )+ )++ return await self._submit_preformed_metadata_batch(entries, None)+# =========================================================================# Internal Helpers# =========================================================================@@ -623,12 +779,6 @@ 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:- returnmax_queue = self._config.max_queue_sizeif max_queue > 0:current_pending = self.pending_count@@ -671,20 +821,38 @@ 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])+ self._ensure_process_loop_started()return metadata.future- async def _submit_passthrough(+ def _ensure_process_loop_started(self) -> None:+ if self._process_task is None:+ self._process_task = asyncio.create_task(+ self._process_loop(),+ name="model-worker-process",+ )++ def _check_running(self) -> None:+ if not self._running:+ msg = "ModelWorker is not running"+ raise RuntimeError(msg)++ async def _submit_preformed_batch(self,prepared_items: Sequence[HasCost],metadata: RequestMetadata,lora: str | None,) -> asyncio.Future[WorkerResult]:- """Run the IPC frame as exactly one GPU forward pass.+ await self._submit_preformed_metadata_batch([(prepared_items, metadata)], lora)+ return metadata.future++ async def _submit_preformed_metadata_batch(+ self,+ entries: Sequence[tuple[Sequence[HasCost], RequestMetadata]],+ lora: str | None,+ ) -> list[asyncio.Future[WorkerResult]]:+ """Run a caller-formed batch without the internal BatchFormer.Builds a synthetic ``FormattedBatch`` directly from ``prepared_items``— bypassing the BatchFormer / FCFS / adaptive controller entirely@@ -692,32 +860,48 @@ class ModelWorker:operation handlers, postprocessors and timing instrumentation allkeep working unchanged.- Concurrency: held under ``_passthrough_lock`` so concurrent submits+ Concurrency: held under ``_adapter_dispatch_lock`` so concurrent callsto different LoRAs cannot interleave the (``set_active_lora`` →``_process_batch``) pair, which otherwise races on the adapter'sactive-LoRA state. The single-thread inference executor wouldalready serialise the GPU work — the lock specifically protectsthe LoRA-set-then-forward atomicity."""+ items_list: list[HasCost] = []+ metadata_per_item: list[RequestMetadata] = []+ futures: list[asyncio.Future[WorkerResult]] = []+ total_cost = 0+# 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)+ for prepared_items, metadata in entries:+ request_items = list(prepared_items)+ if not request_items:+ metadata.future.set_exception(ValueError("preformed request contains no prepared items"))+ futures.append(metadata.future)+ continue+ items_list.extend(request_items)+ total_cost += sum(item.cost for item in request_items)+ # ``_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.extend([metadata] * len(request_items))+ futures.append(metadata.future)++ if not items_list:+ return futures+synthetic_batch: FormattedBatch[HasCost, RequestMetadata] = FormattedBatch(items=items_list,metadata=metadata_per_item,total_cost=total_cost,)- async with self._passthrough_lock:+ async with self._adapter_dispatch_lock:self._adapter.set_active_lora(lora)await self._process_batch(synthetic_batch)- return metadata.future+ return futures# =========================================================================# Batch Processing@@ -774,6 +958,42 @@ class ModelWorker:# Return empty batch to exit gracefullyreturn None, FormattedBatch(items=[], metadata=[], total_cost=0), was_idle+ async def _drain_active_batcher(self, active_lora: str | None) -> bool:+ """Continuous-batching drain of ``active_lora``'s batcher.++ Bounded to the backlog present at entry: a saturated LoRA whose+ ``submit()`` coroutines keep refilling its own batcher during each GPU+ forward pass would otherwise never let this loop exit, starving sibling+ LoRAs / the base model (they are only re-examined once control returns+ to ``_get_next_batch_fcfs``). Draining at most the entry backlog and+ then returning restores the oldest-first FCFS fairness the docstring+ there advertises. See #1606.++ Returns True if any items were drained.+ """+ batcher = self._batchers.get(active_lora)+ if batcher is None:+ return False++ # Snapshot the backlog at entry; items that arrive mid-drain wait for+ # the next FCFS selection instead of extending the drain indefinitely.+ # Cap every drain to the remaining budget so a batch formed late in the+ # loop can't sweep in post-snapshot arrivals and overshoot the backlog.+ drain_budget = batcher.pending_count+ drained = False+ while drain_budget > 0:+ drain_batch = await batcher.try_drain(max_items=drain_budget)+ if drain_batch is None or drain_batch.size == 0:+ break+ drained = True+ drain_budget -= drain_batch.size+ await self._process_batch(drain_batch)+ if _HAS_BATCH_METRICS:+ _label_name = self._model_name or "unknown"+ GPU_BATCH_ITEMS.labels(model=_label_name).observe(drain_batch.size)+ GPU_BATCH_TOKENS.labels(model=_label_name).observe(drain_batch.total_tokens)+ return drained+async def _process_loop(self) -> None:"""Background loop that processes batches using FCFS across LoRAs."""logger.debug("Process loop started")@@ -808,30 +1028,23 @@ class ModelWorker: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)-- # Process the batch and track inference timeinference_start = time.monotonic()- await self._process_batch(batch)-- # Continuous batching: immediately drain items that accumulated- # during GPU inference, bypassing the coalesce/timeout wait.- # This keeps the GPU saturated without re-entering the batch- # formation loop.drained = False- batcher = self._batchers.get(active_lora)- while batcher is not None:- drain_batch = await batcher.try_drain()- if drain_batch is None or drain_batch.size == 0:- break- drained = True- await self._process_batch(drain_batch)- if _HAS_BATCH_METRICS:- _label_name = self._model_name or "unknown"- GPU_BATCH_ITEMS.labels(model=_label_name).observe(drain_batch.size)- GPU_BATCH_TOKENS.labels(model=_label_name).observe(drain_batch.total_tokens)+ async with self._adapter_dispatch_lock:+ # Set active LoRA before processing the batch and any+ # immediate drains. The lock also excludes sidecar+ # pre-formed batches from interleaving a different LoRA+ # selection between set_active_lora and adapter inference.+ self._adapter.set_active_lora(active_lora)++ # Process the batch and track inference time.+ await self._process_batch(batch)++ # Continuous batching: immediately drain items that accumulated+ # during GPU inference, bypassing the coalesce/timeout wait —+ # bounded to the backlog present at entry so a saturated LoRA+ # can't starve sibling LoRAs / the base model (#1606).+ drained = await self._drain_active_batcher(active_lora)# Determine idle state for next iteration.# Worker was busy if we drained items or processed a multi-item@@ -871,19 +1084,18 @@ class ModelWorker:if self._efficiency_tracker is not None:self._efficiency_tracker.record(batch.total_cost, self._batch_config.max_batch_cost)- # Step adaptive controller after processing.- # Note: mutating _batch_config in-place is safe here because- # both assignments happen synchronously (no await between them)- # on the single event-loop thread. BatchFormer reads these- # fields only under its own async lock, which cannot interleave- # with this synchronous block.+ # Step the adaptive controller after processing. ``apply_step``+ # owns the controller-output → _batch_config write-back (see+ # AdaptiveBatchController); it is synchronous, so the in-place+ # mutation stays safe against BatchFormer's async lock, which+ # cannot interleave with it.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 Noneprev_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+ new_wait, new_cost = self._adaptive_controller.apply_step(+ self._batch_config, observed_p50, fill_ratio, batch_size=batch.size+ )if _HAS_BATCH_METRICS:_label = self._model_name or "unknown"diff --git a/packages/sie_server/src/sie_server/core/worker/oom_recovery.py b/packages/sie_server/src/sie_server/core/worker/oom_recovery.pyindex dd53925f6..8cf5223e8 100644--- a/packages/sie_server/src/sie_server/core/worker/oom_recovery.py+++ b/packages/sie_server/src/sie_server/core/worker/oom_recovery.py@@ -16,6 +16,7 @@ from sie_server.core.oom import (ResourceExhaustedError,is_oom_error,)+from sie_server.core.residency import EvictionResultfrom sie_server.observability.metrics import record_oom_recovery_eventif TYPE_CHECKING:@@ -45,12 +46,12 @@ class RegistryCallbacks(Protocol):implementation to each worker at construction time."""- async def evict_lru_excluding(self, exclude_name: str, *, timeout_s: float) -> bool:+ async def evict_lru_excluding(self, exclude_name: str, *, timeout_s: float) -> EvictionResult:"""Evict the least-recently-used model other than ``exclude_name``.- Returns True if a model was actually unloaded, False if there was- no eligible candidate or the lock could not be acquired in time.- Implementations are expected to acquire the registry's load-lock+ Returns an :class:`EvictionResult` reporting whether a sibling was+ unloaded (``EVICTED``) or why not (``NO_CANDIDATE`` / ``LOCK_TIMEOUT``+ / ``UNLOAD_FAILED``). Implementations acquire the registry's load-lockwith the given soft timeout."""...@@ -357,12 +358,16 @@ class BatchExecutor:async def _try_evict_lru(self) -> bool:"""Ask the registry to evict the LRU model, excluding self.- Returns True if a model was actually unloaded.+ Returns True if a sibling model was actually unloaded. The registry+ reports *why* an eviction did not happen via :class:`EvictionResult`;+ we log that reason (so an OOM incident reads as "nothing to evict" vs+ "lock contention") and collapse it to a bool for the recovery+ strategy loop, which today only branches on success."""if self._registry is None:return Falsetry:- return await self._registry.evict_lru_excluding(+ result = await self._registry.evict_lru_excluding(self._model_name,timeout_s=self._config.eviction_lock_timeout_s,)@@ -376,6 +381,13 @@ class BatchExecutor:except Exception:logger.exception("Unexpected error during evict_lru_excluding")return False+ if result is not EvictionResult.EVICTED:+ logger.info(+ "OOM recovery: no eviction for model=%s (%s)",+ self._model_name,+ result.value,+ )+ return result is EvictionResult.EVICTED# ------------------------------------------------------------------# Fan-out and failure helpersdiff --git a/packages/sie_server/src/sie_server/core/worker/types.py b/packages/sie_server/src/sie_server/core/worker/types.pyindex 61a0ecead..134240338 100644--- a/packages/sie_server/src/sie_server/core/worker/types.py+++ b/packages/sie_server/src/sie_server/core/worker/types.py@@ -151,19 +151,6 @@ class WorkerConfig:# 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@dataclassdiff --git a/packages/sie_server/src/sie_server/health/nats_publisher.py b/packages/sie_server/src/sie_server/health/nats_publisher.pydeleted file mode 100644index bafa98bd1..000000000--- a/packages/sie_server/src/sie_server/health/nats_publisher.py+++ /dev/null@@ -1,148 +0,0 @@-"""Periodic worker-health publisher over NATS.--The gateway already subscribes to ``sie.health.>`` in-``packages/sie_gateway/src/discovery/nats_health.rs`` and accepts both-msgpack and JSON payloads. The canonical health transport in the-codebase was originally the WebSocket ``/ws/status`` endpoint; the-routing rollout adds NATS as a parallel, opt-in path so that pure-NATS deployments-(no HTTP fan-out from the gateway to every worker) can carry the same-information — including the new ``saturated`` flag.--**Opt-in.** The publisher only starts when ``SIE_HEALTH_NATS=1``.-The WS path remains the default; we keep the NATS path off until it-has been validated against real workloads (see plan "Risks" #4 for-the budgeting rationale).--The payload is the same ``WorkerStatusMessage`` produced by-``api.ws.build_status_message`` so there is a single source of truth for-the schema. Encoding is msgpack — matching what the gateway parses-first; JSON would also work but msgpack is what the rest of the-worker→gateway plane already speaks.-"""--from __future__ import annotations--import asyncio-import logging-import os-from collections.abc import Awaitable, Callable-from typing import TYPE_CHECKING--import msgpack-import nats-from nats.aio.client import Client as NATSClient--if TYPE_CHECKING:- from sie_sdk.types import WorkerStatusMessage---logger = logging.getLogger(__name__)--# Matches the WS publish cadence in `api/ws.py`. The gateway's existing-# subscriber tolerates either rate; staying in lockstep keeps cluster-# views consistent across transports.-DEFAULT_PUBLISH_INTERVAL_S: float = 0.2--# Subject template. The gateway subscribes to `sie.health.>` per worker-# (see `discovery/nats_health.rs::handle_nats_message`).-HEALTH_SUBJECT_TEMPLATE: str = "sie.health.{worker_id}"--# Env flag that turns the publisher on. Off by default — see module docstring.-ENABLE_ENV: str = "SIE_HEALTH_NATS"---def is_enabled() -> bool:- """True iff the operator opted in to NATS health publishing."""- return os.environ.get(ENABLE_ENV, "") == "1"---class NatsHealthPublisher:- """Background task that publishes ``WorkerStatusMessage`` to NATS.-- The publisher is a thin loop on top of :func:`nats.connect`; it- intentionally does not share the JetStream connection used by- ``nats_pull_loop`` so a publish failure cannot impact work- consumption. The NATS Python client multiplexes over one TCP- connection per process anyway, so the cost is one extra logical- subscription, not a second socket.- """-- def __init__(- self,- nats_url: str,- worker_id: str,- build_status: Callable[[], Awaitable[WorkerStatusMessage]],- interval_s: float = DEFAULT_PUBLISH_INTERVAL_S,- ) -> None:- self._nats_url = nats_url- self._worker_id = worker_id- self._build_status = build_status- self._interval_s = interval_s- self._subject = HEALTH_SUBJECT_TEMPLATE.format(worker_id=worker_id)- self._nc: NATSClient | None = None- self._task: asyncio.Task[None] | None = None- self._stop = asyncio.Event()-- async def start(self) -> None:- """Connect and spawn the periodic publish loop.-- Graceful degradation: a connection failure logs a warning and- leaves the publisher inert. The WS path keeps working either- way.- """- try:- # Bounded connect attempt: we want graceful degradation on- # startup if the NATS endpoint is wrong, not an indefinite- # block. Once connected, the client's own reconnect loop- # handles transient drops.- self._nc = await nats.connect(- self._nats_url,- max_reconnect_attempts=-1,- reconnect_time_wait=2,- connect_timeout=2,- allow_reconnect=True,- )- except Exception: # noqa: BLE001 — degrade gracefully when NATS down- logger.warning(- "NATS health publisher failed to connect (url=%s); WS path remains canonical",- self._nats_url,- exc_info=True,- )- return- self._stop.clear()- self._task = asyncio.create_task(self._run(), name="sie-health-nats-publisher")- logger.info(- "NATS health publisher started: subject=%s, interval_s=%.3f",- self._subject,- self._interval_s,- )-- async def _run(self) -> None:- while not self._stop.is_set():- try:- msg = await self._build_status()- payload = msgpack.packb(dict(msg), use_bin_type=True)- assert self._nc is not None- await self._nc.publish(self._subject, payload)- except Exception: # noqa: BLE001 — never crash the worker on a publish hiccup- logger.debug("NATS health publish failed", exc_info=True)- try:- await asyncio.wait_for(self._stop.wait(), timeout=self._interval_s)- except TimeoutError:- pass-- async def stop(self) -> None:- """Signal the loop to exit and drain the NATS connection."""- self._stop.set()- if self._task is not None:- try:- await asyncio.wait_for(self._task, timeout=2.0)- except TimeoutError:- self._task.cancel()- self._task = None- if self._nc is not None:- try:- await self._nc.drain()- except Exception: # noqa: BLE001 — best-effort cleanup- logger.debug("NATS health publisher drain failed", exc_info=True)- self._nc = Nonediff --git a/packages/sie_server/src/sie_server/health/saturation.py b/packages/sie_server/src/sie_server/health/saturation.pyindex 2fa67096b..a2ea6d6f3 100644--- a/packages/sie_server/src/sie_server/health/saturation.py+++ b/packages/sie_server/src/sie_server/health/saturation.py@@ -1,9 +1,9 @@"""Saturation hysteresis state machine.-The routing rollout surfaces a boolean ``saturated`` flag on the worker's status-payload (WS ``/ws/status`` and, when ``SIE_HEALTH_NATS=1``, also on-``sie.health.{worker_id}``). The gateway uses this to exclude the-worker from the HRW direct-dispatch ring.+The routing rollout surfaces a boolean ``saturated`` flag on the worker status+payload. The sidecar publishes that status over ``sie.health.{worker_id}`` in+queue-mode deployments, and the gateway uses it to exclude the worker from the+HRW direct-dispatch ring.The flag is governed by a two-threshold hysteresis to avoid thrashingunder oscillation around a single setpoint:@@ -14,11 +14,10 @@ under oscillation around a single setpoint:(default 70%), at which point it flips back to ``False``.The state machine is intentionally pure (no I/O, no clock) so it can be-unit-tested in isolation; the call sites in ``nats_pull_loop`` and-``api/ws.py`` drive it from the existing in-flight counter.--The admission-control rollout swaps the input from ``in_flight / max_batch_requests``-to ``kv_reserved / kv_budget`` — the state machine itself stays the same.+unit-tested in isolation; status publishers drive it from the active saturation+signal for their pool. Non-generation pools use an in-flight/capacity ratio,+while generation pools use ``kv_reserved / kv_budget`` — the state machine+itself stays the same."""from __future__ import annotationsdiff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.pyindex 68b8d8218..1f15321cf 100644--- a/packages/sie_server/src/sie_server/ipc_server.py+++ b/packages/sie_server/src/sie_server/ipc_server.py@@ -210,6 +210,10 @@ class IpcServer:def socket_path(self) -> Path:return self._socket_path+ @property+ def worker_id(self) -> str:+ return self._worker_id+def is_heartbeat_fresh(self, *, now_monotonic: float | None = None) -> bool:"""Return True iff the Rust side has pinged within ``stale_after_ms``.@@ -572,12 +576,20 @@ class IpcServer:def _handle_worker_capabilities(self, _req: WorkerCapabilitiesRequest) -> WorkerCapabilitiesResponse:generation_models: list[str] = []+ supported_models: list[str] = []+ loaded_models: list[str] = []try:configs = self._executor.registry.get_configs_snapshot()except Exception: # noqa: BLE001logger.debug("Could not snapshot configs for worker capabilities", exc_info=True)return WorkerCapabilitiesResponse()+ supported_models = sorted(configs)+ try:+ loaded_models = sorted(self._executor.registry.loaded_model_names)+ except Exception: # noqa: BLE001+ logger.debug("Could not snapshot loaded models for worker capabilities", exc_info=True)+for model_id, config in configs.items():try:if config.tasks.generate is not None:@@ -589,6 +601,8 @@ class IpcServer:return WorkerCapabilitiesResponse(has_generation_models=bool(generation_models),generation_models=generation_models,+ supported_models=supported_models,+ loaded_models=loaded_models,)async def _handle_signal_generate_cancel(diff --git a/packages/sie_server/src/sie_server/ipc_types.py b/packages/sie_server/src/sie_server/ipc_types.pyindex f704e61cf..f0c5ce145 100644--- a/packages/sie_server/src/sie_server/ipc_types.py+++ b/packages/sie_server/src/sie_server/ipc_types.py@@ -232,6 +232,8 @@ class WorkerCapabilitiesRequest(msgspec.Struct):class WorkerCapabilitiesResponse(msgspec.Struct):has_generation_models: bool = Falsegeneration_models: list[str] = msgspec.field(default_factory=list)+ supported_models: list[str] = msgspec.field(default_factory=list)+ loaded_models: list[str] = msgspec.field(default_factory=list)class SignalGenerateCancelRequest(msgspec.Struct):@@ -474,7 +476,7 @@ class ItemOutcome(msgspec.Struct):disposition: Dispositionnak_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.+ # The executor produces this before handing settlement back to the sidecar.result_msgpack: bytes | None = Noneerror: str | None = Noneerror_code: str | None = None@@ -529,6 +531,12 @@ class RunBatchItem(msgspec.Struct):encode: EncodeBatchItem | None = Nonescore: ScoreBatchItem | None = Noneextract: ExtractBatchItem | None = None+ # W3C trace context copied off the originating WorkItem by the Rust+ # scheduler so the non-streaming worker loop can re-extract the+ # gateway span and attach ``worker.run_batch`` as its child.+ # ``None`` when the gateway didn't propagate a trace.+ traceparent: str | None = None+ tracestate: str | None = Noneclass RunBatchRequest(msgspec.Struct):diff --git a/packages/sie_server/src/sie_server/observability/tracing.py b/packages/sie_server/src/sie_server/observability/tracing.pyindex 9dce92b24..544280c7c 100644--- a/packages/sie_server/src/sie_server/observability/tracing.py+++ b/packages/sie_server/src/sie_server/observability/tracing.py@@ -1,11 +1,13 @@"""OpenTelemetry tracing setup for SIE Server.Provides distributed tracing via OpenTelemetry with OTLP export.-Disabled by default; enabled via SIE_TRACING_ENABLED=true or --tracing flag.+Disabled by default; export requires SIE_TRACING_ENABLED=true (or --tracing)+and an explicit OTLP endpoint.Configuration via standard OTel environment variables:- OTEL_SERVICE_NAME: Service name (default: sie-server)- OTEL_TRACES_EXPORTER: Exporter type (otlp, console, none)+- OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: Trace-specific OTLP endpoint URL- OTEL_EXPORTER_OTLP_ENDPOINT: OTLP endpoint URL- OTEL_TRACES_SAMPLER: Sampling strategy- OTEL_TRACES_SAMPLER_ARG: Sampling rate@@ -33,10 +35,16 @@ logger = logging.getLogger(__name__)# This is safe to import even when tracing is disabled (returns no-op tracer)tracer = trace.get_tracer("sie_server")+# Bounded flush deadline (ms) so process exit can't stall on an unreachable collector.+TRACING_SHUTDOWN_TIMEOUT_MS = 3000++# Retained provider handle so shutdown_tracing() can flush deterministically.+_provider: TracerProvider | None = None+def is_tracing_enabled() -> bool:"""Check if tracing is enabled via environment variable."""- return os.environ.get("SIE_TRACING_ENABLED", "").lower() in ("true", "1", "yes")+ return os.environ.get("SIE_TRACING_ENABLED", "").strip().lower() in ("true", "1", "yes")def setup_tracing(app: FastAPI) -> None:@@ -52,13 +60,23 @@ def setup_tracing(app: FastAPI) -> None:app: FastAPI application instance to instrument.Note:- No-op if SIE_TRACING_ENABLED is not set to true.+ No-op unless SIE_TRACING_ENABLED is true and an OTLP endpoint is set.All configuration is via standard OTel environment variables."""if not is_tracing_enabled():logger.debug("Tracing disabled (SIE_TRACING_ENABLED not set)")return+ # Trim each var and drop whitespace-only values before the fallback so a+ # whitespace-only trace-specific endpoint can't shadow a valid generic one.+ endpoint = (+ os.environ.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "").strip()+ or os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "").strip()+ )+ if not endpoint:+ logger.warning("SIE_TRACING_ENABLED is set but no OTLP endpoint configured; tracing disabled")+ return+# Import here to avoid loading OTel machinery when tracing is disabledfrom opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (OTLPSpanExporter,@@ -75,15 +93,16 @@ def setup_tracing(app: FastAPI) -> None:# Create resource identifying this serviceresource = Resource.create({SERVICE_NAME: service_name})- # Create tracer provider- provider = TracerProvider(resource=resource)+ # Create tracer provider. We own teardown (see shutdown_tracing), so disable+ # the SDK's unbounded atexit shutdown handler.+ provider = TracerProvider(resource=resource, shutdown_on_exit=False)- # Configure OTLP exporter- # OTLPSpanExporter reads OTEL_EXPORTER_OTLP_ENDPOINT from environment+ # Configure OTLP exporter. The exporter's per-request timeout is the only+ # effective bound on shutdown flushing in the current SDK, so process exit+ # can't stall on an unreachable collector.try:- exporter = OTLPSpanExporter()+ exporter = OTLPSpanExporter(endpoint=endpoint, timeout=TRACING_SHUTDOWN_TIMEOUT_MS / 1000)provider.add_span_processor(BatchSpanProcessor(exporter))- endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317")logger.info("OTLP exporter configured for endpoint: %s", endpoint)except Exception:logger.exception("Failed to configure OTLP exporter")@@ -92,6 +111,10 @@ def setup_tracing(app: FastAPI) -> None:# Set as global tracer providertrace.set_tracer_provider(provider)+ # Retain the provider so shutdown_tracing() can flush/shut down deterministically.+ global _provider+ _provider = provider+# Update module-level tracer to use the new providerglobal tracertracer = trace.get_tracer("sie_server")@@ -103,6 +126,25 @@ def setup_tracing(app: FastAPI) -> None:logger.info("OpenTelemetry tracing initialized successfully")+def shutdown_tracing() -> None:+ """Bounded shutdown/flush of pending spans so exit can't stall on an unreachable collector.++ The bound comes from the exporter's per-request timeout set in+ ``setup_tracing`` — each export attempt inside ``provider.shutdown()`` is+ capped, so this returns promptly even when the collector is down.+ """+ global _provider+ provider = _provider+ if provider is None:+ return+ try:+ provider.shutdown()+ except Exception: # best-effort; never block process exit on tracing+ logger.exception("Tracing shutdown failed")+ finally:+ _provider = None++def get_current_trace_id() -> str | None:"""Get the current trace ID as a hex string.diff --git a/packages/sie_server/src/sie_server/processors/base.py b/packages/sie_server/src/sie_server/processors/base.pyindex d1c081332..ddcf728ee 100644--- a/packages/sie_server/src/sie_server/processors/base.py+++ b/packages/sie_server/src/sie_server/processors/base.py@@ -1,9 +1,7 @@-"""``MessageProcessor`` Protocol — the seam introduced by the walking skeleton.+"""``MessageProcessor`` Protocol for sidecar-driven generation work.-The existing batch path (encode/score/extract) still lives in-``NatsPullLoop._process_messages`` and is not yet flipped through this-protocol — the seam is sufficient for the walking skeleton. Generation-work items are dispatched here.+The sidecar owns queue fetch and settlement. Python generation work items are+dispatched here through the sidecar IPC path.A processor owns the full lifecycle of a single message: deserialization,inference, reply publish, and ACK/NAK. Returning from ``process()``diff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex 07af78501..52ea9761c 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -1,7 +1,7 @@"""Streaming processor for generation work items.-The ``StreamingProcessor`` is the gen-only branch behind the-``MessageProcessor`` seam introduced in ``NatsPullLoop._process_messages``.+The ``StreamingProcessor`` is the gen-only branch behind the sidecar IPC+``MessageProcessor`` path.The streaming rollout (this revision) drives the adapter as an async iterator:@@ -13,7 +13,7 @@ The streaming rollout (this revision) drives the adapter as an async iterator:- on the iterator's terminal yield, publish a ``{done: true}`` chunkwith ``usage`` / ``finish_reason`` / ``ttft_ms`` and ACK the JetStreamwork message-- on cancel (set externally by ``NatsPullLoop`` from the cluster-scope+- on cancel (signaled by the worker-sidecar from the cluster-scope``cancel.>`` subscription), close the iterator, flush a terminal``{finish_reason: "cancelled", done: true}`` chunk, and ACK- on sustained transport failure (>3 publish errors within 1s, or per-@@ -659,7 +659,7 @@ class StreamingProcessor:self._registry = registryself._worker_id = worker_id# request_id → {attempt_id → asyncio.Event} for in-flight generations.- # The NatsPullLoop's cancel-subscription listener calls+ # The worker-sidecar's cancel-subscription listener calls# ``signal_cancel(request_id)`` when a cancel.* message arrives, which# sets EVERY attempt's event for that request_id. The cluster-scope# subscription is on ``cancel.>``; this map is the actual filter.@@ -746,9 +746,9 @@ class StreamingProcessor:async def prewarm_grammars_for_model(self, model_id: str) -> None:"""Compile and cache ``tasks.generate.prewarm_grammars`` for ``model_id``.- Called once per generation model at worker boot (from- :class:`NatsPullLoop.start`), after the registry knows the config- but before the pool subscription dispatches request-shape work.+ Called once per generation model at worker boot through+ ``IpcServer`` after the registry knows the config but before the+ sidecar dispatches request-shape work.The cache key shape mirrors :meth:`_ensure_grammar_ready` exactlyso a request hitting one of the prewarmed grammars takes thecache-hit branch.@@ -1141,7 +1141,7 @@ class StreamingProcessor:_metrics.GENERATION_KV_RESERVED_TOKENS.labels(model=model_id).set(self._reserved)_metrics.GENERATION_IN_FLIGHT.labels(model=model_id).dec()- # -- Cancel registration (called by NatsPullLoop's cancel subscriber) ----+ # -- Cancel registration (called by the sidecar cancel subscriber) --------def _register_cancel(self, request_id: str, attempt_id: str, event: asyncio.Event) -> None:"""Register a per-attempt cancel handle.@@ -1170,7 +1170,7 @@ class StreamingProcessor:Sets the cancel event for EVERY live attempt of ``request_id`` so asingle cancel reaches all concurrent attempts (BUG 2/7). The- ``request_id``-only signature is unchanged for ``nats_pull_loop``.+ ``request_id``-only signature is the sidecar IPC cancel contract.H9 — when no attempt is registered yet (the cancel arrived beforethe work-item pull / decode-start), write a TTL'd tombstone so the@@ -1233,11 +1233,9 @@ class StreamingProcessor:def in_flight_count(self) -> int:"""Number of generate requests currently being processed by this worker.- Drives the saturation gate's ``in_flight / capacity`` fraction- in :meth:`NatsPullLoop.update_saturation`. Counts *requests*,- not fetched batches — the pull loop's- ``_in_flight_tasks`` is per-batch and dramatically understates- concurrency under fan-in load.+ Drives the saturation gate's ``in_flight / capacity`` fraction.+ Counts *requests*, not fetched batches; per-batch accounting+ dramatically understates concurrency under fan-in load."""return len(self._in_flight_cancels)@@ -1363,7 +1361,7 @@ class StreamingProcessor:# H9 — cancel tombstone check.## If the gateway's first-chunk fallback cancelled this request_id- # BEFORE this worker's pull loop registered the in-flight handle,+ # BEFORE this worker process registered the in-flight handle,# ``signal_cancel`` left a tombstone behind. The pool-republished# attempt is already in flight (or has completed) on another worker;# decoding here would burn GPU/KV/billing for a request the client@@ -2439,6 +2437,7 @@ class StreamingProcessor:async def _ensure_loaded(self, model_id: str) -> Any:if self._registry.is_loaded(model_id):+ self._registry.touch_lru(model_id)return self._registry.get(model_id)device = self._registry.devicereturn await self._registry.load_async(model_id, device)diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex e5096527b..2d2b4b7e0 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -1,12 +1,14 @@from __future__ import annotations+import asyncioimport loggingimport osimport tempfilefrom pathlib import Path-from typing import Any, Final, cast+from typing import Any, Finalimport msgpack+import msgspecimport yamlfrom sie_server.api.ws import compute_bundle_config_hash_cached@@ -14,9 +16,11 @@ from sie_server.config.model import ModelConfigfrom sie_server.core.oom import is_oom_errorfrom sie_server.core.prepared import ExtractPreparedItemfrom sie_server.core.registry import ModelRegistry+from sie_server.core.runtime_options import merge_runtime_optionsfrom sie_server.core.score_cost import build_score_prepared_itemsfrom sie_server.core.timing import RequestTimingfrom sie_server.core.worker.handlers.extract import ExtractHandler+from sie_server.core.worker.model_worker import PreformedExtractRequest, PreformedScoreRequestfrom sie_server.ipc_types import (ApplyModelConfigRequest,ApplyModelConfigResponse,@@ -41,12 +45,28 @@ from sie_server.ipc_types import (SparseOutput,)from sie_server.observability.metrics import record_ipc_batch_shape-from sie_server.types.inputs import InvalidMediaError, Item+from sie_server.types.inputs import InvalidMediaError, Item, decode_itemfrom sie_server.types.responses import ErrorCodelogger = logging.getLogger(__name__)+# ---------------------------------------------------------------------------+# Queue-path wire error code+# ---------------------------------------------------------------------------+#+# The queue / sidecar path publishes ``ItemOutcome.error_code`` as a lowercase+# wire string the Rust gateway consumes. The gateway maps any worker code+# outside its stable set to this same ``inference_error`` discriminator (see+# ``stable_code`` in ``handlers/proxy.rs``), so this is the sidecar↔gateway+# contract value — NOT the uppercase ``ErrorCode.INFERENCE_ERROR`` enum, which+# is the *in-process HTTP* surface's generic-failure code. Keep it lowercase+# and keep it here as the single definition every queue-path emitter shares;+# do not "align" it to the HTTP enum or the gateway will fall through to its+# generic arm with a mismatched code.+_INFERENCE_ERROR_CODE: Final[str] = "inference_error"++# ---------------------------------------------------------------------------# Rust-side output framing: every adapter that emits typed RawOutput# ---------------------------------------------------------------------------@@ -365,7 +385,13 @@ def _maybe_multivector_raw_output(# Wire formatting helpers# ----------------------------------------------------------------------------_NP_DTYPE_MAP = {"float32": "float32", "float16": "float16", "int8": "int8", "uint8": "binary"}+# NOTE: uint8 maps to "uint8", NOT "binary". Bit-packed binary is detected by+# the explicit ``is_binary`` shape-check (``arr.shape < dim``) at each call site,+# which is the SOLE emitter of "binary"; a linear uint8 quantization keeps full+# dimensionality so it must stay labelled "uint8" to match the HTTP path+# (api/encode.py::_format_dense -> np_to_dtype). Mapping uint8->"binary" here+# made the queue path disagree with HTTP for the same request. See #1603.+_NP_DTYPE_MAP = {"float32": "float32", "float16": "float16", "int8": "int8", "uint8": "uint8"}def _wrap_encode_output(output: dict, config: Any) -> dict:@@ -446,18 +472,6 @@ def _wrap_encode_output(output: dict, config: Any) -> dict: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# ---------------------------------------------------------------------------@@ -755,6 +769,40 @@ class QueueExecutor:return budgetreturn None+ @staticmethod+ def _options_key(options: dict[str, Any] | None) -> bytes:+ return msgpack.packb(options, use_bin_type=True) if options else b""++ @classmethod+ def _score_sub_group_sizes(cls, items: list[ScoreBatchItem]) -> list[int]:+ groups: dict[tuple[Any, ...], int] = {}+ for bi in items:+ key = (bi.instruction, cls._options_key(bi.options))+ groups[key] = groups.get(key, 0) + 1+ return list(groups.values())++ @staticmethod+ def _extract_lora(options: dict[str, Any] | None) -> str | None:+ if not options:+ return None+ raw = options.get("lora")+ if isinstance(raw, str) and raw:+ return raw+ return None++ @classmethod+ def _extract_sub_group_sizes(cls, items: list[ExtractBatchItem]) -> list[int]:+ groups: dict[tuple[Any, ...], int] = {}+ for bi in items:+ key = (+ cls._extract_lora(bi.options),+ tuple(bi.labels) if bi.labels else None,+ bi.instruction,+ cls._options_key(bi.options),+ )+ groups[key] = groups.get(key, 0) + 1+ return list(groups.values())+# -- Encode ------------------------------------------------------------async def process_encode_batch(self, req: ProcessEncodeBatchRequest) -> BatchOutcome:@@ -814,7 +862,21 @@ class QueueExecutor:(output_types_t, instruction, is_query, options_key, _profile_id, _bundle_hash) = group_keyoutput_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]+ # Validate each item against the typed Item contract at the seam+ # (parity with the HTTP path). A per-item decode failure is isolated+ # as an INVALID_INPUT outcome so one malformed item cannot fail its+ # whole sub-group. See decode_item / issue #1537.+ good_group: list[EncodeBatchItem] = []+ server_items: list[Item] = []+ for bi in group:+ try:+ server_items.append(decode_item(bi.item))+ except (msgspec.ValidationError, InvalidMediaError) as decode_exc:+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, decode_exc)+ continue+ good_group.append(bi)+ if not good_group:+ continue# Collect worker-sidecar prepared_tokens aligned with# ``server_items``. ``None`` per item is expected for the# v1 safety-rule skips (`is_query`, `instruction`,@@ -826,7 +888,7 @@ class QueueExecutor:# 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]+ prepared_tokens_per_item = [bi.prepared_tokens for bi in good_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@@ -834,6 +896,16 @@ class QueueExecutor:prepared_tokens_per_item = Nonetry:+ # The Rust gateway publishes only the raw SDK options to the+ # queue, so — unlike the single-server HTTP path (api.encode) —+ # profile ``adapter_options.runtime`` defaults (query_template,+ # default_instruction, pooling, normalize, …) are not yet merged+ # in. Merge them here so the adapter sees the same effective+ # options regardless of ingress; without this, instruction-tuned+ # embedders silently lose their query template on the cluster+ # path (#1489). An unknown profile name raises ValueError, which+ # the surrounding except turns into per-item failures.+ options = merge_runtime_options(config, options)formatted_outputs, timing = await EncodePipeline.run_encode(registry=self._registry,model=model_id,@@ -844,9 +916,10 @@ class QueueExecutor:is_query=is_query,options=options,prepared_tokens_per_item=prepared_tokens_per_item,+ preformed_batch=True,)- if len(formatted_outputs) != len(group):+ if len(formatted_outputs) != len(good_group):# Output/input length mismatch means the adapter# silently dropped items. Surface as a per-item error# rather than publishing empty success results.@@ -854,16 +927,16 @@ class QueueExecutor:"Encode sub-batch for %s returned %d outputs for %d items — emitting per-item errors",model_id,len(formatted_outputs),- len(group),+ len(good_group),)- for bi in group:+ for bi in good_group:outcomes[bi.work_item_id] = _error_outcome(bi,- "inference_error",+ _INFERENCE_ERROR_CODE,"adapter returned fewer outputs than items",)else:- for idx, bi in enumerate(group):+ for idx, bi in enumerate(good_group):raw_output: RawOutput | None = Noneresult_msgpack: bytes | None = None# Dispatch by the single declared output type —@@ -907,7 +980,7 @@ class QueueExecutor:)except Exception as e: # noqa: BLE001logger.warning("Encode sub-batch failed for model %s: %s", model_id, e)- for bi in group:+ for bi in good_group:outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)return BatchOutcome(outcomes=[outcomes[bi.work_item_id] for bi in items])@@ -915,157 +988,216 @@ class QueueExecutor:# -- 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+ """Run score work items from the sidecar IPC path.+ The worker-sidecar owns queue batching and scheduling. Python prepares+ each score work item and executes it through ModelWorker's pre-formed+ batch entrypoint so it does not re-enter the Python BatchFormer.+ """model_id = req.model_id+ if not req.items:+ return BatchOutcome(outcomes=[])- # 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),+ sub_group_sizes=self._score_sub_group_sizes(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)+ return BatchOutcome(outcomes=[_nak_outcome(bi) for bi in req.items])- query_item = _dict_to_item(bi.query_item)- score_items = [_dict_to_item(it) for it in bi.score_items]+ outcomes: dict[str, ItemOutcome] = {}+ requests: list[PreformedScoreRequest] = []+ request_context: list[tuple[ScoreBatchItem, list[Item]]] = []- try:- timing = RequestTiming()-- timing.start_tokenization()- prepared_items = build_score_prepared_items(query_item, score_items)- 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)+ for bi in req.items:+ try:+ query_item = decode_item(bi.query_item)+ score_items = [decode_item(it) for it in bi.score_items]++ timing = RequestTiming()+ timing.start_tokenization()+ prepared_items = build_score_prepared_items(query_item, score_items)+ timing.end_tokenization()++ requests.append(+ PreformedScoreRequest(+ prepared_items=prepared_items,+ query=query_item,+ items=score_items,+ instruction=bi.instruction,+ options=bi.options or {},+ request_id=bi.request_id,+ timing=timing,+ )+ )+ request_context.append((bi, score_items))+ except Exception as e: # noqa: BLE001+ logger.warning("Score preparation failed for %s: %s", bi.work_item_id, e)+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)++ if requests:+ try:+ futures = await worker.submit_score_preformed_batch(requests)+ results = await asyncio.gather(*futures, return_exceptions=True)+ except Exception as e: # noqa: BLE001+ logger.warning("Score batch failed for model %s: %s", model_id, e)+ for bi, _score_items in request_context:+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)+ else:+ for (bi, score_items), result in zip(request_context, results, strict=True):+ if isinstance(result, BaseException):+ logger.warning("Score failed for %s: %s", bi.work_item_id, result)+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, result)+ else:+ outcomes[bi.work_item_id] = _score_success_outcome(+ bi,+ score_items,+ result,+ )++ return BatchOutcome(outcomes=[outcomes[bi.work_item_id] for bi in req.items])# -- 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-+ """Run extract work items from the sidecar IPC path."""model_id = req.model_id+ if not req.items:+ return BatchOutcome(outcomes=[])record_ipc_batch_shape(model=model_id,endpoint="extract",total_items=len(req.items),- sub_group_sizes=[1] * len(req.items),+ sub_group_sizes=self._extract_sub_group_sizes(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)+ return BatchOutcome(outcomes=[_nak_outcome(bi) for bi in req.items])- server_item = _dict_to_item(bi.item)+ outcomes: dict[str, ItemOutcome] = {}+ grouped_requests: dict[str | None, list[PreformedExtractRequest]] = {}+ grouped_context: dict[str | None, list[ExtractBatchItem]] = {}- 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)+ for bi in req.items:+ try:+ server_item = decode_item(bi.item)++ 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()++ lora = self._extract_lora(bi.options)+ grouped_requests.setdefault(lora, []).append(+ PreformedExtractRequest(+ prepared_items=prepared_items,+ items=[server_item],+ labels=bi.labels,+ output_schema=bi.output_schema,+ instruction=bi.instruction,+ options=bi.options or {},+ request_id=bi.request_id,+ timing=timing,+ )+ )+ grouped_context.setdefault(lora, []).append(bi)+ except Exception as e: # noqa: BLE001+ logger.warning("Extract preparation failed for %s: %s", bi.work_item_id, e)+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)++ for lora, requests_for_lora in grouped_requests.items():+ context = grouped_context[lora]+ try:+ futures = await worker.submit_extract_preformed_batch(requests_for_lora, lora=lora)+ results = await asyncio.gather(*futures, return_exceptions=True)+ except Exception as e: # noqa: BLE001+ logger.warning("Extract batch failed for model %s: %s", model_id, e)+ for bi in context:+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, e)+ else:+ for bi, result in zip(context, results, strict=True):+ if isinstance(result, BaseException):+ logger.warning("Extract failed for %s: %s", bi.work_item_id, result)+ outcomes[bi.work_item_id] = _inference_exception_outcome(bi, result)+ else:+ outcomes[bi.work_item_id] = _extract_success_outcome(bi, result)++ return BatchOutcome(outcomes=[outcomes[bi.work_item_id] for bi in req.items])+++def _score_success_outcome(+ bi: ScoreBatchItem,+ score_items: list[Item],+ worker_result: Any,+) -> ItemOutcome:+ score_output = 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=worker_result.timing.inference_ms,+ tokenization_ms=worker_result.timing.tokenization_ms if worker_result.timing.tokenization_ms > 0 else None,+ postprocessing_ms=worker_result.timing.postprocessing_ms+ if worker_result.timing.postprocessing_ms > 0+ else None,+ )+++def _extract_success_outcome(+ bi: ExtractBatchItem,+ worker_result: Any,+) -> ItemOutcome:+ extraction_results = ExtractHandler.format_output(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=worker_result.timing.inference_ms,+ tokenization_ms=worker_result.timing.tokenization_ms if worker_result.timing.tokenization_ms > 0 else None,+ postprocessing_ms=worker_result.timing.postprocessing_ms+ if worker_result.timing.postprocessing_ms > 0+ else None,+ )# ---------------------------------------------------------------------------@@ -1099,9 +1231,11 @@ def _inference_exception_outcome() -> ItemOutcome:if is_oom_error(exc):return _oom_nak_outcome(bi)- if isinstance(exc, InvalidMediaError):+ if isinstance(exc, (InvalidMediaError, msgspec.ValidationError)):+ # A typed-decode failure (decode_item) or a media contract violation;+ # both surface as INVALID_INPUT (HTTP 400), matching the HTTP path.return _error_outcome(bi, ErrorCode.INVALID_INPUT.value, str(exc))- return _error_outcome(bi, "inference_error", str(exc))+ return _error_outcome(bi, _INFERENCE_ERROR_CODE, str(exc))def _error_outcome(bi: EncodeBatchItem | ScoreBatchItem | ExtractBatchItem, code: str, message: str) -> ItemOutcome:@@ -1122,8 +1256,6 @@ def _default_nak_delay_s() -> float:redelivery behaviour is consistent across either side choosing thefallback."""- import os # noqa: PLC0415-return float(os.environ.get("SIE_NAK_DELAY_S", "5.0"))diff --git a/packages/sie_server/src/sie_server/static/index.html b/packages/sie_server/src/sie_server/static/index.htmlindex db11ba23b..6af59b213 100644--- a/packages/sie_server/src/sie_server/static/index.html+++ b/packages/sie_server/src/sie_server/static/index.html@@ -5,33 +5,177 @@<meta name="viewport" content="width=device-width, initial-scale=1" /><title>SIE Server</title><style>- body { font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif; margin: 2rem; background:#050816; color:#e5e7eb;}- .card { max-width: 640px; padding: 1.75rem 2rem; border-radius: 1rem; background: #020617; box-shadow: 0 20px 40px rgba(0,0,0,0.45); border: 1px solid #1f2937;}- h1 { font-size: 1.75rem; margin: 0 0 0.5rem; }- p { margin: 0.25rem 0; color: #9ca3af; }- code { background: #111827; padding: 0.15rem 0.35rem; border-radius: 0.35rem; font-size: 0.9em; }- .pill { display:inline-flex; align-items:center; gap:0.35rem; padding:0.2rem 0.6rem; border-radius:999px; background:#022c22; color:#6ee7b7; font-size:0.75rem; text-transform:uppercase; letter-spacing:0.08em; }- .links { margin-top: 1.25rem; display:flex; flex-wrap:wrap; gap:0.75rem; }- a { color:#93c5fd; text-decoration:none; font-size:0.9rem; }- a:hover, a:focus { text-decoration:underline; outline:none; }- a:focus-visible { outline:2px solid #93c5fd; outline-offset:2px; }- .badge-dot { width:0.4rem; height:0.4rem; border-radius:999px; background:#22c55e; box-shadow:0 0 0 4px rgba(34,197,94,0.35);}+ :root { color-scheme: dark; }+ body { font-family: system-ui, -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background:#050816; color:#e5e7eb; }+ .wrap { max-width: 860px; margin: 2rem auto; padding: 0 1.25rem; }+ header { display:flex; align-items:center; justify-content:space-between; gap:1rem; margin-bottom: 0.5rem; }+ h1 { font-size: 1.6rem; margin: 0; }+ p.sub { margin: 0.25rem 0 1.25rem; color:#9ca3af; }+ .pill { display:inline-flex; align-items:center; gap:0.4rem; padding:0.2rem 0.6rem; border-radius:999px; background:#022c22; color:#6ee7b7; font-size:0.72rem; text-transform:uppercase; letter-spacing:0.08em; }+ .badge-dot { width:0.4rem; height:0.4rem; border-radius:999px; background:#22c55e; box-shadow:0 0 0 4px rgba(34,197,94,0.35); }+ .tabs { display:flex; gap:0.4rem; margin-bottom: 0.9rem; }+ .tab { padding:0.45rem 0.9rem; border-radius:0.6rem 0.6rem 0 0; background:#0b1220; color:#9ca3af; cursor:pointer; border:1px solid #1f2937; border-bottom:none; font-size:0.9rem; }+ .tab.active { background:#020617; color:#e5e7eb; }+ .panel { display:none; background:#020617; border:1px solid #1f2937; border-radius:0 0.75rem 0.75rem 0.75rem; padding:1.1rem; }+ .panel.active { display:block; }+ label { display:block; font-size:0.78rem; color:#9ca3af; margin:0.6rem 0 0.25rem; text-transform:uppercase; letter-spacing:0.05em; }+ input, textarea { width:100%; box-sizing:border-box; background:#0b1220; color:#e5e7eb; border:1px solid #1f2937; border-radius:0.5rem; padding:0.55rem 0.7rem; font-size:0.95rem; font-family:inherit; }+ textarea { resize:vertical; min-height:3.5rem; }+ button { margin-top:0.8rem; padding:0.55rem 1.1rem; border-radius:0.5rem; border:none; background:#2563eb; color:white; font-weight:600; cursor:pointer; font-size:0.95rem; }+ button:disabled { opacity:0.5; cursor:default; }+ .out { margin-top:1rem; padding:0.8rem; background:#0b1220; border:1px solid #1f2937; border-radius:0.5rem; white-space:pre-wrap; word-break:break-word; min-height:2.5rem; font-size:0.95rem; }+ .meta { margin-top:0.5rem; font-size:0.8rem; color:#6ee7b7; }+ .err { color:#fca5a5; }+ .links { margin-top:1.25rem; display:flex; flex-wrap:wrap; gap:1rem; }+ a { color:#93c5fd; text-decoration:none; font-size:0.88rem; }+ a:hover { text-decoration:underline; }+ .row { display:flex; gap:0.75rem; } .row > div { flex:1; }+ code { background:#111827; padding:0.1rem 0.3rem; border-radius:0.3rem; font-size:0.85em; }</style></head><body>- <div class="card">- <div style="display:flex; align-items:center; justify-content:space-between; gap:1rem;">+ <div class="wrap">+ <header><h1>SIE Server</h1>- <span class="pill"><span class="badge-dot"></span>Running</span>+ <span class="pill"><span class="badge-dot"></span><span id="status">running</span></span>+ </header>+ <p class="sub">One local OpenAI-compatible endpoint — embeddings, reranking, and generation. Try it below or point any OpenAI/Cohere client at <code>/v1</code>.</p>++ <div class="tabs" role="tablist" aria-label="Playground modes">+ <div class="tab active" data-tab="chat" role="tab" tabindex="0" aria-selected="true">Chat</div>+ <div class="tab" data-tab="embed" role="tab" tabindex="0" aria-selected="false">Embeddings</div>+ <div class="tab" data-tab="rerank" role="tab" tabindex="0" aria-selected="false">Rerank</div></div>- <p>Search Inference Engine - embeddings, reranking, and small-model inference.</p>- <p>Use the HTTP API at <code>/v1/encode/<model></code>, or the Python SDK via <code>sie_sdk.SIEClient</code>.</p>++ <div class="panel active" id="panel-chat">+ <label for="chat-model">Model</label>+ <input id="chat-model" value="Qwen/Qwen3.5-4B" />+ <label for="chat-input">Message</label>+ <textarea id="chat-input">Write one sentence about Apple Silicon.</textarea>+ <button id="chat-send">Send</button>+ <div class="out" id="chat-out"></div>+ <div class="meta" id="chat-meta"></div>+ </div>++ <div class="panel" id="panel-embed">+ <label for="embed-model">Model</label>+ <input id="embed-model" value="BAAI/bge-m3" />+ <label for="embed-input">Texts (one per line)</label>+ <textarea id="embed-input">hello world+apple silicon inference</textarea>+ <button id="embed-send">Embed</button>+ <div class="out" id="embed-out"></div>+ <div class="meta" id="embed-meta"></div>+ </div>++ <div class="panel" id="panel-rerank">+ <label for="rerank-model">Model</label>+ <input id="rerank-model" value="BAAI/bge-reranker-v2-m3" />+ <div class="row">+ <div><label for="rerank-query">Query</label><input id="rerank-query" value="apple silicon" /></div>+ </div>+ <label for="rerank-docs">Documents (one per line)</label>+ <textarea id="rerank-docs">M-series chips power Macs+the weather is nice today+Metal GPU inference on Apple</textarea>+ <button id="rerank-send">Rerank</button>+ <div class="out" id="rerank-out"></div>+ <div class="meta" id="rerank-meta"></div>+ </div>+<div class="links">- <a href="/healthz">Health: /healthz</a>- <a href="/readyz">Readiness: /readyz</a>- <a href="/v1/models">List models: /v1/models</a>- <a href="/docs">OpenAPI docs: /docs</a>+ <a href="/docs">OpenAPI docs</a>+ <a href="/v1/models">List models</a>+ <a href="/healthz">/healthz</a>+ <a href="/readyz">/readyz</a></div></div>++ <script>+ const $ = (id) => document.getElementById(id);+ const tabs = [...document.querySelectorAll(".tab")];+ const activateTab = (t) => {+ tabs.forEach((x) => { x.classList.remove("active"); x.setAttribute("aria-selected", "false"); });+ document.querySelectorAll(".panel").forEach((x) => x.classList.remove("active"));+ t.classList.add("active");+ t.setAttribute("aria-selected", "true");+ $("panel-" + t.dataset.tab).classList.add("active");+ t.focus();+ };+ tabs.forEach((t, i) => {+ t.onclick = () => activateTab(t);+ t.onkeydown = (e) => {+ if (e.key === "Enter" || e.key === " ") { e.preventDefault(); activateTab(t); }+ else if (e.key === "ArrowRight" || e.key === "ArrowLeft") {+ e.preventDefault();+ activateTab(tabs[(i + (e.key === "ArrowRight" ? 1 : -1) + tabs.length) % tabs.length]);+ }+ };+ });+ fetch("/readyz").then((r) => { $("status").textContent = r.ok ? "ready" : "loading"; }).catch(() => {});++ // Chat (streaming /v1/chat/completions)+ $("chat-send").onclick = async () => {+ const btn = $("chat-send"), out = $("chat-out"), meta = $("chat-meta");+ out.textContent = ""; out.classList.remove("err"); meta.textContent = ""; btn.disabled = true;+ const t0 = performance.now(); let ttft = null, toks = 0;+ try {+ const resp = await fetch("/v1/chat/completions", {+ method: "POST", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ model: $("chat-model").value, messages: [{ role: "user", content: $("chat-input").value }], max_tokens: 256, temperature: 0.7, stream: true, stream_options: { include_usage: true } }),+ });+ if (!resp.ok) { out.classList.add("err"); out.textContent = "HTTP " + resp.status + ": " + (await resp.text()); btn.disabled = false; return; }+ const reader = resp.body.getReader(); const dec = new TextDecoder(); let buf = "";+ for (;;) {+ const { value, done } = await reader.read(); if (done) break;+ buf += dec.decode(value, { stream: true }); const lines = buf.split("\n"); buf = lines.pop();+ for (let line of lines) {+ line = line.trim(); if (!line.startsWith("data:")) continue; line = line.slice(5).trim();+ if (!line || line === "[DONE]") continue;+ let e; try { e = JSON.parse(line); } catch { continue; }+ const d = (e.choices && e.choices[0] && e.choices[0].delta) || {};+ if (d.content) { if (ttft === null) ttft = performance.now() - t0; toks++; out.textContent += d.content; }+ if (e.usage && e.usage.completion_tokens) toks = e.usage.completion_tokens;+ }+ }+ const dt = (performance.now() - t0) / 1000;+ meta.textContent = `${toks} tokens · ${(toks / dt).toFixed(1)} tok/s` + (ttft !== null ? ` · ttft ${ttft.toFixed(0)} ms` : "");+ } catch (err) { out.classList.add("err"); out.textContent = String(err); }+ btn.disabled = false;+ };++ // Embeddings+ $("embed-send").onclick = async () => {+ const btn = $("embed-send"), out = $("embed-out"), meta = $("embed-meta");+ out.textContent = "…"; out.classList.remove("err"); meta.textContent = ""; btn.disabled = true;+ const texts = $("embed-input").value.split("\n").map((s) => s.trim()).filter(Boolean);+ const t0 = performance.now();+ try {+ const resp = await fetch("/v1/embeddings", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: $("embed-model").value, input: texts }) });+ const data = await resp.json();+ if (!resp.ok) { out.classList.add("err"); out.textContent = JSON.stringify(data, null, 2); btn.disabled = false; return; }+ const dim = data.data[0].embedding.length;+ out.textContent = data.data.map((d, i) => `[${i}] dim=${dim} [${d.embedding.slice(0, 6).map((x) => x.toFixed(4)).join(", ")}, …]`).join("\n");+ meta.textContent = `${data.data.length} vectors · ${((performance.now() - t0) / 1000).toFixed(2)}s`;+ } catch (err) { out.classList.add("err"); out.textContent = String(err); }+ btn.disabled = false;+ };++ // Rerank+ $("rerank-send").onclick = async () => {+ const btn = $("rerank-send"), out = $("rerank-out"), meta = $("rerank-meta");+ out.textContent = "…"; out.classList.remove("err"); meta.textContent = ""; btn.disabled = true;+ const docs = $("rerank-docs").value.split("\n").map((s) => s.trim()).filter(Boolean);+ const t0 = performance.now();+ try {+ const resp = await fetch("/v1/rerank", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model: $("rerank-model").value, query: $("rerank-query").value, documents: docs, return_documents: true }) });+ const data = await resp.json();+ if (!resp.ok) { out.classList.add("err"); out.textContent = JSON.stringify(data, null, 2); btn.disabled = false; return; }+ out.textContent = data.results.map((r) => `${r.relevance_score.toFixed(4)} ${(r.document && r.document.text) || "#" + r.index}`).join("\n");+ meta.textContent = `${data.results.length} ranked · ${((performance.now() - t0) / 1000).toFixed(2)}s`;+ } catch (err) { out.classList.add("err"); out.textContent = String(err); }+ btn.disabled = false;+ };+ </script></body></html>diff --git a/packages/sie_server/src/sie_server/types/inputs.py b/packages/sie_server/src/sie_server/types/inputs.pyindex 465e4cad4..cfab12743 100644--- a/packages/sie_server/src/sie_server/types/inputs.py+++ b/packages/sie_server/src/sie_server/types/inputs.py@@ -214,3 +214,42 @@ def media_bytes(media: object, *, kind: str = "media") -> bytes:f"{kind} data must be bytes, got {type(data).__name__} ""(base64 JSON strings must be decoded to bytes before inference)")+++# =============================================================================+# Validated item decode+# =============================================================================+++def decode_item(raw: dict[str, Any]) -> Item:+ """Validate a wire-format item mapping into a typed :class:`Item`.++ The HTTP ingress path decodes request bodies straight into typed msgspec+ structs (``msgspec.json/msgpack.decode(body, type=...)``), so an item whose+ fields have the wrong type is rejected at the seam with ``INVALID_INPUT``.+ The queue / IPC path receives each item as a plain ``dict``+ (``msgpack.unpackb``) and historically built ``Item(**kwargs)``, which+ performs *no* type validation — a malformed item slipped through to fail+ deep inside a preprocessor/adapter (see issue #1026).++ This is the single validating decode for dict-sourced items: it runs the+ same ``Item`` contract through :func:`msgspec.convert`, so the queue path+ rejects type violations exactly where the HTTP path does and base64-decodes+ ``str`` media ``data`` to ``bytes`` the same way the JSON path does. The+ ``*Input`` TypedDicts are ``total=False``, so missing/empty media ``data``+ is still enforced at point of use by :func:`media_bytes`.++ Args:+ raw: The wire-format item mapping. The SDK ships ``content`` as an+ alias for ``text``; it is remapped when ``text`` is absent.++ Returns:+ A validated :class:`Item`.++ Raises:+ msgspec.ValidationError: If a field is present with the wrong type.+ Both ingress paths surface this as ``INVALID_INPUT`` (HTTP 400).+ """+ if "content" in raw and "text" not in raw:+ raw = {**raw, "text": raw["content"]}+ return msgspec.convert(raw, type=Item)diff --git a/packages/sie_server/tests/adapters/test_flash_pack.py b/packages/sie_server/tests/adapters/test_flash_pack.pynew file mode 100644index 000000000..ca23206f9--- /dev/null+++ b/packages/sie_server/tests/adapters/test_flash_pack.py@@ -0,0 +1,47 @@+"""Equivalence tests for the shared flash varlen packing helper (issue #1538).++``build_position_ids`` replaces per-adapter ``torch.arange`` loops. These tests+pin it to be bit-identical to those loops (zero-based and padding-offset) across+``int32``/``int64`` ``cu_seqlens`` and zero-length sequences.+"""++from __future__ import annotations++import torch+from sie_server.adapters._flash_pack import build_position_ids++# Includes a zero-length middle sequence ([0, 2, 2, 5]) and single-token seqs.+_CASES = [[0, 3, 7, 8], [0, 5], [0, 1, 4, 4, 9], [0, 2, 2, 5], [0, 1, 2, 3]]+++def _loop(cu: list[int], *, offset: int) -> torch.Tensor:+ parts = []+ for i in range(len(cu) - 1):+ seq_len = cu[i + 1] - cu[i]+ parts.append(torch.arange(offset, offset + seq_len, dtype=torch.long))+ return torch.cat(parts)+++def test_matches_zero_based_loop() -> None:+ for dtype in (torch.int32, torch.int64):+ for case in _CASES:+ cu = torch.tensor(case, dtype=dtype)+ assert torch.equal(build_position_ids(cu), _loop(case, offset=0))+++def test_matches_padding_offset_loop() -> None:+ # XLM-RoBERTa style: positions start at padding_idx + 1 (here padding_idx=1).+ for dtype in (torch.int32, torch.int64):+ for case in _CASES:+ cu = torch.tensor(case, dtype=dtype)+ assert torch.equal(build_position_ids(cu, offset=2), _loop(case, offset=2))+++def test_result_is_int64() -> None:+ cu = torch.tensor([0, 3, 5], dtype=torch.int32)+ assert build_position_ids(cu).dtype == torch.int64+++def test_single_token_sequences() -> None:+ cu = torch.tensor([0, 1, 2, 3])+ assert torch.equal(build_position_ids(cu), torch.tensor([0, 0, 0]))diff --git a/packages/sie_server/tests/adapters/test_mlx_generation.py b/packages/sie_server/tests/adapters/test_mlx_generation.pynew file mode 100644index 000000000..2d02d5e4e--- /dev/null+++ b/packages/sie_server/tests/adapters/test_mlx_generation.py@@ -0,0 +1,266 @@+"""Tests for MLXGenerationAdapter (Apple-Silicon generation via mlx_lm.server).++These run on any platform (Linux CI included) — they never spawn a real+subprocess. They mock the httpx layer to exercise the OpenAI ``/v1/completions``+SSE parsing, and cover the device-swap factory, the kwarg translation, and the+``mlx_repo``-required guard.+"""++from __future__ import annotations++from typing import Any, Self+from unittest.mock import patch++import pytest+from sie_server.adapters._generation_base import collect_generation+from sie_server.adapters.mlx.generation import MLXGenerationAdapter+from sie_server.adapters.sglang.generation import (+ SGLangGenerationAdapter,+ _translate_to_mlx_kwargs,+)+++def adapter() -> MLXGenerationAdapter:+ a = MLXGenerationAdapter(model_name_or_path="Qwen/Qwen3.5-4B", mlx_repo="mlx-community/Qwen3.5-4B-4bit")+ # Pretend it loaded (skip the real subprocess) so generate()'s loaded-check passes.+ a._server_url = "http://127.0.0.1:30200"+ return a+++# -- Contract -----------------------------------------------------------------+++def test_contract_flags_and_spec() -> None:+ assert MLXGenerationAdapter.requires_main_thread is False+ assert MLXGenerationAdapter.manages_own_load_timeout is True+ assert "tokens" in MLXGenerationAdapter.spec.outputs+++def test_capabilities(adapter: MLXGenerationAdapter) -> None:+ caps = adapter.capabilities+ assert caps.inputs == ["text"]+ assert caps.outputs == ["tokens"]+++# -- Device swap + kwarg translation -----------------------------------------+++def test_create_for_device_cuda_keeps_sglang() -> None:+ a = SGLangGenerationAdapter.create_for_device("cuda:0", model_name_or_path="Qwen/Qwen3.5-4B")+ assert isinstance(a, SGLangGenerationAdapter)+++def test_create_for_device_mps_swaps_to_mlx() -> None:+ a = SGLangGenerationAdapter.create_for_device(+ "mps",+ model_name_or_path="Qwen/Qwen3.5-4B",+ mlx_repo="mlx-community/Qwen3.5-4B-4bit",+ mem_fraction_static=0.85,+ speculative={"enabled": True},+ )+ assert isinstance(a, MLXGenerationAdapter)+ assert a.mlx_repo == "mlx-community/Qwen3.5-4B-4bit"+++def test_translate_drops_cuda_only_and_keeps_mlx_kwargs() -> None:+ out = _translate_to_mlx_kwargs(+ {+ "model_name_or_path": "Qwen/Qwen3.5-4B",+ "mlx_repo": "mlx-community/Qwen3.5-4B-4bit",+ "max_seq_length": 8192,+ "default_sampling": {"temperature": 0.7},+ "stop_tokens": ["<|im_end|>"],+ "served_model_name": "Qwen/Qwen3.5-4B",+ # CUDA/SGLang-only — must be dropped:+ "mem_fraction_static": 0.9,+ "speculative": {"enabled": True},+ "attention_backend": "triton",+ "grammar_backend": "outlines",+ "tool_call_parser": "qwen3_coder",+ "lora_paths": {"a": "b"},+ "compute_precision": "bfloat16",+ }+ )+ assert out["mlx_repo"] == "mlx-community/Qwen3.5-4B-4bit"+ assert out["max_seq_length"] == 8192+ assert out["default_sampling"] == {"temperature": 0.7}+ for dropped in (+ "mem_fraction_static",+ "speculative",+ "attention_backend",+ "grammar_backend",+ "tool_call_parser",+ "lora_paths",+ "compute_precision",+ ):+ assert dropped not in out+++# -- mlx_repo guard -----------------------------------------------------------+++def test_load_without_mlx_repo_fails_fast() -> None:+ a = MLXGenerationAdapter(model_name_or_path="Qwen/Qwen3.6-27B") # no mlx_repo+ assert a.mlx_repo is None+ with pytest.raises(RuntimeError, match="mlx_repo"):+ a.load("mps")+++def test_load_aborts_when_warmup_fails(adapter: MLXGenerationAdapter) -> None:+ # Health passes but the warmup completion fails → load() must treat it as a load failure+ # (deterministic readiness): raise and reset state instead of reporting "ready".+ adapter._process = None # not loaded yet (the fixture only pre-set _server_url)+ fake_log = type("L", (), {"name": "/tmp/mlx_warmup_test_does_not_exist.log", "close": lambda self: None})() # noqa: S108 — fake path; unlink is suppressed+ with (+ patch("sie_server.adapters.mlx.generation._server.mlx_lm_available", return_value=True),+ patch("sie_server.adapters.mlx.generation._server.find_free_port", return_value=30210),+ patch("sie_server.adapters.mlx.generation._server.open_output_log", return_value=fake_log),+ patch("sie_server.adapters.mlx.generation._server.launch_mlx_server", return_value=object()),+ patch("sie_server.adapters.mlx.generation._server.wait_for_server", return_value=True),+ patch("sie_server.adapters.mlx.generation._server.warmup_model", return_value=False),+ patch("sie_server.adapters.mlx.generation._server.terminate_process") as term,+ pytest.raises(RuntimeError, match="warm up"),+ ):+ adapter.load("mps")+ assert adapter._server_url is None+ assert adapter._process is None+ term.assert_called_once()+++# -- generate(): OpenAI /v1/completions SSE parsing ---------------------------+++class _FakeResponse:+ def __init__(self, lines: list[str], status: int = 200) -> None:+ self.status_code = status+ self._lines = lines++ async def __aenter__(self) -> Self:+ return self++ async def __aexit__(self, *_a: object) -> bool:+ return False++ async def aiter_lines(self):+ for line in self._lines:+ yield line++ async def aread(self) -> bytes:+ return b"error body"++ def raise_for_status(self) -> None:+ return None+++class _FakeClient:+ def __init__(self, lines: list[str], status: int = 200) -> None:+ self._lines = lines+ self._status = status++ async def __aenter__(self) -> Self:+ return self++ async def __aexit__(self, *_a: object) -> bool:+ return False++ def stream(self, _method: str, _url: str, **_kw: Any) -> _FakeResponse:+ return _FakeResponse(self._lines, self._status)+++# Mirrors the real mlx_lm.server /v1/completions stream (verified live): a+# ``: keepalive`` SSE comment, incremental ``choices[0].text`` deltas, a terminal+# choice with finish_reason + empty text, then a usage-only event, then [DONE].+_SSE_LINES = [+ ": keepalive 1/1",+ "",+ 'data: {"object": "text_completion", "choices": [{"index": 0, "finish_reason": null, "text": "Hello"}]}',+ "",+ 'data: {"object": "text_completion", "choices": [{"index": 0, "finish_reason": null, "text": " world"}]}',+ "",+ 'data: {"object": "text_completion", "choices": [{"index": 0, "finish_reason": "length", "text": ""}]}',+ "",+ 'data: {"object": "chat.completion", "choices": [], "usage": {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5}}',+ "",+ "data: [DONE]",+ "",+]+++async def test_generate_parses_sse(adapter: MLXGenerationAdapter) -> None:+ with patch(+ "sie_server.adapters.mlx.generation.httpx.AsyncClient",+ return_value=_FakeClient(_SSE_LINES),+ ):+ chunks = [c async for c in adapter.generate(prompt="hi", max_new_tokens=8, temperature=0.0)]++ deltas = [c for c in chunks if not c.done]+ terminal = [c for c in chunks if c.done]+ assert "".join(c.text_delta for c in deltas) == "Hello world"+ assert deltas[0].is_first is True+ assert len(terminal) == 1+ assert terminal[0].finish_reason == "length"+ assert terminal[0].prompt_tokens == 3+ assert terminal[0].completion_tokens == 2+++async def test_generate_collects_to_result(adapter: MLXGenerationAdapter) -> None:+ with patch(+ "sie_server.adapters.mlx.generation.httpx.AsyncClient",+ return_value=_FakeClient(_SSE_LINES),+ ):+ result = await collect_generation(adapter.generate(prompt="hi", max_new_tokens=8))+ assert result.text == "Hello world"+ assert result.finish_reason == "length"+ assert result.completion_tokens == 2+++async def test_generate_rejects_images(adapter: MLXGenerationAdapter) -> None:+ with pytest.raises(ValueError, match="vision"):+ gen = adapter.generate(prompt="hi", max_new_tokens=8, images=[{"data": b"x", "format": "png"}])+ await gen.__anext__()+++async def test_generate_unloaded_raises() -> None:+ a = MLXGenerationAdapter(model_name_or_path="m", mlx_repo="r") # not loaded (no _server_url)+ with pytest.raises(RuntimeError):+ gen = a.generate(prompt="hi", max_new_tokens=8)+ await gen.__anext__()+++def test_unload_terminates_subprocess(adapter: MLXGenerationAdapter) -> None:+ sentinel = object()+ adapter._process = sentinel # type: ignore[assignment]+ with patch("sie_server.adapters.mlx.generation._server.terminate_process") as term:+ adapter.unload()+ term.assert_called_once_with(sentinel)+ assert adapter._process is None+ assert adapter._server_url is None+++def test_memory_footprint_zero(adapter: MLXGenerationAdapter) -> None:+ assert adapter.memory_footprint() == 0+++def test_build_sampling_body_merges_defaults() -> None:+ a = MLXGenerationAdapter(+ model_name_or_path="m",+ mlx_repo="repo",+ # presence_penalty mirrors the curated Qwen3.5-4B profile — it must NOT reach+ # mlx_lm.server (it's a CUDA/SGLang-only knob).+ default_sampling={"top_p": 0.8, "temperature": 0.7, "presence_penalty": 1.5},+ stop_tokens=["<|im_end|>"],+ )+ body = a._build_sampling_body(+ "prompt", max_new_tokens=16, temperature=0.0, top_p=1.0, top_k=None, stop=["X"], seed=None+ )+ assert body["model"] == "repo"+ assert body["max_tokens"] == 16+ assert body["stream"] is True+ assert body["stream_options"] == {"include_usage": True}+ # explicit request values win over defaults; stop_tokens merged in+ assert body["temperature"] == 0.0+ assert "X" in body["stop"]+ assert "<|im_end|>" in body["stop"]+ # SGLang/OpenAI-only default sampling keys are filtered out for the MLX child.+ assert "presence_penalty" not in bodydiff --git a/packages/sie_server/tests/adapters/test_multivector.py b/packages/sie_server/tests/adapters/test_multivector.pynew file mode 100644index 000000000..7bdd3a564--- /dev/null+++ b/packages/sie_server/tests/adapters/test_multivector.py@@ -0,0 +1,77 @@+"""Tests for the shared multivector MaxSim scoring helpers (issue #1539).++Pins ``maxsim_scores`` (pairwise) and ``maxsim_scores_batched`` (padded) to a+naive reference and to each other, and checks that padding never inflates a+short document's score.+"""++from __future__ import annotations++import torch+from sie_server.adapters._multivector import maxsim_scores, maxsim_scores_batched+++def _naive(query: torch.Tensor, docs: list[torch.Tensor]) -> list[float]:+ return [sum(max(float(q @ d_tok) for d_tok in doc) for q in query) for doc in docs]+++def _fixture() -> tuple[torch.Tensor, list[torch.Tensor]]:+ torch.manual_seed(0)+ query = torch.randn(5, 16)+ docs = [torch.randn(n, 16) for n in (3, 7, 1, 4)]+ return query, docs+++def test_pairwise_matches_naive() -> None:+ query, docs = _fixture()+ got, exp = maxsim_scores(query, docs), _naive(query, docs)+ assert all(abs(a - b) < 1e-4 for a, b in zip(got, exp, strict=True))+++def test_batched_matches_pairwise() -> None:+ query, docs = _fixture()+ pair, batched = maxsim_scores(query, docs), maxsim_scores_batched(query, docs)+ assert all(abs(a - b) < 1e-4 for a, b in zip(pair, batched, strict=True))+++def test_batched_padding_does_not_inflate_short_doc() -> None:+ # A 1-token doc batched with a 6-token doc must score identically to solo.+ torch.manual_seed(1)+ query = torch.randn(3, 8)+ docs = [torch.randn(1, 8), torch.randn(6, 8)]+ solo = maxsim_scores_batched(query, [docs[0]])[0]+ in_batch = maxsim_scores_batched(query, docs)[0]+ assert abs(solo - in_batch) < 1e-5+++def test_single_document() -> None:+ query, docs = _fixture()+ exp = _naive(query, docs[:1])+ assert len(exp) == 1+ assert abs(maxsim_scores(query, docs[:1])[0] - exp[0]) < 1e-4+ assert abs(maxsim_scores_batched(query, docs[:1])[0] - exp[0]) < 1e-4+++def test_empty_docs_list_returns_empty() -> None:+ query = torch.randn(3, 8)+ assert maxsim_scores(query, []) == []+ assert maxsim_scores_batched(query, []) == []+++def test_all_empty_docs_return_neg_inf() -> None:+ # Punctuation-only docs can reach the helper with zero tokens after the+ # caller strips special tokens; this must not raise.+ query = torch.randn(3, 8)+ empties = [torch.zeros(0, 8), torch.zeros(0, 8)]+ assert maxsim_scores(query, empties) == [float("-inf"), float("-inf")]+ assert maxsim_scores_batched(query, empties) == [float("-inf"), float("-inf")]+++def test_mixed_empty_and_nonempty_doc() -> None:+ torch.manual_seed(2)+ query = torch.randn(3, 8)+ docs = [torch.zeros(0, 8), torch.randn(5, 8)]+ pair, batched = maxsim_scores(query, docs), maxsim_scores_batched(query, docs)+ assert pair[0] == float("-inf")+ assert batched[0] == float("-inf")+ assert abs(pair[1] - batched[1]) < 1e-4diff --git a/packages/sie_server/tests/adapters/test_runtime_options.py b/packages/sie_server/tests/adapters/test_runtime_options.pyindex 12b4f185b..363381cb3 100644--- a/packages/sie_server/tests/adapters/test_runtime_options.py+++ b/packages/sie_server/tests/adapters/test_runtime_options.py@@ -1,7 +1,7 @@from __future__ import annotationsfrom typing import ClassVar-from unittest.mock import MagicMock+from unittest.mock import MagicMock, patchimport numpy as npimport pytest@@ -274,6 +274,69 @@ class TestRuntimeOptionsConsumption:)assert texts == ["custom: hello"]+ # --- SGLang append_eos (last-token pooling fix, #1489) ---++ def test_sglang_append_eos_appends_to_queries_and_docs(self) -> None:+ """append_eos appends the resolved EOS to BOTH queries and documents."""+ adapter = SGLangEmbeddingAdapter(+ "test-model",+ query_template="Instruct: {instruction}\nQuery: {text}",+ default_instruction="do retrieval",+ append_eos=True,+ )+ # EOS is resolved from the tokenizer in load(); set it directly here.+ adapter._eos_token = "</s>" # noqa: S105 - EOS token, not a secret++ q = adapter._format_texts([Item(text="hello")], None, is_query=True)+ d = adapter._format_texts([Item(text="world")], None, is_query=False)+ assert q == ["Instruct: do retrieval\nQuery: hello</s>"]+ assert d == ["world</s>"]++ def test_sglang_append_eos_skips_empty_and_whitespace(self) -> None:+ """EOS is NOT appended to empty/whitespace docs, so encode() still routes+ them to the zero-vector fallback instead of an EOS-only input.+ """+ adapter = SGLangEmbeddingAdapter("test-model", append_eos=True)+ adapter._eos_token = "</s>" # noqa: S105 - EOS token, not a secret+ texts = adapter._format_texts(+ [Item(text=""), Item(text=" "), Item(text="real")],+ None,+ is_query=False,+ )+ assert texts == ["", " ", "real</s>"]++ def test_sglang_append_eos_disabled_by_default(self) -> None:+ """Without append_eos, no EOS is appended (current behaviour preserved)."""+ adapter = SGLangEmbeddingAdapter("test-model")+ adapter._eos_token = "</s>" # noqa: S105 - EOS token, not a secret; ignored when append_eos is False+ texts = adapter._format_texts([Item(text="hello")], None, is_query=False)+ assert texts == ["hello"]++ def test_sglang_append_eos_noop_when_eos_unresolved(self) -> None:+ """append_eos with an empty resolved EOS leaves text unchanged (graceful degrade)."""+ adapter = SGLangEmbeddingAdapter("test-model", append_eos=True)+ adapter._eos_token = "" # tokenizer didn't expose an EOS+ texts = adapter._format_texts([Item(text="hello")], None, is_query=False)+ assert texts == ["hello"]++ def test_sglang_resolve_eos_token_reads_tokenizer(self) -> None:+ """_resolve_eos_token reads the real eos_token via the shared loader util."""+ adapter = SGLangEmbeddingAdapter("test-model", append_eos=True)+ mock_tok = MagicMock()+ mock_tok.eos_token = "</s>" # noqa: S105 - EOS token, not a secret+ with patch("sie_server.adapters.sglang.embedding.load_tokenizer", return_value=mock_tok) as ld:+ assert adapter._resolve_eos_token() == "</s>"+ ld.assert_called_once()++ def test_sglang_resolve_eos_token_degrades_on_failure(self) -> None:+ """A tokenizer load failure degrades to '' rather than raising (model stays up)."""+ adapter = SGLangEmbeddingAdapter("test-model", append_eos=True)+ with patch(+ "sie_server.adapters.sglang.embedding.load_tokenizer",+ side_effect=RuntimeError("no tokenizer"),+ ):+ assert adapter._resolve_eos_token() == ""+# --- Normalize override in encode() flow ---def test_encode_respects_normalize_false_override(self) -> None:diff --git a/packages/sie_server/tests/adapters/test_sglang.py b/packages/sie_server/tests/adapters/test_sglang.pyindex 333a617e1..ca2932a60 100644--- a/packages/sie_server/tests/adapters/test_sglang.py+++ b/packages/sie_server/tests/adapters/test_sglang.py@@ -40,6 +40,13 @@ class TestSGLangEmbeddingAdapter:assert SGLangEmbeddingAdapter.requires_main_thread is Falseassert SGLangEmbeddingAdapter.manages_own_load_timeout is True+ def test_load_required_memory_bytes_uses_mem_fraction_static(self) -> None:+ gb = 1024**3+ adapter = SGLangEmbeddingAdapter("test-model", mem_fraction_static=0.8)++ assert adapter.load_required_memory_bytes(device_type="cuda", device_total_bytes=10 * gb) == 9 * gb+ assert adapter.load_required_memory_bytes(device_type="cpu", device_total_bytes=10 * gb) is None+def test_startup_timeout_prefers_explicit_profile_value(self, monkeypatch: pytest.MonkeyPatch) -> None:for name in _server.STARTUP_TIMEOUT_ENV_VARS:monkeypatch.setenv(name, "120")@@ -120,6 +127,38 @@ class TestSGLangEmbeddingAdapter:# Verify server URL is setassert adapter._server_url == "http://localhost:30000"+ @patch("sie_server.adapters.sglang._server.subprocess.Popen")+ @patch("sie_server.adapters.sglang._server.requests.get")+ @patch("sie_server.adapters.sglang._server.find_free_port")+ def test_load_trust_remote_code_flag(+ self,+ mock_find_port: MagicMock,+ mock_requests_get: MagicMock,+ mock_popen: MagicMock,+ ) -> None:+ """--trust-remote-code is emitted only when trust_remote_code is set.++ gte-Qwen2-7B-instruct opts out (trust_remote_code=False) so SGLang loads+ the stock tokenizer instead of the model's fragile remote-code tokenizer.+ """+ mock_find_port.return_value = 30000+ mock_process = MagicMock()+ mock_process.poll.return_value = None+ mock_popen.return_value = mock_process+ mock_requests_get.return_value = MagicMock(status_code=200)++ def _cmd_for(*, trust_remote_code: bool) -> list[str]:+ mock_popen.reset_mock()+ adapter = SGLangEmbeddingAdapter(+ model_name_or_path="Alibaba-NLP/gte-Qwen2-7B-instruct",+ trust_remote_code=trust_remote_code,+ )+ adapter.load("cuda:0")+ return mock_popen.call_args[0][0]++ assert "--trust-remote-code" in _cmd_for(trust_remote_code=True)+ assert "--trust-remote-code" not in _cmd_for(trust_remote_code=False)+@patch("sie_server.adapters.sglang._server.subprocess.Popen")@patch("sie_server.adapters.sglang._server.requests.get")@patch("sie_server.adapters.sglang._server.find_free_port")diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.pyindex c4c2ded67..b69cda1db 100644--- a/packages/sie_server/tests/adapters/test_sglang_generation.py+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py@@ -52,6 +52,14 @@ def test_load_contract_flags() -> None:assert SGLangGenerationAdapter.manages_own_load_timeout is True+def test_load_required_memory_bytes_uses_mem_fraction_static() -> None:+ gb = 1024**3+ adapter = SGLangGenerationAdapter("test-model", mem_fraction_static=0.8)++ assert adapter.load_required_memory_bytes(device_type="cuda", device_total_bytes=10 * gb) == 9 * gb+ assert adapter.load_required_memory_bytes(device_type="cpu", device_total_bytes=10 * gb) is None++@pytest.mark.parametrize(("args", "expected"),[diff --git a/packages/sie_server/tests/api/test_canonical_profile_conformance.py b/packages/sie_server/tests/api/test_canonical_profile_conformance.pynew file mode 100644index 000000000..52f5463e8--- /dev/null+++ b/packages/sie_server/tests/api/test_canonical_profile_conformance.py@@ -0,0 +1,41 @@+"""Conformance: the sie_server worker's bundle_config_hash adapter_options+canonicalization matches the shared cross-language vectors (issue #1542).++The worker advertises a ``bundle_config_hash`` that the gateway must reproduce or+the worker sits in ``pending_workers`` forever. Unlike the gateway (Rust+``canonicalize_adapter_options``) and the config service+(``sie_config._canonical_adapter_options``) — which are GENERIC flat canonicalizers+exercised by the ``strip_to_none`` / ``keep_unchanged`` vectors — the worker's+canonicalizer (``api.ws._compact_adapter_options_for_hash``) is structured: real+profiles always shape ``adapter_options`` as ``{loadtime, runtime}`` and the worker+compacts those two sub-maps. The shared ``transform`` vectors pin that+loadtime/runtime compaction, which all three implementations must agree on.+"""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any++import pytest+from sie_server.api.ws import _compact_adapter_options_for_hash+++def _load_vectors() -> dict[str, Any]:+ for parent in Path(__file__).resolve().parents:+ fixture = parent / "conformance" / "bundle_config_hash" / "canonical_profile_falsy_vectors.json"+ if fixture.exists():+ return json.loads(fixture.read_text())+ msg = "canonical_profile_falsy_vectors.json not found in any parent directory"+ raise FileNotFoundError(msg)+++_VECTORS = _load_vectors()++[email protected]("case", _VECTORS["transform"], ids=lambda c: c["name"])+def test_loadtime_runtime_compaction(case: dict[str, Any]) -> None:+ options = case["adapter_options"]+ got = _compact_adapter_options_for_hash(options.get("loadtime", {}), options.get("runtime", {}))+ assert got == case["expected"]diff --git a/packages/sie_server/tests/api/test_dtype_queue_http_parity.py b/packages/sie_server/tests/api/test_dtype_queue_http_parity.pynew file mode 100644index 000000000..b74ec1272--- /dev/null+++ b/packages/sie_server/tests/api/test_dtype_queue_http_parity.py@@ -0,0 +1,76 @@+"""Wire-dtype parity between the queue path and the HTTP path.++The queue path (`queue_executor._wrap_encode_output`) and the HTTP path+(`api/encode._format_dense` / `_format_multivector`) must tag the wire `dtype`+identically for the same array — a client that round-trips a request over HTTP+vs the queue/cluster edge otherwise decodes the bytes differently.++Regression guard for #1603: a linear `uint8` quantization (full dimensionality)+was tagged `"binary"` on the queue path but `"uint8"` over HTTP, because+`_NP_DTYPE_MAP` hard-coded `uint8 -> "binary"`. Only genuinely bit-packed uint8+(`shape < dim`) is `"binary"`.+"""++from __future__ import annotations++import numpy as np+import pytest+from sie_server.api.encode import _format_dense, _format_multivector+from sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks+from sie_server.queue_executor import _wrap_encode_output++_DENSE_DIM = 8+_MV_DIM = 16+++def _config() -> ModelConfig:+ return ModelConfig(+ sie_id="m",+ hf_id="org/m",+ tasks=Tasks(+ encode=EncodeTask(+ dense=EmbeddingDim(dim=_DENSE_DIM),+ multivector=EmbeddingDim(dim=_MV_DIM),+ )+ ),+ profiles={"default": ProfileConfig(adapter_path="t:A", max_batch_tokens=8192)},+ )+++ ("arr", "expected"),+ [+ (np.arange(_DENSE_DIM, dtype=np.uint8), "uint8"), # linear uint8, full dim+ (np.zeros(_DENSE_DIM // 8, dtype=np.uint8), "binary"), # bit-packed, shape < dim+ (np.arange(_DENSE_DIM, dtype=np.int8), "int8"),+ (np.zeros(_DENSE_DIM, dtype=np.float32), "float32"),+ ],+ ids=["linear-uint8", "packed-binary", "int8", "float32"],+)+def test_dense_dtype_tag_matches_between_queue_and_http(arr: np.ndarray, expected: str) -> None:+ config = _config()+ http_dtype = _format_dense(arr, config)["dtype"]+ queue_dtype = _wrap_encode_output({"dense": arr.copy()}, config)["dense"]["dtype"]++ assert http_dtype == expected+ assert queue_dtype == expected+ assert queue_dtype == http_dtype, f"queue tagged {queue_dtype!r}, HTTP tagged {http_dtype!r}"+++ ("arr", "expected"),+ [+ (np.zeros((5, _MV_DIM), dtype=np.uint8), "uint8"), # linear uint8, full token dim+ (np.zeros((5, _MV_DIM // 8), dtype=np.uint8), "binary"), # bit-packed, shape[1] < dim+ (np.zeros((5, _MV_DIM), dtype=np.int8), "int8"),+ ],+ ids=["linear-uint8", "packed-binary", "int8"],+)+def test_multivector_dtype_tag_matches_between_queue_and_http(arr: np.ndarray, expected: str) -> None:+ config = _config()+ http_dtype = _format_multivector(arr, config)["dtype"]+ queue_dtype = _wrap_encode_output({"multivector": arr.copy()}, config)["multivector"]["dtype"]++ assert http_dtype == expected+ assert queue_dtype == expected+ assert queue_dtype == http_dtype, f"queue tagged {queue_dtype!r}, HTTP tagged {http_dtype!r}"diff --git a/packages/sie_server/tests/api/test_generate_stream.py b/packages/sie_server/tests/api/test_generate_stream.pynew file mode 100644index 000000000..0356a1d9b--- /dev/null+++ b/packages/sie_server/tests/api/test_generate_stream.py@@ -0,0 +1,120 @@+"""Tests for the SIE-native ``/v1/generate`` streaming SSE shaper.++``_stream_generate_events`` emits the ``GenerateChunk`` wire shape that+``sie_sdk.SIEClient.stream_generate`` consumes (mirroring the gateway's+``build_generate_chunk_event``). These run on any platform with a fake adapter —+no MLX/torch — so a regression in the SSE contract is caught in normal CI, not+only the Mac nightly.+"""++from __future__ import annotations++import json+from collections.abc import AsyncIterator+from typing import Any++from sie_server.adapters._generation_base import GenerationChunk+from sie_server.api.generate import _stream_generate_events+++class _FakeAdapter:+ """Duck-typed GenerationAdapter that yields preset chunks (or raises)."""++ def __init__(self, chunks: list[GenerationChunk], raise_after: int | None = None) -> None:+ self._chunks = chunks+ self._raise_after = raise_after++ async def generate(self, **_kwargs: Any) -> AsyncIterator[GenerationChunk]:+ for i, c in enumerate(self._chunks):+ if self._raise_after is not None and i == self._raise_after:+ raise RuntimeError("boom")+ yield c+++def _parse_sse(raw: list[str]) -> tuple[list[dict[str, Any]], bool]:+ """Parse emitted SSE strings into events; returns (events, saw_DONE)."""+ events: list[dict[str, Any]] = []+ saw_done = False+ for block in raw:+ for line in block.splitlines():+ line = line.strip()+ if not line.startswith("data:"):+ continue+ payload = line[len("data:") :].strip()+ if payload == "[DONE]":+ saw_done = True+ continue+ events.append(json.loads(payload))+ return events, saw_done+++async def _drain(adapter: Any) -> list[str]:+ return [+ s+ async for s in _stream_generate_events(+ adapter, prompt="hi", max_new_tokens=8, temperature=0.0, top_p=1.0, stop=None, seed=None, logit_bias=None+ )+ ]+++async def test_stream_shapes_generatechunk() -> None:+ chunks = [+ GenerationChunk(text_delta="Hello", done=False, is_first=True),+ GenerationChunk(text_delta=" world", done=False),+ GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=4, completion_tokens=2),+ ]+ raw = await _drain(_FakeAdapter(chunks))+ events, saw_done = _parse_sse(raw)+ assert saw_done is True++ deltas = [e for e in events if not e.get("done")]+ terminals = [e for e in events if e.get("done")]+ assert [e["text_delta"] for e in deltas] == ["Hello", " world"]+ # monotonic seq + stable request_id across the stream+ assert [e["seq"] for e in deltas] == [0, 1]+ assert len({e["request_id"] for e in events}) == 1++ assert len(terminals) == 1+ term = terminals[0]+ assert term["done"] is True+ assert term["finish_reason"] == "stop"+ assert term["usage"] == {"prompt_tokens": 4, "completion_tokens": 2, "total_tokens": 6}+ assert "ttft_ms" in term # first non-empty delta was observed+++async def test_stream_error_emits_terminal_error_chunk() -> None:+ chunks = [+ GenerationChunk(text_delta="partial", done=False, is_first=True),+ GenerationChunk(text_delta="never", done=False),+ ]+ raw = await _drain(_FakeAdapter(chunks, raise_after=1))+ events, saw_done = _parse_sse(raw)+ assert saw_done is True+ terminal = next(e for e in events if e.get("done"))+ assert terminal["finish_reason"] == "error"+ assert terminal["error"]["code"] == "inference_error"+ # The raw exception text must NOT leak to the client (CodeQL info-exposure);+ # it is logged server-side only. The client gets a generic message.+ assert "boom" not in terminal["error"]["message"]+ assert terminal["error"]["message"] == "internal error during generation"+++async def test_stream_empty_generation_still_terminates() -> None:+ chunks = [GenerationChunk(text_delta="", done=True, finish_reason="stop", prompt_tokens=1, completion_tokens=0)]+ raw = await _drain(_FakeAdapter(chunks))+ events, saw_done = _parse_sse(raw)+ assert saw_done is True+ terminal = next(e for e in events if e.get("done"))+ assert terminal["finish_reason"] == "stop"+ assert terminal["usage"]["completion_tokens"] == 0+ # No text delta was produced → no ttft_ms on the terminal chunk.+ assert "ttft_ms" not in terminal+++async def test_done_is_final_sse_line() -> None:+ chunks = [+ GenerationChunk(text_delta="hi", done=False),+ GenerationChunk(text_delta="", done=True, finish_reason="stop"),+ ]+ raw = await _drain(_FakeAdapter(chunks))+ assert raw[-1].strip() == "data: [DONE]"diff --git a/packages/sie_server/tests/api/test_openai_compat.py b/packages/sie_server/tests/api/test_openai_compat.pyindex 922e4bb16..771990012 100644--- a/packages/sie_server/tests/api/test_openai_compat.py+++ b/packages/sie_server/tests/api/test_openai_compat.py@@ -1,7 +1,7 @@"""Tests for OpenAI-compatible embeddings endpoint."""from typing import Any-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMock, patchimport numpy as npimport pytest@@ -9,6 +9,7 @@ from fastapi import FastAPIfrom fastapi.testclient import TestClientfrom sie_server.api.openai_compat import router as openai_routerfrom sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks+from sie_server.core.oom import ResourceExhausted, ResourceExhaustedErrorfrom sie_server.core.registry import ModelRegistry@@ -276,3 +277,44 @@ class TestOpenAIResponseFormat:data = response.json()indices = [item["index"] for item in data["data"]]assert indices == [0, 1, 2, 3]+++class TestOpenAIEmbeddingsOom:+ """/v1/embeddings must map OOM to 503 RESOURCE_EXHAUSTED + Retry-After+ (OpenAI envelope), matching the native endpoints so the SDK auto-retries+ instead of treating it as a terminal 500. See #1604.+ """++ @pytest.mark.parametrize(+ "failure",+ [+ RuntimeError("CUDA out of memory. Tried to allocate 2 GiB"),+ ResourceExhaustedError(+ "Resource exhausted: CUDA out of memory",+ marker=ResourceExhausted(operation="encode", attempts=4, original_message="CUDA out of memory"),+ ),+ ],+ ids=["raw-cuda-oom", "wrapped-resource-exhausted"],+ )+ def test_embeddings_oom_maps_to_503_resource_exhausted(+ self, client: TestClient, mock_registry: MagicMock, failure: BaseException+ ) -> None:+ # engine_config=None → oom_retry_after_from_registry falls back to the+ # module default (5), same as the native OOM test.+ mock_registry.engine_config = None++ with patch(+ "sie_server.api.openai_compat.EncodePipeline.run_encode",+ new_callable=AsyncMock,+ side_effect=failure,+ ):+ response = client.post(+ "/v1/embeddings",+ json={"model": "text-embedding-3-small", "input": "hello"},+ )++ assert response.status_code == 503, response.text+ assert response.headers.get("Retry-After") == "5"+ error = response.json()["detail"]["error"]+ assert error["code"] == "RESOURCE_EXHAUSTED"+ assert error["type"] == "server_error"diff --git a/packages/sie_server/tests/api/test_openai_local.py b/packages/sie_server/tests/api/test_openai_local.pynew file mode 100644index 000000000..71920303b--- /dev/null+++ b/packages/sie_server/tests/api/test_openai_local.py@@ -0,0 +1,113 @@+"""Input-contract tests for the Mac-local OpenAI routes (/v1/chat/completions, /v1/rerank).++These run on any platform — they exercise the request validation that happens+BEFORE the registry/model is touched, so no MLX subprocess or torch is needed.+The happy paths are covered live by ``mise run mac-smoke`` (Apple Silicon).+"""++from __future__ import annotations++from unittest.mock import MagicMock++from fastapi import FastAPI+from fastapi.testclient import TestClient+from sie_server.api.openai_local import router+++def _client() -> TestClient:+ app = FastAPI()+ app.include_router(router)+ # Registry is only reached AFTER input validation, so a stub is fine for 4xx paths.+ app.state.registry = MagicMock()+ return TestClient(app, raise_server_exceptions=False)+++# -- /v1/chat/completions validation -----------------------------------------+++def test_chat_requires_object_body() -> None:+ r = _client().post("/v1/chat/completions", content=b"[]", headers={"content-type": "application/json"})+ assert r.status_code == 400+++def test_chat_requires_model() -> None:+ r = _client().post("/v1/chat/completions", json={"messages": [{"role": "user", "content": "hi"}]})+ assert r.status_code == 400+ assert r.json()["detail"]["param"] == "model"+++def test_chat_requires_nonempty_messages() -> None:+ r = _client().post("/v1/chat/completions", json={"model": "m", "messages": []})+ assert r.status_code == 400+ assert r.json()["detail"]["param"] == "messages"+++def test_chat_rejects_non_generation_model_before_load() -> None:+ # An embedding/reranker model (no generate task) must be rejected BEFORE ensure_loaded()+ # so a chat request can't kick off a real model load that only 501s afterwards.+ client = _client()+ client.app.state.registry.get_config.return_value.tasks.generate = None+ r = client.post(+ "/v1/chat/completions", json={"model": "embed-model", "messages": [{"role": "user", "content": "hi"}]}+ )+ assert r.status_code == 400+ assert "generation" in r.json()["detail"]["message"].lower()+++def test_chat_rejects_non_bool_stream() -> None:+ msgs = [{"role": "user", "content": "hi"}]+ r = _client().post("/v1/chat/completions", json={"model": "m", "messages": msgs, "stream": "false"})+ assert r.status_code == 400+ assert r.json()["detail"]["param"] == "stream"+++def test_chat_rejects_invalid_max_tokens() -> None:+ msgs = [{"role": "user", "content": "hi"}]+ for bad in (0, -5, "100", True):+ r = _client().post("/v1/chat/completions", json={"model": "m", "messages": msgs, "max_tokens": bad})+ assert r.status_code == 400, bad+ assert r.json()["detail"]["param"] == "max_tokens"+++# -- /v1/rerank validation ----------------------------------------------------+++def test_rerank_requires_model() -> None:+ r = _client().post("/v1/rerank", json={"query": "q", "documents": ["a"]})+ assert r.status_code == 400+ assert r.json()["detail"]["param"] == "model"+++def test_rerank_requires_query() -> None:+ r = _client().post("/v1/rerank", json={"model": "m", "documents": ["a"]})+ assert r.status_code == 400+ assert r.json()["detail"]["param"] == "query"+++def test_rerank_requires_nonempty_string_documents() -> None:+ for docs in ([], "not-a-list", [1, 2], ["ok", 3]):+ r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": docs})+ assert r.status_code == 400, docs+ assert r.json()["detail"]["param"] == "documents"+++def test_rerank_top_n_must_be_positive_int() -> None:+ for bad in (0, -1, "3", True):+ r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a"], "top_n": bad})+ assert r.status_code == 400, bad+ assert r.json()["detail"]["param"] == "top_n"+++def test_rerank_rejects_too_many_documents() -> None:+ from sie_server.api import openai_local++ docs = ["d"] * (openai_local._MAX_RERANK_DOCS + 1)+ r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": docs})+ assert r.status_code == 400+ assert r.json()["detail"]["param"] == "documents"+++def test_rerank_rejects_non_bool_return_documents() -> None:+ r = _client().post("/v1/rerank", json={"model": "m", "query": "q", "documents": ["a"], "return_documents": "true"})+ assert r.status_code == 400+ assert r.json()["detail"]["param"] == "return_documents"diff --git a/packages/sie_server/tests/app/test_app_factory.py b/packages/sie_server/tests/app/test_app_factory.pyindex 1c95f1d37..b0821d634 100644--- a/packages/sie_server/tests/app/test_app_factory.py+++ b/packages/sie_server/tests/app/test_app_factory.py@@ -2,7 +2,9 @@import loggingimport uuid+from collections.abc import AsyncGeneratorfrom concurrent.futures import ThreadPoolExecutor+from contextlib import asynccontextmanagerfrom pathlib import Pathfrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock@@ -25,6 +27,11 @@ def client() -> TestClient:return TestClient(app)+@asynccontextmanager+async def _async_value(value: Any = None) -> AsyncGenerator[Any, None]:+ yield value++class TestAppFactory:"""Tests for the FastAPI app factory."""@@ -52,6 +59,28 @@ class TestAppFactory:assert "/readyz" in paths+class TestAppLifespanState:+ @pytest.mark.asyncio+ async def test_lifespan_wires_ipc_server_as_queue_runtime(self, monkeypatch: pytest.MonkeyPatch) -> None:+ registry = MagicMock()+ ipc_server = MagicMock()++ monkeypatch.setattr(AppFactory, "_configure_torch_threads", MagicMock())+ monkeypatch.setattr(AppFactory, "_configure_cuda_defaults", MagicMock())+ monkeypatch.setattr(AppFactory, "_nvml", MagicMock(return_value=_async_value()))+ monkeypatch.setattr(AppFactory, "_model_registry", MagicMock(return_value=_async_value(registry)))+ monkeypatch.setattr(AppFactory, "_ipc_server", MagicMock(return_value=_async_value(ipc_server)))+ monkeypatch.setattr(AppFactory, "_graceful_shutdown", MagicMock(return_value=_async_value()))+ monkeypatch.setattr(AppFactory, "_readiness_handling", MagicMock(return_value=_async_value()))++ app = AppFactory.create_app(AppStateConfig())++ async with app.router.lifespan_context(app):+ assert app.state.registry is registry+ assert app.state.ipc_server is ipc_server+ assert app.state.queue_runtime is ipc_server++class TestAllRoutersAlwaysMounted:"""Queue routing is the only supported mode, so routers are mountedunconditionally.@@ -112,13 +141,15 @@ class TestIpcHeartbeatReadiness:@pytest.mark.asyncioasync def test_direct_server_readiness_does_not_require_sidecar_ping(self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.delenv("SIE_IPC_REQUIRE_HEARTBEAT", raising=False)+ monkeypatch.setenv("SIE_WORKER_ID", "worker-from-env")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()):+ async with AppFactory._ipc_server(MagicMock()) as server:+ assert server.worker_id == "worker-from-env"assert readiness.is_ready() is Truefinally:readiness.mark_not_ready()diff --git a/packages/sie_server/tests/config/test_bundle_coverage.py b/packages/sie_server/tests/config/test_bundle_coverage.pyindex 7bf7263d3..0e906ff33 100644--- a/packages/sie_server/tests/config/test_bundle_coverage.py+++ b/packages/sie_server/tests/config/test_bundle_coverage.py@@ -10,6 +10,7 @@ from pathlib import Pathimport pytestimport yaml+from sie_sdk.bundle_utils import match_bundle_modelsSIE_SERVER_ROOT = Path(__file__).resolve().parents[2]BUNDLES_DIR = SIE_SERVER_ROOT / "bundles"@@ -110,6 +111,19 @@ def test_bundle_and_model_dirs_are_non_empty() -> None:assert sorted(MODELS_DIR.glob("*.yaml")), f"No model YAML files found in {MODELS_DIR}"+def test_candle_bundle_only_exposes_profile_variants() -> None:+ matches = match_bundle_models(BUNDLES_DIR / "candle.yaml", MODELS_DIR)+ assert matches, "candle bundle should expose at least one model profile variant"++ bare_model_matches = [model for model in matches if ":" not in model]+ formatted_matches = "\n ".join(bare_model_matches)+ assert not bare_model_matches, (+ "Candle must be selected through explicit model profile variants, not bare model ids. "+ "For overlap models, keep the bare default profile on a Python adapter; for Candle-only "+ f"models, omit the default profile and expose only `model:candle`:\n {formatted_matches}"+ )++@pytest.mark.parametrize("bundle_yaml", sorted(BUNDLES_DIR.glob("*.yaml")))def test_bundle_yaml_has_required_fields(bundle_yaml: Path) -> None:data = yaml.safe_load(bundle_yaml.read_text()) or {}diff --git a/packages/sie_server/tests/config/test_config.py b/packages/sie_server/tests/config/test_config.pyindex e2497a769..c9fec25b8 100644--- a/packages/sie_server/tests/config/test_config.py+++ b/packages/sie_server/tests/config/test_config.py@@ -271,14 +271,14 @@ class TestModelConfig:profiles={"default": ProfileConfig(adapter_path="mod:Cls", max_batch_tokens=1)},)- def test_missing_default_profile_rejected(self) -> None:- """Model without default profile is rejected."""- with pytest.raises(ValidationError, match=r"default"):+ def test_empty_profiles_rejected(self) -> None:+ """Model config must define at least one profile."""+ with pytest.raises(ValidationError, match=r"profiles"):ModelConfig(- sie_id="no-default",+ sie_id="no-profiles",hf_id="org/model",tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),- profiles={"custom": ProfileConfig(adapter_path="mod:Cls", max_batch_tokens=8192)},+ profiles={},)def test_default_profile_needs_adapter_path(self) -> None:@@ -534,6 +534,23 @@ class TestModelConfigProfiles:assert "fast" in config.profilesassert config.profiles["fast"].extends == "default"+ def test_model_can_be_profile_only_without_default(self) -> None:+ """Profile-only configs are valid and expose explicit variants only."""+ config = ModelConfig(+ sie_id="test-model",+ hf_id="org/model",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),+ profiles={+ "candle": ProfileConfig(+ adapter_path="sie_server_rust.adapters.candle:CandleEmbeddingAdapter",+ max_batch_tokens=8192,+ ),+ },+ )++ assert set(config.profiles) == {"candle"}+ assert config.resolve_profile("candle").adapter_path == "sie_server_rust.adapters.candle:CandleEmbeddingAdapter"+def test_resolve_default_profile(self) -> None:"""resolve_profile returns ResolvedProfile for default."""config = _make_config(adapter_path="mod:Cls", max_batch_tokens=8192)diff --git a/packages/sie_server/tests/core/test_adaptive_batching.py b/packages/sie_server/tests/core/test_adaptive_batching.pyindex 6a6eca693..acff87746 100644--- a/packages/sie_server/tests/core/test_adaptive_batching.py+++ b/packages/sie_server/tests/core/test_adaptive_batching.py@@ -11,6 +11,7 @@ from sie_server.core.adaptive_batching import (BatchEfficiencyTracker,LatencyTracker,)+from sie_server.core.batcher import BatchConfigfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.core.prepared import make_text_itemfrom sie_server.core.worker import ModelWorker, WorkerConfig@@ -188,6 +189,23 @@ class TestAdaptiveBatchController:wait, _ = ctrl.step(observed_p50_ms=30.0, fill_ratio=0.5)assert wait == pytest.approx(20.0)+ def test_apply_step_writes_back_to_target(self) -> None:+ # apply_step advances the controller and writes the new limits into+ # the target (a real BatchConfig, proving it satisfies the structural+ # AdaptiveBatchTarget), returning the same pair for metrics. Mirrors+ # the deterministic single-step case above.+ ctrl = AdaptiveBatchController(+ target_p50_ms=50.0,+ gain=0.5,+ update_interval=1,+ _current_wait_ms=10.0,+ )+ target = BatchConfig(max_batch_wait_ms=10.0)+ wait, cost = ctrl.apply_step(target, observed_p50_ms=30.0, fill_ratio=0.5)+ assert wait == pytest.approx(20.0)+ assert target.max_batch_wait_ms == wait+ assert target.max_batch_cost == cost+def test_decreases_wait_when_over_target(self) -> None:ctrl = AdaptiveBatchController(target_p50_ms=50.0,diff --git a/packages/sie_server/tests/core/test_batcher.py b/packages/sie_server/tests/core/test_batcher.pyindex dd73fe770..d183eaf43 100644--- a/packages/sie_server/tests/core/test_batcher.py+++ b/packages/sie_server/tests/core/test_batcher.py@@ -670,6 +670,29 @@ class TestBatchFormerDrain:assert result.size == 3assert batcher.pending_count == 0+ @pytest.mark.asyncio+ async def test_try_drain_respects_max_items_cap(self, batcher: BatchFormer[TextPreparedItem, str]) -> None:+ """try_drain(max_items=N) takes at most N items and leaves the rest pending.++ This is the fairness bound behind the LoRA drain loop (#1606): a drain+ must not sweep in more than the caller's snapshot budget, even when the+ batcher holds more items (including ones that arrived mid-drain).+ """+ for i in range(5):+ await batcher.submit(make_text_item([i], i), f"req-{i}")+ assert batcher.pending_count == 5++ first = await batcher.try_drain(max_items=2)+ assert first is not None+ assert first.size == 2+ assert batcher.pending_count == 3++ # A follow-up drain honors its own cap and drains part of the remainder.+ second = await batcher.try_drain(max_items=2)+ assert second is not None+ assert second.size == 2+ assert batcher.pending_count == 1+class TestBatchFormerSubmitMany:"""Tests for BatchFormer submit_many (bulk submit)."""diff --git a/packages/sie_server/tests/core/test_hot_reload.py b/packages/sie_server/tests/core/test_hot_reload.pyindex 10641f91b..fd1293c6c 100644--- a/packages/sie_server/tests/core/test_hot_reload.py+++ b/packages/sie_server/tests/core/test_hot_reload.py@@ -98,6 +98,8 @@ class TestHotReloader:registry._configs = {}registry._model_dirs = {}registry.add_config_async = AsyncMock() # type: ignore[method-assign]+ registry.load_async = AsyncMock() # type: ignore[method-assign]+ registry.unload_async = AsyncMock() # type: ignore[method-assign]return registry@pytest.fixture@@ -190,6 +192,8 @@ class TestHotReloaderHandlers:registry._configs = {}registry._model_dirs = {}registry.add_config_async = AsyncMock() # type: ignore[method-assign]+ registry.load_async = AsyncMock() # type: ignore[method-assign]+ registry.unload_async = AsyncMock() # type: ignore[method-assign]return registry@pytest.mark.asyncio@@ -273,7 +277,7 @@ class TestHotReloaderHandlers:assert result.status == ReloadStatus.SUCCESS# Should not unload (wasn't loaded)- mock_registry.unload.assert_not_called()+ mock_registry.unload_async.assert_not_awaited()@pytest.mark.asyncioasync def test_handle_model_modified_was_loaded(self, temp_models_dir: Path, mock_registry: MagicMock) -> None:@@ -320,8 +324,8 @@ class TestHotReloaderHandlers:result = await reloader._handle_model_modified(change)assert result.status == ReloadStatus.SUCCESS- mock_registry.unload.assert_called_with("loaded-model")- mock_registry.load.assert_called_with("loaded-model", "cpu")+ mock_registry.unload_async.assert_awaited_once_with("loaded-model")+ mock_registry.load_async.assert_awaited_once_with("loaded-model", "cpu")@pytest.mark.asyncioasync def test_handle_model_deleted(self, temp_models_dir: Path, mock_registry: MagicMock) -> None:@@ -352,7 +356,7 @@ class TestHotReloaderHandlers:result = await reloader._handle_model_deleted(change)assert result.status == ReloadStatus.SUCCESS- mock_registry.unload.assert_called_with("delete-model")+ mock_registry.unload_async.assert_awaited_once_with("delete-model")@pytest.mark.asyncioasync def test_drain_requests(self, temp_models_dir: Path, mock_registry: MagicMock) -> None:diff --git a/packages/sie_server/tests/core/test_idle_evict.py b/packages/sie_server/tests/core/test_idle_evict.pyindex 58159d9f2..7dcf3a04e 100644--- a/packages/sie_server/tests/core/test_idle_evict.py+++ b/packages/sie_server/tests/core/test_idle_evict.py@@ -26,6 +26,7 @@ from sie_server.config.engine import EngineConfigfrom sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasksfrom sie_server.core.memory import MemoryConfigfrom sie_server.core.registry import ModelRegistry+from sie_server.core.residency import EvictionResultfrom sie_server.observability.metrics import IDLE_EVICTIONS_TOTAL@@ -346,3 +347,100 @@ async def test_idle_evictor_skips_pinned_model(mock_load_adapter: MagicMock) -># Non-pinned model evicted; pinned model keptassert not reg.is_loaded("model-evictable")assert reg.is_loaded("model-pinned")+++# --------------------------------------------------------------------------+# _do_unload must not leave a MemoryManager "ghost" on adapter failure (#1600)+# --------------------------------------------------------------------------+++@patch("sie_server.core.model_loader.load_adapter")+async def test_do_unload_raising_adapter_leaves_no_ghost(mock_load_adapter: MagicMock) -> None:+ """A raising ``adapter.unload()`` must still unregister the model from the+ MemoryManager.++ Otherwise the model becomes a ghost — absent from ``_loaded`` but still in+ ``_models`` — that ``get_lru_model`` keeps re-selecting while ``_do_unload``+ no-ops on it, a no-yield spin under ``_load_lock`` that hangs the server.+ See #1600.+ """+ adapter = MagicMock()+ adapter.capabilities.outputs = ["dense"]+ adapter.aclose_client = None # not an SGLang-style client-holding adapter+ adapter.unload.side_effect = RuntimeError("unload boom")+ mock_load_adapter.return_value = adapter++ reg = _build_registry(idle_evict_s=None)+ reg.add_config(_make_config(name="doomed"))+ await reg.load_async("doomed", device="cpu")+ assert reg._memory_manager.get_model_info("doomed") is not None++ # _do_unload re-raises the adapter error (try/finally, not try/except)...+ with pytest.raises(RuntimeError, match="unload boom"):+ await reg._do_unload("doomed")++ # ...but the model is gone from BOTH _loaded and the MemoryManager — the+ # finally ran unregister_model, so there is no ghost to spin on.+ assert "doomed" not in reg._loaded+ assert reg._memory_manager.get_model_info("doomed") is None+ assert reg._memory_manager.loaded_model_count == 0+++# --------------------------------------------------------------------------+# evict_lru_excluding — typed EvictionResult (issue #1569)+# --------------------------------------------------------------------------+++@patch("sie_server.core.model_loader.load_adapter")+async def test_evict_lru_excluding_no_candidate(mock_load_adapter: MagicMock) -> None:+ """Only the excluded model is resident → NO_CANDIDATE (not a bare False)."""+ adapter = MagicMock()+ adapter.capabilities.outputs = ["dense"]+ mock_load_adapter.return_value = adapter++ reg = _build_registry(idle_evict_s=None)+ reg.add_config(_make_config(name="only-self"))+ await reg.load_async("only-self", device="cpu")++ assert await reg.evict_lru_excluding("only-self") is EvictionResult.NO_CANDIDATE+++@patch("sie_server.core.model_loader.load_adapter")+async def test_evict_lru_excluding_evicts_sibling(mock_load_adapter: MagicMock) -> None:+ """A cold sibling is unloaded → EVICTED, targeting that sibling."""+ adapters = [MagicMock(), MagicMock()]+ for a in adapters:+ a.capabilities.outputs = ["dense"]+ mock_load_adapter.side_effect = adapters++ reg = _build_registry(idle_evict_s=None)+ reg.add_config(_make_config(name="keep-me"))+ reg.add_config(_make_config(name="evict-me"))+ await reg.load_async("keep-me", device="cpu")+ await reg.load_async("evict-me", device="cpu")++ reg._do_unload = AsyncMock()+ assert await reg.evict_lru_excluding("keep-me") is EvictionResult.EVICTED+ reg._do_unload.assert_awaited_once_with("evict-me")+++@patch("sie_server.core.model_loader.load_adapter")+async def test_evict_lru_excluding_unload_failure(mock_load_adapter: MagicMock) -> None:+ """If the chosen candidate's unload raises → UNLOAD_FAILED."""+ adapters = [MagicMock(), MagicMock()]+ for a in adapters:+ a.capabilities.outputs = ["dense"]+ mock_load_adapter.side_effect = adapters++ reg = _build_registry(idle_evict_s=None)+ reg.add_config(_make_config(name="keep-me"))+ reg.add_config(_make_config(name="evict-me"))+ await reg.load_async("keep-me", device="cpu")+ await reg.load_async("evict-me", device="cpu")++ reg._do_unload = AsyncMock(side_effect=RuntimeError("boom"))+ assert await reg.evict_lru_excluding("keep-me") is EvictionResult.UNLOAD_FAILEDdiff --git a/packages/sie_server/tests/core/test_load_rgb.py b/packages/sie_server/tests/core/test_load_rgb.pynew file mode 100644index 000000000..a86ec0236--- /dev/null+++ b/packages/sie_server/tests/core/test_load_rgb.py@@ -0,0 +1,48 @@+"""Tests for the shared vision RGB image loader ``_load_rgb`` (issue #1540).++Pins the decode + RGB-convert idiom that the vision preprocessors used to+repeat: RGB passthrough preserves size, non-RGB modes are converted, and a+malformed media payload surfaces as ``InvalidMediaError`` (-> 400).+"""++from __future__ import annotations++import io++import pytest+from PIL import Image as PILImage+from sie_server.core.preprocessor.vision import _load_rgb+from sie_server.types.inputs import InvalidMediaError+++def _png_bytes(mode: str, size: tuple[int, int] = (7, 5)) -> bytes:+ buf = io.BytesIO()+ PILImage.new(mode, size).save(buf, format="PNG")+ return buf.getvalue()+++def test_rgb_passthrough_preserves_size() -> None:+ img = _load_rgb({"data": _png_bytes("RGB", (7, 5))})+ assert img.mode == "RGB"+ assert img.size == (7, 5)+++def test_converts_grayscale_to_rgb() -> None:+ img = _load_rgb({"data": _png_bytes("L", (4, 9))})+ assert img.mode == "RGB"+ assert img.size == (4, 9) # convert("RGB") preserves dimensions+++def test_converts_rgba_to_rgb() -> None:+ img = _load_rgb({"data": _png_bytes("RGBA", (3, 3))})+ assert img.mode == "RGB"+++def test_non_bytes_payload_raises_invalid_media() -> None:+ with pytest.raises(InvalidMediaError):+ _load_rgb({"data": "not-bytes"})+++def test_missing_data_raises_invalid_media() -> None:+ with pytest.raises(InvalidMediaError):+ _load_rgb({})diff --git a/packages/sie_server/tests/core/test_postprocessor.py b/packages/sie_server/tests/core/test_postprocessor.pyindex 2118b9c8b..f7b407e4a 100644--- a/packages/sie_server/tests/core/test_postprocessor.py+++ b/packages/sie_server/tests/core/test_postprocessor.py@@ -304,6 +304,109 @@ class TestMuveraPostprocessor:np.testing.assert_array_almost_equal(result_2d[1], [5.0, 6.0, 7.0, 8.0])+class TestMuveraSameDimCountSketchGuard:+ """Tests for the #1493 same-or-larger Count-Sketch guard.++ A Count-Sketch is only ever a reduction; when ``final_projection_dim >=+ intermediate_dim`` it is destructive (collapsed @muvera nDCG@10 to ~0.05).+ The guard skips it and returns the unprojected intermediate FDE.+ """++ def test_guard_skips_same_dim_count_sketch(self) -> None:+ """Same-dim count-sketch is skipped; target_dim == intermediate_dim."""+ # The old buggy answerai config: reps=20, proj=8, token_dim=96 ->+ # intermediate = 20 * 64 * 8 = 10240 == final_projection_dim.+ config = MuveraConfig(+ num_repetitions=20,+ num_simhash_projections=6,+ projection_dim=8,+ final_projection_dim=10240,+ seed=42,+ )+ pp = MuveraPostprocessor(token_dim=96, config=config)+ assert config.intermediate_dim(token_dim=96) == 10240+ assert pp.target_dim == 10240+ assert pp._final_dim is None # sketch skipped++ # Equivalence: a no-sketch postprocessor (final=None) must produce the+ # bit-identical FDE, proving Step 6 was skipped for the guarded config.+ no_sketch_config = MuveraConfig(+ num_repetitions=20,+ num_simhash_projections=6,+ projection_dim=8,+ final_projection_dim=None,+ seed=42,+ )+ no_sketch_pp = MuveraPostprocessor(token_dim=96, config=no_sketch_config)+ assert no_sketch_pp.target_dim == 10240++ rng = np.random.default_rng(42)+ multivector = [rng.standard_normal((12, 96)).astype(np.float32)]++ guarded = EncodeOutput(multivector=[mv.copy() for mv in multivector], batch_size=1)+ unsketched = EncodeOutput(multivector=[mv.copy() for mv in multivector], batch_size=1)+ pp.transform(guarded, is_query=False)+ no_sketch_pp.transform(unsketched, is_query=False)++ np.testing.assert_array_equal(guarded.dense, unsketched.dense)++ def test_genuine_reduction_still_applies_count_sketch(self) -> None:+ """A real reduction (final < intermediate) keeps the count-sketch."""+ # reps=20, proj=8, token_dim=128 -> intermediate = 20 * 64 * 8 = 10240.+ config = MuveraConfig(+ num_repetitions=20,+ num_simhash_projections=6,+ projection_dim=8,+ final_projection_dim=4096,+ seed=42,+ )+ pp = MuveraPostprocessor(token_dim=128, config=config)+ assert config.intermediate_dim(token_dim=128) == 10240+ assert pp.target_dim == 4096+ assert pp._final_dim == 4096 # sketch applied++ multivector = [np.random.default_rng(7).standard_normal((10, 128)).astype(np.float32)]+ output = EncodeOutput(multivector=multivector, batch_size=1)+ pp.transform(output, is_query=False)+ assert output.dense is not None+ assert output.dense.shape == (1, 4096)++ def test_separability_recovered_when_sketch_skipped(self) -> None:+ """End-to-end sanity check: the guarded FDE ranks a near-duplicate doc+ above an unrelated doc for the query.++ This is a sanity check, not the regression guard. The load-bearing+ proof that the same-dim sketch is skipped is the bit-exact equivalence+ assertion in ``test_guard_skips_same_dim_count_sketch`` (which fails+ pre-fix). The destructive sketch's damage shows up at corpus scale+ (near-tied scores across thousands of docs), not on a single pair.+ """+ config = MuveraConfig(+ num_repetitions=20,+ num_simhash_projections=6,+ projection_dim=8,+ final_projection_dim=10240, # same-dim -> guarded (skipped)+ seed=42,+ )+ pp = MuveraPostprocessor(token_dim=96, config=config)++ rng = np.random.default_rng(42)+ query_tokens = rng.standard_normal((12, 96)).astype(np.float32)+ dup_tokens = (query_tokens + rng.standard_normal((12, 96)).astype(np.float32) * 0.01).astype(np.float32)+ unrelated_tokens = rng.standard_normal((20, 96)).astype(np.float32)++ q_out = EncodeOutput(multivector=[query_tokens], batch_size=1)+ dup_out = EncodeOutput(multivector=[dup_tokens], batch_size=1)+ unrelated_out = EncodeOutput(multivector=[unrelated_tokens], batch_size=1)+ pp.transform(q_out, is_query=True)+ pp.transform(dup_out, is_query=False)+ pp.transform(unrelated_out, is_query=False)++ dup_score = float(q_out.dense[0] @ dup_out.dense[0])+ unrelated_score = float(q_out.dense[0] @ unrelated_out.dense[0])+ assert dup_score > unrelated_score++class TestMuveraFDEProperties:"""Tests for mathematical properties of MUVERA FDE."""@@ -386,3 +489,80 @@ class TestMuveraFDEProperties:corr, _ = spearmanr(maxsim_scores, fde_scores)# MUVERA should preserve ranking reasonably wellassert corr > 0.5, f"Expected positive correlation, got {corr}"+++class TestMuveraCenterTokens:+ """Tests for the #1528 ``center_tokens`` fix.++ A dominant shared DC component across a multivector's tokens makes SimHash+ bucket them all into the same partitions, so the FDEs of different docs come+ out near-identical (collapsed ranking) even though MaxSim stays healthy.+ Subtracting the per-multivector mean token before partitioning removes the DC+ component and partitions on the discriminative residual.+ """++ def test_default_is_off(self) -> None:+ """center_tokens defaults False — existing configs/floors are unaffected."""+ assert MuveraConfig().center_tokens is False++ def test_flag_changes_fde_for_dc_heavy_multivector(self) -> None:+ """For a DC-dominated multivector the centered FDE differs from uncentered."""+ common = {"num_repetitions": 8, "projection_dim": None, "final_projection_dim": None, "seed": 42}+ pp_off = MuveraPostprocessor(token_dim=16, config=MuveraConfig(**common, center_tokens=False))+ pp_on = MuveraPostprocessor(token_dim=16, config=MuveraConfig(**common, center_tokens=True))++ rng = np.random.default_rng(0)+ dc = rng.standard_normal(16).astype(np.float32)+ dc /= np.linalg.norm(dc)+ mv = (3.0 * dc + 0.3 * rng.standard_normal((10, 16))).astype(np.float32)++ off = EncodeOutput(multivector=[mv.copy()], batch_size=1)+ on = EncodeOutput(multivector=[mv.copy()], batch_size=1)+ pp_off.transform(off, is_query=False)+ pp_on.transform(on, is_query=False)+ assert not np.allclose(off.dense, on.dense)++ def test_centering_separates_dc_dominated_docs(self) -> None:+ """Load-bearing: two docs sharing a dominant DC direction but differing in+ a small residual have near-tied FDEs without centering; centering pulls+ their FDEs apart (lower pairwise cosine = separable ranking).+ """+ common = {+ "num_repetitions": 20,+ "num_simhash_projections": 6,+ "projection_dim": None,+ "final_projection_dim": None,+ "seed": 42,+ }+ pp_off = MuveraPostprocessor(token_dim=32, config=MuveraConfig(**common, center_tokens=False))+ pp_on = MuveraPostprocessor(token_dim=32, config=MuveraConfig(**common, center_tokens=True))++ rng = np.random.default_rng(1)+ dc = rng.standard_normal(32).astype(np.float32)+ dc /= np.linalg.norm(dc)++ def dc_doc(seed: int) -> np.ndarray:+ # A dominant shared DC direction (15x) plus a small per-doc residual,+ # then unit-normalized as the adapter does. The DC dominance is what+ # tips SimHash into collapse (mirrors answerai's ~0.93 DC on real data).+ r = np.random.default_rng(seed)+ tokens = 15.0 * dc + 0.2 * r.standard_normal((12, 32)).astype(np.float32)+ norms = np.linalg.norm(tokens, axis=1, keepdims=True)+ return (tokens / norms).astype(np.float32)++ doc_a, doc_b = dc_doc(11), dc_doc(22)++ def fde_cos(pp: MuveraPostprocessor) -> float:+ oa = EncodeOutput(multivector=[doc_a.copy()], batch_size=1)+ ob = EncodeOutput(multivector=[doc_b.copy()], batch_size=1)+ pp.transform(oa, is_query=False)+ pp.transform(ob, is_query=False)+ a, b = oa.dense[0], ob.dense[0]+ return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))++ cos_off = fde_cos(pp_off)+ cos_on = fde_cos(pp_on)+ # Without centering the DC component dominates -> near-tied FDEs.+ assert cos_off > 0.85+ # Centering removes it -> the two docs become clearly separable.+ assert cos_on < cos_off - 0.2diff --git a/packages/sie_server/tests/core/test_registry_async.py b/packages/sie_server/tests/core/test_registry_async.pyindex cfbb9d85d..ec734bed9 100644--- a/packages/sie_server/tests/core/test_registry_async.py+++ b/packages/sie_server/tests/core/test_registry_async.py@@ -4,7 +4,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks-from sie_server.core.memory import MemoryConfig+from sie_server.core.memory import MemoryConfig, MemoryStatsfrom sie_server.core.registry import ModelRegistry@@ -374,6 +374,65 @@ class TestProactiveEviction:assert not registry_with_models.is_loaded("model-b")assert registry_with_models.is_loaded("model-c")+ @patch("sie_server.core.model_loader.load_adapter")+ async def test_pre_load_eviction_uses_adapter_load_headroom(+ self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock+ ) -> None:+ """Load evicts for adapter-owned headroom, not only current pressure."""+ gb = 1024**3+ registry = ModelRegistry(device="cuda:0")+ registry.add_config(_make_config(name="model-a", hf_id="org/model-a"))+ registry.add_config(_make_config(name="model-c", hf_id="org/model-c"))+ model_a_adapter = mock_adapter_factory()+ model_c_adapter = mock_adapter_factory()+ required_bytes = 9 * gb+ model_c_adapter.load_required_memory_bytes.return_value = required_bytes+ mock_load_adapter.side_effect = [model_a_adapter, model_c_adapter]++ with patch.object(registry._memory_manager, "should_evict_for_load", return_value=False):+ await registry.load_async("model-a", "cuda:0")++ stats = MemoryStats(used_bytes=2 * gb, total_bytes=10 * gb, device_type="cuda")+ with (+ patch.object(registry._memory_manager, "get_stats", return_value=stats),+ patch.object(registry._memory_manager, "should_evict_for_load", side_effect=[True, False]) as should_evict,+ ):+ await registry.load_async("model-c", "cuda:0")++ model_c_adapter.load_required_memory_bytes.assert_called_once_with(+ device_type="cuda",+ device_total_bytes=10 * gb,+ )+ assert should_evict.call_args_list[0].args == (required_bytes,)+ assert not registry.is_loaded("model-a")+ assert registry.is_loaded("model-c")++ @patch("sie_server.core.model_loader.load_adapter")+ async def test_pre_load_eviction_ignores_adapter_load_headroom_exception(+ self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock+ ) -> None:+ """A bad adapter headroom hook falls back to pressure-only eviction."""+ gb = 1024**3+ registry = ModelRegistry(device="cuda:0")+ registry.add_config(_make_config(name="model-a", hf_id="org/model-a"))+ adapter = mock_adapter_factory()+ adapter.load_required_memory_bytes.side_effect = RuntimeError("boom")+ mock_load_adapter.return_value = adapter++ stats = MemoryStats(used_bytes=2 * gb, total_bytes=10 * gb, device_type="cuda")+ with (+ patch.object(registry._memory_manager, "get_stats", return_value=stats),+ patch.object(registry._memory_manager, "should_evict_for_load", return_value=False) as should_evict,+ ):+ await registry.load_async("model-a", "cuda:0")++ adapter.load_required_memory_bytes.assert_called_once_with(+ device_type="cuda",+ device_total_bytes=10 * gb,+ )+ should_evict.assert_called_once_with(None)+ assert registry.is_loaded("model-a")+async def test_background_monitor_loop_runs(self) -> None:"""Background monitor loop runs and checks pressure periodically."""import asynciodiff --git a/packages/sie_server/tests/core/test_registry_core.py b/packages/sie_server/tests/core/test_registry_core.pyindex 6d6fd7c27..579fc6712 100644--- a/packages/sie_server/tests/core/test_registry_core.py+++ b/packages/sie_server/tests/core/test_registry_core.py@@ -62,6 +62,98 @@ class TestModelRegistry:assert registry.has_model("test-model")assert registry.get_config("test-model") == config+ def test_add_config_expands_profile_variants(self) -> None:+ """Programmatic config updates expose non-default profile aliases."""+ registry = ModelRegistry()++ config = _make_config(name="test-model", hf_id="org/test")+ config.profiles["fast"] = ProfileConfig(+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",+ max_batch_tokens=8192,+ )++ registry.add_config(config)++ assert registry.has_model("test-model:fast")+ variant = registry.get_config("test-model:fast")+ assert set(variant.profiles) == {"default"}+ assert variant.profiles["default"].adapter_path == (+ "sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter"+ )++ def test_add_config_omits_bare_model_without_default_profile(self) -> None:+ """Profile-only configs expose only explicit variant aliases."""+ registry = ModelRegistry()++ config = ModelConfig(+ sie_id="test-model",+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),+ profiles={+ "fast": ProfileConfig(+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",+ max_batch_tokens=8192,+ )+ },+ )++ registry.add_config(config)++ assert not registry.has_model("test-model")+ assert registry.has_model("test-model:fast")+ variant = registry.get_config("test-model:fast")+ assert set(variant.profiles) == {"default"}+ assert variant.profiles["default"].adapter_path == (+ "sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter"+ )++ def test_python_registry_filters_rust_only_profile_variants(self) -> None:+ """The Python worker must not advertise Rust-only adapter routes."""+ registry = ModelRegistry()++ config = _make_config(name="test-model", hf_id="org/test")+ config.profiles["candle"] = ProfileConfig(+ adapter_path="sie_server_rust.adapters.candle:CandleEmbeddingAdapter",+ max_batch_tokens=8192,+ )++ registry.add_config(config)++ assert registry.has_model("test-model")+ assert not registry.has_model("test-model:candle")++ @pytest.mark.asyncio+ async def test_add_config_async_drops_stale_bare_and_profile_variants(self) -> None:+ """Authoritative profile removal must stop serving stale route ids."""+ registry = ModelRegistry()++ config = _make_config(name="test-model", hf_id="org/test")+ config.profiles["fast"] = ProfileConfig(+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",+ max_batch_tokens=8192,+ )+ registry.add_config(config)+ assert registry.has_model("test-model")+ assert registry.has_model("test-model:fast")++ profile_only = ModelConfig(+ sie_id="test-model",+ hf_id="org/test",+ tasks=Tasks(encode=EncodeTask(dense=EmbeddingDim(dim=768))),+ profiles={+ "fast": ProfileConfig(+ adapter_path="sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter",+ max_batch_tokens=8192,+ )+ },+ )++ changed = await registry.add_config_async(profile_only)++ assert changed == {"test-model", "test-model:fast"}+ assert not registry.has_model("test-model")+ assert registry.has_model("test-model:fast")+def test_load_from_directory(self, tmp_path: Path) -> None:"""Can load configs from directory."""# Create flat YAML config file@@ -83,6 +175,43 @@ profiles:assert registry.has_model("my-model")assert registry.get_config("my-model").tasks.encode.dense.dim == 384+ def test_load_from_directory_filters_rust_only_variants(self, tmp_path: Path) -> None:+ """Filesystem catalog loading keeps Rust-only profiles out of Python routes."""+ (tmp_path / "mixed-model.yaml").write_text("""+sie_id: mixed-model+hf_id: org/mixed-model+tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: "sie_server.adapters.sentence_transformer:SentenceTransformerDenseAdapter"+ max_batch_tokens: 8192+ candle:+ adapter_path: "sie_server_rust.adapters.candle:CandleEmbeddingAdapter"+ max_batch_tokens: 8192+""")+ (tmp_path / "candle-only.yaml").write_text("""+sie_id: candle-only+hf_id: org/candle-only+tasks:+ encode:+ dense:+ dim: 384+profiles:+ candle:+ adapter_path: "sie_server_rust.adapters.candle:CandleEmbeddingAdapter"+ max_batch_tokens: 8192+""")++ registry = ModelRegistry(models_dir=tmp_path)++ assert registry.has_model("mixed-model")+ assert not registry.has_model("mixed-model:candle")+ assert not registry.has_model("candle-only")+ assert not registry.has_model("candle-only:candle")+def test_cloud_models_dir_maps_cached_configs(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:"""Cloud models_dir maps each model to the cache directory (flat YAML structure)."""cache_root = tmp_path / "cache"diff --git a/packages/sie_server/tests/core/test_registry_failed_state.py b/packages/sie_server/tests/core/test_registry_failed_state.pyindex bec6458c4..38bd2a5ce 100644--- a/packages/sie_server/tests/core/test_registry_failed_state.py+++ b/packages/sie_server/tests/core/test_registry_failed_state.py@@ -10,12 +10,14 @@ than a retryable ``MODEL_LOADING``.from __future__ import annotations+import tempfileimport timefrom pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytestfrom sie_sdk.exceptions import GatedModelError+from sie_server.adapters.sglang import _server as sglang_serverfrom sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasksfrom sie_server.core.load_errors import (LoadErrorClass,@@ -83,6 +85,18 @@ class TestClassifyLoadError:assert result.cooldown_s is not Noneassert not result.is_permanent+ def test_sglang_startup_error_with_oom_log_is_oom(self) -> None:+ with tempfile.NamedTemporaryFile(mode="w+") as output_file:+ output_file.write("torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 2 GiB\n")+ output_file.flush()++ exc = sglang_server.startup_failure_error(output_file)+ result = classify_load_error(exc)++ assert result.error_class is LoadErrorClass.OOM+ assert result.cooldown_s is not None+ assert "Tried to allocate" not in str(exc)+def test_connection_error_is_network_with_cooldown(self) -> None:result = classify_load_error(ConnectionError("dns failure"))assert result.error_class is LoadErrorClass.NETWORKdiff --git a/packages/sie_server/tests/core/test_registry_memory.py b/packages/sie_server/tests/core/test_registry_memory.pyindex 544caa168..96ef512d9 100644--- a/packages/sie_server/tests/core/test_registry_memory.py+++ b/packages/sie_server/tests/core/test_registry_memory.py@@ -82,8 +82,10 @@ class TestRegistryMemoryManagerIntegration:assert "test" not in registry.memory_manager.loaded_models@patch("sie_server.core.model_loader.load_adapter")- def test_get_touches_model_for_lru(self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock) -> None:- """Getting a model's adapter updates LRU tracking."""+ def test_touch_lru_updates_model_and_get_is_pure(+ self, mock_load_adapter: MagicMock, mock_adapter_factory: MagicMock+ ) -> None:+ """touch_lru() marks a model recently used; get() is a pure read (#1541)."""mock_load_adapter.side_effect = [mock_adapter_factory(), mock_adapter_factory()]registry = ModelRegistry()@@ -97,12 +99,16 @@ class TestRegistryMemoryManagerIntegration:# Initially model-a is LRU (loaded first)assert registry.memory_manager.get_lru_model() == "model-a"- # Access model-a, now model-b should be LRU+ # get() is a pure read — it must NOT change LRU order.registry.get("model-a")+ assert registry.memory_manager.get_lru_model() == "model-a"++ # touch_lru(model-a) makes model-b the LRU.+ registry.touch_lru("model-a")assert registry.memory_manager.get_lru_model() == "model-b"- # Access model-b, now model-a should be LRU again- registry.get("model-b")+ # touch_lru(model-b) makes model-a the LRU again.+ registry.touch_lru("model-b")assert registry.memory_manager.get_lru_model() == "model-a"@patch("sie_server.core.model_loader.load_adapter")diff --git a/packages/sie_server/tests/core/test_registry_multi_model.py b/packages/sie_server/tests/core/test_registry_multi_model.pyindex a090b2dc7..1b9579f1b 100644--- a/packages/sie_server/tests/core/test_registry_multi_model.py+++ b/packages/sie_server/tests/core/test_registry_multi_model.py@@ -187,18 +187,19 @@ class TestMultiModelRouting:# Initially A is LRU (loaded first)assert registry.memory_manager.get_lru_model() == "model-a"- # Access A -> now B is LRU- registry.get("model-a")+ # touch_lru(A) -> now B is LRU. (get() is a pure read since #1541; the+ # request hot paths call touch_lru explicitly to mark recent use.)+ registry.touch_lru("model-a")assert registry.memory_manager.get_lru_model() == "model-b"- # Access B -> now C is LRU- registry.get("model-b")+ # touch_lru(B) -> now C is LRU+ registry.touch_lru("model-b")assert registry.memory_manager.get_lru_model() == "model-c"- # Access C -> now A is LRU (full rotation)- registry.get("model-c")+ # touch_lru(C) -> now A is LRU (full rotation)+ registry.touch_lru("model-c")assert registry.memory_manager.get_lru_model() == "model-a"- # Access A again -> now B is LRU- registry.get("model-a")+ # touch_lru(A) again -> now B is LRU+ registry.touch_lru("model-a")assert registry.memory_manager.get_lru_model() == "model-b"diff --git a/packages/sie_server/tests/core/test_runtime_options.py b/packages/sie_server/tests/core/test_runtime_options.pynew file mode 100644index 000000000..2e31649e4--- /dev/null+++ b/packages/sie_server/tests/core/test_runtime_options.py@@ -0,0 +1,95 @@+"""Unit tests for core.runtime_options.merge_runtime_options.++This is the single merge used by BOTH the single-server HTTP path+(api.options.resolve_runtime_options) and the cluster queue worker+(queue_executor.process_encode_batch). Regression coverage for #1489: the+worker path historically forwarded raw SDK options and dropped profile+``adapter_options.runtime`` defaults (query_template / default_instruction /+pooling / normalize) for every queued request.+"""++from __future__ import annotations++import pytest+from sie_server.config.model import ModelConfig+from sie_server.core.runtime_options import merge_runtime_options+++def _embedder_config() -> ModelConfig:+ """An instruction-tuned embedder whose prompt lives in profile runtime."""+ return ModelConfig.model_validate(+ {+ "sie_id": "test/instruct-embedder",+ "hf_id": "test/instruct-embedder",+ "inputs": {"text": True},+ "tasks": {"encode": {"dense": {"dim": 8}}},+ "max_sequence_length": 512,+ "profiles": {+ "default": {+ "max_batch_tokens": 8192,+ "adapter_path": "sie_server.adapters.sglang.embedding:SGLangEmbeddingAdapter",+ "adapter_options": {+ "runtime": {+ "pooling": "last_token",+ "normalize": True,+ "query_template": "Instruct: {instruction}\nQuery: {text}",+ "default_instruction": "Given a query, retrieve relevant passages",+ },+ },+ },+ "alt": {+ "max_batch_tokens": 8192,+ "adapter_path": "sie_server.adapters.sglang.embedding:SGLangEmbeddingAdapter",+ "adapter_options": {"runtime": {"query_template": "alt: {text}"}},+ },+ },+ }+ )+++def test_merges_profile_runtime_under_request_options() -> None:+ """Profile runtime defaults appear even when the request only sends is_query."""+ config = _embedder_config()+ merged = merge_runtime_options(config, {"is_query": True})++ assert merged["query_template"] == "Instruct: {instruction}\nQuery: {text}"+ assert merged["default_instruction"] == "Given a query, retrieve relevant passages"+ assert merged["pooling"] == "last_token"+ assert merged["normalize"] is True+ # Request-supplied key is preserved alongside the merged defaults.+ assert merged["is_query"] is True+++def test_request_options_win_over_runtime_defaults() -> None:+ """Per-request overrides take precedence over profile runtime defaults."""+ config = _embedder_config()+ merged = merge_runtime_options(config, {"query_template": "custom: {text}", "normalize": False})++ assert merged["query_template"] == "custom: {text}"+ assert merged["normalize"] is False+++def test_none_request_options_yield_profile_defaults() -> None:+ """An empty/None request still receives the profile's runtime defaults."""+ config = _embedder_config()+ merged = merge_runtime_options(config, None)++ assert merged["query_template"] == "Instruct: {instruction}\nQuery: {text}"+ assert merged["default_instruction"] == "Given a query, retrieve relevant passages"+++def test_profile_key_selects_profile_and_is_consumed() -> None:+ """The 'profile' key chooses the profile and is not forwarded to the adapter."""+ config = _embedder_config()+ merged = merge_runtime_options(config, {"profile": "alt", "is_query": True})++ assert merged["query_template"] == "alt: {text}"+ assert "profile" not in merged+ assert merged["is_query"] is True+++def test_unknown_profile_raises_value_error() -> None:+ """An unknown profile name surfaces as ValueError (handled by callers)."""+ config = _embedder_config()+ with pytest.raises(ValueError, match="nope"):+ merge_runtime_options(config, {"profile": "nope"})diff --git a/packages/sie_server/tests/core/test_worker_lora.py b/packages/sie_server/tests/core/test_worker_lora.pyindex ca52a963f..a505031bc 100644--- a/packages/sie_server/tests/core/test_worker_lora.py+++ b/packages/sie_server/tests/core/test_worker_lora.py@@ -1,5 +1,5 @@import asyncio-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockimport numpy as npimport pytest@@ -198,3 +198,39 @@ class TestModelWorkerLoRABatching:finally:await worker.stop()+++class TestDrainActiveBatcherFairness:+ """The continuous-batching drain must be bounded to the backlog present at+ entry, so a saturated LoRA that keeps refilling its own batcher cannot loop+ forever and starve sibling LoRAs / the base model. See #1606.+ """++ @pytest.mark.asyncio+ async def test_drain_is_bounded_by_entry_backlog(self) -> None:+ worker = ModelWorker(MagicMock(), WorkerConfig())+ worker._process_batch = AsyncMock() # don't run real inference++ # A batcher whose try_drain ALWAYS returns a size-1 batch simulates a+ # LoRA refilling itself during every forward pass. Unbounded, this loops+ # forever; bounded by the entry backlog it stops after pending_count.+ entry_backlog = 5+ drain_batch = MagicMock()+ drain_batch.size = 1+ drain_batch.total_tokens = 1++ batcher = MagicMock()+ batcher.pending_count = entry_backlog+ batcher.try_drain = AsyncMock(return_value=drain_batch)+ worker._batchers = {"A": batcher}++ # wait_for is a safety net: if the bound regressed, fail (not hang).+ drained = await asyncio.wait_for(worker._drain_active_batcher("A"), timeout=2.0)++ assert drained is True+ assert worker._process_batch.await_count == entry_backlog++ @pytest.mark.asyncio+ async def test_drain_noop_when_batcher_absent(self) -> None:+ worker = ModelWorker(MagicMock(), WorkerConfig())+ assert await worker._drain_active_batcher("no-such-lora") is Falsediff --git a/packages/sie_server/tests/core/test_worker_passthrough.py b/packages/sie_server/tests/core/test_worker_passthrough.pydeleted file mode 100644index 8ffca0e1b..000000000--- a/packages/sie_server/tests/core/test_worker_passthrough.py+++ /dev/null@@ -1,220 +0,0 @@-"""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._batchersdiff --git a/packages/sie_server/tests/core/test_worker_preformed.py b/packages/sie_server/tests/core/test_worker_preformed.pynew file mode 100644index 000000000..df8821f87--- /dev/null+++ b/packages/sie_server/tests/core/test_worker_preformed.py@@ -0,0 +1,289 @@+"""Tests for ModelWorker pre-formed sidecar batches.++The worker-sidecar owns queue pull, scheduling, batching, and adaptive+control. When Python receives an IPC batch from the sidecar, ModelWorker must+execute that caller-formed batch directly instead of submitting it to the+Python BatchFormer again. Direct ``submit*`` calls still use Python batching for+single-instance HTTP serving.+"""++from __future__ import annotations++import asyncio++import numpy as np+import pytest+from sie_server.core.inference_output import EncodeOutput, ExtractOutput, ScoreOutput+from sie_server.core.prepared import TextPreparedItem, make_text_item+from sie_server.core.worker import ModelWorker, WorkerConfig+from sie_server.core.worker.model_worker import PreformedExtractRequest, PreformedScoreRequest+from sie_server.types.inputs import Item+++class RecordingAdapter:+ def __init__(self) -> None:+ self.encode_calls: list[tuple[int, str | None]] = []+ self.extract_calls: list[tuple[int, str | None]] = []+ self.score_calls: list[int] = []+ self.set_lora_calls: list[str | None] = []+ self._current_lora: str | None = None++ def set_active_lora(self, lora: str | None) -> None:+ self._current_lora = lora+ self.set_lora_calls.append(lora)++ def encode(self, items, *args, **kwargs) -> EncodeOutput:+ self.encode_calls.append((len(items), self._current_lora))+ return EncodeOutput(+ dense=np.array([[0.1, 0.2, 0.3]] * len(items), dtype=np.float32),+ batch_size=len(items),+ )++ def score_pairs(self, queries, items, *args, **kwargs) -> ScoreOutput:+ self.score_calls.append(len(items))+ return ScoreOutput(scores=np.arange(len(items), dtype=np.float32))++ def extract(self, items, *args, **kwargs) -> ExtractOutput:+ self.extract_calls.append((len(items), self._current_lora))+ return ExtractOutput(entities=[[] for _ in items])+++def adapter() -> RecordingAdapter:+ return RecordingAdapter()+++def prepared_item() -> TextPreparedItem:+ return make_text_item([1, 2, 3, 4, 5], 0)+++async def test_preformed_submit_dispatches_immediately(+ adapter: RecordingAdapter, prepared_item: TextPreparedItem+) -> None:+ worker = ModelWorker(adapter, WorkerConfig())+ await worker.start()+ try:+ assert worker._process_task is None++ future = await worker.submit_preformed(+ [prepared_item],+ [Item(text="hello")],+ ["dense"],+ )++ assert future.done()+ worker_result = future.result()+ assert worker_result.output.batch_size == 1+ assert adapter.encode_calls == [(1, None)]+ assert worker.pending_count == 0+ assert worker._process_task is None+ finally:+ await worker.stop()+++async def test_preformed_submit_preserves_caller_batch(+ adapter: RecordingAdapter, prepared_item: TextPreparedItem+) -> None:+ worker = ModelWorker(adapter, WorkerConfig())+ await worker.start()+ try:+ future = await worker.submit_preformed(+ [prepared_item, make_text_item([6, 7], 1)],+ [Item(text="a"), Item(text="b")],+ ["dense"],+ )++ assert future.done()+ assert adapter.encode_calls == [(2, None)]+ finally:+ await worker.stop()+++async def test_preformed_score_batch_preserves_sidecar_grouping(+ adapter: RecordingAdapter, prepared_item: TextPreparedItem+) -> None:+ worker = ModelWorker(adapter, WorkerConfig())+ await worker.start()+ try:+ futures = await worker.submit_score_preformed_batch(+ [+ PreformedScoreRequest(+ prepared_items=[prepared_item],+ query=Item(text="q1"),+ items=[Item(text="a")],+ ),+ PreformedScoreRequest(+ prepared_items=[prepared_item, make_text_item([6, 7], 1)],+ query=Item(text="q2"),+ items=[Item(text="b"), Item(text="c")],+ ),+ ]+ )++ assert len(futures) == 2+ assert [f.result().output.batch_size for f in futures] == [1, 2]+ assert adapter.score_calls == [3]+ finally:+ await worker.stop()+++async def test_preformed_extract_batch_preserves_sidecar_grouping(+ adapter: RecordingAdapter, prepared_item: TextPreparedItem+) -> None:+ worker = ModelWorker(adapter, WorkerConfig())+ await worker.start()+ try:+ futures = await worker.submit_extract_preformed_batch(+ [+ PreformedExtractRequest(+ prepared_items=[prepared_item],+ items=[Item(text="a")],+ options={"lora": "lora-x"},+ ),+ PreformedExtractRequest(+ prepared_items=[prepared_item],+ items=[Item(text="b")],+ options={"lora": "lora-x"},+ ),+ ],+ lora="lora-x",+ )++ assert len(futures) == 2+ assert [f.result().output.batch_size for f in futures] == [1, 1]+ assert adapter.extract_calls == [(2, "lora-x")]+ finally:+ await worker.stop()+++async def test_preformed_batch_rejects_empty_request_without_dispatch(adapter: RecordingAdapter) -> None:+ worker = ModelWorker(adapter, WorkerConfig())+ await worker.start()+ try:+ futures = await worker.submit_extract_preformed_batch(+ [+ PreformedExtractRequest(+ prepared_items=[],+ items=[],+ options={"lora": "lora-x"},+ )+ ],+ lora="lora-x",+ )++ results = await asyncio.wait_for(asyncio.gather(*futures, return_exceptions=True), timeout=0.5)++ assert len(results) == 1+ assert isinstance(results[0], ValueError)+ assert str(results[0]) == "preformed request contains no prepared items"+ assert adapter.extract_calls == []+ assert adapter.set_lora_calls == []+ finally:+ await worker.stop()+++async def test_preformed_score_batch_empty_request_does_not_block_siblings(+ adapter: RecordingAdapter, prepared_item: TextPreparedItem+) -> None:+ worker = ModelWorker(adapter, WorkerConfig())+ await worker.start()+ try:+ futures = await worker.submit_score_preformed_batch(+ [+ PreformedScoreRequest(+ prepared_items=[],+ query=Item(text="q-empty"),+ items=[],+ ),+ PreformedScoreRequest(+ prepared_items=[prepared_item],+ query=Item(text="q"),+ items=[Item(text="a")],+ ),+ ]+ )++ results = await asyncio.wait_for(asyncio.gather(*futures, return_exceptions=True), timeout=0.5)++ assert len(results) == 2+ assert isinstance(results[0], ValueError)+ assert results[1].output.batch_size == 1+ assert adapter.score_calls == [1]+ finally:+ await worker.stop()+++async def test_preformed_submit_does_not_batch_across_calls(+ adapter: RecordingAdapter, prepared_item: TextPreparedItem+) -> None:+ worker = ModelWorker(adapter, WorkerConfig())+ await worker.start()+ try:+ results = await asyncio.gather(+ worker.submit_preformed([prepared_item], [Item(text="a")], ["dense"]),+ worker.submit_preformed([prepared_item], [Item(text="b")], ["dense"]),+ worker.submit_preformed([prepared_item], [Item(text="c")], ["dense"]),+ )++ assert len(results) == 3+ assert adapter.encode_calls == [(1, None), (1, None), (1, None)]+ finally:+ await worker.stop()+++async def test_preformed_submit_serializes_lora_switch(+ adapter: RecordingAdapter, prepared_item: TextPreparedItem+) -> None:+ worker = ModelWorker(adapter, WorkerConfig())+ await worker.start()+ try:+ await asyncio.gather(+ worker.submit_preformed([prepared_item], [Item(text="a")], ["dense"], options={"lora": "lora-x"}),+ worker.submit_preformed(+ [prepared_item, make_text_item([6, 7], 1)],+ [Item(text="b"), Item(text="b2")],+ ["dense"],+ options={"lora": "lora-y"},+ ),+ worker.submit_preformed(+ [prepared_item, make_text_item([8, 9], 1), make_text_item([10], 2)],+ [Item(text="c"), Item(text="c2"), Item(text="c3")],+ ["dense"],+ options={"lora": "lora-x"},+ ),+ )++ assert sorted(adapter.encode_calls) == [(1, "lora-x"), (2, "lora-y"), (3, "lora-x")]+ assert sorted(lora or "" for lora in adapter.set_lora_calls) == ["lora-x", "lora-x", "lora-y"]+ finally:+ await worker.stop()+++async def test_normal_submit_still_uses_python_batcher(+ adapter: RecordingAdapter, prepared_item: TextPreparedItem+) -> None:+ worker = ModelWorker(adapter, WorkerConfig(max_batch_wait_ms=20, coalesce_ms=5))+ await worker.start()+ try:+ assert worker._process_task is None++ futures = await asyncio.gather(+ worker.submit([prepared_item], [Item(text="a")], ["dense"]),+ worker.submit([make_text_item([6, 7], 0)], [Item(text="b")], ["dense"]),+ )+ await asyncio.gather(*futures)++ assert worker._process_task is not None+ assert adapter.encode_calls == [(2, None)]+ finally:+ await worker.stop()diff --git a/packages/sie_server/tests/core/worker/test_oom_recovery.py b/packages/sie_server/tests/core/worker/test_oom_recovery.pyindex 91465aeae..a65ae5830 100644--- a/packages/sie_server/tests/core/worker/test_oom_recovery.py+++ b/packages/sie_server/tests/core/worker/test_oom_recovery.py@@ -11,6 +11,7 @@ from sie_server.core.oom import (OomRecoveryStats,ResourceExhaustedError,)+from sie_server.core.residency import EvictionResultfrom sie_server.core.worker.oom_recovery import BatchExecutor, ConfigGroupfrom sie_server.observability.metrics import (OOM_BATCH_SPLITS,@@ -114,7 +115,7 @@ async def test_eviction_path() -> None:stats = OomRecoveryStats()registry = AsyncMock()- registry.evict_lru_excluding = AsyncMock(return_value=True)+ registry.evict_lru_excluding = AsyncMock(return_value=EvictionResult.EVICTED)executor = BatchExecutor(model_name="m", registry=registry, config=config, stats=stats)@@ -150,7 +151,7 @@ async def test_eviction_no_candidate_falls_through() -> None:stats = OomRecoveryStats()registry = AsyncMock()- registry.evict_lru_excluding = AsyncMock(return_value=False)+ registry.evict_lru_excluding = AsyncMock(return_value=EvictionResult.NO_CANDIDATE)executor = BatchExecutor(model_name="m", registry=registry, config=config, stats=stats)@@ -364,7 +365,7 @@ async def test_prometheus_counters_fire_for_evict_and_split_actions() -> None:)stats = OomRecoveryStats()registry = AsyncMock()- registry.evict_lru_excluding = AsyncMock(return_value=True)+ registry.evict_lru_excluding = AsyncMock(return_value=EvictionResult.EVICTED)executor = BatchExecutor(model_name="prom-evict-split", registry=registry, config=config, stats=stats)group, _ = _make_group(2)diff --git a/packages/sie_server/tests/health/test_nats_publisher.py b/packages/sie_server/tests/health/test_nats_publisher.pydeleted file mode 100644index 410f56225..000000000--- a/packages/sie_server/tests/health/test_nats_publisher.py+++ /dev/null@@ -1,86 +0,0 @@-"""Tests for the NATS health publisher (feature flag + payload shape).--The publisher's runtime path requires a live NATS server, which the-unit-test environment does not provide. We exercise the bits that are-testable without IO:--* The feature flag gate ``is_enabled()`` reads ``SIE_HEALTH_NATS``.-* The subject template matches what the gateway subscribes to.-* The publisher does not raise during a failed connect (graceful- degradation).-"""--from __future__ import annotations--from typing import Any--import msgpack-import pytest-from sie_server.health.nats_publisher import (- ENABLE_ENV,- HEALTH_SUBJECT_TEMPLATE,- NatsHealthPublisher,- is_enabled,-)---def test_is_enabled_default_false(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.delenv(ENABLE_ENV, raising=False)- assert is_enabled() is False---def test_is_enabled_only_when_exactly_one(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv(ENABLE_ENV, "1")- assert is_enabled() is True- monkeypatch.setenv(ENABLE_ENV, "true")- assert is_enabled() is False # strict — must be the literal "1"- monkeypatch.setenv(ENABLE_ENV, "0")- assert is_enabled() is False---def test_subject_template_matches_gateway_subscription() -> None:- # The Rust gateway subscribes to ``sie.health.>`` and parses the- # final token as ``worker_identifier``. The template must place- # the worker_id at that position.- assert HEALTH_SUBJECT_TEMPLATE.format(worker_id="w-42") == "sie.health.w-42"---def test_payload_is_msgpack_dict_of_status_message() -> None:- """The publisher serialises whatever ``build_status`` returns via- msgpack. We assert the round-trip survives so the gateway's- msgpack decoder will accept the bytes.- """- sample = {- "ready": True,- "name": "w-1",- "pool_name": "p",- "loaded_models": ["m"],- "saturated": True,- }- payload = msgpack.packb(sample, use_bin_type=True)- decoded = msgpack.unpackb(payload, raw=False)- assert decoded == sample- assert decoded["saturated"] is True---def test_publisher_constructor_does_not_connect(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """Construction must be I/O free — the publisher only opens a- connection when ``start()`` is called. This lets callers wire it- up in app-factory contexts that may not have an event loop yet.- """-- async def _build() -> dict[str, Any]:- return {"ready": True}-- pub = NatsHealthPublisher(- nats_url="nats://127.0.0.1:1",- worker_id="w-test",- build_status=_build,- )- # No connection should have been initiated.- assert pub._nc is None- assert pub._task is None- # And the subject is fully resolved at construction time.- assert pub._subject == "sie.health.w-test"diff --git a/packages/sie_server/tests/health/test_worker_id_consistency.py b/packages/sie_server/tests/health/test_worker_id_consistency.pyindex 94f506400..5b5c442cf 100644--- a/packages/sie_server/tests/health/test_worker_id_consistency.py+++ b/packages/sie_server/tests/health/test_worker_id_consistency.py@@ -1,11 +1,11 @@-"""Regression test: WS-status ``name`` must match pull-loop ``worker_id``.+"""Regression test: WS-status ``name`` must match queue-runtime ``worker_id``.C1 from the routing-rollout review: when ``SIE_WORKER_ID`` is set (or the-pull loop falls through to ``uuid4``), the gateway used to register+queue runtime falls through to ``uuid4``), the gateway used to registerthe worker under a different name than the worker subscribed on,silently breaking HRW direct dispatch.-The fix threads the pull loop's resolved ``worker_id`` into+The fix threads the queue runtime's resolved ``worker_id`` into``build_status_message`` and uses it for the WS payload's ``name``."""@@ -17,7 +17,11 @@ from unittest.mock import MagicMockimport pytest-class _FakePullLoop:+async def _gpu_healthy() -> bool:+ return True+++class _FakeQueueRuntime:"""Minimal stand-in exposing only the ``worker_id`` attribute thestatus builder reads."""@@ -30,13 +34,13 @@ class _FakePullLoop:@pytest.mark.asyncio-async def test_build_status_message_uses_pull_loop_worker_id(+async def test_build_status_message_uses_queue_runtime_worker_id(monkeypatch: pytest.MonkeyPatch,) -> None:- """When the pull loop is wired in, its ``worker_id`` wins over env vars.+ """When the queue runtime is wired in, its ``worker_id`` wins over env vars.The scenario this prevents: ``SIE_WORKER_ID="w-prod-3"`` is set and- ``HOSTNAME`` is the K8s pod name. Pre-fix, the pull loop subscribed+ ``HOSTNAME`` is the K8s pod name. Pre-fix, the queue runtime subscribedon ``sie.work.{pool}.{machine_profile}.{bundle}.*.w-prod-3`` but theWS payload reported``name = {pod-name}`` — the gateway's HRW pick used ``{pod-name}``@@ -64,9 +68,10 @@ async def test_build_status_message_uses_pull_loop_worker_id()monkeypatch.setattr("sie_server.api.ws.compute_bundle_config_hash_cached", lambda r, b: "")monkeypatch.setattr("sie_server.api.ws.is_ready", lambda: True)+ monkeypatch.setattr("sie_server.api.ws.gpu_is_healthy_async", _gpu_healthy)- pull_loop = _FakePullLoop(worker_id="w-prod-3")- status: dict[str, Any] = await build_status_message(registry, pull_loop=pull_loop)+ queue_runtime = _FakeQueueRuntime(worker_id="w-prod-3")+ status: dict[str, Any] = await build_status_message(registry, queue_runtime=queue_runtime)# The direct-dispatch routing contract: the registered name must equal the# subscription's worker_id.@@ -74,10 +79,10 @@ async def test_build_status_message_uses_pull_loop_worker_id(@pytest.mark.asyncio-async def test_build_status_message_falls_back_to_env_without_pull_loop(+async def test_build_status_message_falls_back_to_env_without_queue_runtime(monkeypatch: pytest.MonkeyPatch,) -> None:- """Non-queue deployments (no pull loop) keep the legacy behaviour+ """Non-queue deployments (no queue runtime) keep the legacy behaviourbut now honour ``SIE_WORKER_ID`` too."""monkeypatch.setenv("SIE_WORKER_ID", "w-env-1")@@ -96,6 +101,7 @@ async def test_build_status_message_falls_back_to_env_without_pull_loop()monkeypatch.setattr("sie_server.api.ws.compute_bundle_config_hash_cached", lambda r, b: "")monkeypatch.setattr("sie_server.api.ws.is_ready", lambda: True)+ monkeypatch.setattr("sie_server.api.ws.gpu_is_healthy_async", _gpu_healthy)- status: dict[str, Any] = await build_status_message(registry, pull_loop=None)+ status: dict[str, Any] = await build_status_message(registry, queue_runtime=None)assert status["name"] == "w-env-1"diff --git a/packages/sie_server/tests/observability/test_trace_propagation.py b/packages/sie_server/tests/observability/test_trace_propagation.pyindex 0a66347b2..04161f641 100644--- a/packages/sie_server/tests/observability/test_trace_propagation.py+++ b/packages/sie_server/tests/observability/test_trace_propagation.py@@ -29,6 +29,8 @@ from opentelemetry import trace as otel_tracefrom opentelemetry.sdk.trace import TracerProviderfrom opentelemetry.sdk.trace.export import SimpleSpanProcessorfrom opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter+from sie_server.adapter_call_loop import handle_run_batch+from sie_server.ipc_types import BatchOutcome, EncodeBatchItem, RunBatchItem, RunBatchRequestfrom sie_server.processors.streaming import StreamingProcessor# A well-known W3C traceparent value, taken verbatim from the W3C@@ -40,6 +42,12 @@ EXAMPLE_TRACE_ID_HEX = "0af7651916cd43dd8448eb211c80319c"EXAMPLE_PARENT_SPAN_HEX = "b7ad6b7169203331"EXAMPLE_TRACEPARENT = f"00-{EXAMPLE_TRACE_ID_HEX}-{EXAMPLE_PARENT_SPAN_HEX}-01"+# A second, distinct trace context used to exercise the run_batch fan-in+# path (two items from two different client requests in one batch).+EXAMPLE_TRACE_ID_HEX_2 = "1bf0762027de54ee9559fc322d91420d"+EXAMPLE_PARENT_SPAN_HEX_2 = "c8be7c8270314442"+EXAMPLE_TRACEPARENT_2 = f"00-{EXAMPLE_TRACE_ID_HEX_2}-{EXAMPLE_PARENT_SPAN_HEX_2}-01"+_MODULE_EXPORTER: InMemorySpanExporter | None = None@@ -248,3 +256,205 @@ async def test_worker_span_is_root_when_envelope_omits_traceparent(assert matching, "worker.streaming_processor span must still emit without traceparent"# No parent — the worker becomes the root of its own trace.assert matching[0].parent is None+++# ---------------------------------------------------------------------------+# Non-streaming worker loop (``handle_run_batch``) trace propagation.+#+# Mirrors the streaming assertions above: the gateway serialises its span+# into each work item's ``traceparent`` / ``tracestate``, the Rust+# scheduler copies those onto the wire ``RunBatchItem`` s, and+# ``handle_run_batch`` re-extracts them so ``worker.run_batch`` attaches to+# the gateway span instead of rooting a fresh trace.+# ---------------------------------------------------------------------------+++def _make_encode_run_batch_item(+ *,+ traceparent: str | None,+ tracestate: str | None = None,+ work_item_id: str = "r.0",+ request_id: str = "r",+ item_index: int = 0,+) -> RunBatchItem:+ """Build an encode ``RunBatchItem`` with a populated encode payload.++ The encode payload must be present (``_dispatch_encode`` reads+ ``ri.encode``) so dispatch reaches the stubbed executor instead of+ rejecting the item as invalid.+ """+ return RunBatchItem(+ op="encode",+ work_item_id=work_item_id,+ request_id=request_id,+ item_index=item_index,+ encode=EncodeBatchItem(+ work_item_id=work_item_id,+ request_id=request_id,+ item_index=item_index,+ total_items=1,+ timestamp=0.0,+ item={"text": "hello"},+ ),+ traceparent=traceparent,+ tracestate=tracestate,+ )+++def _make_run_batch_executor() -> MagicMock:+ """A ``QueueExecutor`` stub whose per-op dispatch is a trivial no-op.++ ``process_encode_batch`` returns an empty :class:`BatchOutcome` so no+ model is loaded — the test only exercises the trace-context boundary+ in ``handle_run_batch``, not the encode pipeline.+ """+ executor = MagicMock()+ executor.process_encode_batch = AsyncMock(return_value=BatchOutcome(outcomes=[]))+ return executor+++def _run_batch_span(in_memory_exporter: InMemorySpanExporter) -> Any:+ spans = in_memory_exporter.get_finished_spans()+ matching = [s for s in spans if s.name == "worker.run_batch"]+ assert matching, f"worker.run_batch span not emitted; saw {[s.name for s in spans]}"+ return matching[0]+++async def test_run_batch_span_is_child_of_single_context(+ in_memory_exporter: InMemorySpanExporter,+) -> None:+ """A single-context batch's span attaches to the gateway span.++ This is the acceptance criterion: a ``/v1/encode`` request carrying a+ ``traceparent`` produces a ``worker.run_batch`` span whose ``trace_id``+ equals the gateway trace_id and whose parent is the gateway span — not+ a fresh root.+ """+ executor = _make_run_batch_executor()+ req = RunBatchRequest(+ model_id="test/model",+ batch_id=7,+ lora_key="",+ total_cost=1,+ items=[_make_encode_run_batch_item(traceparent=EXAMPLE_TRACEPARENT)],+ )++ await handle_run_batch(executor, req)++ span = _run_batch_span(in_memory_exporter)+ assert format(span.context.trace_id, "032x") == EXAMPLE_TRACE_ID_HEX, (+ "run_batch span did not inherit the gateway's trace_id; extraction is broken"+ )+ assert span.parent is not None, "run_batch span has no parent — propagation produced a root"+ assert format(span.parent.span_id, "016x") == EXAMPLE_PARENT_SPAN_HEX, (+ "run_batch span's parent_span_id does not match the gateway span_id from the wire item"+ )+ assert not span.links, "single-context batch must not emit fan-in links"+++async def test_run_batch_span_attributes_include_sie_batch_metadata(+ in_memory_exporter: InMemorySpanExporter,+) -> None:+ """Span carries the batch metadata attributes operators build dashboards on."""+ executor = _make_run_batch_executor()+ req = RunBatchRequest(+ model_id="test/model",+ batch_id=7,+ lora_key="",+ total_cost=1,+ items=[_make_encode_run_batch_item(traceparent=EXAMPLE_TRACEPARENT)],+ )++ await handle_run_batch(executor, req)++ span = _run_batch_span(in_memory_exporter)+ attrs = dict(span.attributes or {})+ assert attrs.get("sie.model") == "test/model"+ assert attrs.get("sie.batch_id") == 7+ assert attrs.get("sie.op") == "encode"+ assert attrs.get("sie.adapter") == "run_batch"+ assert attrs.get("sie.batch_size") == 1+++async def test_run_batch_span_fan_in_links_distinct_contexts(+ in_memory_exporter: InMemorySpanExporter,+) -> None:+ """A fan-in batch parents to the first context and links the rest.++ Two items carrying two DISTINCT traceparents land in one batch: the+ span is a child of the first and carries exactly one OTel link to the+ second so the fan-in is visible in the trace graph.+ """+ executor = _make_run_batch_executor()+ req = RunBatchRequest(+ model_id="test/model",+ batch_id=11,+ lora_key="",+ total_cost=2,+ items=[+ _make_encode_run_batch_item(+ traceparent=EXAMPLE_TRACEPARENT, work_item_id="a.0", request_id="a", item_index=0+ ),+ _make_encode_run_batch_item(+ traceparent=EXAMPLE_TRACEPARENT_2, work_item_id="b.0", request_id="b", item_index=1+ ),+ ],+ )++ await handle_run_batch(executor, req)++ span = _run_batch_span(in_memory_exporter)+ # Child of the FIRST distinct context.+ assert format(span.context.trace_id, "032x") == EXAMPLE_TRACE_ID_HEX+ assert span.parent is not None+ assert format(span.parent.span_id, "016x") == EXAMPLE_PARENT_SPAN_HEX+ # Exactly one link, pointing at the SECOND distinct context.+ assert len(span.links) == 1, f"expected one fan-in link, got {len(span.links)}"+ link_ctx = span.links[0].context+ assert format(link_ctx.trace_id, "032x") == EXAMPLE_TRACE_ID_HEX_2+ assert format(link_ctx.span_id, "016x") == EXAMPLE_PARENT_SPAN_HEX_2+++async def test_run_batch_span_is_root_without_traceparent(+ in_memory_exporter: InMemorySpanExporter,+) -> None:+ """A batch with no trace context still emits a (root) span, no crash."""+ executor = _make_run_batch_executor()+ req = RunBatchRequest(+ model_id="test/model",+ batch_id=3,+ lora_key="",+ total_cost=1,+ items=[_make_encode_run_batch_item(traceparent=None)],+ )++ await handle_run_batch(executor, req)++ span = _run_batch_span(in_memory_exporter)+ assert span.parent is None, "run_batch span should be a root when no traceparent is present"+ assert not span.links+++async def test_run_batch_span_is_root_when_traceparent_malformed(+ in_memory_exporter: InMemorySpanExporter,+) -> None:+ """A malformed traceparent opens a root span and no fan-in links."""+ executor = _make_run_batch_executor()+ req = RunBatchRequest(+ model_id="test/model",+ batch_id=13,+ lora_key="",+ total_cost=1,+ items=[_make_encode_run_batch_item(traceparent="not-a-valid-traceparent")],+ )++ await handle_run_batch(executor, req)++ span = _run_batch_span(in_memory_exporter)+ assert span.parent is None, "run_batch span should be a root when traceparent is malformed"+ assert not span.linksdiff --git a/packages/sie_server/tests/observability/test_tracing.py b/packages/sie_server/tests/observability/test_tracing.pyindex ead929b91..b619f38e7 100644--- a/packages/sie_server/tests/observability/test_tracing.py+++ b/packages/sie_server/tests/observability/test_tracing.py@@ -7,6 +7,7 @@ from sie_server.observability.tracing import (get_current_trace_id,is_tracing_enabled,setup_tracing,+ shutdown_tracing,tracer,)@@ -46,6 +47,16 @@ class TestIsTracingEnabled:with patch.dict(os.environ, {"SIE_TRACING_ENABLED": "false"}):assert is_tracing_enabled() is False+ def test_enabled_with_whitespace_padding(self) -> None:+ """A whitespace-padded truthy value should still enable tracing."""+ with patch.dict(os.environ, {"SIE_TRACING_ENABLED": " true "}):+ assert is_tracing_enabled() is True++ def test_disabled_with_whitespace_only(self) -> None:+ """A whitespace-only value should be treated as unset (disabled)."""+ with patch.dict(os.environ, {"SIE_TRACING_ENABLED": " "}):+ assert is_tracing_enabled() is False+class TestSetupTracing:"""Tests for setup_tracing function."""@@ -79,11 +90,58 @@ class TestSetupTracing:# Should instrument the appmock_instrumentor.instrument_app.assert_called_once_with(mock_app)- # Should create exporter- mock_exporter.assert_called_once()+ # Should create exporter with a bounded per-request timeout (seconds)+ mock_exporter.assert_called_once_with(endpoint="http://localhost:4317", timeout=3.0)# Should set tracer providermock_trace.set_tracer_provider.assert_called_once()+ def test_noop_when_enabled_without_endpoint(self) -> None:+ """setup_tracing should no-op when the flag is set without an endpoint."""+ mock_app = MagicMock()++ with (+ patch.dict(os.environ, {"SIE_TRACING_ENABLED": "true"}, clear=True),+ patch("opentelemetry.instrumentation.fastapi.FastAPIInstrumentor") as mock_instrumentor,+ ):+ setup_tracing(mock_app)++ mock_instrumentor.instrument_app.assert_not_called()++ def test_noop_when_endpoint_whitespace_only(self) -> None:+ """A whitespace-only endpoint should be treated as absent (no instrumentation)."""+ mock_app = MagicMock()++ with (+ patch.dict(+ os.environ,+ {"SIE_TRACING_ENABLED": "true", "OTEL_EXPORTER_OTLP_ENDPOINT": " "},+ clear=True,+ ),+ patch("opentelemetry.instrumentation.fastapi.FastAPIInstrumentor") as mock_instrumentor,+ ):+ setup_tracing(mock_app)++ mock_instrumentor.instrument_app.assert_not_called()+++class TestShutdownTracing:+ """Tests for shutdown_tracing function."""++ def test_noop_when_not_setup(self) -> None:+ """shutdown_tracing should be a no-op (no error) when no provider is retained."""+ with patch("sie_server.observability.tracing._provider", None):+ shutdown_tracing() # should not raise++ def test_shuts_down_and_clears_provider(self) -> None:+ """shutdown_tracing should shut the retained provider down, then clear the handle."""+ mock_provider = MagicMock()+ with patch("sie_server.observability.tracing._provider", mock_provider):+ shutdown_tracing()+ # The handle is cleared after the first call, so a second call is a no-op.+ shutdown_tracing()++ mock_provider.shutdown.assert_called_once()+class TestGetCurrentTraceId:"""Tests for get_current_trace_id function."""diff --git a/packages/sie_server/tests/test_all_models.py b/packages/sie_server/tests/test_all_models.pyindex 375144513..5cde54469 100644--- a/packages/sie_server/tests/test_all_models.py+++ b/packages/sie_server/tests/test_all_models.py@@ -225,7 +225,9 @@ def test_google_embeddinggemma_300m_dense() -> None:# gate the test rather than letting numerical-equivalence drift mask the# underlying problem (sie-test#85).pytest.importorskip("transformers", minversion="4.56.0")- _assert_dense("google/embeddinggemma-300m", 768, [0.01641845703125, 0.052001953125, -0.0009312629699707031])+ # Reference is the sentence-transformers pipeline output (incl. the Dense+ # projection head) for "test" encoded as a document, on CPU/fp32.+ _assert_dense("google/embeddinggemma-300m", 768, [-0.069580078125, -0.03155517578125, 0.025390625])@pytest.mark.xfail(reason="7B model too large for CPU unit tests", strict=False)diff --git a/packages/sie_server/tests/test_decode_item.py b/packages/sie_server/tests/test_decode_item.pynew file mode 100644index 000000000..e6f03b85f--- /dev/null+++ b/packages/sie_server/tests/test_decode_item.py@@ -0,0 +1,103 @@+"""Tests for the single validating item decode (`decode_item`) and its+INVALID_INPUT mapping on the queue path. See issue #1537.++The HTTP path validates request items against the typed ``Item`` struct at the+seam; the queue/IPC path historically built ``Item(**kwargs)`` with no type+validation. ``decode_item`` closes that asymmetry by running the same ``Item``+contract through ``msgspec.convert``.+"""++from __future__ import annotations++import base64+import time++import msgspec+import pytest+from sie_server.ipc_types import EncodeBatchItem+from sie_server.queue_executor import _inference_exception_outcome+from sie_server.types.inputs import InvalidMediaError, decode_item, media_bytes+from sie_server.types.responses import ErrorCode+++class TestDecodeItemAccepts:+ def test_valid_text(self) -> None:+ item = decode_item({"text": "hello", "id": "a"})+ assert item.text == "hello"+ assert item.id == "a"++ def test_remaps_content_to_text(self) -> None:+ # The SDK ships ``content``; the server expects ``text``.+ item = decode_item({"content": "hi"})+ assert item.text == "hi"++ def test_content_ignored_when_text_present(self) -> None:+ item = decode_item({"content": "ignored", "text": "kept"})+ assert item.text == "kept"++ def test_ignores_unknown_keys(self) -> None:+ # Parity with the prior behaviour (which filtered to known fields).+ item = decode_item({"text": "hi", "totally_unknown": 123})+ assert item.text == "hi"++ def test_base64_decodes_str_media_data(self) -> None:+ # Matches the HTTP JSON path: a base64 ``str`` in ``data`` becomes+ # ``bytes``, so ``media_bytes`` downstream gets a valid payload.+ raw = base64.b64encode(b"PNGDATA").decode("ascii")+ item = decode_item({"images": [{"data": raw, "format": "png"}]})+ assert item.images is not None+ assert media_bytes(item.images[0], kind="image") == b"PNGDATA"++ def test_keeps_bytes_media_data(self) -> None:+ item = decode_item({"images": [{"data": b"PNGDATA"}]})+ assert item.images is not None+ assert media_bytes(item.images[0], kind="image") == b"PNGDATA"+++class TestDecodeItemRejects:+ def test_bad_text_type(self) -> None:+ with pytest.raises(msgspec.ValidationError):+ decode_item({"text": 123})++ def test_non_list_images(self) -> None:+ with pytest.raises(msgspec.ValidationError):+ decode_item({"images": "not-a-list"})++ def test_non_dict_image_element(self) -> None:+ with pytest.raises(msgspec.ValidationError):+ decode_item({"images": [123]})++ def test_bad_metadata_type(self) -> None:+ with pytest.raises(msgspec.ValidationError):+ decode_item({"metadata": "not-a-mapping"})++ def test_validation_error_is_value_error(self) -> None:+ # InvalidMediaError documents that both paths surface decode failures+ # as ValueError -> INVALID_INPUT; msgspec.ValidationError is one too.+ assert issubclass(msgspec.ValidationError, ValueError)+++def _bi() -> EncodeBatchItem:+ return EncodeBatchItem(+ work_item_id="req-1.0",+ request_id="req-1",+ item_index=0,+ total_items=1,+ timestamp=time.time(),+ item={"text": "hi"},+ )+++class TestInvalidInputMapping:+ def test_validation_error_maps_to_invalid_input(self) -> None:+ try:+ decode_item({"text": 123})+ except msgspec.ValidationError as exc:+ outcome = _inference_exception_outcome(_bi(), exc)+ assert outcome.disposition == "publish_error_and_ack"+ assert outcome.error_code == ErrorCode.INVALID_INPUT.value++ def test_invalid_media_maps_to_invalid_input(self) -> None:+ outcome = _inference_exception_outcome(_bi(), InvalidMediaError("bad media"))+ assert outcome.disposition == "publish_error_and_ack"+ assert outcome.error_code == ErrorCode.INVALID_INPUT.valuediff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex 59689a6ea..0753dd1d8 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -14,6 +14,8 @@ import msgpackimport numpy as npimport pytestimport yaml+from sie_config.model_registry import ModelRegistry as ConfigModelRegistry+from sie_sdk.bundle_utils import match_bundle_modelsfrom sie_server.api.ws import compute_bundle_config_hash_cachedfrom sie_server.config.model import ModelConfigfrom sie_server.core.inference_output import ExtractOutput, ScoreOutput@@ -48,6 +50,10 @@ def _short_sock_path() -> Path:return base / f"sie-{uuid.uuid4().hex[:12]}.sock"+def _repo_root() -> Path:+ return Path(__file__).resolve().parents[3]++class _Client:"""Minimal UDS IPC client used only by these tests."""@@ -368,6 +374,32 @@ class TestEnsureModelReady:class TestApplyModelConfig:+ def test_python_bundle_hash_matches_config_registry_and_skips_rust_profiles(self) -> None:+ root = _repo_root()+ bundles_dir = root / "packages/sie_server/bundles"+ models_dir = root / "packages/sie_server/models"+ config_registry = ConfigModelRegistry(bundles_dir, models_dir)++ default_filter = match_bundle_models(bundles_dir / "default.yaml", models_dir)+ default_registry = ModelRegistry(+ models_dir=models_dir,+ model_filter=default_filter,+ enable_hot_reload=False,+ )+ assert compute_bundle_config_hash_cached(+ default_registry,+ "default",+ ) == config_registry.compute_bundle_config_hash("default")++ candle_filter = match_bundle_models(bundles_dir / "candle.yaml", models_dir)+ candle_registry = ModelRegistry(+ models_dir=models_dir,+ model_filter=candle_filter,+ enable_hot_reload=False,+ )+ assert compute_bundle_config_hash_cached(candle_registry, "candle") == ""+ assert config_registry.compute_bundle_config_hash("candle")+@pytest.mark.asyncioasync def test_apply_model_config_hash_cache_is_per_registry(self) -> None:stale_registry = ModelRegistry(models_dir=None)@@ -1021,7 +1053,7 @@ profiles:class TestSetPinnedModels:@pytest.mark.asyncio- async def test_executor_passthrough_returns_count(self) -> None:+ async def test_executor_batch_budget_returns_count(self) -> None:registry = ModelRegistry(models_dir=None)registry.start_load_async = AsyncMock(return_value=True) # type: ignore[method-assign]executor = QueueExecutor(registry)@@ -1152,7 +1184,7 @@ class TestProcessScoreAndExtract:wr = WorkerResult(output=score_output, timing=RequestTiming())fut: asyncio.Future[WorkerResult] = asyncio.Future()fut.set_result(wr)- worker.submit_score = AsyncMock(return_value=fut)+ worker.submit_score_preformed_batch = AsyncMock(return_value=[fut])srv._executor._registry.start_worker = AsyncMock(return_value=worker)client = await _Client.connect(sock)@@ -1202,7 +1234,7 @@ class TestProcessScoreAndExtract:wr = WorkerResult(output=extract_output, timing=RequestTiming())fut: asyncio.Future[WorkerResult] = asyncio.Future()fut.set_result(wr)- worker.submit_extract = AsyncMock(return_value=fut)+ worker.submit_extract_preformed_batch = AsyncMock(return_value=[fut])srv._executor._registry.start_worker = AsyncMock(return_value=worker)client = await _Client.connect(sock)@@ -1279,6 +1311,7 @@ class TestGenerationSidecarIpc:"encode/model": encode_cfg,"z-generate/model": gen_cfg,}+ reg.loaded_model_names = ["encode/model"]sock = _short_sock_path()async with IpcServer(sock, executor, worker_id="w"):client = await _Client.connect(sock)@@ -1291,6 +1324,8 @@ class TestGenerationSidecarIpc:assert resp["body"] == {"has_generation_models": True,"generation_models": ["z-generate/model"],+ "supported_models": ["encode/model", "z-generate/model"],+ "loaded_models": ["encode/model"],}@pytest.mark.asynciodiff --git a/packages/sie_server/tests/test_model_yaml_filenames.py b/packages/sie_server/tests/test_model_yaml_filenames.pyindex f968c6774..bb7442b7d 100644--- a/packages/sie_server/tests/test_model_yaml_filenames.py+++ b/packages/sie_server/tests/test_model_yaml_filenames.py@@ -33,3 +33,35 @@ def test_yaml_filename_matches_sie_id(yaml_path: Path) -> None:f"expected {_expected_filename(sie_id)!r}. "f"Case-sensitive filesystems (Linux CI) will fail to find this config.")++[email protected]("yaml_path", sorted(MODELS_DIR.glob("*.yaml")), ids=lambda p: p.name)+def test_instruction_template_has_placeholder(yaml_path: Path) -> None:+ """An ``Instruct:``-prefixed ``query_template`` must contain the ``{instruction}``+ placeholder.++ Otherwise the eval harness's instruction gating+ (``EvalRunner._model_uses_instruction``, added in #1432) treats the model as+ non-instruction-following and silently drops the per-task MTEB prompt, so the+ model is measured with a hardcoded generic instruction instead of each task's+ instruction. This is the stella_en_*_v5 regression (#1340).+ """+ with yaml_path.open() as f:+ config = yaml.safe_load(f) or {}+ profiles = config.get("profiles")+ if not isinstance(profiles, dict):+ return+ offenders: list[str] = []+ for profile_name, profile in profiles.items():+ if not isinstance(profile, dict):+ continue+ adapter_options = profile.get("adapter_options")+ runtime = adapter_options.get("runtime") if isinstance(adapter_options, dict) else None+ query_template = runtime.get("query_template") if isinstance(runtime, dict) else None+ if isinstance(query_template, str) and "Instruct:" in query_template and "{instruction}" not in query_template:+ offenders.append(profile_name)+ assert not offenders, (+ f"{yaml_path.name}: profile(s) {offenders} hardcode an 'Instruct:' instruction "+ f"without a '{{instruction}}' placeholder; the eval harness drops the per-task "+ f"MTEB instruction (#1340). Use 'Instruct: {{instruction}}' + 'default_instruction'."+ )diff --git a/packages/sie_server/tests/test_queue_executor.py b/packages/sie_server/tests/test_queue_executor.pyindex f5360dea2..86e33d57c 100644--- a/packages/sie_server/tests/test_queue_executor.py+++ b/packages/sie_server/tests/test_queue_executor.py@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport msgpackimport numpy as npimport pytest+from sie_server.config.model import ModelConfigfrom sie_server.core.inference_output import ExtractOutput, ScoreOutputfrom sie_server.core.timing import RequestTimingfrom sie_server.core.worker.types import WorkerResult@@ -214,6 +215,154 @@ class TestProcessEncodeBatch:assert inner == {"dense": [0.1, 0.2]}mock_encode.assert_awaited_once()+ @pytest.mark.asyncio+ async def test_malformed_item_isolated_as_invalid_input(self) -> None:+ """A typed-decode failure on one item in a sub-group is isolated as an+ INVALID_INPUT outcome; the valid item in the same group still runs.+ Regression for #1537 (queue path bypassed Item validation).+ """+ 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),+ ) as mock_encode:+ outcome = await ex.process_encode_batch(+ ProcessEncodeBatchRequest(+ model_id="test/model",+ items=[+ _encode_item(wiid="req-1.0", item={"text": "ok"}, item_index=0),+ # text must be str | None — an int is rejected at the seam.+ _encode_item(wiid="req-1.1", item={"text": 123}, item_index=1),+ ],+ )+ )++ by_id = {o.work_item_id: o for o in outcome.outcomes}+ assert by_id["req-1.0"].disposition == "publish_and_ack"+ assert by_id["req-1.1"].disposition == "publish_error_and_ack"+ assert by_id["req-1.1"].error_code == "INVALID_INPUT"+ # The malformed item never reached inference; only the valid one did.+ mock_encode.assert_awaited_once()+ assert len(mock_encode.await_args.kwargs["items"]) == 1++ @pytest.mark.asyncio+ async def test_merges_profile_runtime_options_into_adapter_call(self) -> None:+ """Regression for #1489: the cluster worker path must merge the model+ profile's ``adapter_options.runtime`` defaults (query_template,+ default_instruction, …) into the options the adapter sees — the Rust+ gateway publishes only raw SDK options, so the worker has to do the+ merge that ``api.encode`` does for the single-server path.+ """+ config = ModelConfig.model_validate(+ {+ "sie_id": "test/instruct-embedder",+ "hf_id": "test/instruct-embedder",+ "inputs": {"text": True},+ "tasks": {"encode": {"dense": {"dim": 8}}},+ "max_sequence_length": 512,+ "profiles": {+ "default": {+ "max_batch_tokens": 8192,+ "adapter_path": "sie_server.adapters.sglang.embedding:SGLangEmbeddingAdapter",+ "adapter_options": {+ "runtime": {+ "query_template": "Instruct: {instruction}\nQuery: {text}",+ "default_instruction": "Given a query, retrieve relevant passages",+ "normalize": True,+ },+ },+ },+ },+ }+ )+ reg = _make_registry()+ reg.get_config.return_value = config+ ex = QueueExecutor(reg)++ captured: dict = {}++ async def fake_run_encode(**kwargs):+ captured.update(kwargs["options"])+ 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),+ ):+ outcome = await ex.process_encode_batch(+ ProcessEncodeBatchRequest(+ model_id="test/model",+ items=[_encode_item(options={"is_query": True})],+ )+ )++ assert outcome.outcomes[0].disposition == "publish_and_ack"+ # The adapter must receive the profile's runtime template + instruction,+ # not just the raw {"is_query": True} the SDK sent.+ assert captured["query_template"] == "Instruct: {instruction}\nQuery: {text}"+ assert captured["default_instruction"] == "Given a query, retrieve relevant passages"+ assert captured["normalize"] is True+ assert captured["is_query"] is True++ @pytest.mark.asyncio+ async def test_merges_non_default_profile_runtime_from_options(self) -> None:+ """A queued request selects its profile via options["profile"] (the gateway+ forwards raw SDK options; the wire profile_id is a hardcoded routing+ placeholder), so the worker must resolve that profile's runtime defaults.+ """+ config = ModelConfig.model_validate(+ {+ "sie_id": "test/multi-profile-embedder",+ "hf_id": "test/multi-profile-embedder",+ "inputs": {"text": True},+ "tasks": {"encode": {"dense": {"dim": 8}}},+ "max_sequence_length": 512,+ "profiles": {+ "default": {+ "max_batch_tokens": 8192,+ "adapter_path": "sie_server.adapters.sglang.embedding:SGLangEmbeddingAdapter",+ "adapter_options": {"runtime": {"query_template": "default: {text}"}},+ },+ "fast": {+ "max_batch_tokens": 8192,+ "adapter_path": "sie_server.adapters.sglang.embedding:SGLangEmbeddingAdapter",+ "adapter_options": {"runtime": {"query_template": "fast: {text}"}},+ },+ },+ }+ )+ reg = _make_registry()+ reg.get_config.return_value = config+ ex = QueueExecutor(reg)++ captured: dict = {}++ async def fake_run_encode(**kwargs):+ captured.update(kwargs["options"])+ return [{"dense": [0.0]} for _ in kwargs["items"]], RequestTiming()++ with patch(+ "sie_server.core.encode_pipeline.EncodePipeline.run_encode",+ new=AsyncMock(side_effect=fake_run_encode),+ ):+ await ex.process_encode_batch(+ ProcessEncodeBatchRequest(+ model_id="test/model",+ items=[_encode_item(options={"is_query": True, "profile": "fast"})],+ )+ )++ # The non-default profile's runtime wins, and "profile" is consumed.+ assert captured["query_template"] == "fast: {text}"+ assert "profile" not in captured+@pytest.mark.asyncioasync def test_model_evicted_naks_all(self) -> None:reg = _make_registry()@@ -246,6 +395,9 @@ class TestProcessEncodeBatch:assert len(outcome.outcomes) == 1assert outcome.outcomes[0].disposition == "publish_error_and_ack"+ # Pin the literal lowercase wire value on purpose (not the+ # _INFERENCE_ERROR_CODE constant): this guards the sidecar↔gateway+ # contract so a change to the constant surfaces as a failure here.assert outcome.outcomes[0].error_code == "inference_error"assert "boom" in (outcome.outcomes[0].error or "")@@ -422,7 +574,7 @@ class TestProcessScoreBatch:wr = WorkerResult(output=score_output, timing=RequestTiming())fut: asyncio.Future[WorkerResult] = asyncio.Future()fut.set_result(wr)- worker.submit_score = AsyncMock(return_value=fut)+ worker.submit_score_preformed_batch = AsyncMock(return_value=[fut])reg.start_worker = AsyncMock(return_value=worker)ex = QueueExecutor(reg)@@ -456,6 +608,57 @@ class TestProcessScoreBatch: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_malformed_item_isolated_as_invalid_input(self) -> None:+ """A typed-decode failure on the query item is isolated as INVALID_INPUT+ while a sibling valid item still runs. Regression for #1537 (the score+ path now decodes through the shared decode_item seam).+ """+ reg = _make_registry()+ worker = AsyncMock()+ fut: asyncio.Future[WorkerResult] = asyncio.Future()+ fut.set_result(+ WorkerResult(output=ScoreOutput(scores=np.array([0.9], dtype=np.float32)), timing=RequestTiming())+ )+ worker.submit_score_preformed_batch = 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"}],+ ),+ # query_item.text must be str | None — an int is rejected at the seam.+ ScoreBatchItem(+ work_item_id="req-1.1",+ request_id="req-1",+ item_index=1,+ total_items=1,+ timestamp=time.time(),+ query_item={"text": 123},+ score_items=[{"text": "a", "id": "doc-a"}],+ ),+ ],+ )+ )++ by_id = {o.work_item_id: o for o in outcome.outcomes}+ assert by_id["req-1.0"].disposition == "publish_and_ack"+ assert by_id["req-1.1"].disposition == "publish_error_and_ack"+ assert by_id["req-1.1"].error_code == "INVALID_INPUT"+ assert worker.submit_score_preformed_batch.await_count == 1+ requests = worker.submit_score_preformed_batch.await_args.args[0]+ assert len(requests) == 1+@pytest.mark.asyncioasync def test_multimodal_score_items_contribute_media_batch_cost(self) -> None:reg = _make_registry()@@ -464,7 +667,7 @@ class TestProcessScoreBatch:wr = WorkerResult(output=score_output, timing=RequestTiming())fut: asyncio.Future[WorkerResult] = asyncio.Future()fut.set_result(wr)- worker.submit_score = AsyncMock(return_value=fut)+ worker.submit_score_preformed_batch = AsyncMock(return_value=[fut])reg.start_worker = AsyncMock(return_value=worker)ex = QueueExecutor(reg)@@ -485,7 +688,8 @@ class TestProcessScoreBatch:))- prepared_items = worker.submit_score.await_args.kwargs["prepared_items"]+ requests = worker.submit_score_preformed_batch.await_args.args[0]+ prepared_items = requests[0].prepared_itemsassert prepared_items[0].cost == 5 + 1024@pytest.mark.asyncio@@ -519,7 +723,7 @@ class TestProcessScoreBatch:worker = AsyncMock()fut: asyncio.Future[WorkerResult] = asyncio.Future()fut.set_exception(RuntimeError("MPS backend out of memory"))- worker.submit_score = AsyncMock(return_value=fut)+ worker.submit_score_preformed_batch = AsyncMock(return_value=[fut])reg.start_worker = AsyncMock(return_value=worker)ex = QueueExecutor(reg)@@ -532,18 +736,17 @@ class TestProcessScoreBatch:@pytest.mark.asyncioasync 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.- """+ """Compatible score IPC items stay in one preformed worker batch."""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)+ futures: list[asyncio.Future[WorkerResult]] = []+ for _ in range(4):+ fut: asyncio.Future[WorkerResult] = asyncio.Future()+ fut.set_result(wr)+ futures.append(fut)+ worker.submit_score_preformed_batch = AsyncMock(return_value=futures)reg.start_worker = AsyncMock(return_value=worker)ex = QueueExecutor(reg)@@ -571,7 +774,7 @@ class TestProcessScoreBatch:kwargs = mock_record.call_args.kwargsassert kwargs["endpoint"] == "score"assert kwargs["total_items"] == 4- assert kwargs["sub_group_sizes"] == [1, 1, 1, 1]+ assert kwargs["sub_group_sizes"] == [4]# -----------------------------------------------------------------------------@@ -590,7 +793,7 @@ class TestProcessExtractBatch:wr = WorkerResult(output=extract_output, timing=RequestTiming())fut: asyncio.Future[WorkerResult] = asyncio.Future()fut.set_result(wr)- worker.submit_extract = AsyncMock(return_value=fut)+ worker.submit_extract_preformed_batch = AsyncMock(return_value=[fut])reg.start_worker = AsyncMock(return_value=worker)ex = QueueExecutor(reg)@@ -615,6 +818,58 @@ class TestProcessExtractBatch:inner = msgpack.unpackb(outcome.outcomes[0].result_msgpack, raw=False)assert "entities" in inner+ @pytest.mark.asyncio+ async def test_malformed_item_isolated_as_invalid_input(self) -> None:+ """A typed-decode failure is isolated as INVALID_INPUT while a sibling+ valid item still runs. Regression for #1537 (the extract path now+ decodes through the shared decode_item seam).+ """+ reg = _make_registry()+ worker = AsyncMock()+ extract_output = ExtractOutput(+ entities=[[{"text": "Alice", "label": "person", "score": 0.99, "start": 0, "end": 5}]]+ )+ fut: asyncio.Future[WorkerResult] = asyncio.Future()+ fut.set_result(WorkerResult(output=extract_output, timing=RequestTiming()))+ worker.submit_extract_preformed_batch = 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"],+ ),+ # item.text must be str | None — an int is rejected at the seam.+ ExtractBatchItem(+ work_item_id="req-1.1",+ request_id="req-1",+ item_index=1,+ total_items=1,+ timestamp=time.time(),+ item={"text": 123},+ labels=["person"],+ ),+ ],+ )+ )++ by_id = {o.work_item_id: o for o in outcome.outcomes}+ assert by_id["req-1.0"].disposition == "publish_and_ack"+ assert by_id["req-1.1"].disposition == "publish_error_and_ack"+ assert by_id["req-1.1"].error_code == "INVALID_INPUT"+ assert worker.submit_extract_preformed_batch.await_count == 1+ requests = worker.submit_extract_preformed_batch.await_args.args[0]+ assert len(requests) == 1+@pytest.mark.asyncioasync def test_model_evicted_naks(self) -> None:reg = _make_registry()@@ -644,7 +899,7 @@ class TestProcessExtractBatch:worker = AsyncMock()fut: asyncio.Future[WorkerResult] = asyncio.Future()fut.set_exception(RuntimeError("CUDA out of memory"))- worker.submit_extract = AsyncMock(return_value=fut)+ worker.submit_extract_preformed_batch = AsyncMock(return_value=[fut])reg.start_worker = AsyncMock(return_value=worker)ex = QueueExecutor(reg)@@ -659,14 +914,17 @@ class TestProcessExtractBatch:@pytest.mark.asyncioasync def test_records_ipc_batch_shape(self) -> None:- """Extract is also per-item dispatch; same semantics as score."""+ """Compatible extract IPC items stay in one preformed worker batch."""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)+ futures: list[asyncio.Future[WorkerResult]] = []+ for _ in range(3):+ fut: asyncio.Future[WorkerResult] = asyncio.Future()+ fut.set_result(wr)+ futures.append(fut)+ worker.submit_extract_preformed_batch = AsyncMock(return_value=futures)reg.start_worker = AsyncMock(return_value=worker)ex = QueueExecutor(reg)@@ -693,7 +951,7 @@ class TestProcessExtractBatch:kwargs = mock_record.call_args.kwargsassert kwargs["endpoint"] == "extract"assert kwargs["total_items"] == 3- assert kwargs["sub_group_sizes"] == [1, 1, 1]+ assert kwargs["sub_group_sizes"] == [3]# -----------------------------------------------------------------------------diff --git a/packages/sie_server/tests/test_queue_executor_stage1d.py b/packages/sie_server/tests/test_queue_executor_stage1d.pyindex 9893eb50a..05dddc7b2 100644--- a/packages/sie_server/tests/test_queue_executor_stage1d.py+++ b/packages/sie_server/tests/test_queue_executor_stage1d.py@@ -232,7 +232,7 @@ class TestProcessScoreBatchRustOutputFraming:wr = WorkerResult(output=score_output, timing=RequestTiming())fut: asyncio.Future[WorkerResult] = asyncio.Future()fut.set_result(wr)- worker.submit_score = AsyncMock(return_value=fut)+ worker.submit_score_preformed_batch = AsyncMock(return_value=[fut])reg.start_worker = AsyncMock(return_value=worker)ex = QueueExecutor(reg)@@ -261,7 +261,7 @@ class TestProcessScoreBatchRustOutputFraming: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``).+ # widening too (see ``_score_success_outcome``).assert score.scores == pytest.approx([0.1, 0.9, 0.5])diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lockindex 3ad8077a1..d7ab6e582 100644--- a/packages/sie_server_sidecar/Cargo.lock+++ b/packages/sie_server_sidecar/Cargo.lock@@ -86,9 +86,9 @@ dependencies = [[[package]]name = "anyhow"-version = "1.0.102"+version = "1.0.103"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"+checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"[[package]]name = "arrayref"@@ -98,9 +98,9 @@ checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb"[[package]]name = "arrayvec"-version = "0.7.6"+version = "0.7.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"+checksum = "f02882884d3e1bc524fb12c79f107f6ad0e1cfd498c536ffb494301740995dfe"[[package]]name = "async-nats"@@ -161,6 +161,28 @@ version = "1.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"+[[package]]+name = "aws-lc-rs"+version = "1.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00"+dependencies = [+ "aws-lc-sys",+ "zeroize",+]++[[package]]+name = "aws-lc-sys"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4"+dependencies = [+ "cc",+ "cmake",+ "dunce",+ "fs_extra",+]+[[package]]name = "base64"version = "0.13.1"@@ -181,9 +203,9 @@ checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"[[package]]name = "bitflags"-version = "2.12.1"+version = "2.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "84d7ced0ae9557296835c32bf1b1e02b44c746701f898460fb000d7eaa84f00a"+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"[[package]]name = "blake3"@@ -208,6 +230,15 @@ dependencies = ["generic-array",]+[[package]]+name = "block-buffer"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"+dependencies = [+ "hybrid-array",+]+[[package]]name = "bumpalo"version = "3.20.3"@@ -216,9 +247,9 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"[[package]]name = "bytes"-version = "1.11.1"+version = "1.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"+checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"dependencies = ["serde",]@@ -234,11 +265,13 @@ dependencies = [[[package]]name = "cc"-version = "1.2.63"+version = "1.2.65"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f"+checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96"dependencies = ["find-msvc-tools",+ "jobserver",+ "libc","shlex",]@@ -256,9 +289,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"[[package]]name = "chacha20"-version = "0.10.0"+version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"dependencies = ["cfg-if","cpufeatures 0.3.0",@@ -267,9 +300,9 @@ dependencies = [[[package]]name = "chrono"-version = "0.4.44"+version = "0.4.45"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"dependencies = ["iana-time-zone","num-traits",@@ -317,12 +350,31 @@ version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"+[[package]]+name = "cmake"+version = "0.1.58"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"+dependencies = [+ "cc",+]+[[package]]name = "colorchoice"version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"+[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]+[[package]]name = "compact_str"version = "0.9.1"@@ -384,6 +436,16 @@ dependencies = ["libc",]+[[package]]+name = "crc-fast"+version = "1.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e75b2483e97a5a7da73ac68a05b629f9c53cff58d8ed1c77866079e18b00dba5"+dependencies = [+ "digest 0.10.7",+ "spin",+]+[[package]]name = "crossbeam-deque"version = "0.8.6"@@ -419,6 +481,15 @@ dependencies = ["typenum",]+[[package]]+name = "crypto-common"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"+dependencies = [+ "hybrid-array",+]+[[package]]name = "curve25519-dalek"version = "4.1.3"@@ -428,7 +499,7 @@ dependencies = ["cfg-if","cpufeatures 0.2.17","curve25519-dalek-derive",- "digest",+ "digest 0.10.7","fiat-crypto","rustc_version","subtle",@@ -445,6 +516,12 @@ dependencies = ["syn",]+[[package]]+name = "daachorse"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f55d7153ba3b507595872a3874803f07a8a81d1e888abed8e5db7da0597d6e2"+[[package]]name = "darling"version = "0.20.11"@@ -512,7 +589,6 @@ version = "0.5.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"dependencies = [- "powerfmt","serde_core",]@@ -553,8 +629,18 @@ version = "0.10.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = [- "block-buffer",- "crypto-common",+ "block-buffer 0.10.4",+ "crypto-common 0.1.7",+]++[[package]]+name = "digest"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"+dependencies = [+ "block-buffer 0.12.1",+ "crypto-common 0.2.2",][[package]]@@ -568,6 +654,12 @@ dependencies = ["syn",]+[[package]]+name = "dunce"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"+[[package]]name = "ed25519"version = "2.2.3"@@ -642,12 +734,6 @@ 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"@@ -658,19 +744,10 @@ dependencies = [][[package]]-name = "futures"-version = "0.3.32"+name = "fs_extra"+version = "1.3.0"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",-]+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"[[package]]name = "futures-channel"@@ -734,7 +811,6 @@ 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",@@ -784,23 +860,21 @@ dependencies = [[[package]]name = "getrandom"-version = "0.4.2"+version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"dependencies = ["cfg-if","libc","r-efi 6.0.0","rand_core 0.10.1",- "wasip2",- "wasip3",][[package]]name = "h2"-version = "0.4.14"+version = "0.4.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733"+checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155"dependencies = ["atomic-waker","bytes",@@ -815,15 +889,6 @@ dependencies = ["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"@@ -844,9 +909,9 @@ checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"[[package]]name = "http"-version = "1.4.1"+version = "1.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8be7462df143984c4598a256ef469b251d7d7f9e271135073e78fc535414f3d0"+checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"dependencies = ["bytes","itoa",@@ -893,6 +958,15 @@ version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "135b12329e5e3ce057a9f972339ea52bc954fe1e9358ef27f95e89716fbc5424"+[[package]]+name = "hybrid-array"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c"+dependencies = [+ "typenum",+]+[[package]]name = "hyper"version = "1.10.1"@@ -925,11 +999,22 @@ dependencies = ["hyper","hyper-util","rustls",- "rustls-native-certs","tokio","tokio-rustls","tower-service",- "webpki-roots 1.0.7",+]++[[package]]+name = "hyper-timeout"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"+dependencies = [+ "hyper",+ "hyper-util",+ "pin-project-lite",+ "tokio",+ "tower-service",][[package]]@@ -1061,12 +1146,6 @@ dependencies = ["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"@@ -1101,9 +1180,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"dependencies = ["equivalent",- "hashbrown 0.17.1",- "serde",- "serde_core",+ "hashbrown",][[package]]@@ -1120,18 +1197,18 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"[[package]]name = "itertools"-version = "0.13.0"+version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"dependencies = ["either",][[package]]name = "itertools"-version = "0.14.0"+version = "0.15.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"+checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc"dependencies = ["either",]@@ -1142,15 +1219,73 @@ version = "1.0.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"+[[package]]+name = "jni"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"+dependencies = [+ "cfg-if",+ "combine",+ "jni-macros",+ "jni-sys",+ "log",+ "simd_cesu8",+ "thiserror 2.0.18",+ "walkdir",+ "windows-link",+]++[[package]]+name = "jni-macros"+version = "0.22.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"+dependencies = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "simd_cesu8",+ "syn",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn",+]++[[package]]+name = "jobserver"+version = "0.1.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"+dependencies = [+ "getrandom 0.3.4",+ "libc",+]+[[package]]name = "js-sys"-version = "0.3.99"+version = "0.3.103"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11"+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"dependencies = ["cfg-if","futures-util",- "once_cell","wasm-bindgen",]@@ -1160,12 +1295,6 @@ 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"@@ -1201,9 +1330,9 @@ dependencies = [[[package]]name = "log"-version = "0.4.31"+version = "0.4.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "113b30b4cd05f7c06868fdb2854f66a7b9fece9a48425351cd532e810d74024f"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"[[package]]name = "lru-slab"@@ -1238,19 +1367,19 @@ dependencies = [[[package]]name = "md-5"-version = "0.10.6"+version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"+checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"dependencies = ["cfg-if",- "digest",+ "digest 0.11.3",][[package]]name = "memchr"-version = "2.8.1"+version = "2.8.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"+checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"[[package]]name = "minimal-lexical"@@ -1291,6 +1420,18 @@ dependencies = ["syn",]+[[package]]+name = "nix"+version = "0.31.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"+dependencies = [+ "bitflags",+ "cfg-if",+ "cfg_aliases",+ "libc",+]+[[package]]name = "nkeys"version = "0.4.5"@@ -1351,34 +1492,45 @@ dependencies = [[[package]]name = "object_store"-version = "0.11.2"+version = "0.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3cfccb68961a56facde1163f9319e0d15743352344e7808a11795fb99698dcaf"+checksum = "765784b4390c6bcf80316e5a22f4e3661b639c9d8c83246856643c27d8ce9dbe"dependencies = ["async-trait",+ "aws-lc-rs","base64 0.22.1","bytes","chrono",- "futures",+ "crc-fast",+ "form_urlencoded",+ "futures-channel",+ "futures-core",+ "futures-util",+ "http",+ "http-body-util","httparse","humantime","hyper",- "itertools 0.13.0",+ "itertools 0.15.0","md-5",+ "nix","parking_lot","percent-encoding","quick-xml",- "rand 0.8.6",+ "rand 0.10.1","reqwest",- "ring",- "rustls-pemfile",+ "rustls-pki-types","serde","serde_json",- "snafu",+ "serde_urlencoded",+ "thiserror 2.0.18","tokio","tracing","url","walkdir",+ "wasm-bindgen-futures",+ "web-time",+ "windows-sys 0.61.2",][[package]]@@ -1421,6 +1573,68 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"+[[package]]+name = "opentelemetry"+version = "0.32.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b0142c63252a9e054e68a4c61a5778f7b14f576274d593f8ce883d191a099682"+dependencies = [+ "futures-core",+ "futures-sink",+ "js-sys",+ "pin-project-lite",+ "thiserror 2.0.18",+ "tracing",+]++[[package]]+name = "opentelemetry-otlp"+version = "0.32.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9966929966d17620d7c316c643ba62631826e10021409357772d5eea84f62c35"+dependencies = [+ "http",+ "opentelemetry",+ "opentelemetry-proto",+ "opentelemetry_sdk",+ "prost",+ "thiserror 2.0.18",+ "tokio",+ "tonic",+ "tonic-types",+]++[[package]]+name = "opentelemetry-proto"+version = "0.32.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56d658ba1faf63f7b9c492cfbe6e0ec365440a16132d3270c1065f7b33f1b638"+dependencies = [+ "opentelemetry",+ "opentelemetry_sdk",+ "prost",+ "tonic",+ "tonic-prost",+]++[[package]]+name = "opentelemetry_sdk"+version = "0.32.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b59f80e1ac4d5ff7a2db8fb6c80badb7f0f3f858211fba08dd9aaec750894f9"+dependencies = [+ "futures-channel",+ "futures-executor",+ "futures-util",+ "opentelemetry",+ "percent-encoding",+ "portable-atomic",+ "rand 0.9.4",+ "thiserror 2.0.18",+ "tokio",+ "tokio-stream",+]+[[package]]name = "parking_lot"version = "0.12.5"@@ -1537,16 +1751,6 @@ 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"@@ -1595,6 +1799,38 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "prost"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"+dependencies = [+ "bytes",+ "prost-derive",+]++[[package]]+name = "prost-derive"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"+dependencies = [+ "anyhow",+ "itertools 0.14.0",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "prost-types"+version = "0.14.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"+dependencies = [+ "prost",+]+[[package]]name = "protobuf"version = "3.7.2"@@ -1617,9 +1853,9 @@ dependencies = [[[package]]name = "quick-xml"-version = "0.37.5"+version = "0.40.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "331e97a1af0bf59823e6eadffe373d7b27f485be8748f71471c662c1f269b7fb"+checksum = "2474bd2e5029e7ccb6abb2ba48cf2383a333851dedf495901544281590c7da7f"dependencies = ["memchr","serde",@@ -1627,9 +1863,9 @@ dependencies = [[[package]]name = "quinn"-version = "0.11.9"+version = "0.11.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"+checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"dependencies = ["bytes","cfg_aliases",@@ -1647,10 +1883,11 @@ dependencies = [[[package]]name = "quinn-proto"-version = "0.11.14"+version = "0.11.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"+checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e"dependencies = [+ "aws-lc-rs","bytes","getrandom 0.3.4","lru-slab",@@ -1682,9 +1919,9 @@ dependencies = [[[package]]name = "quote"-version = "1.0.45"+version = "1.0.46"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"dependencies = ["proc-macro2",]@@ -1729,7 +1966,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"dependencies = ["chacha20",- "getrandom 0.4.2",+ "getrandom 0.4.3","rand_core 0.10.1",]@@ -1819,9 +2056,9 @@ dependencies = [[[package]]name = "regex"-version = "1.12.3"+version = "1.12.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"+checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba"dependencies = ["aho-corasick","memchr",@@ -1842,15 +2079,15 @@ dependencies = [[[package]]name = "regex-syntax"-version = "0.8.10"+version = "0.8.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"[[package]]name = "reqwest"-version = "0.12.28"+version = "0.13.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"dependencies = ["base64 0.22.1","bytes",@@ -1869,11 +2106,10 @@ dependencies = ["pin-project-lite","quinn","rustls",- "rustls-native-certs","rustls-pki-types",+ "rustls-platform-verifier","serde","serde_json",- "serde_urlencoded","sync_wrapper","tokio","tokio-rustls",@@ -1886,7 +2122,6 @@ dependencies = ["wasm-bindgen-futures","wasm-streams","web-sys",- "webpki-roots 1.0.7",][[package]]@@ -1976,10 +2211,11 @@ dependencies = [[[package]]name = "rustls"-version = "0.23.40"+version = "0.23.41"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b"+checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f"dependencies = [+ "aws-lc-rs","once_cell","ring","rustls-pki-types",@@ -2000,15 +2236,6 @@ dependencies = ["security-framework",]-[[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"@@ -2019,12 +2246,40 @@ dependencies = ["zeroize",]+[[package]]+name = "rustls-platform-verifier"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"+dependencies = [+ "core-foundation",+ "core-foundation-sys",+ "jni",+ "log",+ "once_cell",+ "rustls",+ "rustls-native-certs",+ "rustls-platform-verifier-android",+ "rustls-webpki",+ "security-framework",+ "security-framework-sys",+ "webpki-root-certs",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls-platform-verifier-android"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"+[[package]]name = "rustls-webpki"version = "0.103.13"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"dependencies = [+ "aws-lc-rs","ring","rustls-pki-types","untrusted",@@ -2188,7 +2443,7 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"dependencies = ["cfg-if","cpufeatures 0.2.17",- "digest",+ "digest 0.10.7",][[package]]@@ -2208,7 +2463,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-server-sidecar"-version = "0.6.14"+version = "0.6.15"dependencies = ["anyhow","async-nats",@@ -2221,11 +2476,15 @@ dependencies = ["hyper","hyper-util","object_store",+ "opentelemetry",+ "opentelemetry-otlp",+ "opentelemetry_sdk","prometheus","reqwest","rmp","rmp-serde","rmpv",+ "rustls","serde","serde_bytes","serde_json",@@ -2234,6 +2493,7 @@ dependencies = ["tokenizers","tokio","tracing",+ "tracing-opentelemetry","tracing-subscriber","url","uuid",@@ -2267,42 +2527,37 @@ version = "2.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"dependencies = [- "digest",+ "digest 0.10.7","rand_core 0.6.4",][[package]]-name = "slab"-version = "0.4.12"+name = "simd_cesu8"+version = "1.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"+checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33"+dependencies = [+ "rustc_version",+ "simdutf8",+][[package]]-name = "smallvec"-version = "1.15.1"+name = "simdutf8"+version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"[[package]]-name = "snafu"-version = "0.8.9"+name = "slab"+version = "0.4.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e84b3f4eacbf3a1ce05eac6763b4d629d60cbc94d632e4092c54ade71f1e1a2"-dependencies = [- "snafu-derive",-]+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"[[package]]-name = "snafu-derive"-version = "0.8.9"+name = "smallvec"+version = "1.15.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c1c97747dbf44bb1ca44a561ece23508e99cb592e862f22222dcf42f51d1e451"-dependencies = [- "heck",- "proc-macro2",- "quote",- "syn",-]+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"[[package]]name = "socket2"@@ -2314,6 +2569,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "spin"+version = "0.10.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d5fe4ccb98d9c292d56fec89a5e07da7fc4cf0dc11e156b41793132775d3e591"+[[package]]name = "spki"version = "0.7.3"@@ -2362,9 +2623,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"[[package]]name = "syn"-version = "2.0.117"+version = "2.0.118"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"+checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"dependencies = ["proc-macro2","quote",@@ -2398,7 +2659,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand",- "getrandom 0.4.2",+ "getrandom 0.4.3","once_cell","rustix 1.1.4","windows-sys 0.61.2",@@ -2455,12 +2716,11 @@ dependencies = [[[package]]name = "time"-version = "0.3.47"+version = "0.3.51"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"+checksum = "85c17d80feb7334b40c484e45ed1a5273dfd8bfda537c3be2e74a06a6686f327"dependencies = ["deranged",- "itoa","num-conv","powerfmt","serde_core",@@ -2470,15 +2730,15 @@ dependencies = [[[package]]name = "time-core"-version = "0.1.8"+version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"[[package]]name = "time-macros"-version = "0.2.27"+version = "0.2.30"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"+checksum = "dcef1a61bdb119096e153208ec5cbec23944ce8bca13be5c7f60c634f7403935"dependencies = ["num-conv","time-core",@@ -2511,13 +2771,13 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"[[package]]name = "tokenizers"-version = "0.22.2"+version = "0.23.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b238e22d44a15349529690fb07bd645cf58149a1b1e44d6cb5bd1641ff1a6223"+checksum = "44e5bea67576e04b6ff8564c5d9e09c2ef0cf476502245f2f120e497769d3112"dependencies = ["ahash",- "aho-corasick","compact_str",+ "daachorse","dary_heap","derive_builder","esaxx-rs",@@ -2625,6 +2885,54 @@ dependencies = ["webpki-roots 0.26.11",]+[[package]]+name = "tonic"+version = "0.14.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"+dependencies = [+ "async-trait",+ "base64 0.22.1",+ "bytes",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-timeout",+ "hyper-util",+ "percent-encoding",+ "pin-project",+ "sync_wrapper",+ "tokio",+ "tokio-stream",+ "tower",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "tonic-prost"+version = "0.14.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0"+dependencies = [+ "bytes",+ "prost",+ "tonic",+]++[[package]]+name = "tonic-types"+version = "0.14.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73ab1b02061f83d519bba3caa167f88f261ef05720ab8ebc954ade70de3348e8"+dependencies = [+ "prost",+ "prost-types",+ "tonic",+]+[[package]]name = "tower"version = "0.5.3"@@ -2633,11 +2941,15 @@ checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"dependencies = ["futures-core","futures-util",+ "indexmap","pin-project-lite",+ "slab","sync_wrapper","tokio",+ "tokio-util","tower-layer","tower-service",+ "tracing",][[package]]@@ -2713,6 +3025,22 @@ dependencies = ["tracing-core",]+[[package]]+name = "tracing-opentelemetry"+version = "0.33.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "adbc64cba7137545b8044cb1fe9814f7aacf3c6b5f9b45be8bb5db538befdb26"+dependencies = [+ "js-sys",+ "opentelemetry",+ "smallvec",+ "tracing",+ "tracing-core",+ "tracing-log",+ "tracing-subscriber",+ "web-time",+]+[[package]]name = "tracing-serde"version = "0.2.0"@@ -2787,12 +3115,6 @@ 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"@@ -2831,11 +3153,11 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"[[package]]name = "uuid"-version = "1.23.2"+version = "1.23.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d258b83ceec21034727ecee8c382cfa6c3e133699b0742c64571814fb420c9f7"+checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53"dependencies = [- "getrandom 0.4.2",+ "getrandom 0.4.3","js-sys","wasm-bindgen",]@@ -2879,27 +3201,18 @@ checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"[[package]]name = "wasip2"-version = "1.0.3+wasi-0.2.9"+version = "1.0.4+wasi-0.2.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"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",+ "wit-bindgen",][[package]]name = "wasm-bindgen"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409"+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"dependencies = ["cfg-if","once_cell",@@ -2910,9 +3223,9 @@ dependencies = [[[package]]name = "wasm-bindgen-futures"-version = "0.4.72"+version = "0.4.76"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9473dbd2991ae90b6291c3c32c30c6187ac49aa32f9905d1cce280ec1e110b0f"+checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d"dependencies = ["js-sys","wasm-bindgen",@@ -2920,9 +3233,9 @@ dependencies = [[[package]]name = "wasm-bindgen-macro"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6"+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"dependencies = ["quote","wasm-bindgen-macro-support",@@ -2930,9 +3243,9 @@ dependencies = [[[package]]name = "wasm-bindgen-macro-support"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e"+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"dependencies = ["bumpalo","proc-macro2",@@ -2943,40 +3256,18 @@ dependencies = [[[package]]name = "wasm-bindgen-shared"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437"+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"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"+version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"+checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"dependencies = ["futures-util","js-sys",@@ -2985,23 +3276,11 @@ dependencies = ["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"+version = "0.3.103"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6d621441cfc37b84979402712047321980c178f299193a3589d05b99e8763436"+checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"dependencies = ["js-sys","wasm-bindgen",@@ -3017,20 +3296,29 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "webpki-root-certs"+version = "1.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267"+dependencies = [+ "rustls-pki-types",+]+[[package]]name = "webpki-roots"version = "0.26.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"dependencies = [- "webpki-roots 1.0.7",+ "webpki-roots 1.0.8",][[package]]name = "webpki-roots"-version = "1.0.7"+version = "1.0.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d"+checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"dependencies = ["rustls-pki-types",]@@ -3268,100 +3556,12 @@ 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"@@ -3370,9 +3570,9 @@ checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"[[package]]name = "yoke"-version = "0.8.2"+version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"dependencies = ["stable_deref_trait","yoke-derive",@@ -3393,18 +3593,18 @@ dependencies = [[[package]]name = "zerocopy"-version = "0.8.50"+version = "0.8.52"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3b065d4f0e55f82fae73202e189638116a87c55ab6b8e6c2721e13dd9d854ad1"+checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f"dependencies = ["zerocopy-derive",][[package]]name = "zerocopy-derive"-version = "0.8.50"+version = "0.8.52"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0b631b19d36a892ab55420c92dbc83ccd79274f25be714855d3074aa71cab639"+checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930"dependencies = ["proc-macro2","quote",@@ -3434,9 +3634,9 @@ dependencies = [[[package]]name = "zeroize"-version = "1.8.2"+version = "1.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"[[package]]name = "zerotrie"diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex 46fef4a13..eeefcd7fb 100644--- a/packages/sie_server_sidecar/Cargo.toml+++ b/packages/sie_server_sidecar/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-server-sidecar"-version = "0.6.14"+version = "0.6.15"edition = "2021"description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."@@ -43,10 +43,21 @@ anyhow = "1"tracing = "0.1"tracing-subscriber = { version = "0.3", features = ["json", "env-filter"] }+# OpenTelemetry tracing — versions kept in lockstep with the gateway+# (`packages/sie_gateway/Cargo.toml`). OTel breaks compat across minor+# versions, so bumping requires updating all four lines together.+# `opentelemetry-http` is intentionally omitted: the sidecar extracts+# trace context from the work-envelope W3C strings, not HTTP headers.+opentelemetry = "0.32"+opentelemetry_sdk = { version = "0.32", features = ["rt-tokio"] }+opentelemetry-otlp = { version = "0.32", default-features = false, features = ["grpc-tonic", "trace"] }+tracing-opentelemetry = "0.33"+async-trait = "0.1"bytes = "1"uuid = { version = "1", features = ["v4"] }-reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }+reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"] }+rustls = { version = "0.23", default-features = false, features = ["ring"] }# Metrics server (matches gateway)prometheus = { version = "0.14", features = ["process"] }@@ -55,7 +66,7 @@ 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", "azure"] }+object_store = { version = "0.14", optional = true, features = ["aws", "gcp", "azure"] }url = { version = "2", optional = true }# HF fast-tokenizers. Used by `src/tokenize/` to verify the@@ -64,7 +75,7 @@ url = { version = "2", optional = true }# 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"] }+tokenizers = { version = "0.23", default-features = false, features = ["onig"] }blake3 = "1"# NOTE: This crate has no GPU-side dependencies. The sidecar talks todiff --git a/packages/sie_server_sidecar/src/batch_cancel.rs b/packages/sie_server_sidecar/src/batch_cancel.rsnew file mode 100644index 000000000..c70e355d8--- /dev/null+++ b/packages/sie_server_sidecar/src/batch_cancel.rs@@ -0,0 +1,90 @@+//! Worker-local cancellation state for abandoned direct-dispatch batch work.++use std::collections::HashMap;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use crate::subject::normalize_model_id;++const BATCH_CANCEL_TTL: Duration = Duration::from_secs(120);++#[derive(Clone, Default)]+pub struct BatchCancelState {+ inner: Arc<Mutex<HashMap<String, Instant>>>,+}++impl BatchCancelState {+ pub(crate) fn cancel(&self, request_id: String) {+ let now = Instant::now();+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ prune_expired(&mut guard, now);+ guard.insert(request_id, now + BATCH_CANCEL_TTL);+ }++ pub(crate) fn is_cancelled(&self, request_id: &str) -> bool {+ let now = Instant::now();+ let mut guard = self.inner.lock().unwrap_or_else(|e| e.into_inner());+ prune_expired(&mut guard, now);+ guard.contains_key(request_id)+ }+}++fn prune_expired(entries: &mut HashMap<String, Instant>, now: Instant) {+ entries.retain(|_, expires_at| *expires_at > now);+}++pub(crate) fn request_id_from_batch_cancel_subject(+ subject: &str,+ local_worker_id: &str,+) -> Option<String> {+ let mut parts = subject.splitn(4, '.');+ match (parts.next(), parts.next(), parts.next(), parts.next()) {+ (Some("batch_cancel"), Some(_router_id), Some(worker_id), Some(request_id))+ if worker_id == normalize_worker_id(local_worker_id) && !request_id.is_empty() =>+ {+ Some(request_id.to_string())+ }+ _ => None,+ }+}++fn normalize_worker_id(worker_id: &str) -> String {+ normalize_model_id(worker_id)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn batch_cancel_subject_parser_filters_worker_id() {+ assert_eq!(+ request_id_from_batch_cancel_subject("batch_cancel.gw.worker-1.req-1", "worker-1"),+ Some("req-1".to_string())+ );+ assert_eq!(+ request_id_from_batch_cancel_subject(+ "batch_cancel.gw.worker-1_dot_svc.req.with.dots",+ "worker-1.svc"+ ),+ Some("req.with.dots".to_string())+ );+ assert_eq!(+ request_id_from_batch_cancel_subject("batch_cancel.gw.worker-2.req-1", "worker-1"),+ None+ );+ assert_eq!(+ request_id_from_batch_cancel_subject("batch_cancel.gw.worker-1", "worker-1"),+ None+ );+ }++ #[test]+ fn batch_cancel_state_marks_request_ids() {+ let state = BatchCancelState::default();+ assert!(!state.is_cancelled("req-1"));+ state.cancel("req-1".to_string());+ assert!(state.is_cancelled("req-1"));+ assert!(!state.is_cancelled("req-2"));+ }+}diff --git a/packages/sie_server_sidecar/src/config_reconciler.rs b/packages/sie_server_sidecar/src/config_reconciler.rsindex 737a9ce6c..3fff543d7 100644--- a/packages/sie_server_sidecar/src/config_reconciler.rs+++ b/packages/sie_server_sidecar/src/config_reconciler.rs@@ -19,7 +19,7 @@ use tokio::time::interval;use tracing::{debug, info, warn};use crate::config_subscriber::{- replace_via_ipc_with_retry, ConfigApplyState, MAX_MODEL_CONFIG_BYTES,+ advertised_bundle_hash, replace_via_ipc_with_retry, ConfigApplyState, MAX_MODEL_CONFIG_BYTES,};use crate::ipc_client::{IpcClient, IpcError};use crate::ipc_types::{@@ -31,12 +31,14 @@ 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);+const DEFAULT_MODEL_POOL: &str = "default";#[derive(Debug, Clone)]pub struct ReconcilerConfig {pub base_url: String,pub admin_token: Option<String>,pub bundle: String,+ pub pool: String,pub poll_interval: Duration,pub full_export_interval: Option<Duration>,}@@ -56,6 +58,8 @@ struct ExportSnapshot {#[serde(default)]bundle_config_hashes: HashMap<String, String>,#[serde(default)]+ bundle_pool_config_hashes: HashMap<String, HashMap<String, String>>,+ #[serde(default)]models: Vec<ExportedModel>,}@@ -69,6 +73,8 @@ struct ExportedModel {model_config: Option<serde_json::Value>,#[serde(default)]affected_bundles: Vec<String>,+ #[serde(default)]+ pool: Option<String>,}impl ExportedModel {@@ -76,6 +82,22 @@ impl ExportedModel {self.affected_bundles.iter().any(|b| b == bundle)}+ fn targets_pool(&self, pool: &str) -> bool {+ self.pool_name() == normalize_pool_name(pool)+ }++ fn pool_name(&self) -> String {+ if let Some(pool) = self.pool.as_deref() {+ return normalize_pool_name(pool);+ }+ self.model_config+ .as_ref()+ .and_then(|value| value.get("pool"))+ .and_then(|value| value.as_str())+ .map(normalize_pool_name)+ .unwrap_or_else(|| DEFAULT_MODEL_POOL.to_string())+ }+fn config_body(&self) -> Result<Option<String>, serde_json::Error> {if let Some(raw) = self.raw_yaml.as_deref() {let trimmed = raw.trim();@@ -129,12 +151,19 @@ struct ReconcileClient {struct ReconcileRuntime<'a> {client: &'a ReconcileClient,bundle: &'a str,+ pool: &'a str,ipc: Arc<IpcClient>,state: Arc<ConfigApplyState>,metrics: Arc<MetricsRegistry>,shutdown: Arc<Shutdown>,}+#[derive(Clone, Copy)]+struct ReconcileScope<'a> {+ bundle: &'a str,+ pool: &'a str,+}+impl ReconcileClient {fn new(base_url: String, admin_token: Option<String>) -> Result<Self, reqwest::Error> {let http = reqwest::Client::builder().timeout(HTTP_TIMEOUT).build()?;@@ -191,6 +220,15 @@ fn record_reconcile(metrics: &MetricsRegistry, result: &str) {.inc();}+fn normalize_pool_name(raw: &str) -> String {+ let pool = raw.trim().to_ascii_lowercase();+ if pool.is_empty() {+ DEFAULT_MODEL_POOL.to_string()+ } else {+ pool+ }+}+fn drift_reason(local_epoch: u64,remote: &EpochSnapshot,@@ -271,6 +309,7 @@ pub fn spawn(info!(base_url = %config.base_url,bundle = %config.bundle,+ pool = %config.pool,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"@@ -279,6 +318,7 @@ pub fn spawn(let runtime = ReconcileRuntime {client: &client,bundle: &config.bundle,+ pool: &config.pool,ipc: Arc::clone(&ipc),state: Arc::clone(&state),metrics: Arc::clone(&metrics),@@ -440,7 +480,10 @@ async fn reconcile_export(let shutdown = Arc::clone(&runtime.shutdown);Ok(reconcile_export_snapshot(snapshot,- runtime.bundle,+ ReconcileScope {+ bundle: runtime.bundle,+ pool: runtime.pool,+ },&runtime.state,&runtime.metrics,ExportReconcileOptions {@@ -459,7 +502,7 @@ async fn reconcile_export(async fn reconcile_export_snapshot<F, Fut>(snapshot: ExportSnapshot,- bundle: &str,+ scope: ReconcileScope<'_>,state: &ConfigApplyState,metrics: &MetricsRegistry,options: ExportReconcileOptions<'_>,@@ -488,11 +531,20 @@ wherelet mut failed = 0usize;let mut skipped = 0usize;let mut exported_models = Vec::new();- let control_plane_hash = snapshot.bundle_config_hashes.get(bundle).cloned();+ let normalized_pool = normalize_pool_name(scope.pool);+ let control_plane_hash = match snapshot.bundle_pool_config_hashes.get(scope.bundle) {+ Some(pool_hashes) => Some(+ pool_hashes+ .get(&normalized_pool)+ .cloned()+ .unwrap_or_default(),+ ),+ None => snapshot.bundle_config_hashes.get(scope.bundle).cloned(),+ };let mut first_hash_mismatch: Option<String> = None;for model in snapshot.models {- if !model.targets_bundle(bundle) {+ if !model.targets_bundle(scope.bundle) || !model.targets_pool(&normalized_pool) {skipped += 1;continue;}@@ -533,7 +585,7 @@ wherelet export_signature = if failed == 0 {Some(compute_export_signature(- bundle,+ scope.bundle,control_plane_hash.as_deref(),&exported_models,))@@ -563,7 +615,7 @@ wherelet state_updated = if failed == 0 {let req = ReplaceModelConfigsRequest {- bundle_id: bundle.to_string(),+ bundle_id: scope.bundle.to_string(),epoch: snapshot.epoch,bundle_config_hash: control_plane_hash.clone().unwrap_or_default(),models: exported_models,@@ -623,8 +675,10 @@ wherefirst_hash_mismatch = Some(resp.bundle_config_hash.clone());}}- let applied_bundle_hash = resp.bundle_config_hash.clone();+ let advertised_hash =+ advertised_bundle_hash(control_plane_hash.as_deref(), &resp.bundle_config_hash);applied = resp.applied_models.len();+ state.set_loaded_models(resp.applied_models);if let (Some(control_hash), Some(applied_hash)) = (control_plane_hash.as_deref(),@@ -634,12 +688,12 @@ whereepoch = snapshot.epoch,advertised_hash = %control_hash,applied_hash = %applied_hash,- "worker-config: Python registry hash differs from control-plane export hash; advertising Python-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,- Some(applied_bundle_hash),+ Some(advertised_hash),options.force_epoch,);if state_updated {@@ -667,6 +721,7 @@ wherefailed,skipped,reason = options.reason,+ pool = %normalized_pool,state_updated,"worker-config: export reconcile attempt finished");@@ -695,6 +750,7 @@ mod tests {raw_yaml: Some(raw_yaml.to_string()),model_config: None,affected_bundles: bundles.iter().map(|b| (*b).to_string()).collect(),+ pool: None,}}@@ -706,6 +762,22 @@ mod tests {)}+ fn exported_model_with_pool(model_id: &str, bundles: &[&str], pool: &str) -> ExportedModel {+ ExportedModel {+ model_id: model_id.into(),+ raw_yaml: Some(format!(+ "sie_id: {model_id}\npool: {pool}\nprofiles:\n default: {{}}\n"+ )),+ model_config: Some(serde_json::json!({"pool": pool})),+ affected_bundles: bundles.iter().map(|b| (*b).to_string()).collect(),+ pool: Some(pool.to_string()),+ }+ }++ fn scope<'a>(bundle: &'a str, pool: &'a str) -> ReconcileScope<'a> {+ ReconcileScope { bundle, pool }+ }+fn metrics() -> MetricsRegistry {MetricsRegistry::new().expect("metrics registry")}@@ -771,6 +843,7 @@ mod tests {raw_yaml: Some("sie_id: m\n".into()),model_config: None,affected_bundles: vec!["default".into(), "vision".into()],+ pool: None,};assert!(model.targets_bundle("default"));assert!(!model.targets_bundle("def"));@@ -784,6 +857,7 @@ mod tests {raw_yaml: Some("sie_id: raw\n".into()),model_config: Some(serde_json::json!({"sie_id": "json"})),affected_bundles: vec!["default".into()],+ pool: None,};assert_eq!(model.config_body().unwrap().as_deref(), Some("sie_id: raw"));}@@ -795,6 +869,7 @@ mod tests {raw_yaml: None,model_config: Some(serde_json::json!({"sie_id": "json"})),affected_bundles: vec!["default".into()],+ pool: None,};assert_eq!(model.config_body().unwrap().as_deref(),@@ -807,6 +882,7 @@ mod tests {let snapshot = ExportSnapshot {epoch: 7,bundle_config_hashes: HashMap::new(),+ bundle_pool_config_hashes: HashMap::new(),models: vec![exported_model("target-model", &["default"]),exported_model("other-model", &["vision"]),@@ -818,7 +894,7 @@ mod tests {let outcome = reconcile_export_snapshot(snapshot,- "default",+ scope("default", "default"),&state,&metrics,reconcile_options("test"),@@ -849,6 +925,10 @@ mod tests {state.bundle_config_hash().read().unwrap().as_str(),"hash-7");+ assert_eq!(+ state.loaded_models().read().unwrap().as_slice(),+ ["target-model".to_string()]+ );let applied = applied.lock().await;assert_eq!(applied.len(), 1);@@ -858,11 +938,81 @@ mod tests {assert_eq!(applied[0].models[0].model_id, "target-model");}+ #[tokio::test]+ async fn export_reconcile_filters_pool_and_uses_pool_hash() {+ let snapshot = ExportSnapshot {+ epoch: 13,+ bundle_config_hashes: HashMap::from([(+ "candle".to_string(),+ "global-hash".to_string(),+ )]),+ bundle_pool_config_hashes: HashMap::from([(+ "candle".to_string(),+ HashMap::from([+ ("default".to_string(), "default-pool-hash".to_string()),+ ("customer-a".to_string(), "tenant-pool-hash".to_string()),+ ]),+ )]),+ models: vec![+ exported_model("default-model", &["candle"]),+ exported_model_with_pool("tenant-model", &["candle"], "customer-a"),+ ],+ };+ let state = ConfigApplyState::new("old".into());+ let metrics = metrics();+ let applied = Arc::new(Mutex::new(Vec::new()));++ let outcome = reconcile_export_snapshot(+ snapshot,+ scope("candle", "default"),+ &state,+ &metrics,+ reconcile_options("test"),+ {+ let applied = Arc::clone(&applied);+ move |req, _epoch| {+ let applied = Arc::clone(&applied);+ async move {+ applied.lock().await.push(req);+ Ok(Some(ReplaceModelConfigsResponse {+ applied: true,+ bundle_config_hash: "default-pool-hash".into(),+ config_version: 13,+ applied_models: vec!["default-model".into()],+ }))+ }+ }+ },+ )+ .await;++ assert_eq!(outcome.applied, 1);+ assert_eq!(outcome.failed, 0);+ assert_eq!(outcome.skipped, 1);+ assert!(outcome.state_updated);+ assert_eq!(+ state.bundle_config_hash().read().unwrap().as_str(),+ "default-pool-hash"+ );+ assert_eq!(+ state.loaded_models().read().unwrap().as_slice(),+ ["default-model".to_string()]+ );++ let applied = applied.lock().await;+ assert_eq!(applied.len(), 1);+ assert_eq!(applied[0].bundle_id, "candle");+ assert_eq!(applied[0].bundle_config_hash, "default-pool-hash");+ assert_eq!(applied[0].models.len(), 1);+ assert_eq!(applied[0].models[0].model_id, "default-model");+ }+#[tokio::test]async fn export_reconcile_partial_failure_does_not_advance_state() {let snapshot = ExportSnapshot {epoch: 8,bundle_config_hashes: HashMap::new(),+ bundle_pool_config_hashes: HashMap::new(),models: vec![exported_model("ok-model", &["default"]),exported_model("bad-model", &["default"]),@@ -873,7 +1023,7 @@ mod tests {let outcome = reconcile_export_snapshot(snapshot,- "default",+ scope("default", "default"),&state,&metrics,reconcile_options("test"),@@ -908,6 +1058,7 @@ mod tests {let snapshot = ExportSnapshot {epoch: 3,bundle_config_hashes: HashMap::new(),+ bundle_pool_config_hashes: HashMap::new(),models: vec![exported_model("target-model", &["default"])],};let state = ConfigApplyState::new("old".into());@@ -916,7 +1067,7 @@ mod tests {let outcome = reconcile_export_snapshot(snapshot,- "default",+ scope("default", "default"),&state,&metrics,ExportReconcileOptions {@@ -945,13 +1096,14 @@ mod tests {}#[tokio::test]- async fn export_reconcile_prefers_python_applied_bundle_hash() {+ async fn export_reconcile_advertises_control_plane_hash_when_worker_hash_differs() {let snapshot = ExportSnapshot {epoch: 11,bundle_config_hashes: HashMap::from([("default".to_string(),"control-hash".to_string(),)]),+ bundle_pool_config_hashes: HashMap::new(),models: vec![exported_model("target-model", &["default"])],};let state = ConfigApplyState::new("old".into());@@ -959,7 +1111,7 @@ mod tests {let outcome = reconcile_export_snapshot(snapshot,- "default",+ scope("default", "default"),&state,&metrics,reconcile_options("test"),@@ -979,7 +1131,7 @@ mod tests {assert_eq!(state.epoch(), 11);assert_eq!(state.bundle_config_hash().read().unwrap().as_str(),- "python-hash"+ "control-hash");}@@ -988,6 +1140,7 @@ mod tests {let snapshot = ExportSnapshot {epoch: 12,bundle_config_hashes: HashMap::from([("default".to_string(), String::new())]),+ bundle_pool_config_hashes: HashMap::new(),models: vec![exported_model("other-model", &["vision"])],};let state = ConfigApplyState::new("old".into());@@ -996,7 +1149,7 @@ mod tests {let outcome = reconcile_export_snapshot(snapshot,- "default",+ scope("default", "default"),&state,&metrics,reconcile_options("test"),@@ -1023,6 +1176,7 @@ mod tests {assert_eq!(outcome.skipped, 1);assert!(outcome.state_updated);assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "");+ assert!(state.loaded_models().read().unwrap().is_empty());let replace_calls = replace_calls.lock().await;assert_eq!(replace_calls.len(), 1);@@ -1042,9 +1196,10 @@ mod tests {"default".to_string(),"control-hash".to_string(),)]),+ bundle_pool_config_hashes: HashMap::new(),models: vec![exported_model("target-model", &["default"])],},- "default",+ scope("default", "default"),&state,&metrics,reconcile_options("startup"),@@ -1074,9 +1229,10 @@ mod tests {"default".to_string(),"control-hash".to_string(),)]),+ bundle_pool_config_hashes: HashMap::new(),models: vec![exported_model("target-model", &["default"])],},- "default",+ scope("default", "default"),&state,&metrics,ExportReconcileOptions {@@ -1120,13 +1276,14 @@ mod tests {"default".to_string(),"stable-routing-hash".to_string(),)]),+ bundle_pool_config_hashes: HashMap::new(),models: vec![exported_model_with_yaml("target-model",&["default"],"sie_id: target-model\nprofiles:\n default:\n max_batch_tokens: 4096\n",)],},- "default",+ scope("default", "default"),&state,&metrics,reconcile_options("startup"),@@ -1156,13 +1313,14 @@ mod tests {"default".to_string(),"stable-routing-hash".to_string(),)]),+ bundle_pool_config_hashes: HashMap::new(),models: vec![exported_model_with_yaml("target-model",&["default"],"sie_id: target-model\nprofiles:\n default:\n max_batch_tokens: 8192\n",)],},- "default",+ scope("default", "default"),&state,&metrics,ExportReconcileOptions {diff --git a/packages/sie_server_sidecar/src/config_subscriber.rs b/packages/sie_server_sidecar/src/config_subscriber.rsindex 82ae9704d..8575a1ab4 100644--- a/packages/sie_server_sidecar/src/config_subscriber.rs+++ b/packages/sie_server_sidecar/src/config_subscriber.rs@@ -7,7 +7,7 @@//! 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::collections::{HashMap, VecDeque};use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, RwLock};@@ -19,10 +19,11 @@ use tokio::task::JoinHandle;use tokio::time::{sleep, Duration};use tracing::{debug, info, warn};-use crate::health_publisher::SharedBundleConfigHash;+use crate::health_publisher::{SharedBundleConfigHash, SharedLoadedModels};use crate::ipc_client::{IpcClient, IpcError};use crate::ipc_types::{- ApplyModelConfigRequest, ReplaceModelConfigsRequest, ReplaceModelConfigsResponse,+ ApplyModelConfigRequest, ReadinessState, ReplaceModelConfigsRequest,+ ReplaceModelConfigsResponse,};use crate::metrics::MetricsRegistry;use crate::shutdown::Shutdown;@@ -32,6 +33,7 @@ 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;+const DEFAULT_MODEL_POOL: &str = "default";/// Default publisher allowlist. Matches the gateway config subscriber.pub const DEFAULT_TRUSTED_PRODUCERS: &[&str] = &["sie-config"];@@ -40,6 +42,7 @@ pub const DEFAULT_TRUSTED_PRODUCERS: &[&str] = &["sie-config"];pub struct ConfigApplyState {epoch: AtomicU64,bundle_config_hash: SharedBundleConfigHash,+ loaded_models: SharedLoadedModels,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.@@ -55,6 +58,7 @@ impl ConfigApplyState {Self {epoch: AtomicU64::new(0),bundle_config_hash: Arc::new(RwLock::new(initial_bundle_config_hash)),+ loaded_models: Arc::new(RwLock::new(Vec::new())),accepted_bundle_config_hashes: RwLock::new(accepted_bundle_config_hashes),apply_lock: Mutex::new(()),}@@ -68,6 +72,10 @@ impl ConfigApplyState {Arc::clone(&self.bundle_config_hash)}+ pub fn loaded_models(&self) -> SharedLoadedModels {+ Arc::clone(&self.loaded_models)+ }+pub fn current_bundle_config_hash(&self) -> String {self.bundle_config_hash.read()@@ -120,6 +128,40 @@ impl ConfigApplyState {*guard = hash;}+ pub fn set_loaded_models<I>(&self, models: I)+ where+ I: IntoIterator<Item = String>,+ {+ let mut deduped: Vec<String> = models+ .into_iter()+ .map(|model| model.trim().to_string())+ .filter(|model| !model.is_empty())+ .collect();+ deduped.sort();+ deduped.dedup();+ let mut guard = self+ .loaded_models+ .write()+ .expect("loaded models lock poisoned");+ *guard = deduped;+ }++ pub fn record_loaded_model(&self, model_id: &str) {+ let model_id = model_id.trim();+ if model_id.is_empty() {+ return;+ }+ let mut guard = self+ .loaded_models+ .write()+ .expect("loaded models lock poisoned");+ if guard.iter().any(|known| known == model_id) {+ return;+ }+ guard.push(model_id.to_string());+ guard.sort();+ }+fn remember_bundle_hash(&self, hash: &str) {if hash.is_empty() {return;@@ -190,6 +232,8 @@ pub struct ConfigNotification {pub epoch: u64,pub bundle_config_hash: String,#[serde(default)]+ pub bundle_pool_config_hashes: HashMap<String, HashMap<String, String>>,+ #[serde(default)]pub model_id: String,#[serde(default)]pub profiles_added: Vec<String>,@@ -197,6 +241,8 @@ pub struct ConfigNotification {pub model_config: String,#[serde(default)]pub affected_bundles: Vec<String>,+ #[serde(default)]+ pub pool: Option<String>,}fn env_bool(name: &str) -> bool {@@ -232,10 +278,12 @@ pub fn trusted_producers_from_env() -> Vec<String> {#[derive(Debug, Clone)]pub struct ConfigSubscriberOptions {pub trusted_producers: Vec<String>,+ pub pool: String,}struct SubscriberRuntime {bundle: String,+ pool: String,trusted_producers: Vec<String>,ipc: Arc<IpcClient>,state: Arc<ConfigApplyState>,@@ -272,6 +320,47 @@ fn notification_targets_bundle(notification: &ConfigNotification, bundle: &str)notification.bundle_id == bundle}+fn normalize_pool_name(raw: &str) -> String {+ let pool = raw.trim().to_ascii_lowercase();+ if pool.is_empty() {+ DEFAULT_MODEL_POOL.to_string()+ } else {+ pool+ }+}++fn notification_targets_pool(notification: &ConfigNotification, pool: &str) -> bool {+ let Some(notification_pool) = notification.pool.as_deref() else {+ // Legacy sie-config payloads did not carry pool metadata; preserve+ // the old "bundle-only" apply behavior during mixed-version rollouts.+ return true;+ };+ normalize_pool_name(notification_pool) == normalize_pool_name(pool)+}++fn notification_bundle_hash_for_pool(notification: &ConfigNotification, pool: &str) -> String {+ let normalized_pool = normalize_pool_name(pool);+ match notification+ .bundle_pool_config_hashes+ .get(¬ification.bundle_id)+ {+ Some(pool_hashes) => pool_hashes+ .get(&normalized_pool)+ .cloned()+ .unwrap_or_default(),+ None => notification.bundle_config_hash.clone(),+ }+}++pub(crate) fn advertised_bundle_hash(+ control_plane_hash: Option<&str>,+ worker_applied_hash: &str,+) -> String {+ control_plane_hash+ .unwrap_or(worker_applied_hash)+ .to_string()+}+fn notification_is_stale(epoch: u64, current_epoch: u64) -> bool {epoch < current_epoch || (epoch == current_epoch && epoch != 0)}@@ -301,6 +390,60 @@ fn retryable_ipc_error(e: &IpcError) -> bool {}}+fn requires_eager_model_ready(bundle_id: &str) -> bool {+ bundle_id.trim() == "candle"+}++async fn ensure_candle_model_ready_if_needed(+ ipc: &Arc<IpcClient>,+ bundle_id: &str,+ model_id: &str,+ epoch: u64,+) -> Result<(), IpcError> {+ if !requires_eager_model_ready(bundle_id) {+ return Ok(());+ }++ match ipc.ensure_model_ready(model_id).await {+ Ok(resp) if resp.state == ReadinessState::Ready => {+ info!(+ model = %model_id,+ epoch,+ "worker-config: Candle model ready after config apply"+ );+ Ok(())+ }+ Ok(resp) => {+ warn!(+ model = %model_id,+ epoch,+ state = ?resp.state,+ "worker-config: Candle model not ready after config apply; retrying"+ );+ Err(IpcError::Timeout)+ }+ Err(e) => Err(e),+ }+}++async fn ensure_candle_models_ready_if_needed(+ ipc: &Arc<IpcClient>,+ bundle_id: &str,+ model_ids: &[String],+ epoch: u64,+) -> Result<Vec<String>, IpcError> {+ if !requires_eager_model_ready(bundle_id) {+ return Ok(model_ids.to_vec());+ }++ let mut ready_models = Vec::with_capacity(model_ids.len());+ for model_id in model_ids {+ ensure_candle_model_ready_if_needed(ipc, bundle_id, model_id, epoch).await?;+ ready_models.push(model_id.clone());+ }+ Ok(ready_models)+}+fn next_retry_delay(current: Duration) -> Duration {std::cmp::min(current.saturating_mul(2), RETRY_MAX_DELAY)}@@ -336,6 +479,7 @@ pub fn spawn(let runtime = SubscriberRuntime {bundle,+ pool: options.pool,trusted_producers: options.trusted_producers,ipc,state,@@ -431,7 +575,43 @@ pub(crate) async fn apply_via_ipc_with_retry(let mut attempt = 0_u64;loop {match ipc.apply_model_config(req.clone()).await {- Ok(resp) => return Ok(Some(resp)),+ Ok(resp) => {+ match ensure_candle_model_ready_if_needed(&ipc, &req.bundle_id, model_id, epoch)+ .await+ {+ Ok(()) => return Ok(Some(resp)),+ Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {+ attempt = attempt.saturating_add(1);+ if attempt == 1+ || attempt == 5+ || attempt == 30+ || attempt.is_multiple_of(120)+ {+ warn!(+ model = %model_id,+ epoch,+ attempt,+ retry_delay_ms = retry_delay.as_millis() as u64,+ error = %e,+ "worker-config: Candle model readiness still waiting after apply; retrying"+ );+ } else {+ debug!(+ model = %model_id,+ epoch,+ attempt,+ error = %e,+ "worker-config: Candle model readiness still waiting"+ );+ }+ if wait_retry_or_shutdown(&shutdown, retry_delay).await {+ return Ok(None);+ }+ retry_delay = next_retry_delay(retry_delay);+ }+ Err(e) => return Err(e),+ }+ }Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {attempt = attempt.saturating_add(1);if attempt == 1 || attempt == 5 || attempt == 30 || attempt.is_multiple_of(120) {@@ -472,7 +652,49 @@ pub(crate) async fn replace_via_ipc_with_retry(let mut attempt = 0_u64;loop {match ipc.replace_model_configs(req.clone()).await {- Ok(resp) => return Ok(Some(resp)),+ Ok(mut resp) => {+ match ensure_candle_models_ready_if_needed(+ &ipc,+ &req.bundle_id,+ &resp.applied_models,+ epoch,+ )+ .await+ {+ Ok(ready_models) => {+ resp.applied_models = ready_models;+ return Ok(Some(resp));+ }+ Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {+ attempt = attempt.saturating_add(1);+ if attempt == 1+ || attempt == 5+ || attempt == 30+ || attempt.is_multiple_of(120)+ {+ warn!(+ epoch,+ attempt,+ retry_delay_ms = retry_delay.as_millis() as u64,+ error = %e,+ "worker-config: Candle model readiness still waiting after replace; retrying"+ );+ } else {+ debug!(+ epoch,+ attempt,+ error = %e,+ "worker-config: Candle model readiness still waiting after replace"+ );+ }+ if wait_retry_or_shutdown(&shutdown, retry_delay).await {+ return Ok(None);+ }+ retry_delay = next_retry_delay(retry_delay);+ }+ Err(e) => return Err(e),+ }+ }Err(e) if retryable_ipc_error(&e) && !shutdown.is_fired() => {attempt = attempt.saturating_add(1);if attempt == 1 || attempt == 5 || attempt == 30 || attempt.is_multiple_of(120) {@@ -567,6 +789,20 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotreturn;}+ if !notification_targets_pool(¬ification, runtime.pool.as_str()) {+ debug!(+ notification_bundle = %notification.bundle_id,+ worker_bundle = %bundle,+ notification_pool = ?notification.pool,+ worker_pool = %runtime.pool,+ epoch = notification.epoch,+ model = %notification.model_id,+ "worker-config: skipping notification for another pool"+ );+ record_delta(metrics, kind, "skipped_pool");+ return;+ }+if notification.model_config.len() > MAX_MODEL_CONFIG_BYTES {warn!(model = %notification.model_id,@@ -604,7 +840,7 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotbundle_id: notification.bundle_id.clone(),model_id: notification.model_id.clone(),epoch: notification.epoch,- bundle_config_hash: notification.bundle_config_hash.clone(),+ bundle_config_hash: notification_bundle_hash_for_pool(¬ification, runtime.pool.as_str()),profiles_added: notification.profiles_added.clone(),model_config: notification.model_config.clone(),};@@ -645,25 +881,31 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotreturn;}- let applied_bundle_hash = resp.bundle_config_hash.clone();+ let control_plane_hash =+ notification_bundle_hash_for_pool(¬ification, runtime.pool.as_str());+ let advertised_hash =+ advertised_bundle_hash(Some(control_plane_hash.as_str()), &resp.bundle_config_hash);- if !notification.bundle_config_hash.is_empty()+ if !control_plane_hash.is_empty()&& !resp.bundle_config_hash.is_empty()- && notification.bundle_config_hash != resp.bundle_config_hash+ && control_plane_hash != resp.bundle_config_hash{warn!(model = %notification.model_id,epoch = notification.epoch,- advertised_hash = %notification.bundle_config_hash,+ advertised_hash = %control_plane_hash,applied_hash = %resp.bundle_config_hash,- "worker-config: Python registry hash differs from control-plane hash; advertising Python-applied 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);+ state.mark_applied(notification.epoch, advertised_hash);+ if requires_eager_model_ready(¬ification.bundle_id) {+ state.record_loaded_model(¬ification.model_id);+ }metrics.config_epoch.set(notification.epoch as i64);}@@ -701,10 +943,12 @@ mod tests {bundle_id: "default".into(),epoch: 1,bundle_config_hash: "h".into(),+ bundle_pool_config_hashes: HashMap::new(),model_id: "m".into(),profiles_added: vec![],model_config: "x".into(),affected_bundles: vec![],+ pool: None,};assert!(notification_targets_bundle(¬ification, "default"));assert!(!notification_targets_bundle(¬ification, "other"));@@ -712,6 +956,52 @@ mod tests {assert!(!notification_targets_bundle(¬ification, "other"));}+ #[test]+ fn notification_targets_pool_and_selects_pool_hash() {+ let notification = ConfigNotification {+ producer_id: "sie-config".into(),+ bundle_id: "candle".into(),+ epoch: 1,+ bundle_config_hash: "global-hash".into(),+ bundle_pool_config_hashes: HashMap::from([(+ "candle".to_string(),+ HashMap::from([+ ("default".to_string(), "default-hash".to_string()),+ ("customer-a".to_string(), "tenant-hash".to_string()),+ ]),+ )]),+ model_id: "m".into(),+ profiles_added: vec![],+ model_config: "x".into(),+ affected_bundles: vec!["candle".into()],+ pool: Some("Customer-A".into()),+ };++ assert!(notification_targets_pool(¬ification, "customer-a"));+ assert!(!notification_targets_pool(¬ification, "default"));+ assert_eq!(+ notification_bundle_hash_for_pool(¬ification, "customer-a"),+ "tenant-hash"+ );+ }++ #[test]+ fn advertised_bundle_hash_prefers_control_plane_value() {+ assert_eq!(+ advertised_bundle_hash(Some("control-hash"), "worker-hash"),+ "control-hash"+ );+ assert_eq!(advertised_bundle_hash(Some(""), "worker-hash"), "");+ assert_eq!(advertised_bundle_hash(None, "worker-hash"), "worker-hash");+ }++ #[test]+ fn eager_model_ready_is_candle_specific() {+ assert!(requires_eager_model_ready("candle"));+ assert!(!requires_eager_model_ready("default"));+ assert!(!requires_eager_model_ready("sglang"));+ }+#[test]fn config_notification_accepts_router_id_alias() {let json = r#"{@@ -728,6 +1018,9 @@ mod tests {assert_eq!(parsed.producer_id, "sie-config-0");assert_eq!(parsed.bundle_id, "default");assert_eq!(parsed.epoch, 3);+ assert!(parsed.bundle_pool_config_hashes.is_empty());+ assert!(parsed.pool.is_none());+ assert!(notification_targets_pool(&parsed, "customer-a"));}#[test]@@ -774,6 +1067,25 @@ mod tests {assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "");}+ #[test]+ fn loaded_models_are_deduped_and_sorted() {+ let state = ConfigApplyState::new("initial".into());+ state.record_loaded_model("model/b");+ state.record_loaded_model("model/a");+ state.record_loaded_model("model/b");++ assert_eq!(+ state.loaded_models().read().unwrap().as_slice(),+ ["model/a".to_string(), "model/b".to_string()]+ );++ state.set_loaded_models(vec!["model/d".into(), "".into(), " model/c ".into()]);+ assert_eq!(+ state.loaded_models().read().unwrap().as_slice(),+ ["model/c".to_string(), "model/d".to_string()]+ );+ }+#[test]fn accepted_hash_history_keeps_inflight_work_processable() {let state = ConfigApplyState::new("h0".into());diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex 7cff90c22..e328eef53 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -26,6 +26,7 @@ use tokio::task::JoinHandle;use tracing::{debug, info, warn};use crate::backend::{BackendError, SharedBackend};+use crate::batch_cancel::BatchCancelState;use crate::config_subscriber::ConfigApplyState;use crate::ipc_client::{IpcClient, IpcError};use crate::ipc_types::{@@ -40,11 +41,11 @@ use crate::payload_store::{PayloadError, PayloadStore};use crate::pool_admission::PoolAdmissionGate;use crate::publisher::{should_publish, Timings, WorkPublisher};use crate::scheduler::{- lora_from_options, Op as SchedOp, ProductionScheduler, ProductionSchedulerRegistry,+ lora_from_options, HasCost, Op as SchedOp, ProductionScheduler, ProductionSchedulerRegistry,SchedulerItem, SchedulerMeta,};use crate::shutdown::Shutdown;-use crate::subject::extract_model_id;+use crate::subject::{extract_model_id, is_worker_direct_work_subject};use crate::tokenize::TokenizerRegistry;use crate::work_types::WorkItem;@@ -348,6 +349,7 @@ pub struct Dispatcher {/// final-drain windows have a chance to complete.pub scheduler_drain_handles: Arc<Mutex<HashMap<String, JoinHandle<()>>>>,pub generation_handles: Arc<Mutex<Vec<JoinHandle<()>>>>,+ pub batch_cancel_state: BatchCancelState,}impl Dispatcher {@@ -376,6 +378,7 @@ impl Dispatcher {shutdown: Option<Arc<Shutdown>>,config_apply_state: Option<Arc<ConfigApplyState>>,pool_admission: Option<Arc<PoolAdmissionGate>>,+ batch_cancel_state: BatchCancelState,) -> Self {debug_assert_eq!(scheduler_registry.is_some(),@@ -397,6 +400,7 @@ impl Dispatcher {pool_admission,scheduler_drain_handles: Arc::new(Mutex::new(HashMap::new())),generation_handles: Arc::new(Mutex::new(Vec::new())),+ batch_cancel_state,}}}@@ -407,6 +411,32 @@ impl Dispatcher {.as_ref().map(|state| state.current_bundle_config_hash())}++ fn is_cancelled_worker_direct_batch(+ &self,+ request_id: &str,+ operation: &str,+ worker_direct: bool,+ ) -> bool {+ worker_direct && operation != "generate" && self.batch_cancel_state.is_cancelled(request_id)+ }++ async fn ack_cancelled_worker_direct_batch(&self, wi: &WorkItem, msg: &Message) {+ debug!(+ request_id = %wi.request_id,+ work_item_id = %wi.work_item_id,+ operation = %wi.operation,+ subject = %msg.subject,+ "batch-direct: ACKing cancelled worker-direct item"+ );+ match ack(msg).await {+ Ok(()) => self.metrics.messages_acked_total.inc(),+ Err(e) => {+ warn!(error = %e, "ack failed on cancelled worker-direct batch item");+ self.metrics.jetstream_ack_failures_total.inc();+ }+ }+ }}fn unknown_bundle_config_hash<'a>(@@ -505,6 +535,15 @@ impl Dispatcher {}continue;}+ let worker_direct = is_worker_direct_work_subject(&msg.subject);+ if self.is_cancelled_worker_direct_batch(+ &wi.request_id,+ &wi.operation,+ worker_direct,+ ) {+ self.ack_cancelled_worker_direct_batch(&wi, &msg).await;+ continue;+ }if let Some(gate) = self.pool_admission.as_ref() {let admission_pool = wi.admission_pool.trim();if !gate.admits_work_item_pool(admission_pool) {@@ -855,6 +894,7 @@ impl Dispatcher {&wi,"internal_error","failed to decode offloaded generate payload",+ is_worker_direct_work_subject(&msg.subject),).await{@@ -917,7 +957,12 @@ impl Dispatcher {"failed to re-encode generate WorkItem — publishing error + ACK");match self- .publish_error(&wi, "internal_error", "failed to encode generate work item")+ .publish_error(+ &wi,+ "internal_error",+ "failed to encode generate work item",+ is_worker_direct_work_subject(&msg.subject),+ ).await{Ok(_) => match ack(&msg).await {@@ -1169,7 +1214,12 @@ impl Dispatcher {for (wi, msg) in &unknown_items {warn!(op = %wi.operation, "unknown operation — publishing error + ACK");match self- .publish_error(wi, "bad_operation", "unknown operation")+ .publish_error(+ wi,+ "bad_operation",+ "unknown operation",+ is_worker_direct_work_subject(&msg.subject),+ ).await{Ok(_) => match ack(msg).await {@@ -1290,7 +1340,12 @@ impl Dispatcher {"failed to resolve encode item");match self- .publish_error(&wi, "payload_error", "failed to resolve item")+ .publish_error(+ &wi,+ "payload_error",+ "failed to resolve item",+ is_worker_direct_work_subject(&msg.subject),+ ).await{Ok(_) => match ack(&msg).await {@@ -1405,7 +1460,12 @@ impl Dispatcher {"failed to resolve score payload");match self- .publish_error(&wi, "payload_error", "failed to resolve score payload")+ .publish_error(+ &wi,+ "payload_error",+ "failed to resolve score payload",+ is_worker_direct_work_subject(&msg.subject),+ ).await{Ok(_) => match ack(&msg).await {@@ -1520,7 +1580,12 @@ impl Dispatcher {"failed to resolve extract item");match self- .publish_error(&wi, "payload_error", "failed to resolve item")+ .publish_error(+ &wi,+ "payload_error",+ "failed to resolve item",+ is_worker_direct_work_subject(&msg.subject),+ ).await{Ok(_) => match ack(&msg).await {@@ -1685,7 +1750,12 @@ impl Dispatcher {});match self.publisher- .publish_result(&wi.reply_subject, outcome, timings)+ .publish_result(+ &wi.reply_subject,+ outcome,+ timings,+ is_worker_direct_work_subject(&msg.subject),+ ).await{Ok(()) => {@@ -1827,6 +1897,7 @@ impl Dispatcher {wi: &WorkItem,code: &str,message: &str,+ worker_direct: bool,) -> Result<bool, crate::publisher::PublishError> {// Synthetic outcome so we reuse the publisher encoder. No timings:// error-only publishes omit queue_ms / processing_ms / payload_fetch_ms.@@ -1846,7 +1917,7 @@ impl Dispatcher {};match self.publisher- .publish_result(&wi.reply_subject, &outcome, None)+ .publish_result(&wi.reply_subject, &outcome, None, worker_direct).await{Ok(()) => Ok(true),@@ -2023,7 +2094,8 @@ impl Dispatcher {payload_fetch_ms: fetch_ms,prepared_tokens,};- let meta = SchedulerMeta::new(wi, msg, fetch_ms);+ let worker_direct = is_worker_direct_work_subject(&msg.subject);+ let meta = SchedulerMeta::new_with_worker_direct(wi, msg, fetch_ms, worker_direct);scheduler.submit(SchedOp::Encode, lora, SchedulerItem::Encode(ebi), meta).await;@@ -2074,7 +2146,8 @@ impl Dispatcher {payload_fetch_ms: fetch_ms,prepared_tokens: None,};- let meta = SchedulerMeta::new(wi, msg, fetch_ms);+ let worker_direct = is_worker_direct_work_subject(&msg.subject);+ let meta = SchedulerMeta::new_with_worker_direct(wi, msg, fetch_ms, worker_direct);scheduler.submit(SchedOp::Score, lora, SchedulerItem::Score(sbi), meta).await;@@ -2122,7 +2195,8 @@ impl Dispatcher {bundle_config_hash: opt_non_empty(&wi.bundle_config_hash),payload_fetch_ms: fetch_ms,};- let meta = SchedulerMeta::new(wi, msg, fetch_ms);+ let worker_direct = is_worker_direct_work_subject(&msg.subject);+ let meta = SchedulerMeta::new_with_worker_direct(wi, msg, fetch_ms, worker_direct);scheduler.submit(SchedOp::Extract, lora, SchedulerItem::Extract(xbi), meta).await;@@ -2144,7 +2218,12 @@ impl Dispatcher {"{log_msg}");match self- .publish_error(wi, "payload_error", "failed to resolve item")+ .publish_error(+ wi,+ "payload_error",+ "failed to resolve item",+ is_worker_direct_work_subject(&msg.subject),+ ).await{Ok(_) => match ack(msg).await {@@ -2748,6 +2827,51 @@ async fn process_scheduler_batch(batch: crate::scheduler::FormattedBatch<SchedulerItem, SchedulerMeta>,role: WaveRole,) {+ if batch.items.is_empty() {+ return;+ }+ assert_eq!(+ batch.items.len(),+ batch.metadata.len(),+ "FormattedBatch items and metadata must stay aligned",+ );+ let crate::scheduler::FormattedBatch {+ items,+ metadata,+ total_cost: _,+ } = batch;+ let mut kept_items = Vec::with_capacity(items.len());+ let mut kept_metadata = Vec::with_capacity(metadata.len());+ let mut kept_cost = 0_u64;+ let mut cancelled = 0_usize;+ for (item, meta) in items.into_iter().zip(metadata) {+ if dispatcher.is_cancelled_worker_direct_batch(+ &meta.wi.request_id,+ &meta.wi.operation,+ meta.worker_direct,+ ) {+ dispatcher+ .ack_cancelled_worker_direct_batch(&meta.wi, &meta.msg)+ .await;+ cancelled += 1;+ continue;+ }+ kept_cost += item.cost();+ kept_items.push(item);+ kept_metadata.push(meta);+ }+ if cancelled > 0 {+ debug!(+ model = %model_id,+ cancelled,+ "batch-direct: dropped cancelled worker-direct scheduler items before IPC"+ );+ }+ let batch = crate::scheduler::FormattedBatch {+ items: kept_items,+ metadata: kept_metadata,+ total_cost: kept_cost,+ };if batch.items.is_empty() {return;}@@ -2767,10 +2891,104 @@ async fn process_scheduler_batch(// ordering guarantees hang off it across threads.let batch_id = SCHEDULER_BATCH_ID_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ // Zip each scheduler item with its parallel metadata so we can copy+ // the originating `WorkItem`'s W3C trace context onto the wire item.+ // `batch.metadata` is borrowed here and only consumed later in this+ // function (the NAK / `apply_outcomes` paths), so `.iter()` is fine.+ // Guard the parallel-vector invariant: `zip()` would silently truncate+ // and drop work items if `items` and `metadata` ever drifted apart.+ assert_eq!(+ batch.items.len(),+ batch.metadata.len(),+ "FormattedBatch items and metadata must stay aligned",+ );+ // Open the `sidecar.dispatch` span so the queue hop is visible in+ // the trace: `gateway.proxy → sidecar.dispatch → worker.run_batch`.+ // It is created here (before the IPC dispatch) and kept alive — but+ // only *entered* synchronously, never across an `.await` — so its+ // OTel duration covers the dispatch and it is not held on the+ // worker thread while the task is parked. When no OTLP exporter is+ // configured the `tracing_opentelemetry` layer is absent, so this+ // span produces no OTel span and the gateway-context fallback below+ // keeps `gateway → worker` linkage intact (propagator-only parity).+ let dispatch_span = tracing::info_span!(+ "sidecar.dispatch",+ otel.name = "sidecar.dispatch",+ sie.op = op_label,+ sie.model = %model_id,+ sie.batch_id = batch_id,+ sie.batch_size = batch_size,+ );+ {+ // A coalesced batch can mix items from several gateway traces.+ // A span has exactly one parent but may carry many links, so we+ // parent on the first valid gateway context and record the+ // remaining distinct contexts as links (OTel batch convention).+ use tracing_opentelemetry::OpenTelemetrySpanExt;+ let mut linked: HashSet<&str> = HashSet::new();+ // Parent on the first item carrying a *valid* inbound context,+ // not merely the first item. A leading untraced item would+ // otherwise root the sidecar span on a fresh trace and — once+ // the outgoing items are overwritten with that context below —+ // strip the gateway lineage from the batch's genuinely-traced+ // items. `set_parent` then always receives a valid context, so+ // its `Result` is an `Ok` we discard.+ if let Some(parent) = batch.metadata.iter().find(|meta| {+ crate::observability::propagation::remote_span_context(+ meta.wi.traceparent.as_deref(),+ meta.wi.tracestate.as_deref(),+ )+ .is_some()+ }) {+ let tp = parent.wi.traceparent.as_deref();+ let ts = parent.wi.tracestate.as_deref();+ let _ = dispatch_span.set_parent(+ crate::observability::propagation::extract_context_from_w3c(tp, ts),+ );+ if let Some(tp) = tp {+ linked.insert(tp);+ }+ }+ for meta in batch.metadata.iter() {+ let Some(tp) = meta.wi.traceparent.as_deref() else {+ continue;+ };+ if !linked.insert(tp) {+ continue;+ }+ if let Some(sc) = crate::observability::propagation::remote_span_context(+ Some(tp),+ meta.wi.tracestate.as_deref(),+ ) {+ dispatch_span.add_link(sc);+ }+ }+ }++ // Serialise the sidecar span back into W3C strings (entered+ // synchronously — no `.await` inside). With an exporter active this+ // yields the sidecar span's context (new span_id under the inbound+ // trace); without one it returns `(None, None)` and the per-item+ // fallback below keeps the gateway context.+ let (sidecar_tp, sidecar_ts) =+ dispatch_span.in_scope(crate::observability::propagation::inject_current_context);+let rb_items: Vec<crate::ipc_types::RunBatchItem> = batch.items.into_iter()- .map(SchedulerItem::into_run_batch_item)+ .zip(batch.metadata.iter())+ .map(|(item, meta)| {+ // `into_run_batch_item_with_trace` copies the gateway+ // context as the fallback; override with the sidecar span's+ // context when one exists so `worker.run_batch` nests under+ // `sidecar.dispatch`.+ let mut rbi = item.into_run_batch_item_with_trace(&meta.wi);+ if let Some(tp) = &sidecar_tp {+ rbi.traceparent = Some(tp.clone());+ rbi.tracestate = sidecar_ts.clone();+ }+ rbi+ }).collect();let req = RunBatchRequest {model_id: model_id.to_string(),@@ -2861,10 +3079,11 @@ async fn process_scheduler_batch(// 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.+ // getting set in `EncodePipeline.run_encode`. Note: the sidecar+ // calls Python's pre-formed batch IPC entrypoint, so Python does+ // not run its per-LoRA BatchFormer on this path; 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@@ -3091,17 +3310,18 @@ pub(crate) async fn scheduler_drain_loop("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`).+ // Python runs the pre-formed batch IPC entrypoint here: there is no+ // per-LoRA BatchFormer on the queue path and every IPC frame is one+ // caller-formed GPU dispatch, serialized by ModelWorker's adapter+ // dispatch lock. All queue 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+ // adapter dispatch 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.//@@ -3115,9 +3335,10 @@ pub(crate) async fn scheduler_drain_loop(// 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:+ // Idle-bypass + continuous-batching state. On the queue path,+ // Python's `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 andiff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rsindex a7fc5cb89..011755bf6 100644--- a/packages/sie_server_sidecar/src/health_publisher.rs+++ b/packages/sie_server_sidecar/src/health_publisher.rs@@ -28,10 +28,10 @@//! gate on the local [`Readiness`] state so the heartbeat agrees//! with `/readyz`.//!-//! `loaded_models` and the GPU memory fields are informational. The-//! sidecar mirrors the adapter-owned loaded-model list from the IPC-//! heartbeat so gateway model/capacity views reflect the live worker-//! registry without adding a second probe path.+//! `loaded_models` and the GPU memory fields are mostly informational, but+//! the gateway also uses `loaded_models` as the per-model dispatch readiness+//! signal. Backends that need explicit residency, such as Candle, must only+//! publish models here after their readiness handshake has made them serveable.//!//! [`WorkerStatusMessage`]: https://github.com/search?q=WorkerStatusMessage+repo%3Asie-internal//! [`resolve_queue_route`]: https://github.com/search?q=resolve_queue_route+repo%3Asie-internal@@ -98,7 +98,8 @@ pub struct HealthPublisherConfig {/// model registry epoch. Updated by the config subscriber after a/// successful Python registry apply.pub bundle_config_hash: SharedBundleConfigHash,- /// Last loaded-model list observed from the Python IPC heartbeat.+ /// Models the colocated adapter reports as loaded or configured for+ /// this runtime. Updated by config apply/reconcile paths.pub loaded_models: SharedLoadedModels,/// How often to publish. Defaults to [`DEFAULT_PUBLISH_INTERVAL`].pub interval: Duration,@@ -376,14 +377,15 @@ mod tests {fn payload_reads_updated_loaded_models() {let c = cfg();{- let mut loaded_models = c.loaded_models.write().unwrap();- *loaded_models = vec!["BAAI/bge-m3".into()];+ let mut models = c.loaded_models.write().unwrap();+ *models = vec!["model/a".into(), "model/b".into()];}-let json: serde_json::Value =serde_json::from_slice(&encode_payload(&c, true, false).unwrap()).unwrap();-- assert_eq!(json["loaded_models"], serde_json::json!(["BAAI/bge-m3"]));+ assert_eq!(+ json["loaded_models"],+ serde_json::json!(["model/a", "model/b"])+ );}#[test]diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex a9da24a4c..b1492ab19 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -7,6 +7,7 @@//! runtime contract.pub mod backend;+pub mod batch_cancel;pub mod config;pub mod config_reconciler;pub mod config_subscriber;@@ -19,6 +20,7 @@ pub mod latency;pub mod log_util;pub mod metrics;pub mod nats_consumer;+pub mod observability;pub mod output;pub mod payload_store;pub mod pinned_reconciler;@@ -34,7 +36,7 @@ pub mod tokenize;pub mod work_types;use std::sync::atomic::{AtomicBool, Ordering};-use std::sync::{Arc, RwLock};+use std::sync::Arc;use std::time::{Duration, Instant};use anyhow::Context;@@ -45,6 +47,7 @@ use tokio::time::{interval, sleep, timeout};use tracing::{debug, info, warn};use crate::backend::{BackendRouter, PythonIpcBackend, SharedBackend};+use crate::batch_cancel::{request_id_from_batch_cancel_subject, BatchCancelState};use crate::config::WorkerConfig;use crate::config_subscriber::ConfigApplyState;use crate::dispatcher::Dispatcher;@@ -271,7 +274,6 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {config.ping_interval_ms,config.ready_stale_mult,));- let loaded_models = Arc::new(RwLock::new(Vec::<String>::new()));info!(ping_interval_ms = config.ping_interval_ms,ready_stale_mult = config.ready_stale_mult,@@ -408,6 +410,8 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {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 loaded_models = config_apply_state.loaded_models();+ let batch_cancel_state = BatchCancelState::default();let dispatcher = Arc::new(Dispatcher::new(Arc::clone(&backend),@@ -421,6 +425,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {Some(shutdown.clone()),Some(Arc::clone(&config_apply_state)),pool_admission.clone(),+ batch_cancel_state.clone(),));let generation_direct_dispatch = Arc::new(GenerationDirectDispatch::new(@@ -434,6 +439,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {pool_admission.clone(),Arc::clone(&ipc),Arc::clone(&nats_direct_active),+ batch_cancel_state,));generation_direct_dispatch.activate("startup")@@ -449,6 +455,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {shutdown.clone(),crate::config_subscriber::ConfigSubscriberOptions {trusted_producers: config.nats_config_trusted_producers.clone(),+ pool: config.pool.clone(),},);let config_reconciler_handle = crate::config_reconciler::spawn(@@ -457,6 +464,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {base_url: base_url.clone(),admin_token: config.config_service_token.clone(),bundle: config.bundle.clone(),+ pool: config.pool.clone(),poll_interval: Duration::from_millis(config.config_poll_interval_ms),full_export_interval: if config.config_full_export_interval_ms == 0 {None@@ -683,11 +691,11 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {#[derive(Default)]struct GenerationDirectHandles {pull: Option<JoinHandle<()>>,- cancel: Option<JoinHandle<()>>,+ generation_cancel: Option<JoinHandle<()>>,+ batch_cancel: Option<JoinHandle<()>>,}-/// Owns the worker-specific direct-dispatch stream and generation cancel-/// subscription.+/// Owns the worker-specific direct-dispatch stream and cancel subscriptions.////// The stream is always active: capped logical batch requests can target an/// assigned worker directly, and generation uses the same worker subject for@@ -703,6 +711,7 @@ struct GenerationDirectDispatch {pool_admission: Option<Arc<PoolAdmissionGate>>,ipc: Arc<IpcClient>,active: Arc<AtomicBool>,+ batch_cancel_state: BatchCancelState,handles: Mutex<GenerationDirectHandles>,}@@ -719,6 +728,7 @@ impl GenerationDirectDispatch {pool_admission: Option<Arc<PoolAdmissionGate>>,ipc: Arc<IpcClient>,active: Arc<AtomicBool>,+ batch_cancel_state: BatchCancelState,) -> Self {Self {jetstream,@@ -731,6 +741,7 @@ impl GenerationDirectDispatch {pool_admission,ipc,active,+ batch_cancel_state,handles: Mutex::new(GenerationDirectHandles::default()),}}@@ -755,6 +766,22 @@ impl GenerationDirectDispatch {}};+ let batch_cancel = match spawn_batch_direct_cancel_subscriber(+ self.nats_client.clone(),+ self.config.worker_id.clone(),+ self.batch_cancel_state.clone(),+ Arc::clone(&self.shutdown),+ )+ .await+ .context("start batch direct-dispatch cancel subscriber")+ {+ Ok(handle) => handle,+ 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);@@ -772,7 +799,7 @@ impl GenerationDirectDispatch {).await;});- let cancel = spawn_generation_cancel_subscriber(+ let generation_cancel = spawn_generation_cancel_subscriber(self.nats_client.clone(),Arc::clone(&self.ipc),Arc::clone(&self.shutdown),@@ -780,7 +807,8 @@ impl GenerationDirectDispatch {let mut handles = self.handles.lock().await;handles.pull = Some(pull);- handles.cancel = Some(cancel);+ handles.generation_cancel = Some(generation_cancel);+ handles.batch_cancel = Some(batch_cancel);info!(reason, "worker direct-dispatch activated");Ok(true)}@@ -790,7 +818,8 @@ impl GenerationDirectDispatch {let mut guard = self.handles.lock().await;GenerationDirectHandles {pull: guard.pull.take(),- cancel: guard.cancel.take(),+ generation_cancel: guard.generation_cancel.take(),+ batch_cancel: guard.batch_cancel.take(),}};@@ -800,7 +829,11 @@ impl GenerationDirectDispatch {}let _ = h.await;}- if let Some(h) = handles.cancel {+ if let Some(h) = handles.generation_cancel {+ h.abort();+ let _ = h.await;+ }+ if let Some(h) = handles.batch_cancel {h.abort();let _ = h.await;}@@ -894,6 +927,67 @@ fn spawn_generation_cancel_subscriber(})}+async fn spawn_batch_direct_cancel_subscriber(+ nats_client: async_nats::Client,+ worker_id: String,+ batch_cancel_state: BatchCancelState,+ shutdown: Arc<Shutdown>,+) -> anyhow::Result<JoinHandle<()>> {+ let subject = "batch_cancel.>".to_string();+ let mut sub = nats_client+ .subscribe(subject.clone())+ .await+ .context("subscribe to batch_cancel.>")?;++ Ok(tokio::spawn(async move {+ info!("batch-direct: cancel subscription started");+ let retry_backoff = Duration::from_millis(500);+ loop {+ tokio::select! {+ biased;+ _ = shutdown.wait() => return,+ maybe_msg = sub.next() => {+ let Some(msg) = maybe_msg else {+ warn!("batch-direct: cancel subscription ended; retrying");+ loop {+ match nats_client.subscribe(subject.clone()).await {+ Ok(next_sub) => {+ sub = next_sub;+ info!("batch-direct: cancel subscription restarted");+ break;+ }+ Err(e) => warn!(+ error = %e,+ "batch-direct: failed to resubscribe to batch_cancel.>"+ ),+ }+ tokio::select! {+ biased;+ _ = shutdown.wait() => return,+ _ = sleep(retry_backoff) => {}+ }+ }+ continue;+ };+ let subject = msg.subject.to_string();+ let Some(request_id) =+ request_id_from_batch_cancel_subject(&subject, &worker_id)+ else {+ debug!(subject = %subject, "batch-direct: ignoring non-local cancel subject");+ continue;+ };+ batch_cancel_state.cancel(request_id.clone());+ debug!(+ request_id = %request_id,+ worker_id = %worker_id,+ "batch-direct: cancel recorded for worker-direct queued work"+ );+ }+ }+ }+ }))+}+fn request_id_from_cancel_subject(subject: &str) -> Option<String> {let mut parts = subject.splitn(3, '.');match (parts.next(), parts.next(), parts.next()) {diff --git a/packages/sie_server_sidecar/src/main.rs b/packages/sie_server_sidecar/src/main.rsindex 97f0e81a5..1dbfddd96 100644--- a/packages/sie_server_sidecar/src/main.rs+++ b/packages/sie_server_sidecar/src/main.rs@@ -155,6 +155,10 @@ struct Cli {#[tokio::main]async fn main() -> anyhow::Result<()> {+ // Release images enable cloud-storage: object_store selects aws-lc-rs+ // while NATS selects ring. Pick one provider before TLS clients start.+ let _ = rustls::crypto::ring::default_provider().install_default();+init_tracing();let cli = Cli::parse();@@ -214,16 +218,18 @@ async fn main() -> anyhow::Result<()> {if let Err(e) = run(config).await.context("server sidecar run loop") {error!(error = ?e, "sie-server-sidecar exited with error");+ // Flush any pending OTLP spans before the hard exit.+ sie_server_sidecar::observability::tracing::shutdown_tracing();std::process::exit(1);}+ // Flush any pending OTLP spans before a clean exit.+ sie_server_sidecar::observability::tracing::shutdown_tracing();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();+ sie_server_sidecar::observability::tracing::init_tracing();}fn validate_lane_segment(name: &str, raw: String) -> anyhow::Result<String> {diff --git a/packages/sie_server_sidecar/src/metrics.rs b/packages/sie_server_sidecar/src/metrics.rsindex ac0659951..70cc5197b 100644--- a/packages/sie_server_sidecar/src/metrics.rs+++ b/packages/sie_server_sidecar/src/metrics.rs@@ -63,7 +63,7 @@ const DELIVER_COUNT_BUCKETS: &[f64] = &[1.0, 2.0, 3.0, 5.0, 10.0];////// 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.+/// that predate the sidecar-owned scheduler.////// ## Label cardinality///diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rsindex bfcc5dac8..9e3375aef 100644--- a/packages/sie_server_sidecar/src/nats_consumer.rs+++ b/packages/sie_server_sidecar/src/nats_consumer.rs@@ -32,9 +32,9 @@ const DEFAULT_MAX_ACK_PENDING: i64 = 1000;const DEFAULT_STREAM_MAX_AGE_SECS: u64 = 1_800;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.+/// Env-overridable `max_deliver`, wired to the worker-sidecar by Helm+/// as `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()@@ -43,8 +43,8 @@ fn max_deliver() -> i64 {.unwrap_or(DEFAULT_MAX_DELIVER)}-/// Env-overridable stream `max_age`. Mirrors Python's-/// `SIE_STREAM_MAX_AGE_S` (default 1800). Should be >+/// Env-overridable stream `max_age`, wired to the worker-sidecar by+/// Helm as `SIE_STREAM_MAX_AGE_S` (default 1800). Should be >/// `max_deliver * ack_wait` so messages remain inspectable after DLQ.fn stream_max_age_secs() -> u64 {std::env::var("SIE_STREAM_MAX_AGE_S")diff --git a/packages/sie_server_sidecar/src/observability/mod.rs b/packages/sie_server_sidecar/src/observability/mod.rsnew file mode 100644index 000000000..f1b4a8376--- /dev/null+++ b/packages/sie_server_sidecar/src/observability/mod.rs@@ -0,0 +1,15 @@+//! Sidecar-side observability: OTLP tracing + W3C Trace Context.+//!+//! The sidecar sits on the queue hop between the gateway and the+//! Python worker. It owns the OpenTelemetry tracer-provider setup, the+//! global W3C propagator install, and the helpers for extracting the+//! inbound gateway context off the work envelope plus injecting the+//! `sidecar.dispatch` span's context onto the IPC `RunBatchItem`s.+//!+//! Mirrors `packages/sie_gateway/src/observability/`. Unlike the+//! gateway, the propagation boundary is W3C *strings* carried on the+//! work envelope (the sidecar has no inbound `HeaderMap`), so the+//! extractor here is `HashMap`-backed rather than header-backed.++pub mod propagation;+pub mod tracing;diff --git a/packages/sie_server_sidecar/src/observability/propagation.rs b/packages/sie_server_sidecar/src/observability/propagation.rsnew file mode 100644index 000000000..842be195a--- /dev/null+++ b/packages/sie_server_sidecar/src/observability/propagation.rs@@ -0,0 +1,252 @@+//! W3C Trace Context propagation helpers for the sidecar.+//!+//! The sidecar sits between two propagation boundaries on the queue+//! hop:+//!+//! 1. **Inbound envelope → in-process Context**. The gateway serialised+//! its span into the work envelope's `traceparent` / `tracestate`+//! strings ([`crate::work_types::WorkItem`]). We extract them via+//! the globally-installed propagator and parent the+//! `sidecar.dispatch` span on the result.+//!+//! 2. **In-process Context → outbound IPC item**. Before sending the+//! [`crate::ipc_types::RunBatchItem`] to the Python worker we+//! serialise the active `sidecar.dispatch` span back into the two+//! header strings and write them onto the wire item, so the+//! worker's `worker.run_batch` span nests under the sidecar span.+//!+//! Both directions go through the **same** propagator instance — the+//! global W3C propagator installed in [`super::tracing::init_tracing`]+//! — so the wire format is identical in both directions. Unlike the+//! gateway, the inbound carrier is a pair of W3C *strings* (not an+//! HTTP `HeaderMap`), so the extractor here is `HashMap`-backed.++use std::collections::HashMap;++use opentelemetry::global;+use opentelemetry::propagation::{Extractor, Injector};+use opentelemetry::trace::{SpanContext, TraceContextExt};+use opentelemetry::Context;++/// Adapter exposing a `HashMap<String, String>` as an OTel+/// [`Extractor`]. The inbound `traceparent` / `tracestate` strings off+/// the work envelope are loaded into this map and handed to the+/// propagator.+struct HashMapExtractor<'a>(&'a HashMap<String, String>);++impl Extractor for HashMapExtractor<'_> {+ fn get(&self, key: &str) -> Option<&str> {+ self.0.get(key).map(String::as_str)+ }++ fn keys(&self) -> Vec<&str> {+ self.0.keys().map(String::as_str).collect()+ }+}++/// Adapter exposing a `HashMap<String, String>` as an OTel+/// [`Injector`]. The propagator writes the two W3C headers as+/// `String`s and we lift them out for the typed wire fields.+struct HashMapInjector<'a>(&'a mut HashMap<String, String>);++impl Injector for HashMapInjector<'_> {+ fn set(&mut self, key: &str, value: String) {+ self.0.insert(key.to_string(), value);+ }+}++/// Build the W3C carrier map from the optional envelope strings.+fn carrier_from_w3c(+ traceparent: Option<&str>,+ tracestate: Option<&str>,+) -> HashMap<String, String> {+ let mut carrier: HashMap<String, String> = HashMap::with_capacity(2);+ if let Some(tp) = traceparent {+ carrier.insert("traceparent".to_string(), tp.to_string());+ }+ if let Some(ts) = tracestate {+ carrier.insert("tracestate".to_string(), ts.to_string());+ }+ carrier+}++/// Extract a parent [`Context`] from the inbound envelope's W3C+/// strings.+///+/// Returns the empty (root) context when no `traceparent` is present,+/// matching W3C semantics: callers should still open their own span;+/// it will simply not be a child of any external trace.+pub fn extract_context_from_w3c(traceparent: Option<&str>, tracestate: Option<&str>) -> Context {+ let carrier = carrier_from_w3c(traceparent, tracestate);+ global::get_text_map_propagator(|propagator| propagator.extract(&HashMapExtractor(&carrier)))+}++/// Extract the inbound [`SpanContext`] from the envelope's W3C+/// strings, for use as a span *link* (batch coalescing means a single+/// `sidecar.dispatch` span can parent items from several gateway+/// traces; the non-primary parents are recorded as links).+///+/// Returns `None` when the strings are absent or yield an invalid+/// context.+pub fn remote_span_context(+ traceparent: Option<&str>,+ tracestate: Option<&str>,+) -> Option<SpanContext> {+ let cx = extract_context_from_w3c(traceparent, tracestate);+ let span_cx = cx.span().span_context().clone();+ span_cx.is_valid().then_some(span_cx)+}++/// Serialise the current OTel [`Context`] (active span) back into the+/// two W3C strings.+///+/// Returns `(traceparent, tracestate)`. Both are `None` when no span+/// is currently active (e.g. no OTLP exporter configured, so the+/// `sidecar.dispatch` `tracing` span has no bridged OTel span) — the+/// caller then falls back to the gateway context on the envelope.+pub fn inject_current_context() -> (Option<String>, Option<String>) {+ inject_context(&Context::current())+}++/// Variant of [`inject_current_context`] taking an explicit context.+pub fn inject_context(cx: &Context) -> (Option<String>, Option<String>) {+ let mut carrier: HashMap<String, String> = HashMap::with_capacity(2);+ global::get_text_map_propagator(|propagator| {+ propagator.inject_context(cx, &mut HashMapInjector(&mut carrier));+ });+ let traceparent = carrier.remove("traceparent");+ let tracestate = carrier.remove("tracestate");+ (traceparent, tracestate)+}++#[cfg(test)]+mod tests {+ use super::*;+ use opentelemetry::trace::{Span as _, Tracer, TracerProvider as _};+ use opentelemetry_sdk::propagation::TraceContextPropagator;+ use opentelemetry_sdk::trace::SdkTracerProvider;++ /// Install the propagator once per test path. Installing twice is+ /// harmless (the global slot accepts the new value), but it must be+ /// live before extract/inject for the wire format to match.+ fn install_propagator() {+ opentelemetry::global::set_text_map_propagator(TraceContextPropagator::new());+ }++ const SAMPLE_TP: &str = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01";++ #[test]+ fn extract_w3c_inherits_trace_id() {+ install_propagator();+ let cx = extract_context_from_w3c(Some(SAMPLE_TP), None);+ let provider = SdkTracerProvider::builder().build();+ let tracer = provider.tracer("test");+ let span = tracer.start_with_context("child", &cx);+ let span_cx = span.span_context().clone();+ assert!(span_cx.is_valid(), "child span context must be valid");+ assert_eq!(+ format!("{:032x}", span_cx.trace_id()),+ "0af7651916cd43dd8448eb211c80319c",+ "child must inherit the extracted trace id",+ );+ }++ #[test]+ fn extract_w3c_absent_is_root_context() {+ install_propagator();+ let cx = extract_context_from_w3c(None, None);+ assert!(+ !cx.span().span_context().is_valid(),+ "no traceparent ⇒ root (invalid) span context",+ );+ }++ #[test]+ fn remote_span_context_present_and_absent() {+ install_propagator();+ let sc = remote_span_context(Some(SAMPLE_TP), None).expect("valid traceparent ⇒ Some");+ assert_eq!(+ format!("{:032x}", sc.trace_id()),+ "0af7651916cd43dd8448eb211c80319c",+ );+ assert_eq!(format!("{:016x}", sc.span_id()), "b7ad6b7169203331");+ assert!(remote_span_context(None, None).is_none());+ }++ #[test]+ fn inject_with_no_active_span_returns_none_pair() {+ install_propagator();+ let (tp, ts) = inject_context(&Context::new());+ assert!(tp.is_none(), "no active span ⇒ no traceparent");+ assert!(ts.is_none(), "no active span ⇒ no tracestate");+ }++ #[test]+ fn inject_with_active_span_yields_w3c_traceparent() {+ install_propagator();+ let provider = SdkTracerProvider::builder().build();+ let tracer = provider.tracer("test");+ let span = tracer.start("parent");+ let cx = Context::current().with_span(span);+ let (tp, _ts) = inject_context(&cx);+ let tp = tp.expect("active span should inject a traceparent");+ let parts: Vec<&str> = tp.split('-').collect();+ assert_eq!(parts.len(), 4, "traceparent must be 4 fields: {tp}");+ assert_eq!(parts[1].len(), 32, "trace_id field 32 hex chars");+ assert_eq!(parts[2].len(), 16, "span_id field 16 hex chars");+ }++ const INBOUND_TRACE: &str = "0af7651916cd43dd8448eb211c80319c";+ const INBOUND_SPAN: &str = "b7ad6b7169203331";++ /// The core nesting contract: with the OTel layer active (i.e. an+ /// exporter is configured), a `sidecar.dispatch` span parented on+ /// the inbound gateway context injects a *new* span under the+ /// *same* trace — so `worker.run_batch` nests under the sidecar+ /// span, which nests under the gateway span.+ #[test]+ fn sidecar_span_injects_new_span_under_inbound_trace() {+ use tracing_subscriber::layer::SubscriberExt;+ install_propagator();+ let provider = SdkTracerProvider::builder().build();+ let subscriber = tracing_subscriber::registry()+ .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("test")));++ let inbound_tp = format!("00-{INBOUND_TRACE}-{INBOUND_SPAN}-01");+ let (tp, _ts) = tracing::subscriber::with_default(subscriber, || {+ use tracing_opentelemetry::OpenTelemetrySpanExt;+ let span = tracing::info_span!("sidecar.dispatch");+ let _ = span.set_parent(extract_context_from_w3c(Some(&inbound_tp), None));+ span.in_scope(inject_current_context)+ });++ let tp = tp.expect("active sidecar span should inject a traceparent");+ let parts: Vec<&str> = tp.split('-').collect();+ assert_eq!(parts.len(), 4, "traceparent must be 4 fields: {tp}");+ assert_eq!(+ parts[1], INBOUND_TRACE,+ "sidecar span must continue the inbound trace",+ );+ assert_ne!(+ parts[2], INBOUND_SPAN,+ "sidecar span must have its own span id (the middle hop)",+ );+ }++ /// Degrade-gracefully parity: without the OTel layer (no exporter),+ /// the `sidecar.dispatch` span has no bridged OTel span, so+ /// injection yields `(None, None)` and the dispatcher falls back to+ /// the gateway context — `gateway → worker` linkage is preserved,+ /// no sidecar span is emitted.+ #[test]+ fn no_otel_layer_injects_nothing() {+ install_propagator();+ let subscriber = tracing_subscriber::registry();+ let (tp, ts) = tracing::subscriber::with_default(subscriber, || {+ let span = tracing::info_span!("sidecar.dispatch");+ span.in_scope(inject_current_context)+ });+ assert!(tp.is_none(), "no exporter/layer ⇒ no sidecar traceparent");+ assert!(ts.is_none(), "no exporter/layer ⇒ no sidecar tracestate");+ }+}diff --git a/packages/sie_server_sidecar/src/observability/tracing.rs b/packages/sie_server_sidecar/src/observability/tracing.rsnew file mode 100644index 000000000..ac588da72--- /dev/null+++ b/packages/sie_server_sidecar/src/observability/tracing.rs@@ -0,0 +1,189 @@+//! OpenTelemetry tracer-provider setup for the sidecar.+//!+//! Mirrors `packages/sie_gateway/src/observability/tracing.rs`. The+//! OTLP exporter is enabled only when `SIE_TRACING_ENABLED` is truthy+//! and an OTLP endpoint is configured via+//! `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`.+//! The W3C [`TraceContextPropagator`] is installed globally regardless+//! of that exporter gate so that the inbound gateway+//! `traceparent` (carried on the work envelope) still propagates+//! through to the Python worker. Without an exporter the sidecar+//! itself records no spans, but the IDs continue to flow — the+//! `into_run_batch_item_with_trace` fallback in the dispatcher copies+//! the gateway context onto the wire items unchanged.+//!+//! [`TraceContextPropagator`]: opentelemetry_sdk::propagation::TraceContextPropagator++use std::env;+use std::sync::OnceLock;+use std::time::Duration;++use opentelemetry::global;+use opentelemetry::trace::TracerProvider as _;+use opentelemetry_otlp::WithExportConfig;+use opentelemetry_sdk::propagation::TraceContextPropagator;+use opentelemetry_sdk::trace::{SdkTracerProvider, Tracer};+use opentelemetry_sdk::Resource;+use tracing_subscriber::layer::SubscriberExt;+use tracing_subscriber::util::SubscriberInitExt;+use tracing_subscriber::{EnvFilter, Layer};++/// Service name used when `OTEL_SERVICE_NAME` is not set.+const DEFAULT_SERVICE_NAME: &str = "sie-worker-sidecar";+static TRACER_PROVIDER: OnceLock<SdkTracerProvider> = OnceLock::new();++/// Bounded flush deadline (ms) so process exit can't stall on an unreachable collector.+const TRACING_SHUTDOWN_TIMEOUT_MS: u64 = 3_000;++/// Initialise OpenTelemetry + tracing-subscriber for the sidecar.+///+/// Pipeline:+/// 1. Install the global W3C [`TraceContextPropagator`] so the+/// inbound `traceparent` / `tracestate` (read off the work+/// envelope) extract into an `opentelemetry::Context`. **Always+/// runs**, even without an exporter — propagation is the+/// load-bearing piece for worker-side correlation.+/// 2. If `SIE_TRACING_ENABLED` is truthy and `OTEL_EXPORTER_OTLP_ENDPOINT`+/// (or the trace-specific `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) is+/// set, build a [`SdkTracerProvider`] with the OTLP gRPC exporter, attach a+/// [`tracing_opentelemetry::OpenTelemetryLayer`] so the+/// `sidecar.dispatch` `tracing::*` span becomes an OTel span,+/// and set the provider as global. Otherwise, only the JSON fmt layer is+/// installed while the propagator remains active.+///+/// Logs are always emitted as JSON, matching the sidecar's prior+/// behaviour. `RUST_LOG` is honoured via `EnvFilter`.+pub fn init_tracing() {+ // Idempotency guard. The subscriber's `.init()` panics on a second+ // call ("a global default trace dispatcher has already been set").+ // The integration tests spin the sidecar up in-process across+ // multiple cases and would otherwise abort on the second case.+ use std::sync::atomic::{AtomicBool, Ordering};+ static INIT_GUARD: AtomicBool = AtomicBool::new(false);+ if INIT_GUARD.swap(true, Ordering::SeqCst) {+ tracing::debug!("init_tracing called more than once; skipping subsequent init");+ return;+ }++ // Step 1: always install the propagator. Even without an OTLP+ // exporter the sidecar needs to *extract* the inbound gateway+ // context and *inject* it onto the wire items so the worker side+ // (which runs the heavy adapter call) can continue the trace.+ global::set_text_map_propagator(TraceContextPropagator::new());++ let endpoint = if sie_tracing_enabled() {+ cleaned_env("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")+ .or_else(|| cleaned_env("OTEL_EXPORTER_OTLP_ENDPOINT"))+ } else {+ None+ };++ let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));++ // Try to build the OTel tracer. On any failure the sidecar+ // continues with the fmt-only subscriber (and propagator-only OTel+ // state) — operators get logs and worker-side trace correlation,+ // just no `sidecar.dispatch` spans.+ let tracer = endpoint.as_deref().and_then(|ep| match init_tracer(ep) {+ Ok(t) => Some(t),+ Err(e) => {+ eprintln!("warn: failed to init OTLP exporter ({e}); continuing without exporter");+ None+ }+ });++ // Place the (boxed) OTel layer FIRST, then the fmt and filter+ // layers — see the gateway's note: boxing against the inner+ // `Registry` is what makes `Option<L>: Layer<S>` compose; OTel-last+ // fails the `Layer<Layered<…>>` bound.+ let otel_layer_boxed: Option<Box<dyn Layer<tracing_subscriber::Registry> + Send + Sync>> =+ tracer.map(|t| {+ let l: Box<dyn Layer<tracing_subscriber::Registry> + Send + Sync> =+ Box::new(tracing_opentelemetry::layer().with_tracer(t));+ l+ });++ tracing_subscriber::registry()+ .with(otel_layer_boxed)+ .with(filter)+ .with(tracing_subscriber::fmt::layer().json())+ .init();++ if let Some(ep) = endpoint {+ tracing::info!(endpoint = %ep, "OpenTelemetry tracing initialized");+ } else {+ tracing::debug!(+ "SIE_TRACING_ENABLED not truthy or OTLP endpoint not set; W3C propagator installed (no exporter)"+ );+ }+}++fn tracing_flag_set(raw: Option<&str>) -> bool {+ raw.is_some_and(|value| {+ let value = value.trim();+ value.eq_ignore_ascii_case("true") || value == "1" || value.eq_ignore_ascii_case("yes")+ })+}++fn sie_tracing_enabled() -> bool {+ let raw = env::var("SIE_TRACING_ENABLED").ok();+ tracing_flag_set(raw.as_deref())+}++/// Read an env var, trimming surrounding whitespace and treating a+/// whitespace-only value as absent so it can't shadow a valid fallback.+fn cleaned_env(name: &str) -> Option<String> {+ env::var(name)+ .ok()+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+}++fn init_tracer(endpoint: &str) -> Result<Tracer, String> {+ let service_name =+ env::var("OTEL_SERVICE_NAME").unwrap_or_else(|_| DEFAULT_SERVICE_NAME.to_string());++ let exporter = opentelemetry_otlp::SpanExporter::builder()+ .with_tonic()+ .with_endpoint(endpoint)+ .build()+ .map_err(|e| format!("build OTLP span exporter: {e}"))?;++ let provider = SdkTracerProvider::builder()+ .with_resource(Resource::builder().with_service_name(service_name).build())+ .with_batch_exporter(exporter)+ .build();+ let tracer = provider.tracer("sie-worker-sidecar");+ global::set_tracer_provider(provider.clone());+ let _ = TRACER_PROVIDER.set(provider);+ Ok(tracer)+}++/// Graceful shutdown — flush any pending spans.+///+/// Called from `main.rs` on the way out so the OTLP exporter has a+/// chance to drain its batch before the process exits.+pub fn shutdown_tracing() {+ if let Some(provider) = TRACER_PROVIDER.get() {+ let _ = provider.shutdown_with_timeout(Duration::from_millis(TRACING_SHUTDOWN_TIMEOUT_MS));+ }+}++#[cfg(test)]+mod tests {+ use super::tracing_flag_set;++ #[test]+ fn tracing_flag_set_accepts_only_positive_truthy_values() {+ assert!(tracing_flag_set(Some("true")));+ assert!(tracing_flag_set(Some("1")));+ assert!(tracing_flag_set(Some("yes")));+ assert!(tracing_flag_set(Some("TRUE")));+ assert!(tracing_flag_set(Some(" true ")));++ assert!(!tracing_flag_set(Some("false")));+ assert!(!tracing_flag_set(Some("")));+ assert!(!tracing_flag_set(Some(" ")));+ assert!(!tracing_flag_set(None));+ }+}diff --git a/packages/sie_server_sidecar/src/payload_store.rs b/packages/sie_server_sidecar/src/payload_store.rsindex db07a8884..38cd85f10 100644--- a/packages/sie_server_sidecar/src/payload_store.rs+++ b/packages/sie_server_sidecar/src/payload_store.rs@@ -23,6 +23,9 @@ use async_trait::async_trait;use thiserror::Error;use tracing::debug;+#[cfg(feature = "cloud-storage")]+use object_store::ObjectStoreExt;+const OBJECT_STORE_SCHEMES: &[&str] = &["s3://", "gs://", "abfs://", "abfss://"];fn object_store_scheme(url: &str) -> Option<&'static str> {@@ -443,6 +446,8 @@ pub async fn create_payload_store(mod tests {use super::*;#[cfg(feature = "cloud-storage")]+ use object_store::ObjectStoreExt;+ #[cfg(feature = "cloud-storage")]use std::sync::{Mutex, OnceLock};use tempfile::TempDir;@@ -637,7 +642,7 @@ mod tests {#[tokio::test]async fn object_store_get_accepts_full_ref_inside_prefix() {use object_store::path::Path;- use object_store::{ObjectStore, PutPayload};+ use object_store::PutPayload;let memory = object_store::memory::InMemory::new();memory@@ -677,7 +682,7 @@ mod tests {#[tokio::test]async fn object_store_get_accepts_azure_full_ref_inside_prefix() {use object_store::path::Path;- use object_store::{ObjectStore, PutPayload};+ use object_store::PutPayload;let memory = object_store::memory::InMemory::new();memory@@ -815,7 +820,7 @@ mod tests {#[tokio::test]async fn object_store_get_accepts_plain_key_under_configured_prefix() {use object_store::path::Path;- use object_store::{ObjectStore, PutPayload};+ use object_store::PutPayload;let memory = object_store::memory::InMemory::new();memorydiff --git a/packages/sie_server_sidecar/src/pinned_reconciler.rs b/packages/sie_server_sidecar/src/pinned_reconciler.rsindex b6231daf6..58d0779d0 100644--- a/packages/sie_server_sidecar/src/pinned_reconciler.rs+++ b/packages/sie_server_sidecar/src/pinned_reconciler.rs@@ -239,11 +239,11 @@ fn pinned_pool_count_for_home_queue(pools: &[Value], home_pool: &str) -> usize {/// non-empty-trimmed list. Missing spec / field / non-array all yield an empty/// set (the worker un-pins everything). Sorting makes change detection stable.///-/// Ids are shipped gateway-canonical (bare or `model:profile`); normalization-/// (strip `:profile`, lowercase) is the worker's job, so the dedup here is on-/// the canonical form. Distinct canonical ids that collapse to the same bare id-/// on the worker are pushed as a "change" and the worker no-ops them — harmless,-/// but it means the logged count is canonical, not effective.+/// Ids are shipped gateway-canonical (bare or `model:profile`); worker-side+/// normalization owns exact profile handling. Python preserves non-default+/// profiles while lowercasing ids, and native Rust workers preserve HuggingFace+/// base-id casing while folding only `:default`, so dedup here stays on the+/// gateway form.fn parse_pinned_models(pool: &Value) -> Vec<String> {let mut out: Vec<String> = pool.get("spec")diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rsindex 34a12f537..ca7799f47 100644--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs@@ -380,6 +380,10 @@ pub struct WorkerCapabilitiesResponse {pub has_generation_models: bool,#[serde(default)]pub generation_models: Vec<String>,+ #[serde(default)]+ pub supported_models: Vec<String>,+ #[serde(default)]+ pub loaded_models: Vec<String>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -798,6 +802,14 @@ pub struct RunBatchItem {pub score: Option<ScoreBatchItem>,#[serde(default)]pub extract: Option<ExtractBatchItem>,+ /// W3C trace context copied off the originating [`crate::work_types::WorkItem`]+ /// so the Python non-streaming worker loop can re-extract the gateway+ /// span and attach `worker.run_batch` as its child. `None` when the+ /// gateway didn't propagate a trace (older builds / untraced request).+ #[serde(default)]+ pub traceparent: Option<String>,+ #[serde(default)]+ pub tracestate: Option<String>,}impl RunBatchItem {@@ -817,6 +829,8 @@ impl RunBatchItem {encode: Some(item),score: None,extract: None,+ traceparent: None,+ tracestate: None,}}@@ -834,6 +848,8 @@ impl RunBatchItem {encode: None,score: Some(item),extract: None,+ traceparent: None,+ tracestate: None,}}@@ -851,6 +867,8 @@ impl RunBatchItem {encode: None,score: None,extract: Some(item),+ traceparent: None,+ tracestate: None,}}}@@ -1063,6 +1081,58 @@ mod tests {assert!(back.prepared_tokens.is_none());}+ #[test]+ fn run_batch_item_trace_context_roundtrips_msgpack() {+ // The trace fields must survive the named-msgpack round-trip so+ // the Python non-streaming worker loop can re-extract the+ // gateway span. Build an encode item and stamp the trace+ // context the way `into_run_batch_item_with_trace` would.+ let mut rbi = RunBatchItem::encode(EncodeBatchItem {+ work_item_id: "r.0".into(),+ request_id: "r".into(),+ item_index: 0,+ total_items: 1,+ timestamp: 0.0,+ item: text_item("hello"),+ output_types: None,+ instruction: None,+ is_query: false,+ options: None,+ profile_id: None,+ bundle_config_hash: None,+ payload_fetch_ms: 0.0,+ prepared_tokens: None,+ });+ rbi.traceparent = Some("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01".into());+ rbi.tracestate = Some("vendor=opaque".into());++ let bytes = rmp_serde::to_vec_named(&rbi).unwrap();+ let back: RunBatchItem = rmp_serde::from_slice(&bytes).unwrap();+ assert_eq!(+ back.traceparent.as_deref(),+ Some("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01")+ );+ assert_eq!(back.tracestate.as_deref(), Some("vendor=opaque"));+ }++ #[test]+ fn run_batch_item_trace_context_absent_decodes_to_none() {+ // Old Python (or an untraced request) omits the trace keys+ // entirely — new Rust must decode them as `None` via the+ // additive `#[serde(default)]` contract.+ let bytes = rmp_serde::to_vec_named(&serde_json::json!({+ "op": "encode",+ "work_item_id": "r.0",+ "request_id": "r",+ "item_index": 0,+ }))+ .unwrap();+ let back: RunBatchItem = rmp_serde::from_slice(&bytes).unwrap();+ assert_eq!(back.op, "encode");+ assert!(back.traceparent.is_none());+ assert!(back.tracestate.is_none());+ }+#[test]fn process_extract_batch_request_preserves_document_bytes() {let pdf_bytes = b"%PDF-1.4 tiny".to_vec();diff --git a/packages/sie_server_sidecar/src/publisher.rs b/packages/sie_server_sidecar/src/publisher.rsindex 366b041ed..8d4e1242f 100644--- a/packages/sie_server_sidecar/src/publisher.rs+++ b/packages/sie_server_sidecar/src/publisher.rs@@ -59,6 +59,7 @@ impl WorkPublisher {reply_subject: &str,outcome: &ItemOutcome,timings: Option<Timings>,+ worker_direct: bool,) -> Result<(), PublishError> {check_reply_subject(reply_subject)?;@@ -75,7 +76,7 @@ impl WorkPublisher {}};- let result = build_work_result(effective, &self.worker_id, timings);+ let result = build_work_result(effective, &self.worker_id, timings, worker_direct);let bytes = rmp_serde::to_vec_named(&result)?;debug!(reply = %reply_subject,@@ -223,6 +224,7 @@ pub fn build_work_result(outcome: &ItemOutcome,worker_id: &str,timings: Option<Timings>,+ worker_direct: bool,) -> WorkResult {let (success, error, error_code) = match outcome.disposition {Disposition::PublishAndAck => (true, None, None),@@ -272,6 +274,7 @@ pub fn build_work_result(tokenization_ms: outcome.tokenization_ms,postprocessing_ms: outcome.postprocessing_ms,payload_fetch_ms,+ worker_direct,}}@@ -317,12 +320,13 @@ mod tests {#[test]fn success_outcome_maps_to_success_result() {- let r = build_work_result(&outcome(), "worker-1", None);+ let r = build_work_result(&outcome(), "worker-1", None, true);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!(r.worker_direct);assert_eq!(r.inference_ms, Some(17.5));assert_eq!(r.tokenization_ms, Some(1.1));assert_eq!(r.postprocessing_ms, Some(0.3));@@ -335,7 +339,7 @@ mod tests {o.disposition = Disposition::PublishErrorAndAck;o.error = Some("kapow".into());o.error_code = Some("INTERNAL".into());- let r = build_work_result(&o, "w", None);+ let r = build_work_result(&o, "w", None, false);assert!(!r.success);assert_eq!(r.error.as_deref(), Some("kapow"));assert_eq!(r.error_code.as_deref(), Some("INTERNAL"));@@ -350,7 +354,7 @@ mod tests {#[test]fn work_result_is_msgpack_round_trippable() {- let r = build_work_result(&outcome(), "w", None);+ let r = build_work_result(&outcome(), "w", None, false);let bytes = rmp_serde::to_vec_named(&r).unwrap();let back: WorkResult = rmp_serde::from_slice(&bytes).unwrap();assert!(back.success);@@ -364,7 +368,7 @@ mod tests {queue_ms: 12.5,payload_fetch_ms: 3.2,};- let r = build_work_result(&outcome(), "w", Some(timings));+ let r = build_work_result(&outcome(), "w", Some(timings), false);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));@@ -378,7 +382,7 @@ mod tests {queue_ms: 5.0,payload_fetch_ms: 0.0,};- let r = build_work_result(&outcome(), "w", Some(timings));+ let r = build_work_result(&outcome(), "w", Some(timings), false);assert_eq!(r.queue_ms, Some(5.0));assert!(r.payload_fetch_ms.is_none());}@@ -410,7 +414,7 @@ mod tests {o.disposition = Disposition::PublishErrorAndAck;o.error = Some("oops".into());o.error_code = Some("payload_error".into());- let r = build_work_result(&o, "w", None);+ let r = build_work_result(&o, "w", None, false);assert!(!r.success);assert!(r.queue_ms.is_none());assert!(r.processing_ms.is_none());diff --git a/packages/sie_server_sidecar/src/scheduler/item.rs b/packages/sie_server_sidecar/src/scheduler/item.rsindex 8cd5fb317..5e0ac3465 100644--- a/packages/sie_server_sidecar/src/scheduler/item.rs+++ b/packages/sie_server_sidecar/src/scheduler/item.rs@@ -107,6 +107,22 @@ impl SchedulerItem {Self::Extract(x) => RunBatchItem::extract(x),}}++ /// Same as [`Self::into_run_batch_item`] but additionally copies the+ /// W3C trace context (`traceparent` / `tracestate`) off the+ /// originating [`WorkItem`] onto the produced [`RunBatchItem`]. The+ /// per-op constructors have no `WorkItem` access, so the trace+ /// context is plumbed here — at the dispatch site where the batch's+ /// items are zipped back together with their metadata — so the+ /// Python non-streaming worker loop can re-extract the gateway span+ /// and attach `worker.run_batch` as its child.+ #[must_use]+ pub fn into_run_batch_item_with_trace(self, wi: &WorkItem) -> RunBatchItem {+ let mut rbi = self.into_run_batch_item();+ rbi.traceparent = wi.traceparent.clone();+ rbi.tracestate = wi.tracestate.clone();+ rbi+ }}impl HasCost for SchedulerItem {@@ -159,6 +175,9 @@ pub struct SchedulerMeta {/// [`crate::publisher::Timings`] and on the `payload_fetch_seconds`/// histogram.pub fetch_ms: f64,+ /// True when this item was pulled from a worker-specific direct-dispatch+ /// subject rather than the pool subject.+ pub worker_direct: bool,/// 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@@ -170,10 +189,22 @@ impl SchedulerMeta {/// Construct the standard triple stamped with `Instant::now`.#[must_use]pub fn new(wi: WorkItem, msg: Message, fetch_ms: f64) -> Self {+ Self::new_with_worker_direct(wi, msg, fetch_ms, false)+ }++ /// Construct metadata with an explicit delivery-origin marker.+ #[must_use]+ pub fn new_with_worker_direct(+ wi: WorkItem,+ msg: Message,+ fetch_ms: f64,+ worker_direct: bool,+ ) -> Self {Self {wi,msg,fetch_ms,+ worker_direct,submitted_at: Instant::now(),}}@@ -188,6 +219,7 @@ impl std::fmt::Debug for SchedulerMeta {.field("wi_work_item_id", &self.wi.work_item_id).field("wi_request_id", &self.wi.request_id).field("fetch_ms", &self.fetch_ms)+ .field("worker_direct", &self.worker_direct).field("submitted_at", &self.submitted_at).finish_non_exhaustive()}@@ -376,6 +408,68 @@ mod tests {assert!(rbi.extract.is_none());}+ #[test]+ fn into_run_batch_item_with_trace_copies_trace_context() {+ let mut wi = sample_work_item();+ wi.traceparent = Some("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01".into());+ wi.tracestate = Some("vendor=opaque".into());++ let rbi = SchedulerItem::Encode(encode_item(0, None)).into_run_batch_item_with_trace(&wi);++ assert_eq!(+ rbi.traceparent.as_deref(),+ Some("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01")+ );+ assert_eq!(rbi.tracestate.as_deref(), Some("vendor=opaque"));+ // The op/payload plumbing must still be intact.+ assert_eq!(rbi.op, "encode");+ assert!(rbi.encode.is_some());+ }++ #[test]+ fn into_run_batch_item_with_trace_defaults_to_none() {+ let wi = sample_work_item();+ let rbi = SchedulerItem::Encode(encode_item(0, None)).into_run_batch_item_with_trace(&wi);+ assert!(rbi.traceparent.is_none());+ assert!(rbi.tracestate.is_none());+ }++ fn sample_work_item() -> WorkItem {+ WorkItem {+ work_item_id: "r.0".into(),+ request_id: "r".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(),+ admission_pool: "l4".into(),+ machine_profile: "l4-spot".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: None,+ routing_key: None,+ prompt_cache_key: None,+ bundle_config_hash: String::new(),+ router_id: "r1".into(),+ reply_subject: "_INBOX.r1.r".into(),+ traceparent: None,+ tracestate: None,+ timestamp: 0.0,+ }+ }+// ---- LoraKey from options ----#[test]diff --git a/packages/sie_server_sidecar/src/subject.rs b/packages/sie_server_sidecar/src/subject.rsindex c52183fcd..a00c74912 100644--- a/packages/sie_server_sidecar/src/subject.rs+++ b/packages/sie_server_sidecar/src/subject.rs@@ -1,7 +1,9 @@//! NATS subject helpers — model-id normalisation + extraction.//!-//! Work subject format:-//! `sie.work.{pool_name}.{machine_profile}.{bundle}.{normalized_model_id}`.+//! Work subject formats:+//! `sie.work.{pool_name}.{machine_profile}.{bundle}.{normalized_model_id}`+//! and direct-dispatch+//! `sie.work.{pool_name}.{machine_profile}.{bundle}.{normalized_model_id}.{worker_id}`./// Subject token index of the normalized model id/// (`sie.work.<POOL>.<MACHINE>.<BUNDLE>.<MODEL>`).@@ -10,6 +12,9 @@ const MODEL_TOKEN_INDEX: usize = 5;/// Minimum number of dot-delimited tokens a valid work subject must have.const MIN_SUBJECT_PARTS: usize = 6;+/// Exact token count for worker-direct work subjects.+const DIRECT_WORK_SUBJECT_PARTS: usize = 7;+/// Inverse of [`normalize_model_id`]. Best-effort: `__` → `/`, `_dot_` → `.`.pub fn denormalize_model_id(normalized: &str) -> String {normalized.replace("__", "/").replace("_dot_", ".")@@ -33,6 +38,14 @@ pub fn extract_model_id(subject: &str) -> Option<String> {Some(denormalize_model_id(parts[MODEL_TOKEN_INDEX]))}+/// True when the subject addresses one concrete worker rather than the pool.+pub fn is_worker_direct_work_subject(subject: &str) -> bool {+ let parts: Vec<&str> = subject.split('.').collect();+ parts.len() == DIRECT_WORK_SUBJECT_PARTS+ && parts.first() == Some(&"sie")+ && parts.get(1) == Some(&"work")+}+/// 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.@@ -120,6 +133,22 @@ mod tests {assert_eq!(extract_model_id("sie.work.default.l4.default"), None);}+ #[test]+ fn worker_direct_subject_detection_requires_worker_token() {+ assert!(!is_worker_direct_work_subject(+ "sie.work.default.rtx6000.default.BAAI__bge-m3"+ ));+ assert!(is_worker_direct_work_subject(+ "sie.work.default.rtx6000.default.BAAI__bge-m3.worker-1"+ ));+ assert!(!is_worker_direct_work_subject(+ "sie.work.default.rtx6000.default.BAAI__bge-m3.worker-1.extra"+ ));+ assert!(!is_worker_direct_work_subject(+ "other.work.default.rtx6000.default.BAAI__bge-m3.worker-1"+ ));+ }+// ----- subjects_overlap ---------------------------------------------------#[test]diff --git a/packages/sie_server_sidecar/src/work_types.rs b/packages/sie_server_sidecar/src/work_types.rsindex 640696b98..b103a3157 100644--- a/packages/sie_server_sidecar/src/work_types.rs+++ b/packages/sie_server_sidecar/src/work_types.rs@@ -109,6 +109,8 @@ pub struct WorkResult {pub postprocessing_ms: Option<f64>,#[serde(default)]pub payload_fetch_ms: Option<f64>,+ #[serde(default)]+ pub worker_direct: bool,}#[cfg(test)]@@ -252,6 +254,7 @@ mod tests {tokenization_ms: None,postprocessing_ms: None,payload_fetch_ms: None,+ worker_direct: true,};let bytes = rmp_serde::to_vec_named(&result).unwrap();let back: WorkResult = rmp_serde::from_slice(&bytes).unwrap();@@ -260,5 +263,6 @@ mod tests {assert_eq!(back.item_index, 2);assert_eq!(back.result_msgpack.len(), 8);assert_eq!(back.inference_ms, Some(12.5));+ assert!(back.worker_direct);}}diff --git a/packages/sie_server_sidecar/tests/integration_smoke.rs b/packages/sie_server_sidecar/tests/integration_smoke.rsindex 84003ed55..fcac86849 100644--- a/packages/sie_server_sidecar/tests/integration_smoke.rs+++ b/packages/sie_server_sidecar/tests/integration_smoke.rs@@ -5,7 +5,7 @@//! * 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).+//! msgpack-framed RPCs (Ping, EnsureModelReady, RunBatch).//! * 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@@ -1121,8 +1121,8 @@ async fn smoke_generation_direct_dispatch_is_active_before_capability_reconcile(/// * 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.+/// * The dispatcher feeds the decoded item into the Rust scheduler and+/// gets a successful `RunBatch` 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() {@@ -2052,12 +2052,11 @@ fn histogram_count(metrics_body: &str, name: &str) -> u64 {/// 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.+/// 4-slot pool, because there's only one `RunBatch` 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`+/// models, the dispatcher's `EnsureModelReady` + `RunBatch`/// for each group become independent RPCs that the pool should run/// in parallel./// - Python-side delay (via `--per-request-delay-ms`) stretches each@@ -2091,8 +2090,8 @@ async fn pool_enables_concurrent_in_flight_ipc() {("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+ // Serialized floor: MODELS.len() groups × (EnsureModelReady ++ // RunBatch) × 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,@@ -2252,7 +2251,7 @@ async fn pool_enables_concurrent_in_flight_ipc() {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)",+ expected >= {} (one per model group's RunBatch RPC)",MODELS.len(),);@@ -2275,7 +2274,7 @@ async fn pool_enables_concurrent_in_flight_ipc() {/// * 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.+/// encode item inside the outgoing `RunBatch` 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 configureddiff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex dd0febedc..9b25662df 100644--- a/packages/sie_ts_sdk/package.json+++ b/packages/sie_ts_sdk/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-sdk",- "version": "0.6.14",+ "version": "0.6.15","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex 4dd59dde8..04b3a7fd5 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.6.14"; // x-release-please-version+export const SDK_VERSION = "0.6.15"; // x-release-please-versiondiff --git a/uv.lock b/uv.lockindex 1eff6c5c2..a25075b44 100644--- a/uv.lock+++ b/uv.lock@@ -4775,11 +4775,11 @@ wheels = [[[package]]name = "pyjwt"-version = "2.12.1"+version = "2.13.0"source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/c2/27/a3b6e5bf6ff856d2509292e95c8f57f0df7017cf5394921fc4e4ef40308a/pyjwt-2.12.1.tar.gz", hash = "sha256:c74a7a2adf861c04d002db713dd85f84beb242228e671280bf709d765b03672b", size = 102564 }+sdist = { url = "https://files.pythonhosted.org/packages/3b/81/58d0ac84e1ef3a3843791d6954d94c0b33d526c75eeb1efbce9d0a4c4077/pyjwt-2.13.0.tar.gz", hash = "sha256:41571c89ca91598c79e8ef18a2d07367d4810fbbd6f637794879baf1b7703423", size = 107515 }wheels = [- { url = "https://files.pythonhosted.org/packages/e5/7a/8dd906bd22e79e47397a61742927f6747fe93242ef86645ee9092e610244/pyjwt-2.12.1-py3-none-any.whl", hash = "sha256:28ca37c070cad8ba8cd9790cd940535d40274d22f80ab87f3ac6a713e6e8454c", size = 29726 },+ { url = "https://files.pythonhosted.org/packages/a3/5e/ecf12fdb62546d64385c158514e9b2b671f7832108ef2ecd2020ce0af2d1/pyjwt-2.13.0-py3-none-any.whl", hash = "sha256:66adcc2aff09b3f1bbd95fc1e1577df8ac8723c978552fd43304c8a290ac5728", size = 31274 },][package.optional-dependencies]@@ -5719,7 +5719,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.6.14"+version = "0.6.15"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5752,7 +5752,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.6.14"+version = "0.6.15"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5837,7 +5837,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.6.14"+version = "0.6.15"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5909,7 +5909,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.6.14"+version = "0.6.15"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5934,7 +5934,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.6.14"+version = "0.6.15"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5959,7 +5959,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.6.14"+version = "0.6.15"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5986,7 +5986,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.6.14"+version = "0.6.15"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -6013,7 +6013,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.6.14"+version = "0.6.15"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -6040,7 +6040,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.6.14"+version = "0.6.15"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -6106,7 +6106,7 @@ dev = [[[package]]name = "sie-qdrant"-version = "0.6.14"+version = "0.6.15"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -6129,7 +6129,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.6.14"+version = "0.6.15"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -6182,7 +6182,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.6.14"+version = "0.6.15"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -6205,6 +6205,7 @@ dependencies = [{ name = "opentelemetry-exporter-otlp" },{ name = "opentelemetry-instrumentation-fastapi" },{ name = "opentelemetry-sdk" },+ { name = "orjson" },{ name = "packaging" },{ name = "pillow" },{ name = "prometheus-client" },@@ -6236,6 +6237,9 @@ flash-attn = [gpu-metrics = [{ name = "nvidia-ml-py" },]+local = [+ { name = "transformers" },+]top = [{ name = "textual" },]@@ -6267,6 +6271,7 @@ requires-dist = [{ name = "opentelemetry-exporter-otlp", specifier = ">=1.28,<2" },{ name = "opentelemetry-instrumentation-fastapi", specifier = ">=0.49b0,<1" },{ name = "opentelemetry-sdk", specifier = ">=1.28,<2" },+ { name = "orjson", specifier = ">=3.10,<4" },{ name = "packaging", specifier = ">=24,<25" },{ name = "pillow", specifier = ">=12.2.0" },{ name = "prometheus-client", specifier = ">=0.21,<1" },@@ -6285,6 +6290,7 @@ requires-dist = [{ name = "torchvision", marker = "sys_platform != 'linux'", specifier = ">=0.18,<1" },{ name = "torchvision", marker = "sys_platform == 'linux'", specifier = ">=0.18,<1", index = "https://download.pytorch.org/whl/cu129" },{ name = "transformers", specifier = ">=4.57,<6" },+ { name = "transformers", marker = "extra == 'local'", specifier = ">=4.57,<5" },{ name = "typer", specifier = ">=0.14,<1" },{ name = "uvicorn", extras = ["standard"], specifier = ">=0.32,<1" },{ name = "uvloop", specifier = ">=0.22" },@@ -6312,7 +6318,7 @@ requires-dist = [[[package]]name = "sie-weaviate"-version = "0.6.14"+version = "0.6.15"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },