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.7
github-actions[bot]8ca2cdd14a7c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 65ffe57fa..63fe8c93c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,28 @@# Changelog+## v0.6.7++- chore(main): release 0.6.7+- fix: guard model ready timeout against liveness budget+- fix: wire model ready timeout through helm+- docs: address sidecar guide review feedback+- fix: address qwen 27b review feedback+- docs: revise sidecar architecture guide+- fix: route qwen 27b fp8 cold starts+- fix: make worker config reconciliation no-op safe+- style(lighton_ocr): hoist test imports to module top per CodeRabbit review+- fix: add qwen3.6 27b 32k rtx serving profile+- fix(generate): label streaming collector/publisher metrics with display model+- fix(generate): route explicit profile variants through grammar_profile+- perf(adapters): extract shared vision patch-embed rebind helper (#1151)+- fix(generate): keep requested model id in /v1/generate grammar gate errors + variant-narrowing tests+- test(generate): handler-level grammar routing dispatch-vs-display tests+- fix(generate): split display vs dispatch model for grammar routing + chat gate ordering+- fix(generate): address review — grammar routing before profile gates + delta refresh+- fix(generate): route grammar requests to a non-speculative profile+- test(lighton_ocr): address CodeRabbit review on #1223+- perf(lighton_ocr): batch generate() across pages to fix #601 L4 throughput+## v0.6.6- chore(main): release 0.6.6diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex d85f5e415..2b94926b4 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.6 # x-release-please-version-appVersion: v0.6.6 # x-release-please-version+version: 0.6.7 # x-release-please-version+appVersion: v0.6.7 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex af00f973a..cb497e707 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -16,6 +16,20 @@ fast at render time.{{- if and $root.Values.workers.common.workerSidecar.enabled (not $root.Values.nats.config.jetstream.enabled) }}{{- fail "workers.common.workerSidecar.enabled=true requires nats.config.jetstream.enabled=true (the sidecar consumes JetStream)" }}{{- end }}+{{- $modelReadyTimeoutS := int (dig "modelReadyTimeoutSec" 900 $root.Values.workers.common) -}}+{{- if le $modelReadyTimeoutS 0 }}+{{- fail "workers.common.modelReadyTimeoutSec must be a positive integer number of seconds" }}+{{- end }}+{{- $workerLiveness := default dict $root.Values.workers.common.probes.liveness -}}+{{- $workerLivenessPeriodS := int (default 30 $workerLiveness.periodSeconds) -}}+{{- $workerLivenessFailures := int (default 36 $workerLiveness.failureThreshold) -}}+{{- if or (le $workerLivenessPeriodS 0) (le $workerLivenessFailures 0) }}+{{- fail "workers.common.probes.liveness.periodSeconds and failureThreshold must be positive when modelReadyTimeoutSec is configured" }}+{{- end }}+{{- $workerLivenessBudgetS := mul $workerLivenessPeriodS $workerLivenessFailures -}}+{{- if le $workerLivenessBudgetS $modelReadyTimeoutS }}+{{- fail (printf "workers.common.modelReadyTimeoutSec=%d must be lower than the Python worker liveness budget (%d * %d = %ds); increase workers.common.probes.liveness.failureThreshold/periodSeconds or lower modelReadyTimeoutSec" $modelReadyTimeoutS $workerLivenessFailures $workerLivenessPeriodS $workerLivenessBudgetS) }}+{{- end }}{{- range $poolName, $pool := .Values.workers.pools }}{{- if $pool.enabled }}{{- if not $pool.bundles }}@@ -122,6 +136,13 @@ spec:# Bundle for multi-bundle routing- name: SIE_BUNDLEvalue: {{ $bundle | quote }}+ # Shared cold-load timeout used by Python SGLang health waits.+ - name: SIE_MODEL_READY_TIMEOUT_S+ value: {{ $modelReadyTimeoutS | quote }}+ # Lets engine-backed adapters reject startup budgets kubelet would+ # kill before completion.+ - name: SIE_WORKER_LIVENESS_BUDGET_S+ value: {{ $workerLivenessBudgetS | quote }}# Device configuration (cpu if no GPU, cuda otherwise)- name: SIE_DEVICEvalue: {{ if gt (int $pool.gpu.count) 0 }}cuda{{ else }}cpu{{ end }}@@ -279,6 +300,12 @@ spec:value: {{ $queuePool | quote }}- name: SIE_BUNDLEvalue: {{ $bundle | quote }}+ # Shared cold-load timeout used by Rust EnsureModelReady IPC calls.+ - name: SIE_MODEL_READY_TIMEOUT_S+ value: {{ $modelReadyTimeoutS | quote }}+ # Same budget check on the Rust sidecar before it accepts the IPC timeout.+ - name: SIE_WORKER_LIVENESS_BUDGET_S+ value: {{ $workerLivenessBudgetS | quote }}- name: SIE_GATEWAY_URLvalue: {{ include "sie-cluster.gateway.internalUrl" $root | quote }}{{- if $root.Values.gateway.auth.tokenSecretName }}diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex c89e359dd..1ab5c1219 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -419,6 +419,16 @@ workers:# value: "5"extraEnv: []+ # -- Shared model cold-start/ready timeout in seconds. The chart renders+ # this into both containers as SIE_MODEL_READY_TIMEOUT_S: the Python worker+ # uses it as an SGLang startup-health timeout fallback, and the Rust+ # worker-sidecar uses it for EnsureModelReady IPC calls. Keep this >= any+ # SGLang profile adapter_options.loadtime.startup_timeout_s. Helm renders+ # SIE_WORKER_LIVENESS_BUDGET_S as periodSeconds * failureThreshold and both+ # Python and sidecar reject larger cold-start timeouts so kubelet does not+ # kill the pod before the cleanup-safe startup timeout can finish.+ modelReadyTimeoutSec: 900+# -- Liveness/readiness/startup probe timing for worker pods. The httpGet# path/port are contracts owned by the template: startup→/healthz (cheap,# process-alive), liveness→/livez (GPU-aware; restarts a wedged CUDA context,@@ -426,9 +436,9 @@ workers:# below are overridable. The liveness threshold must tolerate long GPU model# startup as well as brief contention: /livez runs a CUDA probe, so it can# block while an engine-backed adapter such as SGLang is loading. Keep this- # above SGLang's default 900s startup timeout (30s x 36 = 1080s) so the- # adapter reaches its cleanup-safe timeout instead of kubelet killing the pod- # mid-load.+ # above workers.common.modelReadyTimeoutSec (30s x 36 = 1080s by default)+ # so the adapter reaches its cleanup-safe timeout instead of kubelet killing+ # the pod mid-load.## Defaults are tightened to reduce kubelet probe-poll latency on the# cold-start path (issue #814):@@ -584,6 +594,9 @@ workers:intervalMs: 30000# -- Extra env vars passed through to the sidecar (rendered AFTER# the typed fields above, so any duplicate name overrides them).+ # Use workers.common.modelReadyTimeoutSec for cold-load timeout tuning so+ # Python SGLang health waits, Rust EnsureModelReady IPC calls, and worker+ # liveness-budget validation stay in sync.extraEnv: []# -- Resource requests/limits for the sidecar. Conservative# defaults; the heavy lifting still happens in the Python pod.diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex 0f13b7264..d5e65cd7c 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.6.6"+version = "0.6.7"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 8379bb549..5fbc23b65 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.6.6"+version = "0.6.7"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 1fd7096b7..85ca19a4c 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.6.6"+version = "0.6.7"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 6b1fb81ec..0b3772f9e 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.6.6"+version = "0.6.7"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 a0834919f..08516a95e 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.6.6"+version = "0.6.7"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 50b9a62f5..b5d0672cc 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.6.6"+version = "0.6.7"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex fa248c215..65ca914e9 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.6.6"+version = "0.6.7"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex 93ff0ea4d..63343c007 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.6.6"+version = "0.6.7"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 b15c750c9..e006340fa 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.6",+ "version": "0.6.7","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 301ce721a..cec871aff 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.6",+ "version": "0.6.7","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 6611b0a2d..d250bfb03 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.6",+ "version": "0.6.7","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 abdc7dcde..8ce6cf361 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.6",+ "version": "0.6.7","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 18cdd34ce..6d79cb5b2 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.6.6"+version = "0.6.7"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lockindex 4aad31cf9..f3f0ea315 100644--- a/packages/sie_gateway/Cargo.lock+++ b/packages/sie_gateway/Cargo.lock@@ -2960,7 +2960,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-gateway"-version = "0.6.6"+version = "0.6.7"dependencies = ["arc-swap","async-nats",diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex 795e32bce..0b93994de 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.6.6"+version = "0.6.7"edition = "2021"publish = falsediff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex ccfc873e6..3eeb1b9f8 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -2886,7 +2886,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.6.6"+ "version": "0.6.7"},"openapi": "3.1.0","paths": {diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex 23054f455..53e6d2e3f 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -213,12 +213,12 @@ fn env_static_queue_pools(key: &str) -> Vec<PoolSpec> {/// them. Empty alias/target pairs are skipped; aliases are stored lowercased/// because resolution lowercases the lookup.///-/// A target may be a bare model id (`Org/Model`) or a bundle-qualified spec-/// (`bundle:/Org/Model`). The bundle form lets an operator pin a precision /-/// profile bundle for a job — e.g. map `sql` to a BF16 bundle that avoids the-/// FP8 SQL-accuracy regression (ADR 0001), since the `:profile` variant suffix-/// is stripped before worker dispatch and so cannot itself route by precision.-/// `resolve_model_spec_with_aliases` (proxy.rs) applies the bundle.+/// A target may be a bare model id (`Org/Model`), a concrete profile variant+/// (`Org/Model:profile`), or a bundle-qualified spec (`bundle:/Org/Model`).+/// The bundle form lets an operator pin a precision / profile bundle for a job+/// — e.g. map `sql` to a BF16 bundle that avoids the FP8 SQL-accuracy+/// regression (ADR 0001). `resolve_model_spec_with_aliases` (proxy.rs) applies+/// the bundle and preserves concrete profile variants.fn build_model_aliases(overrides: HashMap<String, String>) -> HashMap<String, String> {let mut map: HashMap<String, String> = HashMap::new();// Built-in: the code-generation job → the model with a MEASUREDdiff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex c75b402f5..261347c50 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -175,6 +175,7 @@ fn worker_only_model_info(name: &str, loaded: bool) -> Value {max_sequence_length: None,max_output_tokens: None,grammar_capabilities: None,+ grammar_profile: None,tools_supported: None,code: false,sql: false,diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 572efb83c..54721dd05 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -1287,6 +1287,34 @@ async fn queue_mode_proxy(.into_response();}+ // Grammar routing: a grammar-constrained generate request runs on the+ // model's declared non-speculative ``grammar_profile`` variant (see+ // ``route_grammar_to_profile``). Resolve it HERE — before the capability and+ // profile-scoped LoRA gates below and the dispatch — and shadow ``model`` so+ // every gate validates against, and the work item dispatches to, the profile+ // the request will actually execute on. Non-generate / non-grammar requests+ // leave ``model`` unchanged (no allocation).+ let routed_model: Option<String> = if endpoint == "generate"+ && params+ .generate+ .as_ref()+ .and_then(|p| p.grammar.as_ref())+ .is_some()+ {+ let mut routed = model.to_string();+ route_grammar_to_profile(&state.model_registry, &mut routed);+ Some(routed)+ } else {+ None+ };+ // Preserve the requested (base) id for the DISPLAY surfaces — response body,+ // ``record_generation_success``, audit log. ``model`` below shadows to the+ // DISPATCH id (the routed variant); only that id changes which worker-loaded+ // model serves the request (NATS subject + work item). They are equal unless+ // routing fired.+ let display_model = model.to_string();+ let model: &str = routed_model.as_deref().unwrap_or(model);+// Grammar capability gate. After ``parse_grammar`` has accepted// the wire shape and enforced the safety caps, check the model's// YAML-declared ``capabilities.grammar`` list. Rejecting here (not@@ -1300,7 +1328,11 @@ async fn queue_mode_proxy(.get_model_info(model).as_ref().and_then(|m| m.info_extras.grammar_capabilities.clone());- if let Err(resp) = super::grammar::check_capability(g, caps.as_deref(), model) {+ // Look the capabilities up on the DISPATCH variant, but name the+ // requested (DISPLAY) model in the rejection so the client never+ // sees the internal ``:no-spec`` id (mirrors the chat path).+ if let Err(resp) = super::grammar::check_capability(g, caps.as_deref(), &display_model)+ {metrics::record_rejected_request_for_pool(pool, gpu, bundle, "grammar_capability");return resp;}@@ -1338,7 +1370,9 @@ async fn queue_mode_proxy(return (StatusCode::BAD_REQUEST,Json(json_openai_error(- format!("unknown profile '{profile_name}' for model '{model}'"),+ format!(+ "unknown profile '{profile_name}' for model '{display_model}'"+ ),oai_type::INVALID_REQUEST,Some("profile"),oai_code::INVALID_REQUEST,@@ -1356,7 +1390,9 @@ async fn queue_mode_proxy(return (StatusCode::BAD_REQUEST,Json(json_openai_error(- format!("unknown lora_adapter '{req_lora}' for model '{model}'"),+ format!(+ "unknown lora_adapter '{req_lora}' for model '{display_model}'"+ ),oai_type::INVALID_REQUEST,Some("lora_adapter"),oai_code::UNKNOWN_LORA_ADAPTER,@@ -1402,7 +1438,8 @@ async fn queue_mode_proxy(return super::sse::build_sse_response(super::sse::SseParams {state,work_publisher: work_publisher_arc,- model: model.to_string(),+ model: display_model.clone(),+ dispatch_model: model.to_string(),bundle: bundle.to_string(),engine: engine.to_string(),gpu: gpu.to_string(),@@ -1419,6 +1456,7 @@ async fn queue_mode_proxy(return queue_mode_streaming_generate(state,work_publisher_arc,+ display_model.as_str(),model,bundle,engine,@@ -1877,7 +1915,12 @@ pub(crate) enum StreamingDriverErr {pub(crate) async fn run_streaming_generate(state: &AppState,work_publisher: Arc<publisher::WorkPublisher>,+ // DISPLAY id (the requested model) — drives metric labels + the cancel+ // guard. ``dispatch_model`` below is the id actually published to NATS /+ // the work item (the grammar ``:no-spec`` variant when routing fired);+ // they are equal for non-routed requests. See ``route_grammar_to_profile``.model: &str,+ dispatch_model: &str,bundle: &str,engine: &str,gpu: &str,@@ -1931,7 +1974,7 @@ pub(crate) async fn run_streaming_generate(pool: pool.to_string(),machine_profile: gpu.to_string(),bundle: bundle.to_string(),- model: model.to_string(),+ model: dispatch_model.to_string(),},0,)@@ -1948,7 +1991,7 @@ pub(crate) async fn run_streaming_generate(admitted_worker_names.as_ref(),);let ring = state.registry.ring_snapshot_for_admitted(- model,+ dispatch_model,pool,gpu,bundle,@@ -1975,7 +2018,7 @@ pub(crate) async fn run_streaming_generate(pool: pool.to_string(),machine_profile: gpu.to_string(),bundle: bundle.to_string(),- model: model.to_string(),+ model: dispatch_model.to_string(),worker_id: worker_id.to_string(),},fallback_lane_worker_count,@@ -1996,7 +2039,7 @@ pub(crate) async fn run_streaming_generate(pool: pool.to_string(),machine_profile: gpu.to_string(),bundle: bundle.to_string(),- model: model.to_string(),+ model: dispatch_model.to_string(),},fallback_lane_worker_count,)@@ -2006,7 +2049,7 @@ pub(crate) async fn run_streaming_generate(// Capture this before the move into `publish_generate_streaming`.let was_direct_dispatched = matches!(target, publisher::PublishTarget::Worker { .. });let (request_id, rx, activity) = match work_publisher- .publish_generate_streaming(target, engine, bundle_config_hash, params)+ .publish_generate_streaming(target, model, engine, bundle_config_hash, params).await{Ok(r) => r,@@ -2061,7 +2104,7 @@ pub(crate) async fn run_streaming_generate(.as_ref().map(|g| g.max_new_tokens).unwrap_or(512);- let timeout_config = generation_timeout_config(state, model, params, max_new_tokens);+ let timeout_config = generation_timeout_config(state, dispatch_model, params, max_new_tokens);let first_chunk_timeout = timeout_config.first_chunk;let inter_chunk_timeout = timeout_config.inter_chunk;let effective_overall = timeout_config.overall;@@ -2527,7 +2570,11 @@ pub(crate) fn build_streaming_publish_failed_for_sse(async fn queue_mode_streaming_generate(state: &AppState,work_publisher: Arc<publisher::WorkPublisher>,+ // DISPLAY id (requested model) — response body, success metrics, audit log.model: &str,+ // DISPATCH id (grammar ``:no-spec`` variant when routed) — NATS subject ++ // work item. Equal to ``model`` for non-routed requests.+ dispatch_model: &str,bundle: &str,engine: &str,gpu: &str,@@ -2543,6 +2590,7 @@ async fn queue_mode_streaming_generate(state,work_publisher,model,+ dispatch_model,bundle,engine,gpu,@@ -4732,6 +4780,59 @@ async fn resolve_generation_route(})}+/// Rewrite a grammar-constrained request's dispatch model id to the model's+/// declared ``grammar_profile`` variant (e.g. ``no-spec``), in place.+///+/// Shared by every grammar-capable surface (``/v1/chat/completions`` and the+/// native ``/v1/generate`` path) so they route identically. NEXTN/MTP+/// speculative decoding bypasses SGLang's Outlines grammar FSM (leaks+/// out-of-schema keys, truncates mid-JSON), so a model whose default profile is+/// speculative points ``grammar_profile`` at a non-speculative profile. The+/// target is resolved off the request's *base* model+/// (``ModelRegistry::grammar_route_variant``), so an explicit sibling-variant+/// id (``…:a100-40gb``, also speculative) reroutes to ``{base}:{grammar_profile}``+/// too, and the grammar-safe variant itself is a no-op (same bundle/pool/lane —+/// only the worker-loaded model changes). Call this BEFORE the capability/LoRA+/// gates and resolve those gates against the routed variant: the variant+/// preserves the base capabilities but narrows the profile-scoped LoRA+/// allow-list, so a gate run against the base would accept an adapter the+/// dispatched profile does not serve. The rewritten (DISPATCH) id governs only+/// the NATS subject + work item; the caller keeps the requested (DISPLAY) id for+/// the response body, success metrics, and audit log. Invoke ONLY when a grammar+/// is present. Degrades to the requested id when no profile is declared or the+/// variant is absent (the cluster still serves on the requested profile — never+/// hang/5xx).+///+/// Both grammar-capable surfaces (``/v1/generate`` and ``/v1/chat/completions``)+/// now route *before* their capability/LoRA gates so those validate against the+/// routed variant. This is safe because grammar capabilities are model/task-level+/// (identical across a model's profiles), so the gate verdict is the same on the+/// base and the routed variant.+fn route_grammar_to_profile(+ registry: &crate::state::model_registry::ModelRegistry,+ model: &mut String,+) {+ use crate::state::model_registry::GrammarRoute;+ match registry.grammar_route_variant(model) {+ GrammarRoute::Rewrite(variant) => {+ tracing::info!(+ base = %model,+ variant = %variant,+ "routing grammar-constrained request to non-speculative profile variant"+ );+ *model = variant;+ }+ GrammarRoute::Keep => {}+ GrammarRoute::MissingVariant(grammar_profile) => {+ tracing::warn!(+ base = %model,+ grammar_profile = %grammar_profile,+ "declared grammar_profile variant not in registry; serving grammar on the requested profile"+ );+ }+ }+}+#[utoipa::path(post,path = "/v1/chat/completions",@@ -4858,8 +4959,24 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> ResErr(resp) => return resp,};- // -- per-request max_output_tokens cap from model config + grammar capability- if let Some(info) = state.model_registry.get_model_info(&model_name) {+ // Grammar routing (follow-up: chat-path gate ordering). Resolve the model's+ // declared ``grammar_profile`` variant and compute the DISPATCH id BEFORE the+ // capability/LoRA gates below, so the gates validate against — and the work+ // item dispatches to — the profile the request actually runs on. The+ // profile-scoped LoRA allow-list is narrowed per variant, so gating the base+ // would accept an adapter the ``:no-spec`` profile does not serve. The+ // DISPLAY id (``model_name``) stays the requested model for the response+ // body, success metrics, and audit log. Equal to ``model_name`` unless a+ // grammar is present and a variant exists. See ``route_grammar_to_profile``.+ let mut dispatch_model = model_name.clone();+ if params.grammar.is_some() {+ route_grammar_to_profile(&state.model_registry, &mut dispatch_model);+ }++ // -- per-request max_output_tokens cap from model config + grammar capability.+ // Gates resolve against the routed DISPATCH model so the profile-scoped+ // LoRA allow-list and capabilities match the profile that will serve.+ if let Some(info) = state.model_registry.get_model_info(&dispatch_model) {// Multi-LoRA: pre-validate the requested adapter against the// *selected profile's* advertised served-names — not the union// across profiles. The chat path has no explicit profile@@ -5117,6 +5234,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Resstate: state.as_ref(),work_publisher: work_publisher_arc,model: model_name.clone(),+ dispatch_model: dispatch_model.clone(),bundle: bundle.clone(),engine: engine.clone(),gpu: effective_machine_profile.clone(),@@ -5134,6 +5252,7 @@ pub async fn proxy_chat(State(state): State<Arc<AppState>>, req: Request) -> Res&state,work_publisher_arc,&model_name,+ &dispatch_model,&bundle,&engine,&effective_machine_profile,@@ -5698,6 +5817,9 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)state: state.as_ref(),work_publisher: work_publisher_arc,model: model_name.clone(),+ // /v1/completions does not accept grammar, so it never routes:+ // dispatch == display.+ dispatch_model: model_name.clone(),bundle: bundle.clone(),engine: engine.clone(),gpu: effective_machine_profile.clone(),@@ -5713,6 +5835,7 @@ pub async fn proxy_completions(State(state): State<Arc<AppState>>, req: Request)&state,work_publisher_arc,&model_name,+ &model_name,&bundle,&engine,&effective_machine_profile,@@ -6269,6 +6392,9 @@ pub async fn proxy_responses(State(state): State<Arc<AppState>>, req: Request) -&state,work_publisher_arc,&model_name,+ // /v1/responses does not accept grammar, so it never routes:+ // dispatch == display.+ &model_name,&bundle,&engine,&effective_machine_profile,@@ -6762,35 +6888,61 @@ fn canonicalize_with_aliases(if let Some(canonical) = canonicalize(id) {return Some(canonical);}- lookup_alias(aliases, id).map(|target| {+ lookup_alias(aliases, id).map(|alias| {// The alias target may be `bundle:/model`; the bundle is routed// separately (resolve_model_spec_with_aliases), so resolve only the// model portion here. A bare target leaves the model unchanged.// Resolve it like any path id: handles the SIE-safe "__"->"/" form and// canonical case-folding, falling back to the target model verbatim (so// model-not-found references the resolved model).- let (_bundle, model) = parse_model_spec(target);+ let model = alias_model_target(alias.target, alias.requested_profile);resolve_path_model_id(&model, &canonicalize)})}-/// Look up a job/friendly alias by its name, tolerating a `:profile` variant-/// suffix on the request.+struct AliasLookup<'a, 'b> {+ target: &'a String,+ requested_profile: Option<&'b str>,+}++/// Look up a job/friendly alias by its name, tolerating a `:profile` suffix.///-/// Tries the full (lowercased) id first, then the base before the first `:`, so-/// `sql:rtx-pro-6000` still resolves the `sql` alias. The `:profile` suffix-/// can't route by precision anyway (it's stripped before worker dispatch), so-/// dropping it for alias resolution is safe; the alias's own bundle is what-/// routes. (A real model id with a `:` resolves through `canonicalize` before-/// this is reached, so this never shadows one.)-fn lookup_alias<'a>(+/// Tries the full lowercased id first, then the base before the first `:`.+/// When the base alias matches, the suffix is returned so callers can apply it+/// to the alias target unless that target already names a concrete profile.+/// A real model id with a `:` resolves through `canonicalize` before this is+/// reached, so alias suffix handling never shadows a registered variant.+fn lookup_alias<'a, 'b>(aliases: &'a std::collections::HashMap<String, String>,- id: &str,-) -> Option<&'a String> {+ id: &'b str,+) -> Option<AliasLookup<'a, 'b>> {let key = id.to_ascii_lowercase();- aliases- .get(&key)- .or_else(|| key.split_once(':').and_then(|(base, _)| aliases.get(base)))+ if let Some(target) = aliases.get(&key) {+ return Some(AliasLookup {+ target,+ requested_profile: None,+ });+ }+ id.split_once(':')+ .filter(|(_, profile)| !profile.is_empty())+ .and_then(|(base, profile)| {+ let base_key = base.to_ascii_lowercase();+ aliases.get(&base_key).map(|target| AliasLookup {+ target,+ requested_profile: Some(profile),+ })+ })+}++fn alias_model_target(target: &str, requested_profile: Option<&str>) -> String {+ let (_bundle, model) = parse_model_spec(target);+ if model.contains(':') {+ return model;+ }+ requested_profile+ .filter(|profile| !profile.is_empty())+ .map(|profile| format!("{model}:{profile}"))+ .unwrap_or(model)}/// Resolve a request's model spec to `(bundle_override, canonical_model_name)`,@@ -6801,10 +6953,8 @@ fn lookup_alias<'a>(/// target, else the `__`->`/` form, else verbatim). The addition: an alias/// *target* may be a full `bundle:/org/model` spec, so an operator can pin a/// precision/profile bundle for a job alias — e.g. map `sql` to a BF16 bundle-/// that avoids the FP8 SQL-accuracy regression (ADR 0001), since the `:profile`-/// variant suffix is stripped before worker dispatch and cannot itself route by-/// precision. An explicit caller bundle (`somebundle:/sql`) always wins over the-/// alias's bundle.+/// that avoids the FP8 SQL-accuracy regression (ADR 0001). An explicit caller+/// bundle (`somebundle:/sql`) always wins over the alias's bundle.pub(crate) fn resolve_model_spec_with_aliases(aliases: &std::collections::HashMap<String, String>,spec: &str,@@ -6819,8 +6969,8 @@ pub(crate) fn resolve_model_spec_with_aliases(// `:profile`-tolerant lookup as the model-name resolution above, so a// `sql:profile` request adopts the `sql` alias bundle too.if req_bundle.is_empty() && canonicalize(&req_model).is_none() {- if let Some(target) = lookup_alias(aliases, &req_model) {- let (alias_bundle, _) = parse_model_spec(target);+ if let Some(alias) = lookup_alias(aliases, &req_model) {+ let (alias_bundle, _) = parse_model_spec(alias.target);return (alias_bundle, model_name);}}@@ -9661,17 +9811,43 @@ mod tests {#[test]fn test_resolve_model_spec_alias_with_profile_suffix_still_routes() {// A profile-suffixed alias request (`sql:rtx-pro-6000`) must still hit- // the `sql` alias and adopt its BF16 bundle; the (precision-inert)- // profile suffix is dropped for alias resolution.+ // the `sql` alias and adopt its BF16 bundle. The suffix applies to+ // the alias target unless the target already names a concrete profile.let mut aliases = std::collections::HashMap::new();aliases.insert("sql".to_string(), "bf16:/Qwen/Qwen3.6-27B".to_string());let (bundle, model) = resolve_model_spec_with_aliases(&aliases,"sql:rtx-pro-6000",- canon_of("Qwen/Qwen3.6-27B"),+ canon_of("Qwen/Qwen3.6-27B:rtx-pro-6000"),);assert_eq!(bundle, "bf16");- assert_eq!(model, "Qwen/Qwen3.6-27B");+ assert_eq!(model, "Qwen/Qwen3.6-27B:rtx-pro-6000");+ }++ #[test]+ fn test_resolve_model_spec_empty_alias_profile_suffix_does_not_fallback() {+ let mut aliases = std::collections::HashMap::new();+ aliases.insert("sql".to_string(), "bf16:/Qwen/Qwen3.6-27B".to_string());+ let (bundle, model) =+ resolve_model_spec_with_aliases(&aliases, "sql:", canon_of("Qwen/Qwen3.6-27B"));+ assert_eq!(bundle, "");+ assert_eq!(model, "sql:");+ }++ #[test]+ fn test_resolve_model_spec_alias_target_profile_wins_over_request_suffix() {+ let mut aliases = std::collections::HashMap::new();+ aliases.insert(+ "sql".to_string(),+ "bf16:/Qwen/Qwen3.6-27B:bf16-sql".to_string(),+ );+ let (bundle, model) = resolve_model_spec_with_aliases(+ &aliases,+ "sql:rtx-pro-6000",+ canon_of("Qwen/Qwen3.6-27B:bf16-sql"),+ );+ assert_eq!(bundle, "bf16");+ assert_eq!(model, "Qwen/Qwen3.6-27B:bf16-sql");}#[test]@@ -12647,6 +12823,278 @@ mod tests {assert_eq!(out.pending_demand_profile.as_deref(), Some("l4-spot"));}+ // ── grammar routing: dispatch vs display model ─────────────────+ //+ // The chat (`proxy_chat`) and native generate (`queue_mode_proxy`)+ // handlers route a grammar-constrained request to the model's declared+ // `:no-spec` `grammar_profile` variant for DISPATCH (NATS subject + work+ // item) while keeping the requested base id for DISPLAY (response body,+ // `record_generation_success`, audit log). Both read+ // `info_extras.grammar_profile` off the resolved model, then call+ // `route_grammar_to_profile`. These tests exercise that exact composition+ // against a live `ModelRegistry`, one level above the+ // `ModelRegistry::grammar_route_variant` unit test (which checks the+ // registry lookup in isolation). A full handler call cannot observe the+ // dispatch id — it is internal to the NATS publish, which the queue-only+ // gateway skips when `work_publisher` is `None`.++ /// An empty `ModelRegistry` with a `default` bundle advertising the+ /// `sentence_transformer` adapter — callers add their model configs. The+ /// temp dirs are read at construction only, so they can drop here.+ fn empty_registry() -> crate::state::model_registry::ModelRegistry {+ let bundles_dir = tempfile::TempDir::new().unwrap();+ let models_dir = tempfile::TempDir::new().unwrap();+ std::fs::write(+ bundles_dir.path().join("default.yaml"),+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.sentence_transformer\n",+ )+ .unwrap();+ crate::state::model_registry::ModelRegistry::new(+ bundles_dir.path(),+ models_dir.path(),+ true,+ )+ }++ fn grammar_routed_registry() -> crate::state::model_registry::ModelRegistry {+ use crate::types::model::{ModelConfig, ProfileConfig};+ use std::collections::HashMap as StdHashMap;++ let registry = empty_registry();+ let mk = || ProfileConfig {+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ };+ let mut profiles = StdHashMap::new();+ profiles.insert("default".to_string(), mk());+ // A non-`default` profile expands into the `org/g:no-spec` variant+ // entry that grammar routing dispatches to.+ profiles.insert("no-spec".to_string(), mk());+ // `tasks.generate.grammar_profile: no-spec` is what surfaces on+ // `info_extras.grammar_profile` — the field the handlers read.+ let tasks: serde_yaml::Value = serde_yaml::from_str(+ "generate:\n grammar_profile: no-spec\n capabilities:\n grammar: [json_schema]\n",+ )+ .unwrap();+ registry+ .add_model_config(ModelConfig {+ name: "org/g".to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: Some(tasks),+ })+ .unwrap();+ registry+ }++ /// Mirror the handler routing step: route the requested model in place.+ /// The variant is resolved off the base model inside+ /// `route_grammar_to_profile`. Returns `(display_id, dispatch_id)`.+ fn route_like_handler(+ registry: &crate::state::model_registry::ModelRegistry,+ requested: &str,+ ) -> (String, String) {+ let display = requested.to_string();+ let mut dispatch = display.clone();+ route_grammar_to_profile(registry, &mut dispatch);+ (display, dispatch)+ }++ #[test]+ fn test_grammar_request_dispatches_variant_display_stays_base() {+ let registry = grammar_routed_registry();+ // Precondition: the declared profile surfaces for the handlers to read.+ assert_eq!(+ registry+ .get_model_info("org/g")+ .and_then(|m| m.info_extras.grammar_profile.clone())+ .as_deref(),+ Some("no-spec"),+ );++ let (display, dispatch) = route_like_handler(®istry, "org/g");+ // DISPATCH id is rewritten to the `:no-spec` variant; the DISPLAY id+ // (response body / metrics / audit) stays the requested base model.+ assert_eq!(dispatch, "org/g:no-spec");+ assert_eq!(display, "org/g");+ }++ #[test]+ fn test_grammar_request_on_variant_id_does_not_double_route() {+ // A request that already names the variant must not re-route to+ // `org/g:no-spec:no-spec`: the variant entry clears its own+ // `grammar_profile` routing hint, so display == dispatch.+ let registry = grammar_routed_registry();+ let (display, dispatch) = route_like_handler(®istry, "org/g:no-spec");+ assert_eq!(dispatch, "org/g:no-spec");+ assert_eq!(display, "org/g:no-spec");+ }++ #[test]+ fn test_non_grammar_model_keeps_base_dispatch() {+ // A model that declares no `grammar_profile` never rewrites: the+ // dispatch id equals the display id.+ use crate::types::model::{ModelConfig, ProfileConfig};+ use std::collections::HashMap as StdHashMap;++ let registry = grammar_routed_registry();+ let mut profiles = StdHashMap::new();+ profiles.insert(+ "default".to_string(),+ ProfileConfig {+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ registry+ .add_model_config(ModelConfig {+ name: "org/plain".to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: None,+ })+ .unwrap();++ let (display, dispatch) = route_like_handler(®istry, "org/plain");+ assert_eq!(dispatch, "org/plain");+ assert_eq!(display, "org/plain");+ }++ #[test]+ fn test_grammar_gate_validates_against_narrowed_variant_adapters() {+ // The gate-ordering fix routes a grammar request to the `:no-spec`+ // variant BEFORE the LoRA gate runs, so the gate validates against the+ // variant's *narrowed* per-profile allow-list, not the base. Here the+ // `default` profile serves adapter `a1` and `no-spec` serves `a2`. A+ // grammar request dispatches to `org/g2:no-spec`, whose allow-list must+ // REJECT `a1` (served only by the base default profile) and accept `a2`.+ // Gating the base — the pre-fix behaviour — would wrongly accept `a1`.+ use crate::types::model::{ModelConfig, ProfileConfig};+ use std::collections::HashMap as StdHashMap;++ let registry = empty_registry();+ let default_profile = ProfileConfig {+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: Some(serde_json::json!({+ "loadtime": { "lora_paths": { "a1": "org/a1" } }+ })),+ extends: None,+ };+ let nospec_profile = ProfileConfig {+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: Some(serde_json::json!({+ "loadtime": { "lora_paths": { "a2": "org/a2" } }+ })),+ extends: None,+ };+ let mut profiles = StdHashMap::new();+ profiles.insert("default".to_string(), default_profile);+ profiles.insert("no-spec".to_string(), nospec_profile);+ let tasks: serde_yaml::Value =+ serde_yaml::from_str("generate:\n grammar_profile: no-spec\n").unwrap();+ registry+ .add_model_config(ModelConfig {+ name: "org/g2".to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: Some(tasks),+ })+ .unwrap();++ let (display, dispatch) = route_like_handler(®istry, "org/g2");+ assert_eq!(display, "org/g2");+ assert_eq!(dispatch, "org/g2:no-spec");++ let base_info = registry.get_model_info(&display).unwrap();+ let variant_info = registry.get_model_info(&dispatch).unwrap();+ // Base default profile serves `a1` — gating the base would accept it.+ assert!(matches!(+ validate_lora_for_profile(&base_info, "default", "a1"),+ LoraValidation::Ok+ ));+ // The routed variant's narrowed allow-list rejects `a1`, accepts `a2`.+ assert!(matches!(+ validate_lora_for_profile(&variant_info, "default", "a1"),+ LoraValidation::UnknownAdapter+ ));+ assert!(matches!(+ validate_lora_for_profile(&variant_info, "default", "a2"),+ LoraValidation::Ok+ ));+ }++ #[test]+ fn test_grammar_variant_absent_degrades_to_base() {+ // Safety contract: a declared `grammar_profile` whose variant is not in+ // the registry degrades to the base model (never hang / 5xx). Here+ // `grammar_profile: ghost` names a profile that is not defined, so no+ // `org/g3:ghost` variant entry is minted and routing keeps the base.+ use crate::types::model::{ModelConfig, ProfileConfig};+ use std::collections::HashMap as StdHashMap;++ let registry = empty_registry();+ let mut profiles = StdHashMap::new();+ profiles.insert(+ "default".to_string(),+ ProfileConfig {+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ let tasks: serde_yaml::Value =+ serde_yaml::from_str("generate:\n grammar_profile: ghost\n").unwrap();+ registry+ .add_model_config(ModelConfig {+ name: "org/g3".to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: Some(tasks),+ })+ .unwrap();++ // The declared (but undefined) profile is still surfaced...+ assert_eq!(+ registry+ .get_model_info("org/g3")+ .and_then(|m| m.info_extras.grammar_profile.clone())+ .as_deref(),+ Some("ghost"),+ );+ // ...yet routing degrades to base because `org/g3:ghost` does not exist.+ let (display, dispatch) = route_like_handler(®istry, "org/g3");+ assert_eq!(display, "org/g3");+ assert_eq!(dispatch, "org/g3");+ }+// ── /v1/chat/completions parsing + body composition ────────────fn _chat_body_min(model: &str) -> serde_json::Value {@@ -15263,6 +15711,7 @@ mod tests {max_sequence_length: None,max_output_tokens: None,grammar_capabilities: None,+ grammar_profile: None,tools_supported: None,code: false,sql: false,diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rsindex e3ea14f61..d9d91870b 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -76,7 +76,14 @@ pub enum SseEndpoint {pub struct SseParams<'a> {pub state: &'a AppState,pub work_publisher: Arc<WorkPublisher>,+ /// DISPLAY id (the requested model) — surfaced in the streamed chunk+ /// ``model`` field and the routing/timeout metric labels.pub model: String,+ /// DISPATCH id — the grammar ``:no-spec`` variant when routing fired,+ /// otherwise equal to ``model``. Governs ONLY the NATS subject + work item+ /// (worker selection / publish target) so the request runs on the profile+ /// that enforces the grammar. See ``proxy::route_grammar_to_profile``.+ pub dispatch_model: String,pub bundle: String,pub engine: String,pub gpu: String,@@ -101,6 +108,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {state,work_publisher,model,+ dispatch_model,bundle,engine,gpu,@@ -146,7 +154,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {pool: pool.clone(),machine_profile: gpu.clone(),bundle: bundle.clone(),- model: model.clone(),+ model: dispatch_model.clone(),},0,)@@ -163,7 +171,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {admitted_worker_names.as_ref(),);let ring = state.registry.ring_snapshot_for_admitted(- &model,+ &dispatch_model,&pool,&gpu,&bundle,@@ -180,7 +188,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {pool: pool.clone(),machine_profile: gpu.clone(),bundle: bundle.clone(),- model: model.clone(),+ model: dispatch_model.clone(),worker_id: worker_id.to_string(),},fallback_lane_worker_count,@@ -194,7 +202,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {pool: pool.clone(),machine_profile: gpu.clone(),bundle: bundle.clone(),- model: model.clone(),+ model: dispatch_model.clone(),},fallback_lane_worker_count,)@@ -204,7 +212,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {let was_direct_dispatched = matches!(target, publisher::PublishTarget::Worker { .. });let (request_id, outcome_rx, chunk_rx) = match work_publisher- .publish_generate_streaming_sse(target, &engine, &bundle_config_hash, &work_params)+ .publish_generate_streaming_sse(target, &model, &engine, &bundle_config_hash, &work_params).await{Ok(triple) => triple,@@ -241,7 +249,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {.unwrap_or(512);let timeout_config = crate::handlers::proxy::generation_timeout_config(state,- &model,+ &dispatch_model,&work_params,max_new_tokens,);diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex 339d4810d..73fc6d1cc 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -1583,9 +1583,14 @@ impl WorkPublisher {/// is appropriate; the gateway-side timeout taxonomy lives in/// ``handlers/proxy.rs`` (Phase F).#[allow(clippy::too_many_arguments)]+ /// ``display_model`` is the requested base id surfaced on all+ /// metric labels for this request; ``target.model()`` is the+ /// dispatch id (a ``:no-spec`` grammar variant when routing fired)+ /// used for the NATS subject / work item. Equal unless routing fired.pub async fn publish_generate_streaming(&self,target: PublishTarget,+ display_model: &str,engine: &str,bundle_config_hash: &str,params: &WorkParams,@@ -1622,6 +1627,9 @@ impl WorkPublisher {// that a fast worker can't beat us to the inbox.let (tx, rx) = oneshot::channel::<StreamOutcome>();let mut collector = StreamCollector::new(tx, model.clone(), pool.clone());+ // Metric labels surface the requested (display) id, never the+ // ``:no-spec`` dispatch variant (#1324).+ collector.display_model = display_model.to_string();collector.pool_fallback_subject = Some(pool_fallback_subject.clone());// Capture the activity handle before the collector moves into// ``pending_streams`` so the caller never has to re-look it up@@ -1696,6 +1704,7 @@ impl WorkPublisher {pub async fn publish_generate_streaming_sse(&self,target: PublishTarget,+ display_model: &str,engine: &str,bundle_config_hash: &str,params: &WorkParams,@@ -1731,6 +1740,9 @@ impl WorkPublisher {// subscriber.let (tx, rx) = oneshot::channel::<StreamOutcome>();let mut collector = StreamCollector::new(tx, model.clone(), pool.clone());+ // Metric labels surface the requested (display) id, never the+ // ``:no-spec`` dispatch variant (#1324).+ collector.display_model = display_model.to_string();collector.pool_fallback_subject = Some(pool_fallback_subject.clone());let chunk_rx = collector.install_chunk_tap();self.pending_streams.insert(request_id.clone(), collector);@@ -2032,7 +2044,7 @@ impl WorkPublisher {// the encoded bytes + the pool subject, bump the attempt// generation. We drop the entry lock before awaiting the// JetStream publish to avoid holding the DashMap shard.- let (subject, payload, generation, model, pool) = {+ let (subject, payload, generation, display_model, pool) = {let Some(mut entry) = self.pending_streams.get_mut(request_id) else {return Ok(RepublishOutcome::NotPossible);};@@ -2060,7 +2072,7 @@ impl WorkPublisher {{metrics::GENERATION_FALLBACK_REFUSED_TOTAL.with_label_values(&[- &metrics::sanitize_model_label(entry.model.as_str()),+ &metrics::sanitize_model_label(entry.display_model.as_str()),&metrics::sanitize_label(entry.pool.as_str()),"rate_limited",])@@ -2073,7 +2085,7 @@ impl WorkPublisher {subject,payload,gen,- entry.model.clone(),+ entry.display_model.clone(),entry.pool.clone(),)};@@ -2109,7 +2121,7 @@ impl WorkPublisher {Ok(ack) => {metrics::ROUTING_FALLBACK_TOTAL.with_label_values(&[- &metrics::sanitize_model_label(model.as_str()),+ &metrics::sanitize_model_label(display_model.as_str()),&metrics::sanitize_label(pool.as_str()),reason,])@@ -2405,14 +2417,14 @@ impl WorkPublisher {// so don't leave the client hanging until the first-chunk// timeout — surface a 429 immediately, mirroring the// pool-republish-failed arm below.- let (model, pool) = self+ let (display_model, pool) = self.pending_streams.get(&nak.request_id)- .map(|e| (e.value().model.clone(), e.value().pool.clone()))+ .map(|e| (e.value().display_model.clone(), e.value().pool.clone())).unwrap_or_else(|| ("unknown".to_string(), "unknown".to_string()));metrics::RATE_LIMIT_TOTAL.with_label_values(&[- &metrics::sanitize_model_label(&model),+ &metrics::sanitize_model_label(&display_model),&metrics::sanitize_label(&pool),"kv_pool_saturated",])@@ -2462,14 +2474,14 @@ impl WorkPublisher {// a concurrent terminal — avoids polluting the metric// with empty label series that don't render in// dashboards.- let (model, pool) = self+ let (display_model, pool) = self.pending_streams.get(&nak.request_id)- .map(|e| (e.value().model.clone(), e.value().pool.clone()))+ .map(|e| (e.value().display_model.clone(), e.value().pool.clone())).unwrap_or_else(|| ("unknown".to_string(), "unknown".to_string()));metrics::RATE_LIMIT_TOTAL.with_label_values(&[- &metrics::sanitize_model_label(&model),+ &metrics::sanitize_model_label(&display_model),&metrics::sanitize_label(&pool),"kv_pool_saturated",])diff --git a/packages/sie_gateway/src/queue/streaming.rs b/packages/sie_gateway/src/queue/streaming.rsindex 1ffb7f8c4..376005ecd 100644--- a/packages/sie_gateway/src/queue/streaming.rs+++ b/packages/sie_gateway/src/queue/streaming.rs@@ -259,7 +259,18 @@ pub struct StreamCollector {pub published_at: Instant,pub first_chunk_at: Option<Instant>,pub last_chunk_at: Option<Instant>,+ /// DISPATCH model id — the routed target (a ``:no-spec`` grammar+ /// variant when grammar routing fired, else the requested base).+ /// Kept for functional dispatch parity with ``PublishTarget.model``+ /// (NATS subject, republish, fallback token bucket). NEVER used to+ /// label metrics — use ``display_model`` for that.pub model: String,+ /// DISPLAY model id — the requested base model. Equal to ``model``+ /// unless grammar routing rewrote the dispatch target. All+ /// collector/publisher metric labels read this so no series carries+ /// the ``:no-spec`` variant (#1324). Defaults to ``model`` in+ /// [`Self::new`]; the publish path overrides it with the requested id.+ pub display_model: String,pub pool: String,/// Pulsed by ``apply()`` on every non-stale chunk. The HTTP handler/// uses this to reset the inter-chunk timer (§4.4.3). Wrapped in@@ -368,6 +379,7 @@ impl StreamCollector {published_at: Instant::now(),first_chunk_at: None,last_chunk_at: None,+ display_model: model.clone(),model,pool,activity: Arc::new(Notify::new()),@@ -520,7 +532,7 @@ impl StreamCollector {if chunk.kind != "chunk" {metrics::GENERATION_INVALID_CHUNKS.with_label_values(&[- &metrics::sanitize_model_label(self.model.as_str()),+ &metrics::sanitize_model_label(self.display_model.as_str()),&metrics::sanitize_label(self.pool.as_str()),"kind",])@@ -531,7 +543,7 @@ impl StreamCollector {if !t.is_finite() {metrics::GENERATION_INVALID_CHUNKS.with_label_values(&[- &metrics::sanitize_model_label(self.model.as_str()),+ &metrics::sanitize_model_label(self.display_model.as_str()),&metrics::sanitize_label(self.pool.as_str()),"ttft_nan",])@@ -543,7 +555,7 @@ impl StreamCollector {if !is_known_finish_reason(reason) {metrics::GENERATION_INVALID_CHUNKS.with_label_values(&[- &metrics::sanitize_model_label(self.model.as_str()),+ &metrics::sanitize_model_label(self.display_model.as_str()),&metrics::sanitize_label(self.pool.as_str()),"finish_reason",])@@ -565,7 +577,7 @@ impl StreamCollector {if self.abandoned_attempt_id.as_deref() == Some(chunk.attempt_id.as_str()) {metrics::GENERATION_STALE_ATTEMPT_CHUNKS.with_label_values(&[- &metrics::sanitize_model_label(self.model.as_str()),+ &metrics::sanitize_model_label(self.display_model.as_str()),&metrics::sanitize_label(self.pool.as_str()),]).inc();@@ -581,7 +593,7 @@ impl StreamCollector {Some(current) if current != &chunk.attempt_id => {metrics::GENERATION_STALE_ATTEMPT_CHUNKS.with_label_values(&[- &metrics::sanitize_model_label(self.model.as_str()),+ &metrics::sanitize_model_label(self.display_model.as_str()),&metrics::sanitize_label(self.pool.as_str()),]).inc();@@ -613,7 +625,7 @@ impl StreamCollector {if chunk.seq <= last {metrics::GENERATION_STALE_ATTEMPT_CHUNKS.with_label_values(&[- &metrics::sanitize_model_label(self.model.as_str()),+ &metrics::sanitize_model_label(self.display_model.as_str()),&metrics::sanitize_label(self.pool.as_str()),]).inc();@@ -631,7 +643,7 @@ impl StreamCollector {if chunk.seq > last + 1 {metrics::GENERATION_SEQ_GAP_CHUNKS.with_label_values(&[- &metrics::sanitize_model_label(self.model.as_str()),+ &metrics::sanitize_model_label(self.display_model.as_str()),&metrics::sanitize_label(self.pool.as_str()),]).inc();@@ -905,6 +917,94 @@ mod tests {);}+ /// #1324: collector chunk-metric labels must surface the DISPLAY+ /// (requested base) model, never the ``:no-spec`` dispatch variant a+ /// grammar request is routed to. Sets ``display_model`` != ``model``+ /// and checks the invalid-chunk and stale-attempt counters advance on+ /// the display series while the dispatch series stays flat.+ #[test]+ fn test_chunk_metrics_label_with_display_model_not_dispatch_variant() {+ let dispatch = "acme/grammar-model:no-spec";+ let display = "acme/grammar-model";+ let pool = "grammar_label_test_pool";++ // ── invalid-kind chunk → GENERATION_INVALID_CHUNKS[.., "kind"] ──+ let invalid_display_before = metrics::GENERATION_INVALID_CHUNKS+ .with_label_values(&[display, pool, "kind"])+ .get();+ let invalid_dispatch_before = metrics::GENERATION_INVALID_CHUNKS+ .with_label_values(&[dispatch, pool, "kind"])+ .get();++ let (tx, _rx) = oneshot::channel();+ let mut c = StreamCollector::new(tx, dispatch.to_string(), pool.to_string());+ c.display_model = display.to_string();+ let mut bad = _make_chunk("att-A", 0, "x", false);+ bad.kind = "garbage".to_string();+ assert_eq!(c.apply(bad), ChunkApplied::Stale);++ assert!(+ (metrics::GENERATION_INVALID_CHUNKS+ .with_label_values(&[display, pool, "kind"])+ .get()+ - invalid_display_before+ - 1.0)+ .abs()+ < f64::EPSILON,+ "display series should increment"+ );+ assert!(+ (metrics::GENERATION_INVALID_CHUNKS+ .with_label_values(&[dispatch, pool, "kind"])+ .get()+ - invalid_dispatch_before)+ .abs()+ < f64::EPSILON,+ "dispatch (:no-spec) series must NOT be labelled"+ );++ // ── stale-attempt chunk → GENERATION_STALE_ATTEMPT_CHUNKS ──+ let stale_display_before = metrics::GENERATION_STALE_ATTEMPT_CHUNKS+ .with_label_values(&[display, pool])+ .get();+ let stale_dispatch_before = metrics::GENERATION_STALE_ATTEMPT_CHUNKS+ .with_label_values(&[dispatch, pool])+ .get();++ let (tx2, _rx2) = oneshot::channel();+ let mut c2 = StreamCollector::new(tx2, dispatch.to_string(), pool.to_string());+ c2.display_model = display.to_string();+ // Latch attempt "att-A", then feed a chunk from a different attempt.+ assert_eq!(+ c2.apply(_make_chunk("att-A", 0, "hi", false)),+ ChunkApplied::Delta+ );+ assert_eq!(+ c2.apply(_make_chunk("att-B", 1, "x", false)),+ ChunkApplied::Stale+ );++ assert!(+ (metrics::GENERATION_STALE_ATTEMPT_CHUNKS+ .with_label_values(&[display, pool])+ .get()+ - stale_display_before+ - 1.0)+ .abs()+ < f64::EPSILON,+ "display series should increment"+ );+ assert!(+ (metrics::GENERATION_STALE_ATTEMPT_CHUNKS+ .with_label_values(&[dispatch, pool])+ .get()+ - stale_dispatch_before)+ .abs()+ < f64::EPSILON,+ "dispatch (:no-spec) series must NOT be labelled"+ );+ }+/// Per-chunk logprobs accumulate across the stream and surface as the/// aggregated ``StreamOutcome.logprobs`` (the non-streaming body's/// ``choices[0].logprobs.content``).diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex 6e9768c28..c0eb0d186 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -69,6 +69,26 @@ pub type AddModelConfigOutcome = (Vec<String>, Vec<String>, Vec<String>);const DEFAULT_MODEL_POOL: &str = "default";const MAX_POOL_NAME_LEN: usize = 128;+/// Outcome of resolving where a grammar-constrained request must dispatch.+///+/// A model declares ``tasks.generate.grammar_profile`` (surfaced as+/// ``ModelInfoExtras::grammar_profile`` on its *base* entry) naming the profile+/// that honours SGLang's Outlines grammar FSM. Speculative-decoding profiles+/// (NEXTN/MTP) bypass that FSM, so every grammar request — whatever id it names+/// — must land on ``{base}:{grammar_profile}``.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum GrammarRoute {+ /// Rewrite the dispatch id to this ``{base}:{grammar_profile}`` variant.+ Rewrite(String),+ /// No rewrite: the model declares no ``grammar_profile``, or the request+ /// already names the grammar-safe target variant.+ Keep,+ /// A ``grammar_profile`` is declared but its variant is absent from the+ /// registry (gateway/config skew). Degrade to the requested id; the caller+ /// should log it. Carries the declared profile name for the log line.+ MissingVariant(String),+}+#[derive(Debug, Clone, Default)]struct RegistrySnapshot {bundles: HashMap<String, BundleInfo>,@@ -413,6 +433,14 @@ impl ModelRegistry {profile_name: &str,) -> ModelInfoExtras {let mut narrowed = base.clone();+ // Clear the per-variant routing hint. A variant entry IS a concrete+ // profile already; keeping the hint here would make+ // ``grammar_route_variant`` target ``{base}:{p}:{grammar_profile}`` (a+ // profile-of-a-profile that doesn't exist). Grammar routing for an+ // explicit variant id instead resolves the hint off the *base* entry+ // (see ``base_grammar_profile``), so a sibling variant such as+ // ``…:a100-40gb`` still reroutes to ``{base}:{grammar_profile}``.+ narrowed.grammar_profile = None;if let Some(map) = base.profile_lora_adapters.as_ref() {let scoped = map.get(profile_name).cloned().unwrap_or_default();if scoped.is_empty() {@@ -841,6 +869,72 @@ impl ModelRegistry {|| snap.models.contains_key(model)}+ /// Resolve the dispatch model id for a grammar-constrained request.+ ///+ /// When a model declares ``tasks.generate.grammar_profile`` (surfaced as+ /// ``ModelInfoExtras::grammar_profile``), grammar requests must run on the+ /// ``{base}:{grammar_profile}`` profile variant rather than a speculative+ /// one — NEXTN/MTP speculative decoding bypasses SGLang's Outlines grammar+ /// FSM, so the constraint must be enforced on a profile that honours it+ /// (e.g. ``no-spec``).+ ///+ /// The routing target is resolved off the request's *base* model, so the+ /// rewrite fires regardless of which id the caller named:+ /// - base id (``Qwen/Qwen3.5-4B``) → ``…:no-spec``+ /// - sibling variant (``…:a100-40gb``, NEXTN) → ``…:no-spec``+ /// - target variant (``…:no-spec``) → ``Keep`` (already safe)+ /// - no ``grammar_profile`` declared → ``Keep``+ /// - target variant missing from registry → ``MissingVariant`` (degrade)+ ///+ /// Resolving off the base is what closes the explicit-variant bypass:+ /// variant entries clear their own ``grammar_profile`` hint (so they don't+ /// recursively re-route to ``{base}:{p}:{grammar_profile}``), so the hint is+ /// read from the base entry here. The caller only invokes this when a+ /// grammar is actually present.+ pub fn grammar_route_variant(&self, model: &str) -> GrammarRoute {+ let snap = self.snapshot.load();+ let Some((base, profile)) = Self::base_grammar_profile(&snap, model) else {+ return GrammarRoute::Keep;+ };+ let target = format!("{base}:{profile}");+ // The request already names the grammar-safe variant (compare canonical+ // ids so a differently-cased ``…:NO-SPEC`` is still recognised).+ if Self::canonical_model_name(&snap, model).as_deref() == Some(target.as_str()) {+ return GrammarRoute::Keep;+ }+ if snap.models.contains_key(&target) {+ GrammarRoute::Rewrite(target)+ } else {+ GrammarRoute::MissingVariant(profile)+ }+ }++ /// Resolve the *base* model id and its declared ``grammar_profile`` for a+ /// possibly-variant request id. The hint lives on the base entry only —+ /// variant entries clear it (see ``narrow_info_extras_to_profile``) so a+ /// variant never recursively re-routes — so an explicit sibling-variant id+ /// (e.g. ``…:a100-40gb``) resolves the *base's* profile here. Returns+ /// ``None`` when no ``grammar_profile`` is declared.+ fn base_grammar_profile(snap: &RegistrySnapshot, model: &str) -> Option<(String, String)> {+ let canonical = Self::canonical_model_name(snap, model)?;+ // Base entry carrying the hint.+ if let Some(gp) = snap+ .models+ .get(&canonical)+ .and_then(|e| e.info_extras.grammar_profile.clone())+ {+ return Some((canonical, gp));+ }+ // Otherwise it may be a variant ``{base}:{profile}`` (variants clear the+ // hint). Strip the trailing ``:profile`` and read the base entry's hint.+ let (base, _profile) = canonical.rsplit_once(':')?;+ let gp = snap+ .models+ .get(base)+ .and_then(|e| e.info_extras.grammar_profile.clone())?;+ Some((base.to_string(), gp))+ }+/// Resolve a caller-supplied model id to the registry's canonical/// stored name, case-insensitively. `model_exists` is already/// case-insensitive (it consults `model_names_lower`), so without@@ -1609,6 +1703,12 @@ impl ModelRegistry {// tighten the advertised set without a full reload.existing.grammar_capabilities = refreshed.grammar_capabilities;existing.tools_supported = refreshed.tools_supported;+ // ``grammar_profile`` is likewise derived from+ // ``tasks.generate`` — refresh it too so a delta that changes+ // the grammar-routing target takes effect without a full+ // reload (otherwise grammar_route_variant keeps routing to the+ // stale profile).+ existing.grammar_profile = refreshed.grammar_profile;}if config.max_sequence_length.is_some() {existing.max_sequence_length = refreshed.max_sequence_length;@@ -1712,6 +1812,166 @@ mod tests {assert!(registry.has_any_models(), "must report populated after add");}+ #[test]+ fn test_grammar_route_variant() {+ 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("default.yaml"),+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.sentence_transformer\n",+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);++ let mk = || ProfileConfig {+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ };+ let mut profiles = StdHashMap::new();+ profiles.insert("default".to_string(), mk());+ // A speculative sibling variant (mirrors the Qwen ``a100-40gb``/``h100``+ // profiles that run NEXTN) and the grammar-safe ``no-spec`` target each+ // expand into ``org/g:<profile>`` variant entries.+ profiles.insert("a100-40gb".to_string(), mk());+ profiles.insert("no-spec".to_string(), mk());+ // ``tasks.generate.grammar_profile: no-spec`` is the routing hint the+ // gateway reads off the base entry.+ let tasks: serde_yaml::Value =+ serde_yaml::from_str("generate:\n grammar_profile: no-spec\n").unwrap();+ registry+ .add_model_config(ModelConfig {+ name: "org/g".to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: Some(tasks),+ })+ .unwrap();++ // Base id + grammar → rewrite to the declared ``no-spec`` variant.+ assert_eq!(+ registry.grammar_route_variant("org/g"),+ GrammarRoute::Rewrite("org/g:no-spec".to_string())+ );+ // Case-insensitive: the base id resolves canonically before routing.+ assert_eq!(+ registry.grammar_route_variant("ORG/G"),+ GrammarRoute::Rewrite("org/g:no-spec".to_string())+ );+ // Explicit *sibling* variant (NEXTN) + grammar → still rewrite to+ // ``no-spec``. This is the bypass the fix closes: the variant entry+ // clears its own hint, so routing resolves it off the base.+ assert_eq!(+ registry.grammar_route_variant("org/g:a100-40gb"),+ GrammarRoute::Rewrite("org/g:no-spec".to_string())+ );+ // The grammar-safe target variant itself → no-op (no recursive reroute+ // to ``org/g:no-spec:no-spec``).+ assert_eq!(+ registry.grammar_route_variant("org/g:no-spec"),+ GrammarRoute::Keep+ );+ }++ #[test]+ fn test_grammar_route_variant_no_profile_keeps() {+ // A model that declares no ``grammar_profile`` never reroutes.+ 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("default.yaml"),+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.sentence_transformer\n",+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);++ let mut profiles = StdHashMap::new();+ profiles.insert(+ "default".to_string(),+ ProfileConfig {+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ registry+ .add_model_config(ModelConfig {+ name: "org/n".to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: None,+ })+ .unwrap();++ assert_eq!(registry.grammar_route_variant("org/n"), GrammarRoute::Keep);+ }++ #[test]+ fn test_grammar_route_variant_missing_target_degrades() {+ // ``grammar_profile`` names a profile whose variant is absent from the+ // registry (gateway/config skew): degrade with the declared name so the+ // caller can log it, rather than rerouting to a non-existent variant.+ 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("default.yaml"),+ "name: default\npriority: 10\nadapters:\n - sie_server.adapters.sentence_transformer\n",+ )+ .unwrap();+ let registry = ModelRegistry::new(&bundles_dir, &models_dir, true);++ // Only a ``default`` profile exists, so no ``org/g:ghost`` variant is+ // ever minted — but the hint points at ``ghost``.+ let mut profiles = StdHashMap::new();+ profiles.insert(+ "default".to_string(),+ ProfileConfig {+ adapter_path: Some("sie_server.adapters.sentence_transformer:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ let tasks: serde_yaml::Value =+ serde_yaml::from_str("generate:\n grammar_profile: ghost\n").unwrap();+ registry+ .add_model_config(ModelConfig {+ name: "org/g".to_string(),+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ max_sequence_length: None,+ tasks: Some(tasks),+ })+ .unwrap();++ assert_eq!(+ registry.grammar_route_variant("org/g"),+ GrammarRoute::MissingVariant("ghost".to_string())+ );+ }+#[test]fn test_add_model_config_rejects_invalid_profile_name_live_path() {// H-medium: the live delta path (`add_model_config` →diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rsindex 23210dc78..368ba536c 100644--- a/packages/sie_gateway/src/state/worker_registry.rs+++ b/packages/sie_gateway/src/state/worker_registry.rs@@ -12,17 +12,6 @@ use crate::types::{ClusterStatus, ModelInfo, WorkerHealth, WorkerInfo, WorkerState, WorkerStatusMessage,};-/// Strip a `:profile` routing suffix down to the base model id.-///-/// Profile variants live in the model registry as `format!("{base}:{profile}")`-/// (see `model_registry::expand_*`), but workers advertise only the base-/// model name in their `loaded_models`. HuggingFace model ids never-/// contain `:`, so the first `:` unambiguously separates the base id from-/// the profile. Returns `model` unchanged when there is no suffix.-fn base_model_id(model: &str) -> &str {- model.split_once(':').map_or(model, |(base, _)| base)-}-/// Rate-limit gate for the duplicate-worker-name warning, in whole/// seconds since process start. `ring_snapshot_for` runs on the/// per-request hot path, so an unconditional `warn!` on a persistent@@ -349,14 +338,13 @@ impl WorkerRegistry {/// [`resolve_queue_route_matching`]. Used by the proxy to build/// per-request HRW snapshots.///- /// A `model:profile` request is matched against the **base** model- /// id: workers advertise only base model names in `loaded_models`- /// (the `:profile` variant is a registry-only routing concept — the- /// adapter is selected per-request, not per-loaded-model), so without- /// stripping the suffix a `model:profile` request would never find an- /// eligible worker and would always fall through to the pool subject- /// (mislabelled `unhealthy_skipped`). HF model ids never contain `:`,- /// so the suffix split is unambiguous.+ /// A `model:profile` request is matched as its own model id. The server+ /// loader expands non-default profiles into concrete `base:profile`+ /// configs with profile-specific SGLang launch args, so collapsing the+ /// suffix here would direct-dispatch to a worker that only has the base+ /// model resident and can silently launch the wrong precision/profile.+ /// If no worker has the variant loaded yet, the request falls through to+ /// the pool subject and lazy-loads that concrete variant.#[cfg(test)]pub fn dispatch_workers_for(&self,@@ -385,7 +373,6 @@ impl WorkerRegistry {bundle_config_hash: &str,admitted_worker_names: Option<&HashSet<String>>,) -> Vec<WorkerState> {- let base_model = base_model_id(model);let snap = self.snapshot.load();snap.all_healthy.iter()@@ -397,7 +384,7 @@ impl WorkerRegistry {&& w.machine_profile.eq_ignore_ascii_case(machine_profile)&& w.bundle.eq_ignore_ascii_case(bundle)&& bundle_config_hash_matches(&w.bundle_config_hash, bundle_config_hash)- && w.models.iter().any(|m| m.eq_ignore_ascii_case(base_model))+ && w.models.iter().any(|m| m.eq_ignore_ascii_case(model))}).cloned().collect()@@ -1215,17 +1202,8 @@ mod tests {// ── dispatch_workers_for / profile-variant routing ─────────────- #[test]- fn test_base_model_id_strips_profile_suffix() {- assert_eq!(base_model_id("BAAI/bge-m3"), "BAAI/bge-m3");- assert_eq!(base_model_id("BAAI/bge-m3:fast"), "BAAI/bge-m3");- // Only the first `:` separates the profile; HF ids never contain `:`.- assert_eq!(base_model_id("org/model:a:b"), "org/model");- assert_eq!(base_model_id(""), "");- }-#[tokio::test]- async fn test_dispatch_workers_for_profile_variant_matches_base_worker() {+ async fn test_dispatch_workers_for_profile_variant_requires_variant_worker() {let reg = registry();// A worker advertising only the *base* model name in a named pool.let mut msg = make_msg(true);@@ -1234,19 +1212,39 @@ mod tests {msg.loaded_models = vec!["BAAI/bge-m3".into()];reg.update_worker("http://w1:8080", msg).await;- // A `:profile` request must direct-dispatch to the base-model- // worker rather than fall through to the pool.+ // A `:profile` request must not direct-dispatch to the base-model+ // worker. The profile variant carries its own launch args.let direct =reg.dispatch_workers_for("BAAI/bge-m3:fast", "default", "l4-spot", "default", "");- assert_eq!(direct.len(), 1, "profile variant should match base worker");- assert_eq!(direct[0].name, "w1");+ assert!(+ direct.is_empty(),+ "profile variant must wait for/load a worker with that exact variant"+ );// The bare base id still works (regression guard).let base = reg.dispatch_workers_for("BAAI/bge-m3", "default", "l4-spot", "default", "");assert_eq!(base.len(), 1);- // The ring snapshot (built from the same filter) is non-empty,- // so HRW can pick a worker for the profile variant.+ // The ring snapshot (built from the same filter) stays empty+ // until the concrete variant is reported loaded.+ let ring = reg.ring_snapshot_for("BAAI/bge-m3:fast", "default", "l4-spot", "default", "");+ assert_eq!(ring.len(), 0);++ let mut msg = make_msg(true);+ msg.name = "w1".into();+ msg.pool_name = "default".into();+ msg.loaded_models = vec!["BAAI/bge-m3:fast".into()];+ reg.update_worker("http://w1:8080", msg).await;++ let direct =+ reg.dispatch_workers_for("BAAI/bge-m3:fast", "default", "l4-spot", "default", "");+ assert_eq!(+ direct.len(),+ 1,+ "loaded profile variant should match exactly"+ );+ assert_eq!(direct[0].name, "w1");+let ring = reg.ring_snapshot_for("BAAI/bge-m3:fast", "default", "l4-spot", "default", "");assert_eq!(ring.len(), 1);diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex c86f202d3..0fd8471aa 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -23,6 +23,14 @@ pub struct ModelInfoExtras {/// ``generate`` task; empty ``Vec`` when grammar is explicitly/// disabled.pub grammar_capabilities: Option<Vec<String>>,+ /// ``tasks.generate.grammar_profile`` from the model YAML — the name of a+ /// profile that grammar-constrained requests must be served on. When set,+ /// the chat/completions/generate handlers rewrite a grammar request's model+ /// id to the ``{model}:{grammar_profile}`` variant so it runs on a profile+ /// that enforces the grammar correctly (e.g. ``no-spec`` — speculative+ /// decoding bypasses SGLang's Outlines FSM). ``None`` when the model has no+ /// ``generate`` task or does not declare the field (no rewrite).+ pub grammar_profile: Option<String>,/// ``tasks.generate.capabilities.tools`` from the model YAML — a/// single boolean advertising whether the model supports/// OpenAI-style tool calling. The chat completion handler gates@@ -171,6 +179,13 @@ impl ModelInfoExtras {}).unwrap_or_default();extras.grammar_capabilities = Some(grammar);+ // ``tasks.generate.grammar_profile: <name>`` — optional profile+ // that grammar requests are routed to (the gateway rewrites the+ // model id to ``{model}:{name}``). Absent => no rewrite.+ extras.grammar_profile = gen+ .get("grammar_profile")+ .and_then(|v| v.as_str())+ .map(String::from);// ``capabilities.tools: bool`` defaults to ``false``// — mirrors :class:`GenerateCapabilities` in the// worker config. Absent ``capabilities`` block also@@ -264,6 +279,7 @@ impl ModelInfoExtras {max_sequence_length: config.max_sequence_length,max_output_tokens: None,grammar_capabilities: None,+ grammar_profile: None,tools_supported: None,code: false,sql: false,diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex aadc6a5d8..c7b31635f 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.6.6"+version = "0.6.7"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml b/packages/sie_server/models/Qwen__Qwen3.5-4B.yamlindex 593b63241..4b133306a 100644--- a/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3.5-4B.yaml@@ -17,6 +17,14 @@ tasks:# raise this on a per-profile basis.context_length: 8192max_output_tokens: 4096+ # Route grammar-constrained requests (response_format / grammar) to the+ # non-speculative variant. The default/a100/h100 profiles run NEXTN+ # speculative decoding for free-text throughput, but NEXTN bypasses SGLang's+ # Outlines grammar FSM (leaks out-of-schema keys, truncates mid-JSON —+ # verified on L4). The `no-spec` profile (speculative off, same Outlines+ # backend) enforces the grammar correctly; the gateway rewrites grammar+ # requests to `Qwen/Qwen3.5-4B:no-spec` so free-text keeps NEXTN.+ grammar_profile: no-speccapabilities:# NOTE: scoped to what the production backend (``outlines``, set# per-profile under ``adapter_options.loadtime``) actually supportsdiff --git a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml b/packages/sie_server/models/Qwen__Qwen3.6-27B.yamlindex 02e4b9469..5a58b7968 100644--- a/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml+++ b/packages/sie_server/models/Qwen__Qwen3.6-27B.yaml@@ -14,16 +14,10 @@ inputs:tasks:generate:# Native context length is 262,144 tokens (YaRN extends to ~1M).- # Default to 4096 here — this matches the empirically-calibrated- # reference point in the profile comments below- # (mem_fraction_static=0.93, weight 51.05 GB + kvcache 11.63 GB).- # 8192 was the original optimistic default but SGLang's- # init_memory_pool refused to fit it inside the conservative- # mem_fraction envelope on H100-80GB even when bumped to 0.97 —- # NEXTN speculative-decoding draft KV pushes the total past the- # available headroom. Raise both context_length AND- # mem_fraction_static together if you need longer contexts;- # benchmarking and prod requests today fit comfortably in 4096.+ # Keep the base model contract at the measured 4K window. The managed+ # tester rollout exposes the 32K surface only through the+ # ``:rtx-pro-6000`` variant below, whose profile-level ``max_seq_length``+ # is promoted into the generated variant config by the loader.context_length: 4096max_output_tokens: 4096capabilities:@@ -42,12 +36,9 @@ tasks:code: true# CAVEAT: this flag is precision-agnostic, but FP8 weight quant regresses# SQL ~13pts (Spider 0.71 BF16 -> 0.58 FP8, same-subset control; see the- # ADR + baseline). Code/tools/MC are FP8-safe. The default rtx-pro-6000- # profile is FP8, so route SQL-critical traffic to the BF16+NEXTN variant- # (the 96GB card fits it). The `:profile` variant suffix can't route by- # precision (it's stripped before worker dispatch), so deploy the BF16- # variant under a distinct bundle and point the `sql` job alias at it via- # a bundle-qualified target, e.g.+ # ADR + baseline). Code/tools/MC are FP8-safe. The RTX FP8 profile below is+ # for code/tools/general. Route SQL-critical traffic to the BF16 profile+ # or a BF16 bundle-qualified alias, e.g.# SIE_GATEWAY_MODEL_ALIASES={"sql":"<bf16-bundle>:/Qwen/Qwen3.6-27B"}# (gateway resolve_model_spec_with_aliases; see ADR 0001).sql: true@@ -72,7 +63,7 @@ tasks:type: stringrequired: [answer]max_sequence_length: 4096-# ── KV-cache math (placeholder, pending Modal calibration) ──+# ── KV-cache math ──## Qwen3.6-27B layer breakdown (per model card / config.json):# * 64 layers in a 16 × (3 × DeltaNet + 1 × GatedAttention) pattern@@ -80,44 +71,26 @@ max_sequence_length: 4096# * 48 recurrent Gated-DeltaNet layers — managed by SGLang's mamba# scheduler under ``--mamba-scheduler-strategy extra_buffer``#-# BF16 weights ≈ 27e9 × 2 B ≈ 54 GB before activations / KV.-# * L4 (22 GB) → infeasible-# * A100-40GB (40 GB) → infeasible BF16; would need FP8 or TP2-# * H100-80GB → primary target (single-GPU, BF16)-# * H100×2 (160 GB) → for context >32k or large concurrencies-#-# ``kv_budget_tokens`` is a conservative analytical placeholder pending-# the first /get_server_info dump from tools/smoke_qwen36_27b.py on-# Modal. Re-calibrate from the empirical token_capacity before relying-# on these numbers in production.+# BF16 weights ≈ 27e9 × 2 B ≈ 54 GB before activations / KV. FP8 weight+# quantization cuts the VRAM weight footprint to ~27 GB but still requires+# enough host RAM to read the BF16 checkpoint before quantization.+# * L4 (24 GB) → infeasible+# * A100-40GB (40 GB) → infeasible BF16; FP8/TP2 only+# * H100-80GB → BF16 speculative profiles at the measured 4K window+# * RTX PRO 6000 96GB → FP8 + NEXTN profile with a 32K variant surfaceprofiles:- # L4 / A100-40GB profiles intentionally omitted — Qwen3.6-27B's BF16- # weights (~54 GB) do not fit. Add an FP8 or TP2 profile if those- # tiers become required.+ # L4 / A100-40GB BF16 profiles intentionally omitted — Qwen3.6-27B's BF16+ # weights (~54 GB) do not fit.default:max_batch_tokens: 16384compute_precision: bfloat16adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter- # Conservative H100-80GB placeholder pending the first- # /get_server_info dump from tools/smoke_qwen36_27b.py on Modal.- # Empirical reference point (2026-05-27 smoke, mem_fraction_static=0.93,- # context_length=4096, no-spec): SGLang reported- # ``weight=51.05 GB, kvcache=11.63 GB, token_capacity=190,543``.- # Sizing here at ~1/12 of that capacity to leave room for NEXTN- # draft KV + grammar/Outlines compile arena once spec is re-enabled.- # Re-calibrate after a smoke run on this profile's actual settings.- # Halved from 16384 to leave more H100-80GB headroom for the NEXTN- # draft activation arena. 8192 KV slots × ~64 KB/token ≈ 0.5 GB —- # plenty for the realistic per-request concurrency on this profile.+ # H100-80GB speculative launch shape carried forward at the measured 4K+ # base-model context. The managed cluster routes 32K 27B generation to+ # ``rtx-pro-6000``.kv_budget_tokens: 8192adapter_options:loadtime:- # 0.95 paired with ``context_length: 4096`` + the *smaller*- # NEXTN draft below (num_steps=2 / num_draft_tokens=2 vs the- # 3/4 model-card default). The 0.93+default-draft cell still- # OOM'd ``init_memory_pool`` because verification batch grows- # with num_steps × num_draft_tokens; halving both shrinks the- # activation arena enough to fit.mem_fraction_static: 0.95served_model_name: Qwen/Qwen3.6-27Bdisable_cuda_graph: true@@ -125,15 +98,9 @@ profiles:grammar_backend: outlinesreasoning_parser: qwen3tool_call_parser: qwen3_coder- # MTP/NEXTN per the Qwen3.x model-card recipe (SGLang implements- # NEXTN under the EAGLE codepath; ``/server_info`` reports- # ``speculative_algorithm: EAGLE``). Smaller-draft variant- # (num_steps=2 / num_draft_tokens=2 vs the model-card 3/4) so- # the verification batch fits inside H100-80GB at ctx=4096 +- # mfs=0.95. The 3/4 default reliably OOM'd- # ``init_memory_pool`` even at mfs=0.97 — the trade is a- # slightly smaller speculative window for the ability to fit at- # all. Re-tune (or re-enable 3/4) once FP8 / TP=2 is wired up.+ # MTP/NEXTN per the Qwen3.x model-card recipe. Keep the smaller 2/2+ # H100 draft shape from main; the larger 3/4 draft remains on the+ # RTX-PRO-6000 FP8 profile.speculative:enabled: truealgorithm: nextn@@ -141,9 +108,9 @@ profiles:eagle_topk: 1num_draft_tokens: 2# ``--mamba-scheduler-strategy extra_buffer`` is the required- # pair-flag for NEXTN spec on the hybrid Gated-DeltaNet- # architecture. With spec disabled it's also harmless to keep,- # so we leave it for when spec is re-enabled.+ # pair-flag for NEXTN spec on the hybrid Gated-DeltaNet architecture.+ # Keep it paired with ``--disable-overlap-schedule`` for all NEXTN+ # launch profiles.extra_launch_args:- "--mamba-scheduler-strategy"- "extra_buffer"@@ -156,19 +123,19 @@ profiles:temperature: 0.7top_p: 0.8presence_penalty: 1.5+ min_new_tokens: 10stop_tokens:- "<|im_end|>"h100:max_batch_tokens: 32768compute_precision: bfloat16adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter- # Same H100-80GB target as ``default``; this profile widens- # ``max_batch_tokens`` for batch-heavy workloads once calibration- # confirms KV headroom.+ # Same H100-80GB target as ``default`` with the model-card 3/4 NEXTN draft+ # preserved from main. Keep the public H100 context at the measured 4K+ # base-model window until a separate 32K H100 smoke lands.kv_budget_tokens: 32768adapter_options:loadtime:- # Same as ``default`` — see that profile's mfs comment.mem_fraction_static: 0.93served_model_name: Qwen/Qwen3.6-27Bdisable_cuda_graph: true@@ -197,6 +164,7 @@ profiles:temperature: 0.7top_p: 0.8presence_penalty: 1.5+ min_new_tokens: 10stop_tokens:- "<|im_end|>"# RTX PRO 6000 (96 GB GDDR7, Blackwell Server Edition, sm_120) profile.@@ -226,12 +194,17 @@ profiles:max_batch_tokens: 32768compute_precision: bfloat16adapter_path: sie_server.adapters.sglang.generation:SGLangGenerationAdapter- # FP8 weights (~27 GB) + 96 GB total leaves generous KV/draft headroom;- # start conservative and raise after the first /get_server_info dump on- # the actual RTX-PRO-6000 smoke.- kv_budget_tokens: 16384+ # FP8 weights (~27 GB) + 96 GB total leaves KV/draft headroom for two+ # 32K-context admissions on the validated RTX-PRO-6000 serving path.+ kv_budget_tokens: 65536adapter_options:loadtime:+ # Profile-scoped launch/context override. ``loadtime`` already+ # overrides adapter constructor kwargs; loader variant expansion+ # also promotes this into the generated ``:rtx-pro-6000`` model's+ # ``tasks.generate.context_length`` / ``max_sequence_length`` so+ # the 32K contract is attached to the RTX variant, not the base model.+ max_seq_length: 32768# 0.90 is a conservative starting point — FP8 weights free enough# memory that the 3/4 NEXTN verification batch should fit with room# to spare. Iterate upward (smoke ``--mem-fraction-static``) once the@@ -321,5 +294,6 @@ profiles:temperature: 0.7top_p: 0.8presence_penalty: 1.5+ min_new_tokens: 10stop_tokens:- "<|im_end|>"diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex bea892431..9ad40182b 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.6"+ "version": "0.6.7"},"paths": {"/": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex 814009b23..797683315 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.6.6"+version = "0.6.7"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }diff --git a/packages/sie_server/src/sie_server/adapters/_vision_patch_embed.py b/packages/sie_server/src/sie_server/adapters/_vision_patch_embed.pynew file mode 100644index 000000000..0d8a86179--- /dev/null+++ b/packages/sie_server/src/sie_server/adapters/_vision_patch_embed.py@@ -0,0 +1,123 @@+from __future__ import annotations++import logging+import math++import torch+import torch.nn.functional as F++logger = logging.getLogger(__name__)+++def rebind_vision_patch_embed(model: torch.nn.Module | None, label: str) -> None:+ """Rebind a VLM vision patch-embed Conv to an equivalent ``F.linear``.++ Several VLM vision encoders embed patches with a non-overlapping conv+ (``kernel == stride``) applied to *pre-patched* input ``(num_patches, …)``.+ On CUDA cuDNN dispatches that as ~one tiny kernel launch per patch (tens of+ thousands per page), so the GPU sits idle while a single CPU thread launches+ kernels — the dominant cost of every request. The op is mathematically a+ per-patch linear projection, so rebinding ``conv.forward`` to a single+ ``F.linear`` GEMM (same weights) is numerically identical and orders of+ magnitude faster.++ Discovers the patch-embed by structure (the unique vision conv with+ ``kernel == stride`` and RGB input, ``in_channels <= 4``) rather than a+ hardcoded attribute path, so it handles every affected backbone (Qwen2/2.5/3-VL+ and GLM-4V Conv3d, PaddleOCR-VL Conv2d). Self-validating: a small synthetic+ patch batch is run through both the original conv and the matmul at load time,+ and the fast path is kept only if the outputs match (within bf16 rounding);+ otherwise a warning is logged and the original conv is left in place. No+ weights are changed and the check stays off the request path.++ Best-effort and idempotent in effect: on any structural mismatch or numeric+ divergence it logs and returns, leaving the original conv untouched.++ Args:+ model: the loaded adapter model (the full ``nn.Module`` tree is scanned).+ label: short adapter tag used only as a log prefix, e.g. ``"glm_ocr"``.+ """+ if model is None:+ return++ # Non-overlapping convs (kernel == stride) inside the vision tower. The patch+ # embed is one such conv, but the tower may have others — e.g. a spatial-merge+ # ``downsample`` conv (also kernel == stride). The patch embed is the+ # pathological one (~one tiny kernel launch per patch); disambiguate by input+ # channels: the patch embed consumes raw image channels (RGB, <= 4), while+ # merge/downsample convs consume the hidden dim.+ convs: list[tuple[str, torch.nn.Conv2d | torch.nn.Conv3d]] = []+ for name, mod in model.named_modules():+ lname = name.lower()+ if (+ isinstance(mod, (torch.nn.Conv2d, torch.nn.Conv3d))+ and tuple(mod.kernel_size) == tuple(mod.stride)+ and ("vis" in lname or "patch" in lname or "embed" in lname)+ ):+ convs.append((name, mod))++ # Identify the patch embed strictly by structure: it is the only vision conv+ # that consumes raw image channels (RGB). Any other kernel==stride conv (e.g.+ # a spatial-merge downsample) consumes the hidden dim. If this is not unique we+ # do not guess — leave the original conv in place rather than risk rebinding a+ # module whose runtime input is not per-patch shaped (fast_forward assumes one+ # flattened patch per row).+ patch = [c for c in convs if c[1].in_channels <= 4]+ if len(patch) != 1:+ logger.warning(+ "[%s] patch-embed rebind skipped: expected exactly one RGB-input (in_channels<=4) "+ "vision conv, found %d among %s",+ label,+ len(patch),+ [n for n, _ in convs],+ )+ return++ name, conv = patch[0]+ out_ch = conv.out_channels+ spatial_dims = len(conv.kernel_size)+ in_features = conv.in_channels * math.prod(conv.kernel_size)+ weight_2d = conv.weight.reshape(out_ch, in_features) # view; shares storage, no copy+ bias = conv.bias++ def fast_forward(x: torch.Tensor) -> torch.Tensor:+ n = x.shape[0]+ out = F.linear(x.reshape(n, -1).to(weight_2d.dtype), weight_2d, bias)+ return out.reshape(n, out_ch, *([1] * spatial_dims))++ # Validate equivalence on a small synthetic patch batch at load time (off the+ # request path) before swapping. The op is mathematically a matmul over the+ # flattened patch, so any divergence beyond bf16 rounding means the shape+ # assumption is wrong — keep the original conv if so.+ with torch.inference_mode():+ probe = torch.randn(8, conv.in_channels, *conv.kernel_size, device=conv.weight.device, dtype=conv.weight.dtype)+ ref = conv(probe).float()+ got = fast_forward(probe).float().reshape_as(ref)+ max_abs = (ref - got).abs().max().item()+ # The conv and the matmul are the same operation, so they differ only by+ # low-precision (bf16) rounding — small relative to the output scale. A genuine+ # shape mismatch instead produces differences on the order of the outputs+ # themselves. Tolerance scaled to the output magnitude separates the two+ # cleanly without a magic absolute constant.+ tol = 1e-2 + 0.05 * ref.abs().max().item()+ if not math.isfinite(max_abs) or max_abs > tol:+ logger.warning(+ "[%s] patch-embed rebind skipped: %s output mismatch (max_abs_diff=%.3e tol=%.3e)",+ label,+ name,+ max_abs,+ tol,+ )+ return++ conv.forward = fast_forward # ty: ignore[invalid-assignment]+ logger.info(+ "[%s] rebound vision patch-embed %s (%s, kernel=%s) to F.linear (in=%d out=%d, max_abs_diff=%.3e)",+ label,+ name,+ type(conv).__name__,+ tuple(conv.kernel_size),+ in_features,+ out_ch,+ max_abs,+ )diff --git a/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py b/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.pyindex cecbc45f5..ad3074a9f 100644--- a/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colqwen2/__init__.py@@ -33,6 +33,7 @@ from torch import nnfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecision+from sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.types.inputs import media_bytes@@ -219,6 +220,12 @@ class ColQwen2Adapter(BaseAdapter):self._multivector_dim = getattr(self._model, "dim", 128)+ # FIX[#1151]: rebind the Qwen2.5-VL vision Conv3d patch-embed (kernel ==+ # stride, run per-patch) to its matmul equivalent. The non-overlapping+ # Conv3d hits a pathologically slow per-patch cuDNN path that dominates the+ # vision-tower forward; the rebind is numerically identical (same weights).+ rebind_vision_patch_embed(self._model, "colqwen2")+def _resolve_dtype(self) -> torch.dtype:if not self._device or not str(self._device).startswith("cuda"):return torch.float32diff --git a/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.pyindex 87cba2d36..3751202f9 100644--- a/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/colqwen3/__init__.py@@ -12,6 +12,7 @@ from torch.nn import functional as Ffrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecision+from sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.types.inputs import media_bytes@@ -141,8 +142,8 @@ class ColQwen3Adapter(BaseAdapter):# FIX[#1055]: replace the vision Conv3d patch-embed with its matmul# equivalent. It dominated the forward at ~169s/6-image batch (99.7% of# the vision tower; the transformer blocks were only ~140ms each) — see- # _patch_vision_patch_embed for why.- self._patch_vision_patch_embed()+ # rebind_vision_patch_embed for why.+ rebind_vision_patch_embed(self._model, "colqwen3")def _resolve_dtype(self) -> torch.dtype:if not self._device or not str(self._device).startswith("cuda"):@@ -184,40 +185,6 @@ class ColQwen3Adapter(BaseAdapter):except Exception: # noqa: BLE001 - best-effort, keep loaded default on failurelogger.warning("ColQwen3: could not set inner-VLM attn=%s; keeping default", attn_impl, exc_info=True)- def _patch_vision_patch_embed(self) -> None:- """Rebind the Qwen3-VL vision Conv3d patch-embed to its matmul equivalent.-- ``Qwen3VLVisionPatchEmbed`` projects patches with a ``nn.Conv3d`` whose- kernel equals its stride, i.e. a non-overlapping per-patch linear- projection. On this GPU the cuDNN Conv3d path for the (~30k-patch,- tiny-kernel) shape is pathologically slow — measured at ~169s for a- 6-image batch, ~99.7% of the whole vision-tower forward, while the 24- transformer blocks took only ~140ms each. Reshaping to ``F.linear`` with- the *same weights* is numerically identical but runs as a fast matmul.-- Best-effort: on any structural mismatch we leave the original Conv3d.- """- try:- visual = self._model.vlm.model.visual- patch_embed = visual.patch_embed- proj = patch_embed.proj- if not isinstance(proj, torch.nn.Conv3d):- return- embed_dim = proj.out_channels- in_features = proj.in_channels * proj.kernel_size[0] * proj.kernel_size[1] * proj.kernel_size[2]-- def fast_patch_embed_forward(- hidden_states: torch.Tensor, _pe: Any = patch_embed, _embed: int = embed_dim, _in: int = in_features- ) -> torch.Tensor:- weight = _pe.proj.weight- hs = hidden_states.to(weight.dtype).reshape(-1, _in)- return F.linear(hs, weight.reshape(_embed, _in), _pe.proj.bias)-- patch_embed.forward = fast_patch_embed_forward- logger.info("ColQwen3: replaced vision Conv3d patch-embed with matmul equivalent")- except Exception: # noqa: BLE001 - best-effort, keep the original Conv3d on failure- logger.warning("ColQwen3: could not rebind vision patch-embed; keeping Conv3d", exc_info=True)-# ------------------------------------------------------------------# Encode# ------------------------------------------------------------------diff --git a/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.py b/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.pyindex 88eb7c541..acb92e019 100644--- a/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/glm_ocr/__init__.py@@ -3,13 +3,12 @@ from __future__ import annotationsimport gcimport ioimport logging-import mathfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literalimport torch-import torch.nn.functional as F+from sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDimsfrom sie_server.core.inference_output import EncodeOutput, ExtractOutputfrom sie_server.types.inputs import media_bytes@@ -126,107 +125,12 @@ class GlmOcrAdapter(ModelAdapter):# per page), so the GPU sits idle while a single CPU thread launches# kernels — the dominant cost of every request. Rebind it to the# mathematically identical F.linear (one GEMM) to remove that.- self._patch_vision_patch_embed()+ rebind_vision_patch_embed(self._model, "glm_ocr")self._create_preprocessor()logger.info("GLM-OCR model loaded successfully")- def _patch_vision_patch_embed(self) -> None:- """Rebind the vision patch-embed Conv to an equivalent F.linear.-- Finds the non-overlapping convolution (``kernel_size == stride``) inside- the vision tower and replaces its ``forward`` with the numerically- identical matmul. Self-validating: a small synthetic patch batch is run- through both the original conv and the matmul at load time, and the fast- path is kept only if the outputs match (within bf16 rounding); otherwise- a warning is logged and the original conv is left in place. No weights- are changed and the check stays off the request path.- """- if self._model is None:- return-- # Non-overlapping convs (kernel == stride) inside the vision tower. The- # patch embed is one such conv, but the tower may have others — e.g. a- # spatial-merge ``downsample`` Conv2d (also kernel == stride). The patch- # embed is the pathological one (~one tiny kernel launch per patch);- # disambiguate by input channels: the patch embed consumes raw image- # channels (RGB, ≤ 4), while merge/downsample convs consume the hidden dim.- convs: list[tuple[str, torch.nn.Conv2d | torch.nn.Conv3d]] = []- for name, mod in self._model.named_modules():- lname = name.lower()- if (- isinstance(mod, (torch.nn.Conv2d, torch.nn.Conv3d))- and tuple(mod.kernel_size) == tuple(mod.stride)- and ("vis" in lname or "patch" in lname or "embed" in lname)- ):- convs.append((name, mod))-- # Identify the patch embed strictly by structure: it is the only vision- # conv that consumes raw image channels (RGB). Any other kernel==stride- # conv (e.g. a spatial-merge downsample) consumes the hidden dim. If this- # is not unique we do not guess — leave the original conv in place rather- # than risk rebinding a module whose runtime input is not per-patch- # shaped (fast_forward assumes one flattened patch per row).- patch = [c for c in convs if c[1].in_channels <= 4]- if len(patch) != 1:- logger.warning(- "[glm_ocr] patch-embed rebind skipped: expected exactly one RGB-input (in_channels<=4) "- "vision conv, found %d among %s",- len(patch),- [n for n, _ in convs],- )- return-- name, conv = patch[0]- out_ch = conv.out_channels- spatial_dims = len(conv.kernel_size)- in_features = conv.in_channels * math.prod(conv.kernel_size)- weight_2d = conv.weight.reshape(out_ch, in_features) # view; shares storage, no copy- bias = conv.bias-- def fast_forward(x: torch.Tensor) -> torch.Tensor:- n = x.shape[0]- out = F.linear(x.reshape(n, -1).to(weight_2d.dtype), weight_2d, bias)- return out.reshape(n, out_ch, *([1] * spatial_dims))-- # Validate equivalence on a small synthetic patch batch at load time- # (off the request path) before swapping. The op is mathematically a- # matmul over the flattened patch, so any divergence beyond bf16 rounding- # means the shape assumption is wrong — keep the original conv if so.- with torch.inference_mode():- probe = torch.randn(- 8, conv.in_channels, *conv.kernel_size, device=conv.weight.device, dtype=conv.weight.dtype- )- ref = conv(probe).float()- got = fast_forward(probe).float().reshape_as(ref)- max_abs = (ref - got).abs().max().item()- # The conv and the matmul are the same operation, so they differ only by- # low-precision (bf16) rounding — small relative to the output scale. A- # genuine shape mismatch instead produces differences on the order of the- # outputs themselves. Tolerance scaled to the output magnitude separates- # the two cleanly without a magic absolute constant.- tol = 1e-2 + 0.05 * ref.abs().max().item()- if not math.isfinite(max_abs) or max_abs > tol:- logger.warning(- "[glm_ocr] patch-embed rebind skipped: %s output mismatch (max_abs_diff=%.3e tol=%.3e)",- name,- max_abs,- tol,- )- return-- conv.forward = fast_forward # ty: ignore[invalid-assignment]- logger.info(- "[glm_ocr] rebound vision patch-embed %s (%s, kernel=%s) to F.linear (in=%d out=%d, max_abs_diff=%.3e)",- name,- type(conv).__name__,- tuple(conv.kernel_size),- in_features,- out_ch,- max_abs,- )-def _resolve_dtype(self, device: str) -> torch.dtype:"""Resolve dtype based on device and config."""if not device.startswith("cuda"):diff --git a/packages/sie_server/src/sie_server/adapters/lighton_ocr/__init__.py b/packages/sie_server/src/sie_server/adapters/lighton_ocr/__init__.pyindex 667ded470..56f984f02 100644--- a/packages/sie_server/src/sie_server/adapters/lighton_ocr/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/lighton_ocr/__init__.py@@ -7,6 +7,7 @@ from pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literalimport torch+import torch.nn.functional as Ffrom sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDimsfrom sie_server.core.inference_output import EncodeOutput, ExtractOutput@@ -48,6 +49,7 @@ class LightOnOCRAdapter(ModelAdapter):num_beams: int = 1,attn_implementation: str = "sdpa",system_prompt: str = DEFAULT_SYSTEM_PROMPT,+ max_batch_images: int = 4,**kwargs: Any,) -> None:"""Initialize the adapter.@@ -59,6 +61,11 @@ class LightOnOCRAdapter(ModelAdapter):num_beams: Number of beams for beam search.attn_implementation: Attention implementation - "eager", "sdpa", or "flash_attention_2".system_prompt: System prompt for the chat template.+ max_batch_images: Max images per batched ``generate()`` call. Bounds KV-cache /+ vision-activation memory so a large incoming batch cannot OOM (issue #33,+ decoder-batching KV-OOM). The+ default (4) is safe on a 24GB L4 with ``max_new_tokens=4096``; raise it on+ higher-VRAM GPUs to batch more pages per call.**kwargs: Ignored extra arguments from the loader."""del kwargs # Unused - accepts normalize, max_seq_length, etc.@@ -68,6 +75,7 @@ class LightOnOCRAdapter(ModelAdapter):self._num_beams = num_beamsself._attn_implementation = attn_implementationself._system_prompt = system_prompt+ self._max_batch_images = max(1, max_batch_images)self._model: Any = Noneself._processor: Any = None@@ -114,6 +122,14 @@ class LightOnOCRAdapter(ModelAdapter):self._model_name_or_path,)+ # Batched generation left-pads input_ids (prompt length varies with image+ # resolution), so the decoder must pad on the left and have a pad token.+ tokenizer = getattr(self._processor, "tokenizer", None)+ if tokenizer is not None:+ tokenizer.padding_side = "left"+ if tokenizer.pad_token_id is None and tokenizer.eos_token is not None:+ tokenizer.pad_token = tokenizer.eos_token+self._model = LightOnOcrForConditionalGeneration.from_pretrained(self._model_name_or_path,torch_dtype=dtype,@@ -275,11 +291,19 @@ class LightOnOCRAdapter(ModelAdapter):num_beams: Beam search width.Returns:- ExtractOutput with entities.+ ExtractOutput with entities in original item order.++ Preprocessed payloads are run through a single batched ``generate()`` per+ sub-batch instead of one call per image, so GPU concurrency actually scales+ OCR throughput (issue #601). Images may differ in resolution (Pixtral is+ variable-resolution), so pixel_values are zero-padded to the per-batch max and+ input_ids are left-padded — mirroring transformers' own batched Pixtral path."""from sie_server.core.prepared import LightOnOCRPayload, PreparedItem- all_entities = []+ results: list[list[Entity]] = [[] for _ in items]+ payloads: list[Any] = []+ payload_indices: list[int] = []for i, prepared in enumerate(prepared_items):if isinstance(prepared, PreparedItem):@@ -287,40 +311,104 @@ class LightOnOCRAdapter(ModelAdapter):else:payload = getattr(prepared, "payload", prepared)- if not isinstance(payload, LightOnOCRPayload):- entities = self._extract_single(+ if isinstance(payload, LightOnOCRPayload):+ payloads.append(payload)+ payload_indices.append(i)+ else:+ results[i] = self._extract_single(items[i],instruction=None,max_new_tokens=max_new_tokens,num_beams=num_beams,)- all_entities.append(entities)- continue-- pixel_values = payload.pixel_values.unsqueeze(0).to(device=self._device, dtype=self._model.dtype)- input_ids = payload.input_ids.unsqueeze(0).to(self._device)- attention_mask = payload.attention_mask.unsqueeze(0).to(self._device)- image_sizes = payload.image_sizes.unsqueeze(0).to(self._device)- prompt_len = input_ids.shape[1]-- with torch.inference_mode():- output_ids = self._model.generate(- input_ids=input_ids,- attention_mask=attention_mask,- pixel_values=pixel_values,- image_sizes=image_sizes,- max_new_tokens=max_new_tokens,- do_sample=False,- num_beams=num_beams,- )- generated_ids = output_ids[0, prompt_len:]- generated_text = self._processor.decode(generated_ids, skip_special_tokens=True)+ # Sub-batch to bound KV-cache / vision-activation memory (issue #33, decoder-batching KV-OOM): a large+ # incoming batch under high concurrency could otherwise OOM a 24GB L4.+ for start in range(0, len(payloads), self._max_batch_images):+ chunk = payloads[start : start + self._max_batch_images]+ chunk_indices = payload_indices[start : start + self._max_batch_images]+ texts = self._generate_batch(chunk, max_new_tokens=max_new_tokens, num_beams=num_beams)+ for text, i in zip(texts, chunk_indices):+ results[i] = self._convert_output(text)- entities = self._convert_output(generated_text)- all_entities.append(entities)+ return ExtractOutput(entities=results)- return ExtractOutput(entities=all_entities)+ def _generate_batch(+ self,+ payloads: list[Any],+ *,+ max_new_tokens: int,+ num_beams: int,+ ) -> list[str]:+ """Run one batched ``generate()`` over preprocessed LightOnOCR payloads.++ Args:+ payloads: LightOnOCRPayload items (pixel_values [C,H,W], input_ids [L],+ attention_mask [L], image_sizes [2]) that may have different resolutions.+ max_new_tokens: Max tokens to generate.+ num_beams: Beam search width.++ Returns:+ Decoded Markdown text per payload, in input order.+ """+ device = self._device+ dtype = self._model.dtype++ # pixel_values: zero-pad each [C, H_i, W_i] to the per-batch max (bottom/right),+ # then stack to [N, C, H_max, W_max]. image_sizes carries the TRUE (h, w) per image+ # so the Pixtral encoder masks the padding out (mirrors HF _pad_for_batching).+ max_h = max(int(p.pixel_values.shape[1]) for p in payloads)+ max_w = max(int(p.pixel_values.shape[2]) for p in payloads)+ padded_pixels = [+ F.pad(p.pixel_values, (0, max_w - int(p.pixel_values.shape[2]), 0, max_h - int(p.pixel_values.shape[1])))+ for p in payloads+ ]+ pixel_values = torch.stack(padded_pixels).to(device=device, dtype=dtype)+ image_sizes = torch.stack([p.image_sizes for p in payloads]).to(device)++ # input_ids / attention_mask: LEFT-pad to the longest prompt so every row's real+ # tokens align at the right edge (required for correct batched greedy decode;+ # prompt length varies with image resolution).+ pad_id = self._pad_token_id()+ max_len = max(int(p.input_ids.shape[0]) for p in payloads)+ input_ids_rows: list[torch.Tensor] = []+ attention_rows: list[torch.Tensor] = []+ for p in payloads:+ n_pad = max_len - int(p.input_ids.shape[0])+ ids = p.input_ids+ mask = p.attention_mask+ if n_pad:+ ids = torch.cat([torch.full((n_pad,), pad_id, dtype=ids.dtype), ids])+ mask = torch.cat([torch.zeros(n_pad, dtype=mask.dtype), mask])+ input_ids_rows.append(ids)+ attention_rows.append(mask)+ input_ids = torch.stack(input_ids_rows).to(device)+ attention_mask = torch.stack(attention_rows).to(device)++ with torch.inference_mode():+ output_ids = self._model.generate(+ input_ids=input_ids,+ attention_mask=attention_mask,+ pixel_values=pixel_values,+ image_sizes=image_sizes,+ max_new_tokens=max_new_tokens,+ do_sample=False,+ num_beams=num_beams,+ )++ # Left-padding right-aligns every prompt, so generation starts at column max_len.+ generated = output_ids[:, max_len:]+ return self._processor.batch_decode(generated, skip_special_tokens=True)++ def _pad_token_id(self) -> int:+ """Resolve the pad token id for left-padding (Qwen3 has one; fall back to eos)."""+ tokenizer = getattr(self._processor, "tokenizer", None)+ pad_id = getattr(tokenizer, "pad_token_id", None) if tokenizer is not None else None+ if pad_id is None:+ pad_id = self._model.config.text_config.eos_token_id+ if isinstance(pad_id, (list, tuple)):+ pad_id = pad_id[0]+ return int(pad_id)def _extract_single(self,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 157379a5a..6bafccadd 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@@ -36,6 +36,7 @@ import torchfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecision+from sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.types.inputs import media_bytes@@ -184,52 +185,28 @@ class NemoColEmbedAdapter(BaseAdapter):except Exception: # noqa: BLE001 - best-effort, keep loaded default on failurelogger.warning("NemoColEmbed: could not set attn=%s; keeping default", attn_impl, exc_info=True)- # FIX[#1055]: replace the Qwen3-VL vision Conv3d patch-embed with its- # matmul equivalent (same weights). The non-overlapping Conv3d hits a- # pathologically slow cuDNN path on this GPU; for the sibling ColQwen3 it- # was ~99.7% of the vision-tower forward. No-op for the v1 SigLIP path.- self._patch_vision_patch_embed()-- # Create preprocessor only when the model exposes v1-style attrs (image_size,- # num_image_token). v2 (Qwen3-VL) does not, and the SigLIP+Llama-keyed- # NemoColEmbedPreprocessor does not apply.- if loaded_via_v1_path or (hasattr(self._model, "image_size") and hasattr(self._model, "num_image_token")):+ # v1 (SigLIP+Llama) vs v2 (Qwen3-VL) backbone. v1 exposes image_size /+ # num_image_token (and always takes the dynamic-module fallback path); v2+ # does not.+ is_v1 = loaded_via_v1_path or (hasattr(self._model, "image_size") and hasattr(self._model, "num_image_token"))++ # FIX[#1055]/[#1151]: rebind the Qwen3-VL (v2) vision Conv3d patch-embed to+ # its matmul equivalent (same weights). The non-overlapping Conv3d hits a+ # pathologically slow per-patch cuDNN path that dominated the vision-tower+ # forward (~99.7% for the sibling ColQwen3). Restrict to v2: the v1 SigLIP+ # patch conv runs over the full image (not pre-patched rows), so the+ # per-patch F.linear rebind would mis-shape it — and the load-time probe+ # (per-patch shaped) would not catch that.+ if not is_v1:+ rebind_vision_patch_embed(self._model, "nemo_colembed")++ # Create preprocessor only for v1 — the SigLIP+Llama-keyed+ # NemoColEmbedPreprocessor does not apply to the v2 (Qwen3-VL) backbone.+ if is_v1:self._create_processor()else:logger.info("Skipping NemoColEmbedPreprocessor — model lacks v1 attrs (likely v2 backbone).")- def _patch_vision_patch_embed(self) -> None:- """Rebind the Qwen3-VL vision Conv3d patch-embed to its matmul equivalent.-- The non-overlapping Conv3d patch projection (kernel == stride) hits a- pathologically slow cuDNN path on this GPU; for the sibling ColQwen3 it- was ~99.7% of the vision-tower forward. Reshaping to ``F.linear`` with the- same weights is numerically identical but runs as a fast matmul. Locates- the vision tower under the v2 (Qwen3-VL) backbone; no-op for the v1 path.- """- from torch.nn import functional-- try:- visual = getattr(getattr(self._model, "model", None), "visual", None)- patch_embed = getattr(visual, "patch_embed", None)- proj = getattr(patch_embed, "proj", None)- if not isinstance(proj, torch.nn.Conv3d):- return- embed_dim = proj.out_channels- in_features = proj.in_channels * proj.kernel_size[0] * proj.kernel_size[1] * proj.kernel_size[2]-- def fast_patch_embed_forward(- hidden_states: torch.Tensor, _pe: Any = patch_embed, _embed: int = embed_dim, _in: int = in_features- ) -> torch.Tensor:- weight = _pe.proj.weight- hs = hidden_states.to(weight.dtype).reshape(-1, _in)- return functional.linear(hs, weight.reshape(_embed, _in), _pe.proj.bias)-- patch_embed.forward = fast_patch_embed_forward # ty: ignore[invalid-assignment]- logger.info("NemoColEmbed: replaced vision Conv3d patch-embed with matmul equivalent")- except Exception: # noqa: BLE001 - best-effort, keep the original Conv3d on failure- logger.warning("NemoColEmbed: could not rebind vision patch-embed; keeping Conv3d", exc_info=True)-def _load_v1_dynamic(self, device: str, dtype: torch.dtype) -> Any:"""Load v1 (SigLIP+Llama) via the explicit dynamic-module path.diff --git a/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py b/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.pyindex 78a123849..c9e62f755 100644--- a/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/paddleocr_vl/__init__.py@@ -10,6 +10,7 @@ import torchfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision+from sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import EncodeOutput, ExtractOutputfrom sie_server.types.inputs import media_bytesfrom sie_server.types.responses import Entity@@ -166,6 +167,12 @@ class PaddleOCRVLAdapter(BaseAdapter):self._model.to(device) # ty: ignore[invalid-argument-type]self._model.eval()+ # FIX[#1151]: rebind the PaddleOCR-VL vision Conv2d patch-embed to its+ # matmul equivalent (same weights). Its encoder runs the conv per-patch+ # (the full-grid branch raises NotImplementedError), so the non-overlapping+ # Conv2d hits the same pathologically slow per-patch cuDNN path.+ rebind_vision_patch_embed(self._model, "paddleocr_vl")+self._create_preprocessor()logger.info("PaddleOCR-VL model loaded successfully")diff --git a/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.pyindex 52d431fe9..52bbe1ec3 100644--- a/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py@@ -12,6 +12,7 @@ from torch.nn import functional as Ffrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED, ComputePrecision+from sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import EncodeOutputfrom sie_server.types.inputs import media_bytes@@ -171,6 +172,11 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):logger.warning("Could not determine hidden_size from config, defaulting to 2048")self._dense_dim = self._validate_or_set_dense_dim(2048)+ # FIX[#1151]: rebind the Qwen3-VL vision Conv3d patch-embed to its matmul+ # equivalent (same weights). The non-overlapping per-patch Conv3d hits a+ # pathologically slow cuDNN path that dominates the vision-tower forward.+ rebind_vision_patch_embed(self._model, "qwen3_vl_embedding")+def _validate_or_set_dense_dim(self, observed_dim: int) -> int:"""Validate observed model width against configured dense_dim."""if self._configured_dense_dim is not None and observed_dim != self._configured_dense_dim:diff --git a/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.pyindex 74295eb59..f51e71487 100644--- a/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/qwen3_vl_reranker/__init__.py@@ -11,6 +11,7 @@ import torchfrom sie_server.adapters._base_adapter import BaseAdapterfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ComputePrecision+from sie_server.adapters._vision_patch_embed import rebind_vision_patch_embedfrom sie_server.core.inference_output import ScoreOutputfrom sie_server.types.inputs import media_bytes@@ -182,6 +183,11 @@ class Qwen3VLRerankerAdapter(BaseAdapter):)self._model.eval()+ # FIX[#1151]: rebind the Qwen3-VL vision Conv3d patch-embed to its matmul+ # equivalent (same weights). The non-overlapping per-patch Conv3d hits a+ # pathologically slow cuDNN path that dominates the vision-tower forward.+ rebind_vision_patch_embed(self._model, "qwen3_vl_reranker")+# Pre-resolve the yes/no token IDs for scoring and validate they# are real tokens (convert_tokens_to_ids silently returns the UNK id# if the token is missing from the vocabulary).diff --git a/packages/sie_server/src/sie_server/adapters/sglang/_server.py b/packages/sie_server/src/sie_server/adapters/sglang/_server.pyindex 29e6e8f2c..1697a89f5 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/_server.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/_server.py@@ -13,6 +13,7 @@ lifecycle of a single SGLang HTTP server child process.from __future__ import annotationsimport logging+import mathimport osimport randomimport signal@@ -40,15 +41,83 @@ _RESERVED_PORTS: set[int] = set()_RESERVED_PORTS_LOCK = threading.Lock()# 8B+ models can take 5+ min just to download from HF on a fresh cache,-# plus SGLang itself then loads the model onto the GPU. Override via-# SIE_SGLANG_STARTUP_TIMEOUT_S for hosts with slow network or larger models.-STARTUP_TIMEOUT_S = int(os.environ.get("SIE_SGLANG_STARTUP_TIMEOUT_S", "900"))+# plus SGLang itself then loads the model onto the GPU. Override via the+# SGLang-specific env var below, or one of the adapter/server aliases that+# operators commonly try when tuning cold-start budgets.+DEFAULT_STARTUP_TIMEOUT_S = 900.0+STARTUP_TIMEOUT_ENV_VARS = (+ "SIE_SGLANG_STARTUP_TIMEOUT_S",+ "SIE_MODEL_READY_TIMEOUT_S",+ "SIE_ADAPTER_STARTUP_TIMEOUT_S",+ "SIE_SERVER_STARTUP_TIMEOUT_S",+)+LIVENESS_BUDGET_ENV_VAR = "SIE_WORKER_LIVENESS_BUDGET_S"+STARTUP_TIMEOUT_S = DEFAULT_STARTUP_TIMEOUT_SHEALTH_CHECK_INTERVAL_S = 2.0BASE_PORT = 30000 # Starting port for SGLang serversERR_SERVER_STARTUP = "SGLang server failed to start within timeout"+def _resolve_liveness_budget() -> float | None:+ raw = os.environ.get(LIVENESS_BUDGET_ENV_VAR)+ if raw is None or raw.strip() == "":+ return None+ try:+ value = float(raw)+ except ValueError:+ logger.warning("Ignoring invalid %s=%r; expected seconds", LIVENESS_BUDGET_ENV_VAR, raw)+ return None+ if math.isfinite(value) and value > 0:+ return value+ logger.warning("Ignoring invalid %s=%r; expected finite seconds > 0", LIVENESS_BUDGET_ENV_VAR, raw)+ return None+++def _validate_liveness_budget(timeout_s: float) -> float:+ budget_s = _resolve_liveness_budget()+ if budget_s is not None and timeout_s >= budget_s:+ msg = (+ f"SGLang startup timeout {timeout_s:g}s must be lower than "+ f"{LIVENESS_BUDGET_ENV_VAR}={budget_s:g}s so kubelet liveness does not kill the worker mid-load"+ )+ raise ValueError(msg)+ return timeout_s+++def resolve_startup_timeout(timeout_s: float | None = None) -> float:+ """Resolve the SGLang startup-health timeout.++ Precedence:+ 1. Explicit adapter/profile value (``adapter_options.loadtime.startup_timeout_s``).+ 2. Environment variables in ``STARTUP_TIMEOUT_ENV_VARS`` order.+ 3. ``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 _validate_liveness_budget(value)+ logger.warning("Ignoring invalid SGLang 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 _validate_liveness_budget(value)+ logger.warning("Ignoring invalid %s=%r; expected finite seconds > 0", name, raw)++ return _validate_liveness_budget(DEFAULT_STARTUP_TIMEOUT_S)++def find_free_port(start_port: int = BASE_PORT) -> int:"""Find a free port in ``[start_port, start_port + 100)``.@@ -145,7 +214,7 @@ def wait_for_server(process: subprocess.Popen[bytes],*,output_file: tempfile._TemporaryFileWrapper | None = None,- timeout_s: float = STARTUP_TIMEOUT_S,+ timeout_s: float | None = None,) -> bool:"""Poll the SGLang ``/health`` endpoint until the server is ready.@@ -154,6 +223,7 @@ def wait_for_server(timeout elapses or the subprocess dies. Subprocess output (when``output_file`` is provided) is logged on failure for diagnostics."""+ timeout_s = resolve_startup_timeout(timeout_s)health_url = f"{server_url}/health"start_time = time.monotonic()diff --git a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py b/packages/sie_server/src/sie_server/adapters/sglang/embedding.pyindex 12c237c00..84bb241cb 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/embedding.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/embedding.py@@ -90,6 +90,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):lora_paths: dict[str, str] | None = None,max_loras_per_batch: int = 8,dense_dim: int | None = None,+ startup_timeout_s: float | None = None,**kwargs: Any, # Accept extra args from loader (e.g., pooling)) -> None:r"""Initialize the adapter.@@ -115,6 +116,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):At request time, select via lora parameter in encode().max_loras_per_batch: Maximum LoRA adapters per batch. Default 8.dense_dim: Configured dense embedding dimension.+ startup_timeout_s: SGLang startup-health timeout in seconds.**kwargs: Additional arguments (ignored, for compatibility)."""_ = kwargs # Unused, but accepted for loader compatibility@@ -130,6 +132,7 @@ class SGLangEmbeddingAdapter(BaseAdapter):self._pooling_method = pooling_methodself._lora_paths = lora_paths or {}self._max_loras_per_batch = max_loras_per_batch+ self._startup_timeout_s = _server.resolve_startup_timeout(startup_timeout_s)self._process: subprocess.Popen[bytes] | None = Noneself._server_url: str | None = None@@ -220,7 +223,12 @@ class SGLangEmbeddingAdapter(BaseAdapter):self._output_file = _server.open_output_log()self._process = _server.launch_sglang_server(cmd, device_index=device_index, output_file=self._output_file)- if not _server.wait_for_server(self._server_url, self._process, output_file=self._output_file):+ if not _server.wait_for_server(+ self._server_url,+ self._process,+ output_file=self._output_file,+ timeout_s=self._startup_timeout_s,+ ):_server.terminate_process(self._process)self._process = Noneraise RuntimeError(_server.ERR_SERVER_STARTUP)diff --git a/packages/sie_server/src/sie_server/adapters/sglang/generation.py b/packages/sie_server/src/sie_server/adapters/sglang/generation.pyindex eaeb7a507..95951d653 100644--- a/packages/sie_server/src/sie_server/adapters/sglang/generation.py+++ b/packages/sie_server/src/sie_server/adapters/sglang/generation.py@@ -194,6 +194,7 @@ class SGLangGenerationAdapter(GenerationAdapter):speculative: dict[str, Any] | None = None,extra_launch_args: list[str] | None = None,extra_env: dict[str, str] | None = None,+ startup_timeout_s: float | None = None,# Multi-LoRA: served-name → HF-id/path map. When non-empty the server# launches with ``--enable-lora`` and per-request ``lora_path``# selection is available. ``max_loras_per_batch`` caps concurrent@@ -251,6 +252,7 @@ class SGLangGenerationAdapter(GenerationAdapter):self._speculative = speculativeself._extra_launch_args = list(extra_launch_args or [])self._extra_env = dict(extra_env or {})+ self._startup_timeout_s = _server.resolve_startup_timeout(startup_timeout_s)self._lora_paths = dict(lora_paths or {})self._max_loras_per_batch = max_loras_per_batch@@ -411,7 +413,12 @@ class SGLangGenerationAdapter(GenerationAdapter):extra_env=extra_env or None,)- if not _server.wait_for_server(self._server_url, self._process, output_file=self._output_file):+ if not _server.wait_for_server(+ self._server_url,+ self._process,+ output_file=self._output_file,+ timeout_s=self._startup_timeout_s,+ ):log_path = getattr(self._output_file, "name", None)if log_path:logger.error("SGLang failed to reach health. log_path=%s", log_path)diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.pyindex 9b075381c..6e6c1c846 100644--- a/packages/sie_server/src/sie_server/config/model.py+++ b/packages/sie_server/src/sie_server/config/model.py@@ -157,6 +157,18 @@ class GenerateTask(BaseModel)::class:`ProfileConfig` rather than here, because thebudget is a per-worker/per-profile shape rather than a per-tasksemantic.++ ``grammar_profile`` optionally names a profile that grammar-constrained+ requests (OpenAI ``response_format`` / SIE-native ``grammar``) must run on.+ When set, the gateway rewrites such a request's model id to the+ ``{sie_id}:{grammar_profile}`` variant so it is served by that profile,+ while unconstrained requests keep the request's resolved profile. This+ exists because some throughput optimisations are incompatible with+ decode-time grammar enforcement — notably NEXTN/MTP speculative decoding+ bypasses SGLang's Outlines FSM (leaks out-of-schema keys, truncates+ mid-JSON), so a model whose default profile is speculative points+ ``grammar_profile`` at a non-speculative profile (e.g. ``no-spec``). ``None``+ (default) means no rewrite — grammar runs on the request's resolved profile."""model_config = ConfigDict(extra="forbid")@@ -166,6 +178,7 @@ class GenerateTask(BaseModel):capabilities: GenerateCapabilities = GenerateCapabilities()chat_template_kwargs: dict[str, Any] = Field(default_factory=dict)prewarm_grammars: list[PrewarmGrammar] = Field(default_factory=list)+ grammar_profile: str | None = Noneclass Tasks(BaseModel):@@ -473,6 +486,22 @@ class ModelConfig(BaseModel):if "default" not in self.profiles:msg = "'default' key must exist in profiles"raise ValueError(msg)++ # ``grammar_profile`` must name a real profile (it becomes the+ # ``{sie_id}:{grammar_profile}`` variant the gateway routes grammar+ # requests to). Rejecting an unknown name here turns a silent+ # no-op (the gateway would skip the rewrite) into a load-time error.+ if self.tasks.generate is not None and self.tasks.generate.grammar_profile is not None:+ gp = self.tasks.generate.grammar_profile+ if gp not in self.profiles:+ msg = (+ f"tasks.generate.grammar_profile '{gp}' is not a defined profile. Available: {list(self.profiles)}"+ )+ raise ValueError(msg)+ if gp == "default":+ msg = "tasks.generate.grammar_profile must not be 'default' (it names a non-default variant profile)"+ raise ValueError(msg)+for name, profile in self.profiles.items():if profile.extends is not None:if profile.extends not in self.profiles:diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.pyindex 90f2275ba..031dee3d0 100644--- a/packages/sie_server/src/sie_server/core/loader.py+++ b/packages/sie_server/src/sie_server/core/loader.py@@ -5,6 +5,7 @@ import loggingimport osimport sysimport tempfile+import threadingfrom pathlib import Pathfrom typing import Any@@ -18,7 +19,7 @@ from sie_sdk.storage import (from sie_server.adapters._generation_base import GenerationAdapterfrom sie_server.adapters.base import ModelAdapterfrom sie_server.config.engine import ComputePrecision-from sie_server.config.model import AdapterOptions, ModelConfig, ProfileConfig+from sie_server.config.model import AdapterOptions, ModelConfig, ProfileConfig, ResolvedProfilefrom sie_server.core.inference import AttentionBackendlogger = logging.getLogger(__name__)@@ -106,6 +107,7 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:for profile_name, profile in config.profiles.items():if profile_name == "default":continue+ resolved: ResolvedProfile | None = None# Resolve extending profiles, use standalone profiles as-isif profile.extends is not None:resolved = config.resolve_profile(profile_name)@@ -119,6 +121,9 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:loadtime=dict(resolved.loadtime),runtime=dict(resolved.runtime),),+ adaptive_batching=resolved.adaptive_batching,+ kv_budget_tokens=resolved.kv_budget_tokens,+ admission_enabled=resolved.admission_enabled,)else:variant_default = profile.model_copy(update={"extends": None})@@ -128,12 +133,30 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:logger.warning("Variant '%s' collides with existing config; skipping expansion", variant_id)continuevariant_profiles = {"default": variant_default}+ variant_updates: dict[str, Any] = {+ "sie_id": variant_id,+ "profiles": variant_profiles,+ }+ loadtime = resolved.loadtime if resolved is not None else profile.adapter_options.loadtime+ profile_max_seq = loadtime.get("max_seq_length")+ if isinstance(profile_max_seq, int) and profile_max_seq > 0:+ variant_updates["max_sequence_length"] = profile_max_seq+ if config.tasks.generate is not None:+ variant_updates["tasks"] = config.tasks.model_copy(+ update={+ "generate": config.tasks.generate.model_copy(+ update={"context_length": profile_max_seq},+ ),+ },+ )variant_config = config.model_copy(- update={- "sie_id": variant_id,- "profiles": variant_profiles,- },+ update=variant_updates,)+ # ``model_copy`` carries PrivateAttr values, including the resolved+ # profile cache. Variants must not share cached "default" profiles+ # with the base config or sibling variants.+ variant_config._resolved_cache = {}+ variant_config._resolved_lock = threading.Lock()variants[variant_id] = variant_configlogger.info("Expanded profile '%s' as variant: %s", profile_name, variant_id)diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex 14d4c46a7..894a78716 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -13,6 +13,8 @@ Model loading workflow is delegated to ModelLoader.from __future__ import annotationsimport asyncio+import hashlib+import jsonimport loggingimport timefrom collections.abc import Iterable@@ -53,6 +55,16 @@ _ERR_MODEL_NOT_LOADED = "Model '{name}' is not loaded"_ERR_MODEL_ALREADY_LOADED = "Model '{name}' is already loaded"+def _model_config_semantic_hash(config: ModelConfig) -> str:+ """Stable hash for config equality that ignores Pydantic private attrs."""+ payload = json.dumps(config.model_dump(mode="json"), sort_keys=True, separators=(",", ":"))+ return hashlib.sha256(payload.encode()).hexdigest()+++def _model_configs_semantically_equal(left: ModelConfig | None, right: ModelConfig) -> bool:+ return left is not None and _model_config_semantic_hash(left) == _model_config_semantic_hash(right)++class ModelRegistry:"""Registry for managing model configs and loaded models.@@ -1104,9 +1116,18 @@ class ModelRegistry:lock = self._get_load_lock()async with lock:removed = set(self._configs) - set(new_configs)- changed = {name for name, config in new_configs.items() if self._configs.get(name) != config}+ changed = {+ name+ for name, config in new_configs.items()+ if not _model_configs_semantically_equal(self._configs.get(name), config)+ }+ if model_dir is not None:+ changed.update(name for name in new_configs if self._model_dirs.get(name) != model_dir)invalidated = removed | changed+ if not invalidated:+ return set()+for name in sorted(invalidated):if name in self._loaded:await self._do_unload(name)diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex 4bdcc2e85..d687cb6ba 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -555,8 +555,6 @@ class QueueExecutor:invalidated = await self._registry.replace_configs_async(configs)for model_id in invalidated:self.invalidate_model_descriptor(model_id)- for config in configs:- self.invalidate_model_descriptor(config.sie_id)bundle_hash = compute_bundle_config_hash_cached(self._registry, req.bundle_id)applied_models = sorted(self._registry.get_configs_snapshot(req.bundle_id))return ReplaceModelConfigsResponse(diff --git a/packages/sie_server/tests/adapters/test_lighton_ocr.py b/packages/sie_server/tests/adapters/test_lighton_ocr.pyindex 263034fd2..099327e51 100644--- a/packages/sie_server/tests/adapters/test_lighton_ocr.py+++ b/packages/sie_server/tests/adapters/test_lighton_ocr.py@@ -1,8 +1,75 @@from __future__ import annotations+from typing import TYPE_CHECKING+import pytest+import torch+from sie_server.core.prepared import LightOnOCRPayload, PreparedItemfrom sie_server.types.inputs import Item+if TYPE_CHECKING:+ from sie_server.adapters.lighton_ocr import LightOnOCRAdapter+++class _FakeTextConfig:+ eos_token_id = 0+++class _FakeConfig:+ text_config = _FakeTextConfig()+++class _FakeTokenizer:+ pad_token_id = 0+++class _FakeProcessor:+ tokenizer = _FakeTokenizer()++ @staticmethod+ def batch_decode(generated: torch.Tensor, skip_special_tokens: bool = True) -> list[str]:+ # Receives only the post-slice generated tokens (adapter passes out[:, max_len:]);+ # _FakeModel echoes each row's last real input id as the first generated column.+ return [f"id{int(row[0])}" for row in generated]+++class _FakeModel:+ """Records generate() calls and echoes each row's last real token as output."""++ dtype = torch.float32+ config = _FakeConfig()++ def __init__(self) -> None:+ self.generate_calls: list[dict] = []++ def generate(self, *, input_ids, attention_mask, pixel_values, image_sizes, **kwargs):+ self.generate_calls.append(+ {+ "input_ids": input_ids.clone(),+ "attention_mask": attention_mask.clone(),+ "pixel_values_shape": tuple(pixel_values.shape),+ "image_sizes": image_sizes.clone(),+ }+ )+ marker = input_ids[:, -1:].clone() # last (right-aligned) real token per row+ return torch.cat([input_ids, marker], dim=1)+++def _payload(input_id_tail: int, length: int, h: int, w: int):+ ids = torch.arange(1, length, dtype=torch.long)+ ids = torch.cat([ids, torch.tensor([input_id_tail], dtype=torch.long)]) # unique last token+ return LightOnOCRPayload(+ pixel_values=torch.ones(3, h, w),+ input_ids=ids,+ attention_mask=torch.ones(length, dtype=torch.long),+ image_sizes=torch.tensor([h, w], dtype=torch.long),+ original_size=(w, h),+ )+++def _prepared(payload, index: int):+ return PreparedItem(payload=payload, cost=1, original_index=index)+class TestLightOnOCRAdapter:"""Tests for LightOnOCRAdapter with mocked model."""@@ -93,3 +160,98 @@ class TestLightOnOCRAdapter:messages = adapter._build_messages(instruction=None)assert messages[0]["content"] == custom_prompt++ def test_extract_preprocessed_batches_and_left_pads(self, adapter: LightOnOCRAdapter) -> None:+ """Heterogeneous payloads run through ONE batched generate with left-padding."""+ adapter._model = _FakeModel()+ adapter._processor = _FakeProcessor()+ adapter._device = "cpu"++ # Different prompt lengths (3/5/4) and pixel sizes -> exercises pad + left-pad.+ payloads = [_payload(501, 3, 2, 2), _payload(502, 5, 4, 3), _payload(503, 4, 3, 5)]+ prepared = [_prepared(p, i) for i, p in enumerate(payloads)]++ out = adapter._extract_preprocessed(+ items=[Item(text="x") for _ in range(3)], prepared_items=prepared, max_new_tokens=8, num_beams=1+ )++ # One batched generate (not three serial calls).+ assert len(adapter._model.generate_calls) == 1+ call = adapter._model.generate_calls[0]++ # input_ids left-padded to max length 5; shortest row (len 3) has 2 left pads.+ assert call["input_ids"].shape == (3, 5)+ assert torch.equal(call["input_ids"][0, :2], torch.zeros(2, dtype=torch.long)) # pad_id=0+ assert torch.equal(call["attention_mask"][0], torch.tensor([0, 0, 1, 1, 1]))+ # Real last token preserved at the right edge for every row.+ assert [int(call["input_ids"][i, -1]) for i in range(3)] == [501, 502, 503]++ # pixel_values zero-padded to per-batch max (H=4, W=5) and stacked.+ assert call["pixel_values_shape"] == (3, 3, 4, 5)+ # image_sizes carries TRUE (h, w), never the padded size.+ assert torch.equal(call["image_sizes"], torch.tensor([[2, 2], [4, 3], [3, 5]]))++ # Results decoded per row, in original order.+ assert [ents[0]["text"] for ents in out.entities] == ["id501", "id502", "id503"]++ def test_extract_preprocessed_respects_max_batch_images(self) -> None:+ """max_batch_images chunks a large batch into bounded sub-batches."""+ from sie_server.adapters.lighton_ocr import LightOnOCRAdapter++ adapter = LightOnOCRAdapter("lightonai/LightOnOCR-2-1B", max_batch_images=2)+ adapter._model = _FakeModel()+ adapter._processor = _FakeProcessor()+ adapter._device = "cpu"++ payloads = [_payload(500 + i, 4, 3, 3) for i in range(5)]+ prepared = [_prepared(p, i) for i, p in enumerate(payloads)]++ out = adapter._extract_preprocessed(+ items=[Item(text="x") for _ in range(5)], prepared_items=prepared, max_new_tokens=8, num_beams=1+ )++ # cap=2 over 5 items -> sub-batches of 2, 2, 1.+ assert [c["input_ids"].shape[0] for c in adapter._model.generate_calls] == [2, 2, 1]+ assert [ents[0]["text"] for ents in out.entities] == [f"id{500 + i}" for i in range(5)]++ def test_extract_preprocessed_max_batch_one_is_serial(self) -> None:+ """max_batch_images=1 issues one generate() per item, preserving order."""+ from sie_server.adapters.lighton_ocr import LightOnOCRAdapter++ adapter = LightOnOCRAdapter("lightonai/LightOnOCR-2-1B", max_batch_images=1)+ adapter._model = _FakeModel()+ adapter._processor = _FakeProcessor()+ adapter._device = "cpu"++ prepared = [_prepared(_payload(500 + i, 4, 3, 3), i) for i in range(3)]+ out = adapter._extract_preprocessed(+ items=[Item(text="x") for _ in range(3)], prepared_items=prepared, max_new_tokens=8, num_beams=1+ )++ assert [c["input_ids"].shape[0] for c in adapter._model.generate_calls] == [1, 1, 1]+ assert [ents[0]["text"] for ents in out.entities] == [f"id{500 + i}" for i in range(3)]++ def test_extract_preprocessed_mixed_payloads_fall_back(self, adapter: LightOnOCRAdapter) -> None:+ """Non-LightOnOCRPayload items route to _extract_single; payloads still batch, order kept."""+ adapter._model = _FakeModel()+ adapter._processor = _FakeProcessor()+ adapter._device = "cpu"++ def _fake_single(item, **kw):+ return [{"text": "fallback", "label": "markdown", "score": 1.0}]++ adapter._extract_single = _fake_single # ty: ignore[invalid-assignment]++ # Middle item carries a non-LightOnOCRPayload payload -> fallback path.+ prepared = [+ _prepared(_payload(501, 4, 3, 3), 0),+ _prepared(object(), 1),+ _prepared(_payload(503, 4, 3, 3), 2),+ ]+ out = adapter._extract_preprocessed(+ items=[Item(text="x") for _ in range(3)], prepared_items=prepared, max_new_tokens=8, num_beams=1+ )++ # Only the two real payloads are batched (one generate call of size 2).+ assert [c["input_ids"].shape[0] for c in adapter._model.generate_calls] == [2]+ assert [ents[0]["text"] for ents in out.entities] == ["id501", "fallback", "id503"]diff --git a/packages/sie_server/tests/adapters/test_sglang.py b/packages/sie_server/tests/adapters/test_sglang.pyindex 0d9d6c089..333a617e1 100644--- a/packages/sie_server/tests/adapters/test_sglang.py+++ b/packages/sie_server/tests/adapters/test_sglang.py@@ -4,6 +4,7 @@ from unittest.mock import MagicMock, patchimport numpy as npimport pytest+from sie_server.adapters.sglang import _serverfrom sie_server.adapters.sglang._server import STARTUP_TIMEOUT_S as _STARTUP_TIMEOUT_Sfrom sie_server.adapters.sglang._server import parse_device_indexfrom sie_server.adapters.sglang.embedding import SGLangEmbeddingAdapter@@ -39,6 +40,35 @@ class TestSGLangEmbeddingAdapter:assert SGLangEmbeddingAdapter.requires_main_thread is Falseassert SGLangEmbeddingAdapter.manages_own_load_timeout is True+ 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")++ assert _server.resolve_startup_timeout(1800) == 1800++ def test_startup_timeout_accepts_operator_aliases(self, monkeypatch: pytest.MonkeyPatch) -> None:+ for name in _server.STARTUP_TIMEOUT_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setenv("SIE_MODEL_READY_TIMEOUT_S", "1234")++ assert _server.resolve_startup_timeout() == 1234++ def test_startup_timeout_rejects_non_finite_values(self, monkeypatch: pytest.MonkeyPatch) -> None:+ for name in _server.STARTUP_TIMEOUT_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setenv("SIE_MODEL_READY_TIMEOUT_S", "inf")+ monkeypatch.setenv("SIE_SERVER_STARTUP_TIMEOUT_S", "1200")++ assert _server.resolve_startup_timeout(float("inf")) == 1200++ def test_startup_timeout_rejects_liveness_budget_mismatch(self, monkeypatch: pytest.MonkeyPatch) -> None:+ for name in _server.STARTUP_TIMEOUT_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+ monkeypatch.setenv("SIE_WORKER_LIVENESS_BUDGET_S", "900")++ with pytest.raises(ValueError, match="SIE_WORKER_LIVENESS_BUDGET_S"):+ _server.resolve_startup_timeout(900)+def test_dims_before_load_returns_none(self) -> None:"""Dims returns None before first encode."""adapter = SGLangEmbeddingAdapter("test-model")diff --git a/packages/sie_server/tests/adapters/test_sglang_generation.py b/packages/sie_server/tests/adapters/test_sglang_generation.pyindex 98931dbec..f04bd248b 100644--- a/packages/sie_server/tests/adapters/test_sglang_generation.py+++ b/packages/sie_server/tests/adapters/test_sglang_generation.py@@ -90,6 +90,29 @@ def test_load_drops_is_embedding(assert adapter._server_url == "http://localhost:30005"+@patch("sie_server.adapters.sglang._server.wait_for_server", return_value=True)+@patch("sie_server.adapters.sglang._server.subprocess.Popen")+@patch("sie_server.adapters.sglang._server.find_free_port")+def test_load_passes_profile_startup_timeout_to_health_wait(+ mock_find_port: MagicMock,+ mock_popen: MagicMock,+ mock_wait_for_server: MagicMock,+) -> None:+ mock_find_port.return_value = 30005+ mock_process = MagicMock()+ mock_process.poll.return_value = None+ mock_popen.return_value = mock_process+ adapter = SGLangGenerationAdapter(+ model_name_or_path="Qwen/Qwen3.6-27B",+ served_model_name="Qwen/Qwen3.6-27B",+ startup_timeout_s=1800,+ )++ adapter.load("cuda:0")++ assert mock_wait_for_server.call_args.kwargs["timeout_s"] == 1800++@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_vision_patch_embed.py b/packages/sie_server/tests/adapters/test_vision_patch_embed.pynew file mode 100644index 000000000..76f5f4821--- /dev/null+++ b/packages/sie_server/tests/adapters/test_vision_patch_embed.py@@ -0,0 +1,107 @@+from __future__ import annotations++import logging++import pytest+import torch+from sie_server.adapters._vision_patch_embed import rebind_vision_patch_embed+++def _patch_input(conv: torch.nn.Conv2d | torch.nn.Conv3d, n: int = 5) -> torch.Tensor:+ """A pre-patched input batch shaped (n, C, *kernel) — one row per patch."""+ return torch.randn(n, conv.in_channels, *conv.kernel_size)+++class _Conv3dPatchEmbed(torch.nn.Module):+ """Minimal Qwen/GLM-style vision tower: Conv3d patch-embed, kernel == stride, RGB in."""++ def __init__(self) -> None:+ super().__init__()+ self.visual_patch_embed_proj = torch.nn.Conv3d(3, 16, kernel_size=(2, 14, 14), stride=(2, 14, 14))+++class _Conv2dPatchEmbed(torch.nn.Module):+ """Minimal PaddleOCR-VL-style vision tower: Conv2d patch-embed, kernel == stride, RGB in."""++ def __init__(self) -> None:+ super().__init__()+ self.vision_embeddings_patch_embedding = torch.nn.Conv2d(3, 16, kernel_size=(14, 14), stride=(14, 14))+++class _ConvWithDownsample(torch.nn.Module):+ """Vision tower with both an RGB patch-embed AND a spatial-merge downsample conv.++ Only the RGB-input (in_channels <= 4) conv must be rebound; the downsample+ conv consumes the hidden dim and must be left alone.+ """++ def __init__(self) -> None:+ super().__init__()+ self.visual_patch_embed_proj = torch.nn.Conv3d(3, 16, kernel_size=(2, 14, 14), stride=(2, 14, 14))+ self.visual_downsample = torch.nn.Conv2d(16, 32, kernel_size=(2, 2), stride=(2, 2))+++def _assert_rebound_equivalent(model: torch.nn.Module, conv: torch.nn.Conv2d | torch.nn.Conv3d) -> None:+ model.eval()+ probe = _patch_input(conv)+ with torch.inference_mode():+ ref = conv(probe).clone()+ rebind_vision_patch_embed(model, "test")+ with torch.inference_mode():+ got = conv(probe)+ assert got.shape == ref.shape+ assert torch.allclose(got, ref, atol=1e-4, rtol=1e-4)+++def test_rebinds_conv3d_patch_embed_equivalently() -> None:+ model = _Conv3dPatchEmbed()+ _assert_rebound_equivalent(model, model.visual_patch_embed_proj)+++def test_rebinds_conv2d_patch_embed_equivalently() -> None:+ model = _Conv2dPatchEmbed()+ _assert_rebound_equivalent(model, model.vision_embeddings_patch_embedding)+++def test_ignores_non_rgb_downsample_conv() -> None:+ model = _ConvWithDownsample()+ down = model.visual_downsample+ probe_down = _patch_input(down)+ with torch.inference_mode():+ down_ref = down(probe_down).clone()+ _assert_rebound_equivalent(model, model.visual_patch_embed_proj)+ with torch.inference_mode():+ down_after = model.visual_downsample(probe_down)+ assert torch.allclose(down_after, down_ref, atol=1e-4, rtol=1e-4)+++def test_none_model_is_noop() -> None:+ rebind_vision_patch_embed(None, "test")+++def test_no_candidate_conv_skips(caplog: pytest.LogCaptureFixture) -> None:+ class _NoVisionConv(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.linear = torch.nn.Linear(8, 8)++ model = _NoVisionConv()+ with caplog.at_level(logging.WARNING):+ rebind_vision_patch_embed(model, "test")+ assert isinstance(model.linear, torch.nn.Linear)+ assert any("rebind skipped" in r.message for r in caplog.records)+++def test_ambiguous_two_rgb_convs_skips() -> None:+ class _TwoPatchEmbeds(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.visual_patch_embed_a = torch.nn.Conv2d(3, 16, kernel_size=14, stride=14)+ self.visual_patch_embed_b = torch.nn.Conv2d(3, 16, kernel_size=14, stride=14)++ model = _TwoPatchEmbeds()+ a, b = model.visual_patch_embed_a, model.visual_patch_embed_b+ a_fwd, b_fwd = a.forward, b.forward+ rebind_vision_patch_embed(model, "test")+ assert a.forward == a_fwd+ assert b.forward == b_fwddiff --git a/packages/sie_server/tests/config/test_config.py b/packages/sie_server/tests/config/test_config.pyindex 5d533f2f9..e2497a769 100644--- a/packages/sie_server/tests/config/test_config.py+++ b/packages/sie_server/tests/config/test_config.py@@ -744,3 +744,47 @@ class TestKvBudgetTokensValidator:assert isinstance(resolved, ResolvedProfile)assert resolved.kv_budget_tokens == 8192assert resolved.admission_enabled is True+++class TestGrammarProfile:+ """``tasks.generate.grammar_profile`` validation (grammar-request routing)."""++ @staticmethod+ def _config(grammar_profile: str | None, *, with_no_spec: bool = True) -> ModelConfig:+ profiles = {+ "default": ProfileConfig(+ adapter_path="sie_server.adapters.test:TestAdapter",+ max_batch_tokens=8192,+ kv_budget_tokens=1024,+ ),+ }+ if with_no_spec:+ profiles["no-spec"] = ProfileConfig(+ adapter_path="sie_server.adapters.test:TestAdapter",+ max_batch_tokens=8192,+ kv_budget_tokens=1024,+ )+ return ModelConfig(+ sie_id="gen-model",+ hf_id="org/gen",+ tasks=Tasks(+ generate=GenerateTask(context_length=8192, max_output_tokens=512, grammar_profile=grammar_profile)+ ),+ profiles=profiles,+ )++ def test_valid_grammar_profile(self) -> None:+ config = self._config("no-spec")+ assert config.tasks.generate.grammar_profile == "no-spec" # type: ignore[union-attr]++ def test_none_is_default(self) -> None:+ config = self._config(None)+ assert config.tasks.generate.grammar_profile is None # type: ignore[union-attr]++ def test_unknown_grammar_profile_rejected(self) -> None:+ with pytest.raises(ValidationError, match="grammar_profile"):+ self._config("does-not-exist")++ def test_grammar_profile_default_rejected(self) -> None:+ with pytest.raises(ValidationError, match="must not be 'default'"):+ self._config("default")diff --git a/packages/sie_server/tests/core/test_loader.py b/packages/sie_server/tests/core/test_loader.pyindex 2c119668e..0be0d791e 100644--- a/packages/sie_server/tests/core/test_loader.py+++ b/packages/sie_server/tests/core/test_loader.py@@ -165,6 +165,89 @@ profiles:assert len(configs) == 1assert "valid-model" in configs+ def test_profile_max_seq_length_is_promoted_to_variant_context(self, tmp_path: Path) -> None:+ """Profile variants can expose a larger generation context than the base model."""+ (tmp_path / "qwen.yaml").write_text("""+sie_id: Qwen/Qwen3.6-27B+hf_id: Qwen/Qwen3.6-27B+tasks:+ generate:+ context_length: 4096+ max_output_tokens: 4096+max_sequence_length: 4096+profiles:+ default:+ adapter_path: "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"+ max_batch_tokens: 16384+ kv_budget_tokens: 8192+ admission_enabled: true+ adaptive_batching:+ target_p50_ms: 250+ min_wait_ms: 2+ rtx-pro-6000:+ adapter_path: "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"+ max_batch_tokens: 32768+ kv_budget_tokens: 65536+ adapter_options:+ loadtime:+ max_seq_length: 32768+ long-startup:+ adapter_path: "sie_server.adapters.sglang.generation:SGLangGenerationAdapter"+ max_batch_tokens: 32768+ kv_budget_tokens: 32768+ adapter_options:+ loadtime:+ max_seq_length: 32768+ startup_timeout_s: 900+ extra_launch_args:+ - "--example-flag"+ extended-startup:+ extends: default+ adapter_options:+ loadtime:+ max_seq_length: 32768+ startup_timeout_s: 1200+""")++ configs = load_model_configs(tmp_path)++ base = configs["Qwen/Qwen3.6-27B"]+ variant = configs["Qwen/Qwen3.6-27B:rtx-pro-6000"]+ long_startup_variant = configs["Qwen/Qwen3.6-27B:long-startup"]+ extended_startup_variant = configs["Qwen/Qwen3.6-27B:extended-startup"]+ assert base.tasks.generate is not None+ assert variant.tasks.generate is not None+ assert long_startup_variant.tasks.generate is not None+ assert extended_startup_variant.tasks.generate is not None+ assert base.tasks.generate.context_length == 4096+ assert base.max_sequence_length == 4096+ assert variant.tasks.generate.context_length == 32768+ assert variant.max_sequence_length == 32768+ assert long_startup_variant.tasks.generate.context_length == 32768+ assert long_startup_variant.max_sequence_length == 32768+ assert extended_startup_variant.tasks.generate.context_length == 32768+ assert extended_startup_variant.max_sequence_length == 32768+ assert _build_adapter_kwargs(variant, "bfloat16")["max_seq_length"] == 32768+ long_startup_kwargs = _build_adapter_kwargs(long_startup_variant, "bfloat16")+ assert long_startup_kwargs["max_seq_length"] == 32768+ assert long_startup_kwargs["startup_timeout_s"] == 900+ assert long_startup_kwargs["extra_launch_args"] == ["--example-flag"]+ extended_startup_kwargs = _build_adapter_kwargs(extended_startup_variant, "bfloat16")+ assert extended_startup_kwargs["max_seq_length"] == 32768+ assert extended_startup_kwargs["startup_timeout_s"] == 1200+ extended_profile = extended_startup_variant.resolve_profile("default")+ assert extended_profile.kv_budget_tokens == 8192+ assert extended_profile.admission_enabled is True+ assert extended_profile.adaptive_batching is not None+ assert extended_profile.adaptive_batching.target_p50_ms == 250+ assert extended_profile.adaptive_batching.min_wait_ms == 2+ assert extended_startup_variant._resolved_cache is not base._resolved_cache+ assert extended_startup_variant._resolved_cache is not variant._resolved_cache+ assert extended_startup_variant._resolved_cache is not long_startup_variant._resolved_cache+ assert extended_startup_variant._resolved_lock is not base._resolved_lock+ assert extended_startup_variant._resolved_lock is not variant._resolved_lock+ assert extended_startup_variant._resolved_lock is not long_startup_variant._resolved_lock+def test_missing_models_dir(self, tmp_path: Path) -> None:"""Raises FileNotFoundError for missing models directory."""missing_dir = tmp_path / "nonexistent"diff --git a/packages/sie_server/tests/core/test_registry_async.py b/packages/sie_server/tests/core/test_registry_async.pyindex b96eacdd3..b4218e4aa 100644--- a/packages/sie_server/tests/core/test_registry_async.py+++ b/packages/sie_server/tests/core/test_registry_async.py@@ -1,6 +1,6 @@import asynciofrom pathlib import Path-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom sie_server.config.model import EmbeddingDim, EncodeTask, ModelConfig, ProfileConfig, Tasks@@ -55,6 +55,26 @@ class TestAsyncLoading:registry.add_config(config)return registry+ async def test_replace_configs_invalidates_when_model_dir_changes(self, tmp_path: Path) -> None:+ """Same config with a new model_dir must update adapter resolution state."""+ registry = ModelRegistry()+ config = _make_config(name="test-model", hf_id="org/test")+ old_dir = tmp_path / "old"+ new_dir = tmp_path / "new"++ await registry.replace_configs_async([config], model_dir=old_dir)+ registry._loaded["test-model"] = MagicMock()+ registry._do_unload = AsyncMock()++ invalidated = await registry.replace_configs_async(+ [_make_config(name="test-model", hf_id="org/test")],+ model_dir=new_dir,+ )++ assert invalidated == {"test-model"}+ assert registry._model_dirs["test-model"] == new_dir+ registry._do_unload.assert_awaited_once_with("test-model")+async def test_load_async_basic(self, registry_with_model: ModelRegistry) -> None:"""Test basic async loading."""with patch("sie_server.core.model_loader.load_adapter") as mock_load:diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex d33215686..19e284fae 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -461,6 +461,116 @@ profiles:assert not registry.has_model("stale/model")assert registry.has_model("kept/model")+ @pytest.mark.asyncio+ async def test_replace_model_configs_keeps_loaded_model_for_identical_config(self) -> None:+ registry = ModelRegistry(models_dir=None)+ executor = QueueExecutor(registry)++ def model_yaml(model_id: str) -> str:+ return f"""+sie_id: {model_id}+hf_id: sentence-transformers/all-MiniLM-L6-v2+tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+ max_batch_tokens: 4096+"""++ await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=7,+ bundle_config_hash="",+ models=[+ ReplaceModelConfigEntry(+ model_id="kept/model",+ model_config=model_yaml("kept/model"),+ )+ ],+ )+ )+ config_version = registry._config_version+ registry._loaded["kept/model"] = MagicMock()+ registry._do_unload = AsyncMock()++ resp = await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=8,+ bundle_config_hash="",+ models=[+ ReplaceModelConfigEntry(+ model_id="kept/model",+ model_config=model_yaml("kept/model"),+ )+ ],+ )+ )++ assert resp.applied is True+ assert resp.applied_models == ["kept/model"]+ registry._do_unload.assert_not_awaited()+ assert registry._config_version == config_version+ assert registry.has_model("kept/model")++ @pytest.mark.asyncio+ async def test_replace_model_configs_unloads_loaded_model_for_changed_config(self) -> None:+ registry = ModelRegistry(models_dir=None)+ executor = QueueExecutor(registry)++ def model_yaml(model_id: str, *, max_batch_tokens: int) -> str:+ return f"""+sie_id: {model_id}+hf_id: sentence-transformers/all-MiniLM-L6-v2+tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: sie_server.adapters.sentence_transformer:Adapter+ max_batch_tokens: {max_batch_tokens}+"""++ await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=7,+ bundle_config_hash="",+ models=[+ ReplaceModelConfigEntry(+ model_id="kept/model",+ model_config=model_yaml("kept/model", max_batch_tokens=4096),+ )+ ],+ )+ )+ registry._loaded["kept/model"] = MagicMock()+ registry._do_unload = AsyncMock()++ resp = await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=8,+ bundle_config_hash="",+ models=[+ ReplaceModelConfigEntry(+ model_id="kept/model",+ model_config=model_yaml("kept/model", max_batch_tokens=8192),+ )+ ],+ )+ )++ assert resp.applied is True+ assert resp.applied_models == ["kept/model"]+ registry._do_unload.assert_awaited_once_with("kept/model")+ assert registry.get_config("kept/model").profiles["default"].max_batch_tokens == 8192+@pytest.mark.asyncioasync def test_replace_model_configs_reports_pool_filtered_models(self) -> None:registry = ModelRegistry(models_dir=None, pool_name="customer-a")diff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lockindex c293611e6..c6286c4e4 100644--- a/packages/sie_server_sidecar/Cargo.lock+++ b/packages/sie_server_sidecar/Cargo.lock@@ -2208,7 +2208,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-server-sidecar"-version = "0.6.6"+version = "0.6.7"dependencies = ["anyhow","async-nats",diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex ebe88d5e9..2a90c6fdc 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.6"+version = "0.6.7"edition = "2021"description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex dbfc18c35..206d076cc 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -1,365 +1,283 @@# SIE Server Sidecar Architecture-This is the canonical reference for `packages/sie_server_sidecar`.+`packages/sie_server_sidecar` contains the Rust queue runtime used by+sidecar-enabled SIE worker pods.-## Status+The sidecar runs next to `sie-server` in the same worker pod. It consumes NATS+JetStream work, talks to the Python adapter over Unix-domain-socket IPC, and+publishes results back to NATS Core.-The package is production-oriented but still deployment-gated by Helm:+```text+gateway -> NATS JetStream -> worker-sidecar -> UDS IPC -> sie-server adapter+ |+ +-> NATS Core reply subject+```++References:++- [Worker runtime](../../../product/design/worker-runtime.md)+- [Deployment topologies](../../../product/design/deployment-topologies.md)+- [Gateway architecture guide](../../sie_gateway/docs/architecture-guide.md)+- [Sidecar README](../README.md)++## Component Boundaries-- Source package: `packages/sie_server_sidecar`-- Cargo package: `sie-server-sidecar`-- Binary: `sie-server-sidecar`+`sie_gateway` accepts client inference requests, resolves the model, bundle,+machine profile, and pool, publishes work to JetStream, collects worker results,+and owns DLQ publication from JetStream max-delivery advisories.++`worker-sidecar` owns JetStream consumption, subject validation, payload fetch,+batch formation, adaptive scheduling, Rust tokenization when enabled by adapter+descriptors, result framing, ACK/NAK decisions, reply publication, HTTP probes,+Prometheus metrics, NATS health publication, pool admission, and bundle-scoped+config apply.++`sie-server` owns model registry behavior, lazy model loading, GPU residency,+adapter execution, adapter-specific preprocessing and postprocessing, generation+execution, and the IPC server.++The sidecar does not load model weights and does not link GPU libraries.++Public names:++- Rust package and binary: `sie-server-sidecar`- Kubernetes container: `worker-sidecar`- Container image: `ghcr.io/superlinked/sie-server-sidecar`-- Prometheus metric prefix: `sie_worker_`+- Metrics prefix: `sie_worker_*`++## Request Flow++Encode, score, and extract queue traffic follows this path:++1. The gateway publishes a msgpack `WorkItem` to a lane-aware JetStream subject.+2. The sidecar consumes the message from the matching durable consumer.+3. The sidecar validates the NATS subject and reply subject.+4. The sidecar resolves payload references when the work item uses external+ payload storage.+5. The sidecar groups work by model.+6. The sidecar calls `EnsureModelReady` over IPC.+7. The scheduler batches compatible items by operation and LoRA key.+8. The sidecar sends scheduled batches over IPC with `RunBatch`.+9. Python returns per-item outcomes.+10. The sidecar publishes a `WorkResult` to the reply subject.+11. The sidecar ACKs the JetStream message after successful reply publication.++Message settlement:++- Unsafe reply subjects are ACK-dropped.+- Malformed subjects and bad msgpack payloads are NAKed.+- Unknown operations publish per-item error outcomes when reply publication+ succeeds.+- Transient backend, decode, stream, and drain failures are NAKed.+- Reply publication failure leaves the JetStream message unacked.-The Kubernetes container is named `worker-sidecar`, while sidecar-only build-artifacts use the `sie-server-sidecar` family to match the colocated-`sie-server` adapter process. Prometheus metric families use the-`sie_worker_*` prefix because they describe worker-side runtime behavior.+Source: [`dispatcher.rs`](../src/dispatcher.rs),+[`publisher.rs`](../src/publisher.rs), and [`work_types.rs`](../src/work_types.rs).-GPU-independent preparation code lives in this package:+## NATS Subjects-- `src/protocol/` owns the Rust IPC schema.-- `src/prep/` owns GPU-independent prep/framing helpers.-- `src/ipc_types.rs` remains as a re-export so sidecar code can keep using- `crate::ipc_types`.+Pool work uses this subject shape:-`tools/ci/check_ipc_types_parity.py` checks the Rust protocol schema against-`packages/sie_server/src/sie_server/ipc_types.py`.+```text+sie.work.{pool}.{machine_profile}.{bundle}.{model}+```-## Runtime Split+Generation direct dispatch uses this subject shape:-A queue-mode worker pod has two cooperating containers:+```text+sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}+```++The pool stream subject is:```text-gateway -> NATS JetStream -> worker-sidecar -> UDS IPC -> sie-server adapter- |- +-> NATS Core reply subject+sie.work.{pool}.*.*.*```-Responsibilities:--| Component | Owns |-| --- | --- |-| `sie_gateway` | HTTP/API edge, model and pool resolution, JetStream publish, inbox collection, DLQ listener |-| `worker-sidecar` | JetStream pull consumer, subject validation, payload fetch, batch formation, adaptive scheduling, Rust tokenization fast path, result framing, ACK/NAK, reply publish, sidecar metrics/readiness |-| `sie-server` | Python adapter execution, model registry and GPU lifecycle, adapter-specific preprocessing/fallbacks, IPC server, direct HTTP API |--The sidecar never loads model weights and has no GPU dependency. It talks to-the colocated adapter over a Unix domain socket.--## Request Path--1. Gateway publishes a msgpack `WorkItem` on `sie.work.{pool}.{machine_profile}.{bundle}.{model}`.-2. The sidecar's long-lived JetStream pull stream receives messages from- stream `WORK_POOL_{pool}`.-3. The dispatcher extracts the model from the subject and rejects malformed- subjects before trusting payload data.-4. The dispatcher validates `reply_subject`; non-empty values must start with- `_INBOX.`.-5. The sidecar groups by model, calls `EnsureModelReady`, and resolves payload- references if present.-6. The Rust scheduler batches by `(operation, lora_key)` and sends `RunBatch`- over UDS IPC when the adapter declares `supports_run_batch`.-7. Python returns `BatchOutcome` with per-item `ItemOutcome`s.-8. The sidecar frames/publishes `WorkResult` and ACKs the JetStream message.- Publish failure skips ACK so JetStream redelivers.--Failure rules:--- Bad msgpack, malformed subject, transient backend failures, and draining- generally NAK with a delay.-- Unsafe reply subjects are ACK-dropped to avoid publish amplification.-- Unknown operations publish an error outcome and ACK when the reply publish- succeeds.-- IPC transport errors retry once transparently before the group is NAKed.-- Gateway owns DLQ publication by listening to JetStream max-delivery- advisories; the sidecar only ACKs or NAKs.--## NATS Contract--Worker stream and consumer settings must stay aligned with the gateway and SDK:--| Field | Value |-| --- | --- |-| Stream | `WORK_POOL_{pool}` |-| Stream subjects | `sie.work.{pool}.*.*.*` |-| Consumer filter | `sie.work.{pool}.{machine_profile}.{bundle}.*` |-| Retention | WorkQueue |-| Storage | Memory |-| Consumer | `{pool}_{machine_profile}_{bundle}` |-| Ack policy | Explicit |-| Ack wait | 30 s |-| Max deliver | `SIE_MAX_DELIVER`, default 20 |-| Max ack pending | `SIE_MAX_ACK_PENDING`, default 1000 |--On existing streams, the gateway and sidecar reconcile the subject list to-exactly `sie.work.{pool}.*.*.*`. Legacy subjects such as `sie.work.*.{pool}` are-intentionally removed from stream configuration. This release is a cutover to-the lane-aware subject shape, not a mixed-version bridge: all gateways and-workers in the cluster must use the new shape, and any old queued work should be-drained or purged before rollout.--The pull stream must be long-lived. Dropping and recreating pull streams inside-the fetch loop can make async-nats mark unread messages as delivered, causing-redelivery only after the 30 s `ack_wait`. The implementation creates one pull-stream and polls it continuously.-Integration tests guard this with concurrent and sustained-load scenarios that-watch `sie_worker_nats_redelivery_total`.--The sidecar also runs a slow stream/durable reconciler. It periodically-re-ensures `WORK_POOL_{pool}` and `{pool}_{machine_profile}_{bundle}` so NATS-metadata drift can self-heal without adding reconnect-event work or locks to-the fetch loop. It does not rebuild the active pull stream; terminal-pull-stream errors still use the normal pull-loop recovery path.--Generation models use a worker-specific JetStream subject-`sie.work.{pool}.{machine_profile}.{bundle}.{model}.{worker_id}`. The sidecar-creates and polls that worker stream only after Python `WorkerCapabilities`-reports at least one generation model. If live config reconciliation later adds-a generation model to an already-running sidecar, a capability reconciler-activates the direct stream and cancel subscriber exactly once.--When `SIE_GATEWAY_URL` is set, the sidecar runs the pool admission gate before-pulling from either the pool stream or the generation worker stream. Capped-named pools fail closed unless `/v1/pools/{pool}` lists this pod in-`status.assigned_workers`; uncapped pools and profile-uncapped workers continue-pulling. The default pool fails open during transient gateway/status errors so-baseline capacity remains available.--## IPC Contract--Framing is:+The pool durable filter is:++```text+sie.work.{pool}.{machine_profile}.{bundle}.*+```++The sidecar extracts the model from the sixth subject token. Model IDs, bundle+IDs, machine profiles, pool names, and worker IDs are normalized to single NATS+subject tokens by the gateway and sidecar helpers.++The sidecar creates one long-lived async-nats pull stream for pool work. A slow+reconciler re-ensures stream and durable metadata outside the fetch loop.++When generation direct dispatch is active, the sidecar also creates and polls+the worker-specific generation stream and subscribes to `cancel.>`.++Source: [`nats_consumer.rs`](../src/nats_consumer.rs),+[`subject.rs`](../src/subject.rs), and the gateway+[queue publisher](../../sie_gateway/src/queue/publisher.rs).++## Pool Admission++When `SIE_GATEWAY_URL` is configured and pool admission is enabled, the sidecar+checks gateway pool status before pulling from the pool stream or the+worker-specific generation stream.++Capped named pools require the worker to appear in+`status.assigned_workers`. The default pool continues pulling during transient+gateway/status errors.++Source: [`pool_admission.rs`](../src/pool_admission.rs).++## Generation++Generation work uses `ProcessGenerate` over IPC. The sidecar passes the+msgpack-encoded `WorkItem` to Python and handles streaming IPC events.++The gateway streaming path selects either a pool subject or a worker-specific+subject. Worker-specific routing uses HRW over eligible workers. The gateway+stores a pool fallback subject for streaming work and uses it for republish+paths such as NAK handling and first-chunk timeout handling.++The sidecar starts generation direct dispatch after `WorkerCapabilities`+reports generation models. The generation capability reconciler repeats that+probe after live config apply when direct dispatch is not active.++The sidecar subscribes to `cancel.>`. Subjects shaped as+`cancel.{router_id}.{request_id}` are forwarded to Python through+`SignalGenerateCancel`.++Source: [`lib.rs`](../src/lib.rs), [`dispatcher.rs`](../src/dispatcher.rs),+[`ipc_client.rs`](../src/ipc_client.rs), and+[`packages/sie_gateway/src/handlers/proxy.rs`](../../sie_gateway/src/handlers/proxy.rs).++## IPC++IPC framing is:```text[4-byte big-endian length][msgpack named-map body]```-The method surface is:+The Rust and Python protocol copies define the same method names:- `Ping`- `EnsureModelReady`- `ProcessEncodeBatch`- `ProcessScoreBatch`- `ProcessExtractBatch`+- `ProcessGenerate`+- `WorkerCapabilities`+- `SignalGenerateCancel`- `RunBatch`+- `ApplyModelConfig`+- `ReplaceModelConfigs`- `Drain`-`RunBatch` is the hot scheduler path. It carries a homogeneous-op batch; mixed-ops are rejected by Python and pinned by parity fixtures under `tests/parity/`.-Envelope identity fields on `RunBatchItem` preserve `work_item_id`,-`request_id`, and `item_index` even when the operation-specific payload is-missing.+`tools/ci/check_ipc_types_parity.py` checks the Rust protocol schema against+`packages/sie_server/src/sie_server/ipc_types.py`.-`ModelDescriptor` is returned by `EnsureModelReady` and lets the sidecar learn-per-model capabilities at runtime:+`EnsureModelReady` returns readiness state and an optional `ModelDescriptor`.+The descriptor carries tokenizer path, tokenizer content hash, maximum sequence+length, output types, default text templates, and `supports_run_batch`.-- tokenizer path and tokenizer content hash-- maximum sequence length-- supported output types-- `supports_run_batch`+Source: [`protocol/ipc_types.rs`](../src/protocol/ipc_types.rs),+[`ipc_client.rs`](../src/ipc_client.rs), and+[`packages/sie_server/src/sie_server/ipc_types.py`](../../sie_server/src/sie_server/ipc_types.py).-## Scheduler And Batching+## Scheduling-The Rust scheduler is live for queue-mode traffic that reaches this sidecar.-There is no sidecar-local active model list that gates the path; routing is a-gateway/pool decision.+The sidecar scheduler handles queue-mode encode, score, and extract batches for+sidecar-enabled worker pools.-Preserved Python semantics:+Batching keys include operation and LoRA key. Batch formation uses item cost,+request count, coalescing windows, adaptive pull timing, and model-specific+scheduler state. Oversize items flush alone. Per-item outcomes are published+without dropping the rest of the batch.-- cost, count, max-wait, and coalesce-window flush triggers-- oversize item flushes alone-- cost-sorted sub-batch packing-- per-model adaptive controller-- score runs on the base LoRA path-- per-item outcomes fan out without dropping the rest of the batch+Routing remains gateway-owned. The sidecar has no local active-model allowlist+for queue routing.-Production-tuned sidecar defaults:+Source: [`scheduler/`](../src/scheduler/), [`latency.rs`](../src/latency.rs),+and [`dispatcher.rs`](../src/dispatcher.rs).-| Knob | Default | Notes |-| --- | ---: | --- |-| `SIE_RUST_PIPELINE_DEPTH` | 2 | one active adapter batch plus one queued behind it |-| `SIE_BATCHER_COALESCE_MS` | 5 | intentionally lower than Python reference |-| `SIE_BATCHER_MAX_BATCH_REQUESTS` | 12 | intentionally lower than Python reference |-| `SIE_ADAPTIVE_MIN_QUANTUM_MS` | 2 | pull-loop coalesce floor |-| `SIE_ADAPTIVE_MAX_QUANTUM_MS` | 15 | pull-loop coalesce ceiling |-| `SIE_ADAPTIVE_TARGET_P50_MS` | 50 | pull-loop latency target |+## Preparation And Framing-These worker-local defaults cap coalescing and queue depth for CPU-side-responsiveness; they are locked by Rust tests and should be retuned together.+The sidecar performs GPU-independent preparation and framing:-`SIE_PULL_QUANTUM_INCLUDE_QUEUE_MS=1` opts into controller input that includes-queue wait. Default is off because saturation queue time can collapse the pull-quantum even when the pull loop is not the bottleneck.+- text template application for Rust tokenization;+- HF fast-tokenizer loading from adapter-declared paths;+- `PreparedTokens` attachment for encode IPC items;+- payload-store fetch and inline replacement for offloaded work items;+- dense, sparse, multivector, score, and generated-output framing;+- `msgpack_numpy` sentinel-compatible payload handling.-## Prep And Result Framing+Python retokenizes when prepared tokens are absent or the tokenizer hash does+not match. Score pair construction stays in Python. Extract tokenization stays+in Python.-The sidecar owns GPU-independent work:+Large generation and vision payloads are fetched from payload storage and+inlined before `ProcessGenerate`, so Python receives a self-contained msgpack+work item.-- text template application for the safe Rust-tokenization path-- HF fast-tokenizer loading from the adapter-declared tokenizer path-- `PreparedTokens` attachment for encode IPC items where safe-- dense, sparse, multivector, and score `RawOutput` framing-- `msgpack_numpy` sentinel-compatible payload bytes+Source: [`prep/`](../src/prep/), [`tokenize/`](../src/tokenize/),+[`output/`](../src/output/), [`payload_store.rs`](../src/payload_store.rs), and+[`dispatcher.rs`](../src/dispatcher.rs).-Python remains the correctness fallback. If tokens are absent or the-`tokenizer_id` mismatches, Python retokenizes. If a result cannot be represented-by a typed `RawOutput`, Python-framed `result_msgpack` passes through.+## Readiness, Health, And Metrics-Current worker-side boundaries:+The sidecar HTTP server exposes:-- Encode tokenization fast path exists, but individual text adapters still need- byte-identity validation before consuming it everywhere.-- Score pair construction stays adapter-side because query/document pair policy- is model-specific.-- Extract tokenization stays Python-side.-- Native Candle/tch-rs adapter work remains future work behind the same IPC boundary.+- `/healthz`: process liveness;+- `/readyz`: readiness based on successful IPC `Ping`, heartbeat freshness, and+ drain state;+- `/metrics`: Prometheus metrics.-## Readiness And Metrics+Readiness state is shared with the NATS health publisher. The health publisher+emits worker identity, bundle, machine profile, readiness, and the current+bundle config hash.-The sidecar serves HTTP on `SIE_WORKER_METRICS_PORT`, default `9095`:+Source: [`metrics.rs`](../src/metrics.rs),+[`readiness.rs`](../src/readiness.rs), and+[`health_publisher.rs`](../src/health_publisher.rs).-- `/healthz`: always returns 200 while the process is alive.-- `/readyz`: returns 200 only after a successful IPC `Ping`, while the most- recent ping is fresh, and before drain starts.-- `/metrics`: Prometheus metrics.+## Live Config-In Helm, the `worker-sidecar` container exposes container port `metrics`, the-worker Service exposes it as service port `worker-metrics`, and the-ServiceMonitor scrapes that endpoint. Metric families remain `sie_worker_*`-and `sie_pull_loop_*`; do not rename them with the Kubernetes container.--Freshness is `SIE_WORKER_PING_INTERVAL_MS * SIE_WORKER_READYZ_STALE_MULT`.-Defaults are 2000 ms and 3.--Helm can route probes to the sidecar with-`workers.common.workerSidecar.probes.enabled`. This is separate from enabling the-sidecar container itself.--## Important Environment Variables--| Variable | Purpose |-| --- | --- |-| `SIE_NATS_URL` | NATS endpoint; required |-| `SIE_POOL` | pool segment in `sie.work.{pool}.{machine_profile}.{bundle}.{model}` |-| `SIE_MACHINE_PROFILE` | machine-profile segment; required and set explicitly by Helm |-| `SIE_BUNDLE` | bundle/runtime segment and consumer-name segment |-| `SIE_IPC_SOCKET_PATH` | UDS path to the adapter |-| `SIE_IPC_POOL_SIZE` | concurrent IPC connections, default matches dispatch concurrency |-| `SIE_NATS_FETCH_BUDGET` | pull-stream credit and fallback model budget |-| `SIE_NATS_PULL_EXPIRES_S` | server-side pull expiry, default 5 s and must stay below ack wait |-| `SIE_NATS_CONSUMER_RECONCILE_INTERVAL_MS` | slow stream/durable reconcile interval, default 30000; non-zero values below 10000 are clamped; `0` disables |-| `SIE_GENERATION_CAPABILITY_RECONCILE_INTERVAL_MS` | generation direct-dispatch activation check interval after startup reports no generation models, default 30000; non-zero values below 5000 are clamped; `0` disables |-| `SIE_STREAM_MAX_AGE_S` | worker stream max age if worker creates the stream first |-| `SIE_PAYLOAD_STORE_URL` | optional shared payload-store backend (`s3://`, `gs://`, `abfs://`, `abfss://`, or a local path shared with the gateway) |-| `SIE_GATEWAY_URL` | optional gateway base URL used by the pool admission gate |-| `SIE_GATEWAY_API_KEY` | optional bearer token for gateway pool-status reads |-| `SIE_POOL_ADMISSION_ENABLED` | pool admission gate toggle, default true when `SIE_GATEWAY_URL` is set |-| `SIE_POOL_ADMISSION_CHECK_INTERVAL_S` | pool admission status check cadence, default 5 s |-| `SIE_POOL_ADMISSION_PAUSE_S` | sleep while this pod is not admitted to pull, default 1 s |-| `SIE_POOL_ADMISSION_STALE_AFTER_S` | cached-decision window after transient gateway/status errors, default 30 s |-| `SIE_WORKER_METRICS_PORT` | sidecar HTTP port |-| `SIE_HEALTH_PUBLISH_ENABLED` | NATS heartbeat publisher toggle |-| `SIE_HEALTH_PUBLISH_INTERVAL_MS` | NATS heartbeat publish interval |-| `SIE_BUNDLE_CONFIG_HASH` | optional initial local bundle hash; normally populated by live apply/export reconciliation |-| `SIE_CONFIG_SERVICE_URL` | optional `sie-config` base URL for worker-side epoch/export reconciliation |-| `SIE_ADMIN_TOKEN` | optional bearer token for `GET /v1/configs/export` when config auth is enabled |-| `SIE_WORKER_CONFIG_POLL_INTERVAL_MS` | worker config epoch poll interval, default 30000 |-| `SIE_WORKER_CONFIG_FULL_EXPORT_INTERVAL_MS` | slow full-export reconcile interval, default 300000; `0` disables after startup |-| `SIE_NATS_CONFIG_TRUSTED_PRODUCERS` | comma-separated producer allowlist for `sie.config.models.<bundle>`; binary default `sie-config`; Helm sets the release-scoped config Deployment name |-| `SIE_NATS_CONFIG_TRUST_ANY_PRODUCER` | disables producer validation for local/dev only |--Operator-provided Helm `extraEnv` is rendered after chart defaults so explicit-overrides still win.--## Live Config Apply--The sidecar subscribes to `sie.config.models.<SIE_BUNDLE>`. Each notification is-accepted only after producer allowlist, bundle, epoch, and size checks pass.-Accepted deltas are forwarded to Python over IPC `ApplyModelConfig`; Python-validates the YAML as `ModelConfig`, mutates its local `ModelRegistry`, clears-the model descriptor cache, and returns the bundle hash it computes locally.--When `SIE_CONFIG_SERVICE_URL` is set, the sidecar also runs an export-reconciler. It performs a startup `GET /v1/configs/export`, then polls-`GET /v1/configs/epoch`. If the control-plane epoch is ahead, if the-control-plane `bundle_config_hashes_hash` changes, or if the slow full-export-reconcile is due for an epoch-0/no-config-store deployment, it sends the full-bundle-relevant export set to Python over IPC `ReplaceModelConfigs`. Python-validates every entry, unloads removed or changed loaded models, and replaces-the bundle-scoped registry view. The advertised hash advances only after that-replacement succeeds, so a partial export does not produce a false worker ACK.--The NATS health publisher reads that hash dynamically, so the gateway's-`/v1/configs/models/{id}/status` endpoint observes worker convergence without-an explicit ACK message. The dispatcher also checks each incoming work item's-expected `bundle_config_hash` against the current local hash plus a small recent-hash history. Unknown hashes are NAKed before `EnsureModelReady` or Python IPC,-so workers behind the gateway redeliver work after their live NATS subscriber or-export reconciler catches up, while accepted in-flight work remains processable-after an append-only config advance.--Config apply also nudges the generation capability reconciler. This covers the-case where a bundle starts encode-only and later receives a generation model:-the sidecar keeps the encode-only hot path until Python exposes the generation-task, then creates the worker-specific generation stream.--## Known Caveats--- **Stream `max_age` race.** Gateway and worker can both create the stream.- Whichever side creates it first wins. Keep gateway and worker settings aligned- when changing retention.-- **Durable config drift.** The sidecar cleans up overlapping consumers, but a- pure durable config change may still need operator cleanup if JetStream- rejects an update.-- **Config replay scope.** Worker-side export reconciliation replaces model- configs, not bundle definitions or adapter code. Bundle changes still require- a matching `sie-config`/worker image rollout; the running sidecar can only- apply configs for adapters already present in the co-located Python image.-- **Subject shape coupling.** The worker extracts the model from subject token- `parts[5]` in `sie.work.{pool}.{machine_profile}.{bundle}.{model}`. Gateway- subject changes must update worker parsing in lock-step.-- **Unit integration scope.** Rust integration tests use real NATS and a stub- Python IPC server; local Tilt E2E covers the real gateway-to-worker path.-- **Sidecar enablement changes deployment behavior.** Keeping- `workers.common.workerSidecar.enabled` off leaves queue-mode worker pods without- a queue consumer. Flipping that default changes Helm behavior and should be a- deliberate deployment decision.--## Testing--Use the repo tasks:--```bash-mise run server-sidecar-check-mise run server-sidecar-fmt -- --check-mise run server-sidecar-clippy-mise run server-sidecar-test-mise exec -- python tools/ci/check_ipc_types_parity.py-mise run test -- packages/sie_server/tests/test_parity_run_batch.py+The sidecar subscribes to bundle-scoped config deltas:++```text+sie.config.models.{bundle}```-What is covered:--- Rust unit tests for scheduler, adaptive controller, IPC framing/retry,- payload confinement, metrics, output framing, tokenizer registry, publisher,- shutdown, and NATS helpers. `mise run server-sidecar-test` runs the crate once with- default features and once with `cloud-storage` so S3/GCS/Azure payload-store- code is compiled and tested in the normal worker path.-- Rust integration smoke tests with real `nats-server`, real `sie-server-sidecar`, and- a Python IPC harness.-- Python parity tests for `RunBatch` fixtures under `tests/parity/`.-- IPC type parity between Rust and Python schema declarations.--## Architecture Decisions--- Use a sidecar around Python adapters, not a full native rewrite.-- Keep the adapter boundary over UDS msgpack IPC.-- Use a long-lived async-nats pull stream.-- Keep the runtime binary name stable as `sie-server-sidecar`; render the Kubernetes- sidecar container as `worker-sidecar`; publish the container image as- `sie-server-sidecar`.-- Keep queue/runtime/prep/framing work in Rust while adapters remain in Python.-- Treat native Candle/tch-rs backends as future work behind the same adapter- boundary.+Each notification is checked for trusted producer, bundle, epoch, and payload+size. Accepted deltas are forwarded to Python through `ApplyModelConfig`.+Python returns the applied bundle config hash. The sidecar stores that hash in+`ConfigApplyState`.++When `SIE_CONFIG_SERVICE_URL` is configured, the export reconciler fetches+`/v1/configs/epoch` and `/v1/configs/export` from `sie-config`. Bundle-relevant+exports are sent to Python through `ReplaceModelConfigs`.++Export reconciliation skips unchanged periodic exports. Exports older than the+local epoch are skipped unless the reconciler is handling an epoch-rewind+recovery. Partial or rejected replacements do not update the advertised bundle+hash.++Grouped encode, score, and extract work carries the gateway's expected bundle+config hash for the resolved pool and bundle. The dispatcher compares that hash+with the current local hash and the accepted recent-hash window before+`EnsureModelReady`. Unknown hashes are NAKed.++Live config apply updates model configuration in the colocated Python registry.+It does not update adapter code or bundle definitions inside the running worker+image.++Source: [`config_subscriber.rs`](../src/config_subscriber.rs),+[`config_reconciler.rs`](../src/config_reconciler.rs),+[`dispatcher.rs`](../src/dispatcher.rs), and the gateway+[config guide](../../sie_gateway/docs/architecture-guide.md#43-live-deltas).++## Source Links++- Package summary: [README](../README.md)+- Helm values: [`deploy/helm/sie-cluster/values.yaml`](../../../deploy/helm/sie-cluster/values.yaml)+- Runtime config parsing: [`config.rs`](../src/config.rs) and [`main.rs`](../src/main.rs)+- IPC parity check: [`tools/ci/check_ipc_types_parity.py`](../../../tools/ci/check_ipc_types_parity.py)+- Gateway queue contract: [gateway architecture guide](../../sie_gateway/docs/architecture-guide.md)diff --git a/packages/sie_server_sidecar/src/config.rs b/packages/sie_server_sidecar/src/config.rsindex 15e2f2ed8..0f16fd43a 100644--- a/packages/sie_server_sidecar/src/config.rs+++ b/packages/sie_server_sidecar/src/config.rs@@ -29,6 +29,17 @@ pub struct WorkerConfig {/// `SIE_MAX_CONCURRENT_BATCHES`'s default (4).pub ipc_pool_size: usize,+ /// Per-RPC timeout for ordinary sidecar → Python IPC calls. Sourced from+ /// `SIE_IPC_REQUEST_TIMEOUT_S`.+ pub ipc_request_timeout_s: u64,++ /// Timeout for sidecar → Python `EnsureModelReady` calls. Must be at least+ /// as long as the slowest expected cold start; SGLang adapters may+ /// legitimately spend many minutes loading large models before they can+ /// answer the readiness handshake. Sourced from+ /// `SIE_MODEL_READY_TIMEOUT_S`.+ pub model_ready_timeout_s: u64,+/// Optional payload store URL — if unset, workers expect items inline/// (large items will be rejected by the gateway's offload). Local paths/// point at a shared directory; `s3://…` / `gs://…` / `abfs://…` /@@ -194,6 +205,8 @@ mod tests {bundle: "default".into(),ipc_socket_path: PathBuf::from("/tmp/sie-ipc.sock"),ipc_pool_size: 1,+ ipc_request_timeout_s: 60,+ model_ready_timeout_s: 900,payload_store_url: None,gateway_url: None,gateway_api_key: None,diff --git a/packages/sie_server_sidecar/src/config_reconciler.rs b/packages/sie_server_sidecar/src/config_reconciler.rsindex 9c549eb46..7e8e64926 100644--- a/packages/sie_server_sidecar/src/config_reconciler.rs+++ b/packages/sie_server_sidecar/src/config_reconciler.rs@@ -5,8 +5,8 @@//! published while a worker was disconnected. This module closes that gap by//! polling `GET /v1/configs/epoch` and fetching `GET /v1/configs/export` when//! the control plane is ahead or when its compact per-bundle config fingerprint-//! changes. A slower full-export pass also covers legacy/no-config-store-//! deployments where `sie-config` keeps epoch at `0`.+//! changes. A slower full-export pass also covers legacy deployments where+//! `sie-config` cannot provide a compact fingerprint.use std::collections::HashMap;use std::future::Future;@@ -111,6 +111,14 @@ struct ExportOutcome {skipped: usize,shutdown: bool,state_updated: bool,+ export_signature: Option<blake3::Hash>,+}++#[derive(Debug, Clone, Copy)]+struct ExportReconcileOptions<'a> {+ force_epoch: bool,+ reason: &'a str,+ previous_export_signature: Option<blake3::Hash>,}struct ReconcileClient {@@ -207,6 +215,33 @@ fn drift_reason(None}+fn compute_export_signature(+ bundle: &str,+ bundle_config_hash: Option<&str>,+ models: &[ReplaceModelConfigEntry],+) -> blake3::Hash {+ fn update_len_prefixed(hasher: &mut blake3::Hasher, value: &str) {+ hasher.update(&(value.len() as u64).to_le_bytes());+ hasher.update(value.as_bytes());+ }++ let mut hasher = blake3::Hasher::new();+ update_len_prefixed(&mut hasher, bundle);+ update_len_prefixed(&mut hasher, bundle_config_hash.unwrap_or_default());++ let mut entries: Vec<(&str, &str)> = models+ .iter()+ .map(|model| (model.model_id.as_str(), model.model_config.as_str()))+ .collect();+ entries.sort_unstable_by(|left, right| left.0.cmp(right.0).then_with(|| left.1.cmp(right.1)));+ hasher.update(&(entries.len() as u64).to_le_bytes());+ for (model_id, model_config) in entries {+ update_len_prefixed(&mut hasher, model_id);+ update_len_prefixed(&mut hasher, model_config);+ }+ hasher.finalize()+}+/// Spawn the optional export reconciler.////// The task is disabled when `config.base_url` is empty. The caller owns the@@ -252,6 +287,7 @@ pub fn spawn(shutdown: Arc::clone(&shutdown),};let mut last_successful_export: Option<Instant> = None;+ let mut last_export_signature: Option<blake3::Hash> = None;let mut last_bundle_config_hashes_hash = match client.fetch_epoch().await {Ok(snapshot) => snapshot.bundle_config_hashes_hash,Err(e) => {@@ -262,10 +298,13 @@ pub fn spawn(String::new()}};- match reconcile_export(&runtime, false, "startup").await {+ match reconcile_export(&runtime, false, "startup", None).await {Ok(outcome) if outcome.shutdown => return,Ok(outcome) if outcome.failed == 0 => {last_successful_export = Some(Instant::now());+ if let Some(signature) = outcome.export_signature {+ last_export_signature = Some(signature);+ }if outcome.applied > 0 {if let Some(notify) = generation_reconcile.as_ref() {notify.notify_one();@@ -354,12 +393,15 @@ pub fn spawn();}- match reconcile_export(&runtime, force_epoch, reason)+ match reconcile_export(&runtime, force_epoch, reason, last_export_signature).await{Ok(outcome) if outcome.shutdown => return,Ok(outcome) if outcome.failed == 0 => {last_successful_export = Some(Instant::now());+ if let Some(signature) = outcome.export_signature {+ last_export_signature = Some(signature);+ }if !remote_bundle_config_hashes_hash.is_empty() {last_bundle_config_hashes_hash =remote_bundle_config_hashes_hash.clone();@@ -403,6 +445,7 @@ async fn reconcile_export(runtime: &ReconcileRuntime<'_>,force_epoch: bool,reason: &str,+ previous_export_signature: Option<blake3::Hash>,) -> Result<ExportOutcome, ReconcileError> {let snapshot = runtime.client.fetch_export().await?;let ipc = Arc::clone(&runtime.ipc);@@ -412,8 +455,11 @@ async fn reconcile_export(runtime.bundle,&runtime.state,&runtime.metrics,- force_epoch,- reason,+ ExportReconcileOptions {+ force_epoch,+ reason,+ previous_export_signature,+ },move |req, epoch| {let ipc = Arc::clone(&ipc);let shutdown = Arc::clone(&shutdown);@@ -428,8 +474,7 @@ async fn reconcile_export_snapshot<F, Fut>(bundle: &str,state: &ConfigApplyState,metrics: &MetricsRegistry,- force_epoch: bool,- reason: &str,+ options: ExportReconcileOptions<'_>,mut apply: F,) -> ExportOutcomewhere@@ -438,7 +483,7 @@ where{let _apply_guard = state.lock_apply().await;- if !force_epoch && snapshot.epoch < state.epoch() {+ if !options.force_epoch && snapshot.epoch < state.epoch() {record_reconcile(metrics, "stale_export");return ExportOutcome {epoch: snapshot.epoch,@@ -447,6 +492,7 @@ whereskipped: snapshot.models.len(),shutdown: false,state_updated: false,+ export_signature: None,};}@@ -497,6 +543,36 @@ where});}+ let export_signature = if failed == 0 {+ Some(compute_export_signature(+ bundle,+ control_plane_hash.as_deref(),+ &exported_models,+ ))+ } else {+ None+ };++ if options.reason == "periodic_export"+ && export_signature.is_some()+ && export_signature == options.previous_export_signature+ {+ record_reconcile(metrics, "no_change");+ debug!(+ epoch = snapshot.epoch,+ skipped, "worker-config: periodic export unchanged; skipping replace"+ );+ return ExportOutcome {+ epoch: snapshot.epoch,+ applied: 0,+ failed: 0,+ skipped,+ shutdown: false,+ state_updated: false,+ export_signature,+ };+ }+let state_updated = if failed == 0 {let req = ReplaceModelConfigsRequest {bundle_id: bundle.to_string(),@@ -515,6 +591,7 @@ whereskipped,shutdown: true,state_updated: false,+ export_signature,};}Err(e) => {@@ -531,6 +608,7 @@ whereskipped,shutdown: false,state_updated: false,+ export_signature,};}};@@ -548,6 +626,7 @@ whereskipped,shutdown: false,state_updated: false,+ export_signature,};}@@ -570,8 +649,11 @@ where"worker-config: Python registry hash differs from control-plane export hash; advertising Python-applied hash");}- let state_updated =- state.mark_export_reconciled(snapshot.epoch, Some(applied_bundle_hash), force_epoch);+ let state_updated = state.mark_export_reconciled(+ snapshot.epoch,+ Some(applied_bundle_hash),+ options.force_epoch,+ );if state_updated {metrics.config_epoch.set(snapshot.epoch as i64);}@@ -596,7 +678,7 @@ whereapplied,failed,skipped,- reason,+ reason = options.reason,state_updated,"worker-config: export reconcile attempt finished");@@ -608,6 +690,7 @@ whereskipped,shutdown: false,state_updated,+ export_signature,}}@@ -618,19 +701,35 @@ mod tests {use tokio::sync::Mutex;- fn exported_model(model_id: &str, bundles: &[&str]) -> ExportedModel {+ fn exported_model_with_yaml(model_id: &str, bundles: &[&str], raw_yaml: &str) -> ExportedModel {ExportedModel {model_id: model_id.into(),- raw_yaml: Some(format!("sie_id: {model_id}\nprofiles:\n default: {{}}\n")),+ raw_yaml: Some(raw_yaml.to_string()),model_config: None,affected_bundles: bundles.iter().map(|b| (*b).to_string()).collect(),}}+ fn exported_model(model_id: &str, bundles: &[&str]) -> ExportedModel {+ exported_model_with_yaml(+ model_id,+ bundles,+ &format!("sie_id: {model_id}\nprofiles:\n default: {{}}\n"),+ )+ }+fn metrics() -> MetricsRegistry {MetricsRegistry::new().expect("metrics registry")}+ fn reconcile_options(reason: &'static str) -> ExportReconcileOptions<'static> {+ ExportReconcileOptions {+ force_epoch: false,+ reason,+ previous_export_signature: None,+ }+ }+#[test]fn drift_reason_detects_same_epoch_bundle_config_hashes_hash_change() {let remote = EpochSnapshot {@@ -654,6 +753,29 @@ mod tests {);}+ #[test]+ fn drift_reason_preserves_epoch_zero_periodic_export_with_stable_fingerprint() {+ let remote = EpochSnapshot {+ epoch: 0,+ bundle_config_hashes_hash: "stable-fingerprint".into(),+ };++ assert_eq!(+ drift_reason(0, &remote, "stable-fingerprint", true),+ Some("periodic_export")+ );+ assert_eq!(drift_reason(0, &remote, "stable-fingerprint", false), None);++ let legacy_remote = EpochSnapshot {+ epoch: 0,+ bundle_config_hashes_hash: String::new(),+ };+ assert_eq!(+ drift_reason(0, &legacy_remote, "stable-fingerprint", true),+ Some("periodic_export")+ );+ }+#[test]fn exported_model_targets_exact_bundle_only() {let model = ExportedModel {@@ -706,8 +828,13 @@ mod tests {let metrics = metrics();let applied = Arc::new(Mutex::new(Vec::new()));- let outcome =- reconcile_export_snapshot(snapshot, "default", &state, &metrics, false, "test", {+ let outcome = reconcile_export_snapshot(+ snapshot,+ "default",+ &state,+ &metrics,+ reconcile_options("test"),+ {let applied = Arc::clone(&applied);move |req, _epoch| {let applied = Arc::clone(&applied);@@ -721,8 +848,9 @@ mod tests {}))}}- })- .await;+ },+ )+ .await;assert_eq!(outcome.applied, 1);assert_eq!(outcome.failed, 0);@@ -760,8 +888,7 @@ mod tests {"default",&state,&metrics,- false,- "test",+ reconcile_options("test"),|req, _epoch| async move {if req.models.iter().any(|model| model.model_id == "bad-model") {Err(IpcError::Server("apply failed".into()))@@ -804,8 +931,10 @@ mod tests {"default",&state,&metrics,- true,- "test",+ ExportReconcileOptions {+ force_epoch: true,+ ..reconcile_options("test")+ },|_req, _epoch| async move {Ok(Some(ReplaceModelConfigsResponse {applied: true,@@ -845,8 +974,7 @@ mod tests {"default",&state,&metrics,- false,- "test",+ reconcile_options("test"),|_req, _epoch| async move {Ok(Some(ReplaceModelConfigsResponse {applied: true,@@ -878,8 +1006,13 @@ mod tests {let metrics = metrics();let replace_calls = Arc::new(Mutex::new(Vec::new()));- let outcome =- reconcile_export_snapshot(snapshot, "default", &state, &metrics, false, "test", {+ let outcome = reconcile_export_snapshot(+ snapshot,+ "default",+ &state,+ &metrics,+ reconcile_options("test"),+ {let replace_calls = Arc::clone(&replace_calls);move |req, _epoch| {let replace_calls = Arc::clone(&replace_calls);@@ -893,8 +1026,9 @@ mod tests {}))}}- })- .await;+ },+ )+ .await;assert_eq!(outcome.applied, 0);assert_eq!(outcome.failed, 0);@@ -906,4 +1040,172 @@ mod tests {assert_eq!(replace_calls.len(), 1);assert!(replace_calls[0].models.is_empty());}++ #[tokio::test]+ async fn export_reconcile_skips_unchanged_periodic_snapshot_before_ipc() {+ let state = ConfigApplyState::new("old".into());+ let metrics = metrics();+ let replace_calls = Arc::new(Mutex::new(Vec::new()));++ let initial = reconcile_export_snapshot(+ ExportSnapshot {+ epoch: 0,+ bundle_config_hashes: HashMap::from([(+ "default".to_string(),+ "control-hash".to_string(),+ )]),+ models: vec![exported_model("target-model", &["default"])],+ },+ "default",+ &state,+ &metrics,+ reconcile_options("startup"),+ {+ let replace_calls = Arc::clone(&replace_calls);+ move |req, _epoch| {+ let replace_calls = Arc::clone(&replace_calls);+ async move {+ replace_calls.lock().await.push(req);+ Ok(Some(ReplaceModelConfigsResponse {+ applied: true,+ bundle_config_hash: "control-hash".into(),+ config_version: 1,+ applied_models: vec!["target-model".into()],+ }))+ }+ }+ },+ )+ .await;+ let signature = initial.export_signature.expect("initial signature");++ let unchanged = reconcile_export_snapshot(+ ExportSnapshot {+ epoch: 0,+ bundle_config_hashes: HashMap::from([(+ "default".to_string(),+ "control-hash".to_string(),+ )]),+ models: vec![exported_model("target-model", &["default"])],+ },+ "default",+ &state,+ &metrics,+ ExportReconcileOptions {+ previous_export_signature: Some(signature),+ ..reconcile_options("periodic_export")+ },+ {+ let replace_calls = Arc::clone(&replace_calls);+ move |req, _epoch| {+ let replace_calls = Arc::clone(&replace_calls);+ async move {+ replace_calls.lock().await.push(req);+ Ok(Some(ReplaceModelConfigsResponse {+ applied: true,+ bundle_config_hash: "control-hash".into(),+ config_version: 2,+ applied_models: vec!["target-model".into()],+ }))+ }+ }+ },+ )+ .await;++ assert_eq!(unchanged.applied, 0);+ assert_eq!(unchanged.failed, 0);+ assert!(!unchanged.state_updated);+ assert_eq!(replace_calls.lock().await.len(), 1);+ }++ #[tokio::test]+ async fn export_reconcile_applies_epoch_zero_periodic_snapshot_when_body_changes() {+ let state = ConfigApplyState::new("old".into());+ let metrics = metrics();+ let replace_calls = Arc::new(Mutex::new(Vec::new()));++ let initial = reconcile_export_snapshot(+ ExportSnapshot {+ epoch: 0,+ bundle_config_hashes: HashMap::from([(+ "default".to_string(),+ "stable-routing-hash".to_string(),+ )]),+ models: vec![exported_model_with_yaml(+ "target-model",+ &["default"],+ "sie_id: target-model\nprofiles:\n default:\n max_batch_tokens: 4096\n",+ )],+ },+ "default",+ &state,+ &metrics,+ reconcile_options("startup"),+ {+ let replace_calls = Arc::clone(&replace_calls);+ move |req, _epoch| {+ let replace_calls = Arc::clone(&replace_calls);+ async move {+ replace_calls.lock().await.push(req);+ Ok(Some(ReplaceModelConfigsResponse {+ applied: true,+ bundle_config_hash: "stable-routing-hash".into(),+ config_version: 1,+ applied_models: vec!["target-model".into()],+ }))+ }+ }+ },+ )+ .await;+ let signature = initial.export_signature.expect("initial signature");++ let changed = reconcile_export_snapshot(+ ExportSnapshot {+ epoch: 0,+ bundle_config_hashes: HashMap::from([(+ "default".to_string(),+ "stable-routing-hash".to_string(),+ )]),+ models: vec![exported_model_with_yaml(+ "target-model",+ &["default"],+ "sie_id: target-model\nprofiles:\n default:\n max_batch_tokens: 8192\n",+ )],+ },+ "default",+ &state,+ &metrics,+ ExportReconcileOptions {+ previous_export_signature: Some(signature),+ ..reconcile_options("periodic_export")+ },+ {+ let replace_calls = Arc::clone(&replace_calls);+ move |req, _epoch| {+ let replace_calls = Arc::clone(&replace_calls);+ async move {+ let applied_models = req+ .models+ .iter()+ .map(|model| model.model_id.clone())+ .collect();+ replace_calls.lock().await.push(req);+ Ok(Some(ReplaceModelConfigsResponse {+ applied: true,+ bundle_config_hash: "stable-routing-hash".into(),+ config_version: 2,+ applied_models,+ }))+ }+ }+ },+ )+ .await;++ assert_eq!(changed.applied, 1);+ assert_eq!(changed.failed, 0);+ assert_eq!(replace_calls.lock().await.len(), 2);+ }}diff --git a/packages/sie_server_sidecar/src/ipc_client.rs b/packages/sie_server_sidecar/src/ipc_client.rsindex b2e0b7188..365b8853e 100644--- a/packages/sie_server_sidecar/src/ipc_client.rs+++ b/packages/sie_server_sidecar/src/ipc_client.rs@@ -357,6 +357,7 @@ pub struct IpcClient {pool: Arc<Pool>,next_request_id: AtomicU64,request_timeout: Duration,+ model_ready_timeout: Duration,metrics: Option<Arc<MetricsRegistry>>,/// When `Some`, every `call(…)` is delegated to the multiplexed/// transport instead of acquiring a slot from the pool. Lazily@@ -390,6 +391,7 @@ impl IpcClient {pool: Arc::new(Pool::new(capacity, None)),next_request_id: AtomicU64::new(1),request_timeout: Duration::from_secs(60),+ model_ready_timeout: Duration::from_secs(60),metrics: None,mux,}@@ -400,6 +402,11 @@ impl IpcClient {self}+ pub fn with_model_ready_timeout(mut self, timeout: Duration) -> Self {+ self.model_ready_timeout = timeout;+ self+ }+/// Attach a metrics registry so each RPC records per-method latency,/// frame sizes, and connect/reconnect events — plus pool saturation/// (`ipc_pool_inflight`, `ipc_pool_acquire_wait_seconds`). No-op if@@ -483,6 +490,20 @@ impl IpcClient {/// successful RPC. Trait bound `Req: Clone` was removed with this/// refactor; only `Serialize` remains.pub async fn call<Req, Resp>(&self, method: &str, body: Req) -> Result<Resp, IpcError>+ where+ Req: Serialize,+ Resp: DeserializeOwned,+ {+ self.call_with_timeout(method, body, self.request_timeout)+ .await+ }++ async fn call_with_timeout<Req, Resp>(+ &self,+ method: &str,+ body: Req,+ request_timeout: Duration,+ ) -> Result<Resp, IpcError>whereReq: Serialize,Resp: DeserializeOwned,@@ -515,7 +536,7 @@ impl IpcClient {// confused with a stale response.if let Some(mux) = &self.mux {let first = self- .mux_call::<Resp>(mux, method, request_id.clone(), &payload)+ .mux_call::<Resp>(mux, method, request_id.clone(), &payload, request_timeout).await;return match first {Ok(v) => {@@ -532,7 +553,7 @@ impl IpcClient {m.ipc_reconnect_total.inc();}match self- .mux_call::<Resp>(mux, method, request_id, &payload)+ .mux_call::<Resp>(mux, method, request_id, &payload, request_timeout).await{Ok(v) => {@@ -558,7 +579,7 @@ impl IpcClient {let mut slot_guard = self.pool.acquire().await;slot_guard.arm();let first = timeout(- self.request_timeout,+ request_timeout,self.call_inner::<Resp>(method, &payload, slot_guard.slot_mut()),).await;@@ -600,7 +621,7 @@ impl IpcClient {let mut retry_guard = self.pool.acquire().await;retry_guard.arm();let second = timeout(- self.request_timeout,+ request_timeout,self.call_inner::<Resp>(method, &payload, retry_guard.slot_mut()),).await;@@ -652,16 +673,12 @@ impl IpcClient {method: &str,request_id: String,payload: &[u8],+ request_timeout: Duration,) -> Result<Resp, IpcError>whereResp: DeserializeOwned,{- let raw = match timeout(- self.request_timeout,- mux.call_raw(request_id, payload.to_vec()),- )- .await- {+ let raw = match timeout(request_timeout, mux.call_raw(request_id, payload.to_vec())).await {Ok(r) => r,Err(_) => return Err(IpcError::Timeout),};@@ -903,11 +920,12 @@ impl IpcClient {&self,model_id: impl Into<String>,) -> Result<EnsureModelReadyResponse, IpcError> {- self.call(+ self.call_with_timeout(METHOD_ENSURE_MODEL_READY,EnsureModelReadyRequest {model_id: model_id.into(),},+ self.model_ready_timeout,).await}diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex 5d539e115..ac916b24d 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -321,12 +321,15 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {// raw IPC client, only the backend trait object.let ipc = Arc::new(IpcClient::new_pool(&config.ipc_socket_path, config.ipc_pool_size)- .with_timeout(Duration::from_secs(60))+ .with_timeout(Duration::from_secs(config.ipc_request_timeout_s))+ .with_model_ready_timeout(Duration::from_secs(config.model_ready_timeout_s)).with_metrics(Arc::clone(&metrics_registry)),);info!(socket = %config.ipc_socket_path.display(),ipc_pool_size = config.ipc_pool_size,+ ipc_request_timeout_s = config.ipc_request_timeout_s,+ model_ready_timeout_s = config.model_ready_timeout_s,"IPC client initialized with connection pool");let generation_capable = detect_generation_capable(&ipc).await;diff --git a/packages/sie_server_sidecar/src/main.rs b/packages/sie_server_sidecar/src/main.rsindex caa6ec7b7..97f0e81a5 100644--- a/packages/sie_server_sidecar/src/main.rs+++ b/packages/sie_server_sidecar/src/main.rs@@ -35,6 +35,21 @@ struct Cli {#[arg(long, env = "SIE_IPC_POOL_SIZE")]ipc_pool_size: Option<usize>,+ /// Timeout, in seconds, for ordinary sidecar → Python IPC calls.+ #[arg(long, env = "SIE_IPC_REQUEST_TIMEOUT_S", default_value = "60")]+ ipc_request_timeout_s: u64,++ /// Timeout, in seconds, for EnsureModelReady cold-load calls. Large SGLang+ /// models can spend minutes here while the subprocess loads and reaches+ /// health.+ #[arg(long, env = "SIE_MODEL_READY_TIMEOUT_S")]+ model_ready_timeout_s: Option<u64>,++ /// Python worker liveness budget in seconds. When set by Helm, the sidecar+ /// rejects an EnsureModelReady timeout kubelet would kill before completion.+ #[arg(long, env = "SIE_WORKER_LIVENESS_BUDGET_S")]+ worker_liveness_budget_s: Option<u64>,+#[arg(long, env = "SIE_PAYLOAD_STORE_URL")]payload_store_url: Option<String>,@@ -146,6 +161,8 @@ async fn main() -> anyhow::Result<()> {let pool = validate_lane_segment("SIE_POOL", cli.pool)?;let bundle = validate_lane_segment("SIE_BUNDLE", cli.bundle)?;let machine_profile = validate_lane_segment("SIE_MACHINE_PROFILE", cli.machine_profile)?;+ let model_ready_timeout_s = cli.model_ready_timeout_s.unwrap_or(900).max(1);+ validate_model_ready_liveness_budget(model_ready_timeout_s, cli.worker_liveness_budget_s)?;let config = WorkerConfig {nats_url: cli.nats_url,pool,@@ -155,6 +172,8 @@ async fn main() -> anyhow::Result<()> {.ipc_pool_size.filter(|&n| n > 0).unwrap_or_else(default_max_concurrent_batches),+ ipc_request_timeout_s: cli.ipc_request_timeout_s.max(1),+ model_ready_timeout_s,payload_store_url: cli.payload_store_url,gateway_url: cli.gateway_url.filter(|url| !url.trim().is_empty()),gateway_api_key: cli.gateway_api_key.filter(|token| !token.trim().is_empty()),@@ -239,9 +258,30 @@ fn seconds_to_millis(seconds: f64, min_ms: u64) -> u64 {((seconds * 1_000.0).round() as u64).max(min_ms)}+fn validate_model_ready_liveness_budget(+ model_ready_timeout_s: u64,+ worker_liveness_budget_s: Option<u64>,+) -> anyhow::Result<()> {+ let Some(worker_liveness_budget_s) = worker_liveness_budget_s else {+ return Ok(());+ };+ if worker_liveness_budget_s == 0 {+ anyhow::bail!("SIE_WORKER_LIVENESS_BUDGET_S must be positive when set");+ }+ if model_ready_timeout_s >= worker_liveness_budget_s {+ anyhow::bail!(+ "SIE_MODEL_READY_TIMEOUT_S ({model_ready_timeout_s}s) must be lower than \+ SIE_WORKER_LIVENESS_BUDGET_S ({worker_liveness_budget_s}s) so kubelet liveness \+ does not kill the worker mid-load"+ );+ }+ Ok(())+}+#[cfg(test)]mod tests {use super::validate_lane_segment;+ use super::validate_model_ready_liveness_budget;#[test]fn validate_lane_segment_trims_valid_values() {@@ -257,4 +297,17 @@ mod tests {assert!(validate_lane_segment("SIE_POOL", raw.to_string()).is_err());}}++ #[test]+ fn validate_model_ready_liveness_budget_accepts_missing_or_larger_budget() {+ validate_model_ready_liveness_budget(900, None).unwrap();+ validate_model_ready_liveness_budget(900, Some(1080)).unwrap();+ }++ #[test]+ fn validate_model_ready_liveness_budget_rejects_impossible_budget() {+ assert!(validate_model_ready_liveness_budget(900, Some(0)).is_err());+ assert!(validate_model_ready_liveness_budget(900, Some(900)).is_err());+ assert!(validate_model_ready_liveness_budget(1200, Some(1080)).is_err());+ }}diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rsindex a7fd4e4e5..b7160b43f 100644--- a/packages/sie_server_sidecar/src/nats_consumer.rs+++ b/packages/sie_server_sidecar/src/nats_consumer.rs@@ -704,6 +704,8 @@ mod tests {bundle: "b".into(),ipc_socket_path: PathBuf::from("/tmp/s.sock"),ipc_pool_size: 1,+ ipc_request_timeout_s: 60,+ model_ready_timeout_s: 900,payload_store_url: None,gateway_url: None,gateway_api_key: None,diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex 09fe06ced..dbd8785de 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.6",+ "version": "0.6.7","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 0b60cdb79..994394973 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.6"; // x-release-please-version+export const SDK_VERSION = "0.6.7"; // x-release-please-versiondiff --git a/uv.lock b/uv.lockindex a679de347..9c56158bb 100644--- a/uv.lock+++ b/uv.lock@@ -5718,7 +5718,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.6.6"+version = "0.6.7"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5751,7 +5751,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.6.6"+version = "0.6.7"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5836,7 +5836,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.6.6"+version = "0.6.7"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5908,7 +5908,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.6.6"+version = "0.6.7"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5933,7 +5933,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.6.6"+version = "0.6.7"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5958,7 +5958,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.6.6"+version = "0.6.7"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5985,7 +5985,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.6.6"+version = "0.6.7"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -6012,7 +6012,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.6.6"+version = "0.6.7"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -6039,7 +6039,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.6.6"+version = "0.6.7"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -6105,7 +6105,7 @@ dev = [[[package]]name = "sie-qdrant"-version = "0.6.6"+version = "0.6.7"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -6128,7 +6128,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.6.6"+version = "0.6.7"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -6181,7 +6181,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.6.6"+version = "0.6.7"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -6311,7 +6311,7 @@ requires-dist = [[[package]]name = "sie-weaviate"-version = "0.6.6"+version = "0.6.7"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },