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
fix(config): validate model config writes against the worker schema and support chart rollback (#392)
Krisztian Gajdar296998f630f2
diff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex 66ae15e94..ad25aebfd 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -306,9 +306,10 @@ release record conservative with maximum-length, high-entropy identities. WithHelm 3.16.4, the external profile encodes 192 lanes to about 840 KiB and theworst bundled profile encodes 96 lanes to about 853 KiB, each leaving at least64 KiB below the 917,504-byte release budget at this revision.-The ordinary post-install/post-upgrade hook applies the target shards and-prunes removed release-managed ScaledObjects. It refuses to adopt a same-name-object unless that object already carries this Helm release's exact identity.+The ordinary post-install/post-upgrade/post-rollback hook applies the target+shards and prunes removed release-managed ScaledObjects. It refuses to adopt a+same-name object unless that object already carries this Helm release's exact+identity.Because those manifests are intentionally non-secret ConfigMaps, restrictwrite access in the workload namespace to trusted control-plane principals.@@ -361,6 +362,12 @@ kubectl delete configmap "$LEGACY_KEDA_CONFIGMAP" -n <NAMESPACE> --ignore-not-fo```Fresh installs and later compatible releases use the normal Helm procedure.+`helm rollback` runs the target revision's stored hooks: it re-applies that+revision's ScaledObjects and prunes the others, and a target revision with+autoscaling disabled first removes the release-owned ScaledObjects. Health+gates run on install and upgrade only. A revision installed by an earlier chart+version carries no rollback hooks, so rolling back to it leaves ScaledObjects+unchanged; roll forward instead.Disabling autoscaling or uninstalling runs a small hook that deletes onlyScaledObjects carrying this release's managed identity or the exact canonicaldiff --git a/deploy/helm/sie-cluster/templates/keda-lifecycle.yaml b/deploy/helm/sie-cluster/templates/keda-lifecycle.yamlindex cdf6bb2d9..f481cfff2 100644--- a/deploy/helm/sie-cluster/templates/keda-lifecycle.yaml+++ b/deploy/helm/sie-cluster/templates/keda-lifecycle.yaml@@ -5,11 +5,10 @@{{- $hooks := "pre-delete" -}}{{- if not .Values.autoscaling.enabled -}}{{- /*- pre-upgrade removes ScaledObjects while a bundled source KEDA controller is- still present. A failed upgrade is repaired and retried forward; rollback is- intentionally unsupported.+ pre-upgrade and pre-rollback remove ScaledObjects while a bundled source KEDA+ controller is still present.*/ -}}-{{- $hooks = "pre-upgrade,pre-delete" -}}+{{- $hooks = "pre-upgrade,pre-rollback,pre-delete" -}}{{- end -}}apiVersion: v1kind: ServiceAccountdiff --git a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml b/deploy/helm/sie-cluster/templates/keda-scaledobject.yamlindex c750399da..393ba9e61 100644--- a/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml+++ b/deploy/helm/sie-cluster/templates/keda-scaledobject.yaml@@ -35,9 +35,10 @@{{- $promAddr = include "sie-cluster.kubePrometheusStack.prometheusAddress" . }}{{- end }}{{- /*- ScaledObjects are rendered into a ConfigMap and applied by a post-install/post-upgrade- hook Job. This avoids the chicken-and-egg problem where Helm validates ScaledObject CRDs- before the KEDA sub-chart has installed them.+ ScaledObjects are rendered into a ConfigMap and applied by a post-install/post-upgrade/+ post-rollback hook Job. This avoids the chicken-and-egg problem where Helm validates+ ScaledObject CRDs before the KEDA sub-chart has installed them. Rollback reuses the target+ revision's stored hooks, so it re-applies that revision's shards.*/ -}}# RBAC for the apply Job (weight 1; must exist before the Job at weight 2)apiVersion: v1@@ -48,7 +49,7 @@ metadata:labels:app.kubernetes.io/component: keda-applyannotations:- helm.sh/hook: post-install,post-upgrade+ helm.sh/hook: post-install,post-upgrade,post-rollbackhelm.sh/hook-delete-policy: before-hook-creation,hook-succeededhelm.sh/hook-weight: "1"---@@ -60,7 +61,7 @@ metadata:labels:app.kubernetes.io/component: keda-applyannotations:- helm.sh/hook: post-install,post-upgrade+ helm.sh/hook: post-install,post-upgrade,post-rollbackhelm.sh/hook-delete-policy: before-hook-creation,hook-succeededhelm.sh/hook-weight: "1"rules:@@ -79,7 +80,7 @@ metadata:labels:app.kubernetes.io/component: keda-applyannotations:- helm.sh/hook: post-install,post-upgrade+ helm.sh/hook: post-install,post-upgrade,post-rollbackhelm.sh/hook-delete-policy: before-hook-creation,hook-succeededhelm.sh/hook-weight: "1"roleRef:@@ -322,7 +323,7 @@ metadata:labels:app.kubernetes.io/component: keda-applyannotations:- helm.sh/hook: post-install,post-upgrade+ helm.sh/hook: post-install,post-upgrade,post-rollbackhelm.sh/hook-delete-policy: before-hook-creation,hook-succeededhelm.sh/hook-weight: "2"spec:diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 3a0652b4e..1fffd5bc1 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -1281,8 +1281,9 @@ dashboards:# -- Health gate hooks. autoscaling.enabled always enables the Prometheus and# KEDA ScaledObject/HPA control-path gates. The explicit switch below adds-# application HTTP smoke Jobs. The KEDA/OTLP transition is forward-only and-# deliberately has no post-rollback hook path.+# application HTTP smoke Jobs. Gates run on install and upgrade only; a+# rollback re-applies the target revision's ScaledObjects without re-running+# them. The canonical 0.6.20 KEDA/OTLP transition itself is forward-only.healthGates:# -- Enable gateway and config HTTP health gates.# This cannot disable the mandatory autoscaling control-path gates.diff --git a/packages/sie_config/pyproject.toml b/packages/sie_config/pyproject.tomlindex 044555383..a48323cd3 100644--- a/packages/sie_config/pyproject.toml+++ b/packages/sie_config/pyproject.toml@@ -6,6 +6,7 @@ requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }dependencies = ["fastapi>=0.115,<1",+ "jsonschema>=4,<5","uvicorn[standard]>=0.32,<1","uvloop>=0.22","nats-py>=2.9,<3",diff --git a/packages/sie_config/src/sie_config/config_api.py b/packages/sie_config/src/sie_config/config_api.pyindex 0f78d05f5..ba789d723 100644--- a/packages/sie_config/src/sie_config/config_api.py+++ b/packages/sie_config/src/sie_config/config_api.py@@ -24,6 +24,7 @@ from sie_config.model_registry import (ProfileConflictError,parse_model_spec,)+from sie_config.model_schema import model_config_schema_errorsfrom sie_config.nats_publisher import NatsPublisher, PartialPublishErrorfrom sie_config.types import AuditEntry@@ -343,6 +344,16 @@ def _validate_model_id(model_id: str) -> None:)+def _reject_worker_schema_errors(config: dict[str, Any]) -> None:+ """Reject a body with 422 when a worker's model-config schema would refuse it."""+ details = model_config_schema_errors(config)+ if details:+ raise HTTPException(+ status_code=422,+ detail={"error": "validation_error", "details": details},+ )++def _load_filesystem_yaml(models_dir: Any, model_name: str) -> str | None:"""Load raw YAML for a filesystem-backed model (blocking; call via to_thread).@@ -599,6 +610,7 @@ async def add_model(request: Request) -> Response:status_code=400,detail={"error": "parse_error", "message": "Expected YAML mapping at top level"},)+ _reject_worker_schema_errors(config)# Validate model ID before touching the registrymodel_id = config.get("sie_id", "")@@ -703,7 +715,7 @@ async def add_model(request: Request) -> Response:# Merge invariants (append-only):# - Existing top-level fields that the new body omits# are PRESERVED (minimal profile-append bodies must- # not erase `description`, `default_bundle`, etc.).+ # not erase `hf_id`, `max_sequence_length`, etc.).# - A new body may introduce top-level fields that the# stored document doesn't have.# - If both sides set the same non-`profiles` top-level@@ -1032,6 +1044,7 @@ async def replace_model(request: Request, model_id: str) -> Response:status_code=400,detail={"error": "parse_error", "message": "Expected YAML mapping at top level"},)+ _reject_worker_schema_errors(config)body_sie_id = config.get("sie_id")if body_sie_id and body_sie_id != model_id:diff --git a/packages/sie_config/src/sie_config/model_config.schema.json b/packages/sie_config/src/sie_config/model_config.schema.jsonnew file mode 100644index 000000000..e0ac8f6c8--- /dev/null+++ b/packages/sie_config/src/sie_config/model_config.schema.json@@ -0,0 +1,661 @@+{+ "$defs": {+ "AdapterOptions": {+ "additionalProperties": false,+ "properties": {+ "loadtime": {+ "additionalProperties": true,+ "title": "Loadtime",+ "type": "object"+ },+ "runtime": {+ "additionalProperties": true,+ "title": "Runtime",+ "type": "object"+ }+ },+ "title": "AdapterOptions",+ "type": "object"+ },+ "EmbeddingDim": {+ "additionalProperties": false,+ "properties": {+ "dim": {+ "title": "Dim",+ "type": "integer"+ }+ },+ "required": [+ "dim"+ ],+ "title": "EmbeddingDim",+ "type": "object"+ },+ "EncodeTask": {+ "additionalProperties": false,+ "properties": {+ "dense": {+ "anyOf": [+ {+ "$ref": "#/$defs/EmbeddingDim"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "sparse": {+ "anyOf": [+ {+ "$ref": "#/$defs/EmbeddingDim"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "multivector": {+ "anyOf": [+ {+ "$ref": "#/$defs/EmbeddingDim"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ }+ },+ "title": "EncodeTask",+ "type": "object"+ },+ "ExtractTask": {+ "additionalProperties": false,+ "properties": {},+ "title": "ExtractTask",+ "type": "object"+ },+ "GenerateCapabilities": {+ "additionalProperties": false,+ "description": "Generation capability flags advertised by the model config.\n\nGateway-readable surface; used by ``proxy_generate`` to enforce that a\nrequested grammar / tools / streaming flavour is actually supported.\n``grammar`` accepts ``json_schema``, ``regex``, and ``ebnf``; the\ncapability gate at the gateway uses this list to reject unsupported\nkinds before any work hits the queue.",+ "properties": {+ "grammar": {+ "default": [],+ "items": {+ "enum": [+ "json_schema",+ "regex",+ "ebnf"+ ],+ "type": "string"+ },+ "title": "Grammar",+ "type": "array"+ },+ "streaming": {+ "default": true,+ "title": "Streaming",+ "type": "boolean"+ },+ "tools": {+ "default": false,+ "title": "Tools",+ "type": "boolean"+ },+ "code": {+ "default": false,+ "title": "Code",+ "type": "boolean"+ },+ "sql": {+ "default": false,+ "title": "Sql",+ "type": "boolean"+ },+ "guard": {+ "default": false,+ "title": "Guard",+ "type": "boolean"+ }+ },+ "title": "GenerateCapabilities",+ "type": "object"+ },+ "GenerateTask": {+ "additionalProperties": false,+ "description": "Generation task declaration.\n\n``context_length`` is the maximum shared prompt-plus-completion envelope by\ndefault. Encoder-decoder adapters may instead declare independent axes, in\nwhich case it bounds encoder input and ``max_output_tokens`` independently\ncaps decoder output. The gateway uses ``max_output_tokens`` for\npre-admission, and the worker authoritatively enforces it as the per-request\nhard cap on ``max_new_tokens`` before adapter dispatch.\n\n``chat_template_kwargs`` are a bounded operator-owned mapping forwarded\nto the tokenizer's ``apply_chat_template(**kwargs)`` call when the worker\nrenders an OpenAI-shaped ``messages`` request. The accepted schema covers\n``enable_thinking`` and Granite Guardian's bounded ``guardian_config``;\nunknown keys and invalid nested shapes fail at config load. Empty dict by\ndefault \u2014 non-chat / prompt-shape requests ignore the field.\n\n``prewarm_grammars`` is an optional list of grammars to compile at\nmodel-load time so the cold-start TTFT for these schemas excludes\nOutlines compile cost. See :class:`PrewarmGrammar` for the entry\nshape; the worker iterates the list once on boot and silently\ncontinues past individual compile failures (which are surfaced via\n``sie.worker.generation.grammar.compile.duration`` with\n``phase=\"prewarm\", outcome=\"error\"``).\n\n``kv_budget_tokens`` for admission control lives on\n:class:`ProfileConfig` rather than here, because the\nbudget is a per-worker/per-profile shape rather than a per-task\nsemantic.\n\n``grammar_profile`` optionally names a profile that grammar-constrained\nrequests (OpenAI ``response_format`` / SIE-native ``grammar``) must run on.\nWhen set, the gateway rewrites such a request's model id to the\n``{sie_id}:{grammar_profile}`` variant so it is served by that profile,\nwhile unconstrained requests keep the request's resolved profile. A\nprofile may override this with its own grammar-safe sibling so context,\nhardware launch shape, and thinking mode remain unchanged. A directly\ninheriting explicit variant may remain selected when its resolved launch\nsettings are already grammar-safe. This exists\nbecause some throughput optimisations are incompatible with\ndecode-time grammar enforcement \u2014 notably NEXTN/MTP speculative decoding\nbypasses SGLang's Outlines FSM (leaks out-of-schema keys, truncates\nmid-JSON), so a model whose default profile is speculative points\n``grammar_profile`` at a non-speculative profile (e.g. ``no-spec``). ``None``\n(default) means no rewrite \u2014 grammar runs on the request's resolved profile.",+ "properties": {+ "context_length": {+ "title": "Context Length",+ "type": "integer"+ },+ "max_output_tokens": {+ "title": "Max Output Tokens",+ "type": "integer"+ },+ "capabilities": {+ "$ref": "#/$defs/GenerateCapabilities",+ "default": {+ "grammar": [],+ "streaming": true,+ "tools": false,+ "code": false,+ "sql": false,+ "guard": false+ }+ },+ "chat_template_kwargs": {+ "additionalProperties": true,+ "title": "Chat Template Kwargs",+ "type": "object"+ },+ "prewarm_grammars": {+ "items": {+ "$ref": "#/$defs/PrewarmGrammar"+ },+ "title": "Prewarm Grammars",+ "type": "array"+ },+ "grammar_profile": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Grammar Profile"+ }+ },+ "required": [+ "context_length",+ "max_output_tokens"+ ],+ "title": "GenerateTask",+ "type": "object"+ },+ "InputModalities": {+ "additionalProperties": false,+ "properties": {+ "text": {+ "default": true,+ "title": "Text",+ "type": "boolean"+ },+ "image": {+ "default": false,+ "title": "Image",+ "type": "boolean"+ },+ "audio": {+ "default": false,+ "title": "Audio",+ "type": "boolean"+ },+ "video": {+ "default": false,+ "title": "Video",+ "type": "boolean"+ },+ "document": {+ "default": false,+ "title": "Document",+ "type": "boolean"+ }+ },+ "title": "InputModalities",+ "type": "object"+ },+ "PrewarmGrammar": {+ "additionalProperties": false,+ "description": "Operator-declared grammar to compile during model load.\n\nPre-compiling hot schemas/regexes at worker boot moves Outlines compile\ncost out of cold-start TTFT. Each entry corresponds to one ``(kind, value)``\npair that would otherwise be compiled lazily on first request.\n\n``name`` is a human-readable label used in log lines and is otherwise\ninformational \u2014 the cache key is derived from ``value`` via\n:func:`~sie_server.types.grammar.hash_grammar`. ``kind`` must be one\nof :data:`PrewarmGrammarKind` (the narrower per-capability surface,\nnot the full :data:`GrammarKind` literal). ``value`` matches the\non-wire shape: a JSON Schema ``dict`` for ``kind: json_schema`` and\na regex/EBNF ``str`` for ``kind: regex`` / ``kind: ebnf``.",+ "properties": {+ "name": {+ "title": "Name",+ "type": "string"+ },+ "kind": {+ "enum": [+ "json_schema",+ "regex",+ "ebnf"+ ],+ "title": "Kind",+ "type": "string"+ },+ "value": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "string"+ }+ ],+ "title": "Value"+ }+ },+ "required": [+ "name",+ "kind",+ "value"+ ],+ "title": "PrewarmGrammar",+ "type": "object"+ },+ "ProfileAdaptiveBatching": {+ "additionalProperties": false,+ "description": "Per-model adaptive batching overrides.\n\nAll fields are optional. None means inherit from engine config or parent\nprofile. This enables fieldwise merge: a child profile can override one\nfield while inheriting the rest from the parent or engine defaults.",+ "properties": {+ "target_p50_ms": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Target P50 Ms"+ },+ "calibration_multiplier": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Calibration Multiplier"+ },+ "min_target_p50_ms": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Min Target P50 Ms"+ },+ "max_target_p50_ms": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Max Target P50 Ms"+ },+ "min_wait_ms": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Min Wait Ms"+ },+ "max_wait_ms": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Max Wait Ms"+ },+ "gain": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Gain"+ },+ "integral_gain": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Integral Gain"+ }+ },+ "title": "ProfileAdaptiveBatching",+ "type": "object"+ },+ "ProfileConfig": {+ "additionalProperties": false,+ "description": "Per-profile configuration.\n\n``kv_budget_tokens`` is the per-worker KV-cache budget\nused by the streaming admission controller to reject requests whose\n``input_tokens_estimate + max_new_tokens`` would push the worker\nover capacity. **Required** (positive int) for profiles whose\n``adapter_path`` resolves to a ``GenerationAdapter`` subclass \u2014\ni.e. for any profile attached to a model with ``tasks.generate``\nset. Calibration of the actual value lives in the calibration\nfollow-up; until then the model YAML may carry a sentinel\nplaceholder, but a missing / zero / negative value at config-load\ntime is a hard error pointing operators at the calibration\ndeliverable.\n\n``admission_enabled`` gates admission control per\nprofile. ``None`` defers to the ``SIE_GENERATION_ADMISSION`` env\nvar (default-off until the calibration ablation flips it); explicit\n``True`` / ``False`` wins unless the env var is set to ``on`` or\n``off`` (which override the profile in both directions).\n\n``max_output_tokens`` optionally overrides the model-level generation cap\nfor the materialized ``model:profile`` variant. This lets a long-context\nreasoning profile expose the checkpoint's supported decode budget without\nweakening the conservative cap on the bare model or shorter profiles.\n\n``chat_template_kwargs`` optionally overrides the same bounded model-level\n:class:`GenerateTask` defaults for the materialized ``model:profile``\nvariant. This keeps tokenizer render presets such as explicit thinking\nmode on the profile identity while preserving the bare model's safer\nnon-thinking default. The profile mapping is merged over the task mapping;\nrequest-time kwargs are still applied later by the generation processor.\n\n``grammar_profile`` optionally overrides the model-level grammar fallback\nfor this concrete profile. It must name a non-default sibling profile. The\ngateway uses it only for constrained requests, allowing a long-context or\nthinking profile to route to a non-speculative twin without losing its\ncontext window, hardware launch shape, or tokenizer mode.",+ "properties": {+ "extends": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Extends"+ },+ "max_batch_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Max Batch Tokens"+ },+ "compute_precision": {+ "anyOf": [+ {+ "enum": [+ "float16",+ "bfloat16",+ "float32"+ ],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Compute Precision"+ },+ "adapter_path": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Adapter Path"+ },+ "adapter_options": {+ "$ref": "#/$defs/AdapterOptions",+ "default": {+ "loadtime": {},+ "runtime": {}+ }+ },+ "adaptive_batching": {+ "anyOf": [+ {+ "$ref": "#/$defs/ProfileAdaptiveBatching"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "kv_budget_tokens": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Kv Budget Tokens"+ },+ "admission_enabled": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Admission Enabled"+ },+ "max_output_tokens": {+ "anyOf": [+ {+ "exclusiveMinimum": 0,+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Max Output Tokens"+ },+ "chat_template_kwargs": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Chat Template Kwargs"+ },+ "grammar_profile": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Grammar Profile"+ }+ },+ "title": "ProfileConfig",+ "type": "object"+ },+ "ScoreTask": {+ "additionalProperties": false,+ "properties": {},+ "title": "ScoreTask",+ "type": "object"+ },+ "Tasks": {+ "additionalProperties": false,+ "properties": {+ "encode": {+ "anyOf": [+ {+ "$ref": "#/$defs/EncodeTask"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "score": {+ "anyOf": [+ {+ "$ref": "#/$defs/ScoreTask"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "extract": {+ "anyOf": [+ {+ "$ref": "#/$defs/ExtractTask"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "generate": {+ "anyOf": [+ {+ "$ref": "#/$defs/GenerateTask"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ }+ },+ "title": "Tasks",+ "type": "object"+ }+ },+ "additionalProperties": false,+ "properties": {+ "sie_id": {+ "title": "Sie Id",+ "type": "string"+ },+ "hf_id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Hf Id"+ },+ "hf_revision": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Hf Revision"+ },+ "hf_tokenizer_dependencies": {+ "additionalProperties": {+ "type": "string"+ },+ "title": "Hf Tokenizer Dependencies",+ "type": "object"+ },+ "weights_path": {+ "anyOf": [+ {+ "format": "path",+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Weights Path"+ },+ "package_backed": {+ "default": false,+ "title": "Package Backed",+ "type": "boolean"+ },+ "pool": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Pool"+ },+ "inputs": {+ "$ref": "#/$defs/InputModalities",+ "default": {+ "text": true,+ "image": false,+ "audio": false,+ "video": false,+ "document": false+ }+ },+ "tasks": {+ "$ref": "#/$defs/Tasks"+ },+ "max_sequence_length": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Max Sequence Length"+ },+ "profiles": {+ "additionalProperties": {+ "$ref": "#/$defs/ProfileConfig"+ },+ "title": "Profiles",+ "type": "object"+ }+ },+ "required": [+ "sie_id",+ "tasks",+ "profiles"+ ],+ "title": "ModelConfig",+ "type": "object"+}diff --git a/packages/sie_config/src/sie_config/model_registry.py b/packages/sie_config/src/sie_config/model_registry.pyindex d854621a4..f4d8dc828 100644--- a/packages/sie_config/src/sie_config/model_registry.py+++ b/packages/sie_config/src/sie_config/model_registry.py@@ -539,7 +539,7 @@ class ModelRegistry:self._model_profiles: dict[str, set[str]] = {} # model -> profile namesself._model_profile_configs: dict[str, dict[str, dict]] = {} # model -> {profile_name: config_dict}# Full merged model config (including top-level metadata like- # `description`, `default_bundle`). Populated on reload() from the+ # `hf_id`, `max_sequence_length`). Populated on reload() from the# on-disk YAML and on add_model_config() via append-only merge.# This is the authoritative source for `/v1/configs/export` in# no-config-store deployments, where we otherwise have no way todiff --git a/packages/sie_config/src/sie_config/model_schema.py b/packages/sie_config/src/sie_config/model_schema.pynew file mode 100644index 000000000..48ab4901a--- /dev/null+++ b/packages/sie_config/src/sie_config/model_schema.py@@ -0,0 +1,81 @@+"""Structural validation of model configs against the worker's schema.++``model_config.schema.json`` is the JSON Schema of the worker's+``sie_server.config.model.ModelConfig``; a test keeps it equal to the worker+model. Only unknown keys and value types are enforced: ``required`` is dropped+because append-only writes carry partial bodies, and cross-field rules stay+with the worker. JSON types apply strictly, so values pydantic's lax mode would+coerce (a quoted number, a boolean in an integer field) are rejected.+"""++from __future__ import annotations++import json+from functools import cache+from pathlib import Path+from typing import Any++from jsonschema import Draft202012Validator+from jsonschema.exceptions import ValidationError, best_match++SCHEMA_PATH = Path(__file__).with_name("model_config.schema.json")+_NULL_BRANCH = {"type": "null"}+_UNKNOWN_FIELD_MESSAGE = "Unknown field: the worker model config schema does not define it."+++def _without_required(node: Any) -> Any:+ if isinstance(node, dict):+ return {+ key: _without_required(value)+ for key, value in node.items()+ if not (key == "required" and isinstance(value, list))+ }+ if isinstance(node, list):+ return [_without_required(item) for item in node]+ return node+++@cache+def _validator() -> Draft202012Validator:+ schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))+ return Draft202012Validator(_without_required(schema))+++def _loc(path: Any) -> list[str | int]:+ return [part if isinstance(part, (str, int)) else str(part) for part in path]+++def _union_branch_errors(error: ValidationError) -> list[ValidationError]:+ schema = error.schema if isinstance(error.schema, dict) else {}+ branches = schema.get(str(error.validator), [])+ by_branch: dict[int, list[ValidationError]] = {}+ for sub_error in error.context or []:+ index = sub_error.relative_schema_path[0]+ if not isinstance(index, int) or branches[index] == _NULL_BRANCH:+ continue+ by_branch.setdefault(index, []).append(sub_error)+ best = best_match(sub_error for sub_errors in by_branch.values() for sub_error in sub_errors)+ if best is None:+ return []+ return by_branch[int(best.relative_schema_path[0])]+++def _details(error: ValidationError) -> list[dict[str, Any]]:+ loc = _loc(error.absolute_path)+ if error.validator in ("anyOf", "oneOf"):+ branch_errors = _union_branch_errors(error)+ if branch_errors:+ return [detail for sub_error in branch_errors for detail in _details(sub_error)]+ if error.validator == "additionalProperties" and isinstance(error.instance, dict):+ schema = error.schema if isinstance(error.schema, dict) else {}+ known = schema.get("properties", {})+ unknown = sorted((key for key in error.instance if key not in known), key=str)+ if unknown:+ return [{"loc": [*loc, str(key)], "message": _UNKNOWN_FIELD_MESSAGE} for key in unknown]+ return [{"loc": loc, "message": error.message}]+++def model_config_schema_errors(config: dict[str, Any]) -> list[dict[str, Any]]:+ """Return one ``{"loc", "message"}`` entry per field the worker schema rejects."""+ details = [detail for error in _validator().iter_errors(config) for detail in _details(error)]+ return sorted(details, key=lambda detail: ([str(part) for part in detail["loc"]], detail["message"]))diff --git a/packages/sie_config/tests/test_config_api.py b/packages/sie_config/tests/test_config_api.pyindex ec49585e9..0810e7bc3 100644--- a/packages/sie_config/tests/test_config_api.py+++ b/packages/sie_config/tests/test_config_api.py@@ -408,12 +408,12 @@ class TestConfigAPIModels:" default:\n"" adapter_path: sie_server.adapters.bert_flash:Bert\n"" max_batch_tokens: 8192\n"- " max_sequence_length: 256\n"+ " compute_precision: float16\n")resp1 = client.post("/v1/configs/models", content=yaml_body)assert resp1.status_code == 201- conflict_body = yaml_body.replace("max_sequence_length: 256", "max_sequence_length: 128")+ conflict_body = yaml_body.replace("compute_precision: float16", "compute_precision: bfloat16")resp2 = client.post("/v1/configs/models", content=conflict_body)assert resp2.status_code == 409data = resp2.json()@@ -1946,8 +1946,8 @@ class TestIdempotencyEvictionSafety:class TestMergePreservesTopLevelFields:"""Appending a profile via `POST /v1/configs/models` must merge ontop of the stored document, not replace it. A minimal append body- cannot erase previously-written top-level fields (`description`,- `default_bundle`, ...); conflicting values raise 409 because the+ cannot erase previously-written top-level fields (`hf_id`,+ `max_sequence_length`, ...); conflicting values raise 409 because theconfig API is append-only for model metadata."""@@ -1972,8 +1972,8 @@ class TestMergePreservesTopLevelFields:"/v1/configs/models",content=("sie_id: acme/bert\n"- "description: keep-me-around\n"- "default_bundle: premium\n"+ "hf_id: acme/bert-base\n"+ "max_sequence_length: 512\n""profiles:\n"" default:\n"" adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n"@@ -1982,8 +1982,8 @@ class TestMergePreservesTopLevelFields:)assert resp1.status_code == 201- # Append a second profile with a minimal body (no description /- # default_bundle in the incoming payload).+ # Append a second profile with a minimal body (no hf_id /+ # max_sequence_length in the incoming payload).resp2 = self.client.post("/v1/configs/models",content=(@@ -1998,8 +1998,8 @@ class TestMergePreservesTopLevelFields:stored_path = self._store / "models" / "acme__bert.yaml"stored = yaml.safe_load(stored_path.read_text())- assert stored["description"] == "keep-me-around"- assert stored["default_bundle"] == "premium"+ assert stored["hf_id"] == "acme/bert-base"+ assert stored["max_sequence_length"] == 512assert set(stored["profiles"].keys()) == {"default", "fast"}def test_conflicting_top_level_field_returns_409(self) -> None:@@ -2007,7 +2007,7 @@ class TestMergePreservesTopLevelFields:"/v1/configs/models",content=("sie_id: acme/bert\n"- "description: initial\n"+ "hf_id: acme/bert-initial\n""profiles:\n"" default:\n"" adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n"@@ -2016,13 +2016,13 @@ class TestMergePreservesTopLevelFields:)assert resp1.status_code == 201- # Reusing the same sie_id but mutating `description` must fail 409+ # Reusing the same sie_id but mutating `hf_id` must fail 409# — config API is append-only for top-level metadata.resp2 = self.client.post("/v1/configs/models",content=("sie_id: acme/bert\n"- "description: mutated!\n"+ "hf_id: acme/bert-mutated\n""profiles:\n"" fast:\n"" adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n"@@ -2032,7 +2032,7 @@ class TestMergePreservesTopLevelFields:assert resp2.status_code == 409body = resp2.json()assert body["detail"]["error"] == "content_conflict"- assert "description" in body["detail"]["conflicting_fields"]+ assert "hf_id" in body["detail"]["conflicting_fields"]def test_append_can_introduce_new_top_level_field(self) -> None:resp1 = self.client.post(@@ -2051,7 +2051,7 @@ class TestMergePreservesTopLevelFields:"/v1/configs/models",content=("sie_id: acme/bert\n"- "description: added-later\n"+ "hf_id: acme/bert-base\n""profiles:\n"" fast:\n"" adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter\n"@@ -2061,7 +2061,7 @@ class TestMergePreservesTopLevelFields:assert resp2.status_code == 201stored = yaml.safe_load((self._store / "models" / "acme__bert.yaml").read_text())- assert stored["description"] == "added-later"+ assert stored["hf_id"] == "acme/bert-base"class TestRejectUnroutableModels:diff --git a/packages/sie_config/tests/test_model_schema.py b/packages/sie_config/tests/test_model_schema.pynew file mode 100644index 000000000..dab523553--- /dev/null+++ b/packages/sie_config/tests/test_model_schema.py@@ -0,0 +1,130 @@+import json+from pathlib import Path++import pytest+import yaml+from fastapi import FastAPI+from fastapi.testclient import TestClient+from sie_config.config_api import router as config_router+from sie_config.config_store import ConfigStore+from sie_config.model_registry import ModelRegistry+from sie_config.model_schema import SCHEMA_PATH, model_config_schema_errors+from sie_server.config.model import ModelConfig++_REPO_ROOT = Path(__file__).resolve().parents[3]+_REGENERATE = (+ "mise exec -- uv run --frozen --project . --no-sync python -c "+ "'import json; from sie_server.config.model import ModelConfig; "+ "print(json.dumps(ModelConfig.model_json_schema(), indent=2))' "+ "> packages/sie_config/src/sie_config/model_config.schema.json"+)+_ADAPTER = "sie_server.adapters.bert_flash:BertFlashAdapter"+_UNKNOWN = "Unknown field: the worker model config schema does not define it."+++def _model(**top_level: object) -> dict:+ profile = {"adapter_path": _ADAPTER, "max_batch_tokens": 4096}+ return {"sie_id": "acme/bert", "profiles": {"default": profile}, **top_level}+++def test_checked_in_schema_matches_the_worker_model_config() -> None:+ expected = json.dumps(ModelConfig.model_json_schema(), indent=2) + "\n"+ assert SCHEMA_PATH.read_text(encoding="utf-8") == expected, f"Regenerate the schema: {_REGENERATE}"+++def test_every_shipped_model_config_passes() -> None:+ models_dir = _REPO_ROOT / "packages" / "sie_server" / "models"+ paths = sorted(models_dir.glob("*.yaml"))+ assert paths+ rejected = {+ path.name: errors for path in paths if (errors := model_config_schema_errors(yaml.safe_load(path.read_text())))+ }+ assert rejected == {}+++def test_partial_append_body_passes() -> None:+ assert model_config_schema_errors(_model()) == []+++def test_unknown_keys_are_reported_per_field() -> None:+ config = _model(bogus=1, tasks={"generate": {"context_length": 8, "max_output_tokens": 8, "wat": True}})+ config["profiles"]["default"]["max_output_token"] = 5++ assert model_config_schema_errors(config) == [+ {"loc": ["bogus"], "message": _UNKNOWN},+ {"loc": ["profiles", "default", "max_output_token"], "message": _UNKNOWN},+ {"loc": ["tasks", "generate", "wat"], "message": _UNKNOWN},+ ]+++ ("field", "value", "loc", "message"),+ [+ ("max_batch_tokens", "8192", ["max_batch_tokens"], "'8192' is not of type 'integer'"),+ (+ "compute_precision",+ "fp8",+ ["compute_precision"],+ "'fp8' is not one of ['float16', 'bfloat16', 'float32']",+ ),+ ("adapter_options", {"loadtime": []}, ["adapter_options", "loadtime"], "[] is not of type 'object'"),+ ],+)+def test_type_errors_name_the_field(field: str, value: object, loc: list[str], message: str) -> None:+ config = _model()+ config["profiles"]["default"][field] = value++ assert model_config_schema_errors(config) == [{"loc": ["profiles", "default", *loc], "message": message}]+++class TestConfigApiRejectsWorkerInvalidBodies:+ @pytest.fixture+ def client(self, tmp_path: Path) -> TestClient:+ bundles_dir = tmp_path / "bundles"+ models_dir = tmp_path / "models"+ bundles_dir.mkdir()+ models_dir.mkdir()+ bundle = {"name": "default", "priority": 10, "adapters": ["sie_server.adapters.bert_flash"]}+ (bundles_dir / "default.yaml").write_text(yaml.safe_dump(bundle))+ app = FastAPI()+ app.include_router(config_router)+ app.state.model_registry = ModelRegistry(bundles_dir, models_dir)+ app.state.nats_publisher = None+ app.state.config_store = ConfigStore(str(tmp_path / "store"))+ return TestClient(app)++ def test_post_with_unknown_profile_key_is_422_and_not_persisted(self, client: TestClient, tmp_path: Path) -> None:+ config = _model()+ config["profiles"]["default"]["max_output_token"] = 512++ resp = client.post("/v1/configs/models", content=yaml.safe_dump(config))++ assert resp.status_code == 422+ assert resp.json()["detail"] == {+ "error": "validation_error",+ "details": [{"loc": ["profiles", "default", "max_output_token"], "message": _UNKNOWN}],+ }+ assert client.get("/v1/configs/models/acme/bert").status_code == 404+ assert client.get("/v1/configs/epoch").json()["epoch"] == 0+ assert not (tmp_path / "store" / "models" / "acme__bert.yaml").exists()++ def test_post_append_with_type_error_keeps_existing_profiles(self, client: TestClient, tmp_path: Path) -> None:+ assert client.post("/v1/configs/models", content=yaml.safe_dump(_model())).status_code == 201+ append = {"sie_id": "acme/bert", "profiles": {"fast": {"extends": "default", "max_batch_tokens": "lots"}}}++ resp = client.post("/v1/configs/models", content=yaml.safe_dump(append))++ assert resp.status_code == 422+ assert resp.json()["detail"]["details"] == [+ {"loc": ["profiles", "fast", "max_batch_tokens"], "message": "'lots' is not of type 'integer'"}+ ]+ stored = yaml.safe_load((tmp_path / "store" / "models" / "acme__bert.yaml").read_text())+ assert set(stored["profiles"]) == {"default"}+ assert client.get("/v1/configs/epoch").json()["epoch"] == 1++ def test_put_with_unknown_top_level_key_is_422(self, client: TestClient) -> None:+ resp = client.put("/v1/configs/models/acme/bert", content=yaml.safe_dump(_model(description="x")))++ assert resp.status_code == 422+ assert resp.json()["detail"]["details"] == [{"loc": ["description"], "message": _UNKNOWN}]+ assert client.get("/v1/configs/models/acme/bert").status_code == 404diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 7d6958e51..973118bcd 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -79,7 +79,7 @@ Gateway-generated **JSON error** bodies (validation, routing, auth, config read,All config mutations go to `sie-config`. The gateway has no write handler.1. Admin or deploy tooling sends `POST /v1/configs/models` with a model config YAML body to `sie-config`. Auth: `_check_write_auth` (`packages/sie_config/src/sie_config/config_api.py`) requires a bearer matching `SIE_ADMIN_TOKEN` when that variable is set; if `SIE_ADMIN_TOKEN` is unset and `SIE_AUTH_TOKEN` is set, writes are rejected with `403` (the inference token never grants write access); if neither token is set (dev/local only) writes are accepted unauthenticated. Production deployments always set `SIE_ADMIN_TOKEN`.-2. **Pre-lock validation** (outside the per-app write lock, on the FastAPI event loop): parse the YAML body and — when a top-level `sie_id` is present — run `_validate_model_id` (regex + `..`/`\\` rejection + `status`-suffix rejection). Reject invalid input with `400` before any state is touched.+2. **Pre-lock validation** (outside the per-app write lock, on the FastAPI event loop): parse the YAML body and — when a top-level `sie_id` is present — run `_validate_model_id` (regex + `..`/`\\` rejection + `status`-suffix rejection). Reject invalid input with `400` before any state is touched. The body is also checked against `packages/sie_config/src/sie_config/model_config.schema.json`, the JSON Schema of the worker's `ModelConfig` (a test keeps the two equal): an unknown key or a wrong value type at any level returns `422 validation_error` with one `{loc, message}` entry per field, instead of accepting a config that every worker rejects. JSON types are applied strictly, so values that pydantic's lax mode would coerce, such as a quoted number, are rejected too. Required fields are not enforced here, since append bodies are partial. `PUT` runs the same check.3. **Critical section** under `_get_write_lock` (a lazy, per-app `asyncio.Lock` stored on `app.state`):1. `ModelRegistry.validate_model_config` — pure check against the in-memory registry (no mutation), run under the registry's internal `threading.RLock`. Validation rejects any write whose post-state resolves to zero routable bundles (`422`), so an `extends`-only profile cannot land a brand-new model that no worker bundle can serve. Appending a new `extends`-only profile to an already-routable model is allowed.2. **Compute `created_profiles` vs `existing_profiles_skipped`.** The write is treated as append-only: profiles already present in the registry with a compatible body are reported as skipped, not rewritten. If there are no new profiles *and* at least one skip, an on-disk conflict check compares the incoming YAML against `ConfigStore`'s existing file for this model (guards against disk drift from the in-memory registry).@@ -236,7 +236,7 @@ Concurrency on the gateway's `ModelRegistry`:## 6. Worker-Ack Status (`GET /v1/configs/models/{id}/status`)-Admin tooling uses this endpoint after a `sie-config` write to observe whether configured workers are reporting the expected `bundle_config_hash` for each affected bundle. Worker-sidecar containers advance that hash after their bundle-scoped NATS delta is accepted by backend IPC `ApplyModelConfig`, or after the worker export reconciler replaces the bundle-scoped backend registry/catalog view from `sie-config`.+Admin tooling uses this endpoint after a `sie-config` write to observe whether configured workers are reporting the expected `bundle_config_hash` for each affected bundle. Worker-sidecar containers advance that hash after their bundle-scoped NATS delta is accepted by backend IPC `ApplyModelConfig`, or after the worker export reconciler replaces the bundle-scoped backend registry/catalog view from `sie-config`. During that replacement the Python worker applies every entry its `ModelConfig` schema accepts; for a rejected entry it logs the model and reason and keeps that model's current registry entries, if any. The sidecar still advances the advertised hash only when the worker's resulting hash equals the control-plane hash.Response shape:diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.pyindex e644463f4..44e57cb1e 100644--- a/packages/sie_server/src/sie_server/core/registry.py+++ b/packages/sie_server/src/sie_server/core/registry.py@@ -19,7 +19,7 @@ import jsonimport loggingimport threadingimport time-from collections.abc import Coroutine, Iterable+from collections.abc import Collection, Coroutine, Iterablefrom pathlib import Pathfrom typing import Any@@ -123,6 +123,11 @@ def _model_configs_semantically_equal(left: ModelConfig | None, right: ModelConfreturn left is not None and _model_config_semantic_hash(left) == _model_config_semantic_hash(right)+def _config_base_name(name: str, config: ModelConfig) -> str:+ source = config.synthetic_profile_variant_source+ return source[0] if source is not None else name++def _is_python_runtime_adapter(adapter_path: str) -> bool:return not adapter_path.startswith("sie_server_rust.")@@ -2410,6 +2415,8 @@ class ModelRegistry:self,configs: Iterable[ModelConfig],model_dir: Path | None = None,+ *,+ retained_models: Collection[str] = (),) -> set[str]:"""Replace the registry config set from an authoritative snapshot.@@ -2417,6 +2424,10 @@ class ModelRegistry:loaded models are unloaded while no load is admitted, before theconfig map is swapped, so a worker cannot keep serving a model thatdisappeared from the authoritative bundle export.++ Current entries of a base model named in ``retained_models`` (the model+ and its profile variants) are kept unchanged when ``configs`` does not+ carry that model."""new_configs: dict[str, ModelConfig] = {}for config in expand_profile_variants(configs).values():@@ -2427,21 +2438,28 @@ class ModelRegistry:raise ValueError(msg)new_configs[config.sie_id] = config- if self._pool_name is not None:- accepted: dict[str, ModelConfig] = {}- for name, config in new_configs.items():- validate_pool_isolation(- candidate_name=name,- candidate_config=config,- existing_configs=accepted,- pool_name=self._pool_name,- )- accepted[name] = config- for name, config in new_configs.items():- validate_no_legacy_scalar_lora_id(name=name, config=config)-update_lock = self._get_config_update_lock()async with update_lock:+ if retained_models:+ snapshot_bases = {_config_base_name(name, config) for name, config in new_configs.items()}+ for name, config in self._configs.items():+ base_name = _config_base_name(name, config)+ if base_name in retained_models and base_name not in snapshot_bases and name not in new_configs:+ new_configs[name] = config++ if self._pool_name is not None:+ accepted: dict[str, ModelConfig] = {}+ for name, config in new_configs.items():+ validate_pool_isolation(+ candidate_name=name,+ candidate_config=config,+ existing_configs=accepted,+ pool_name=self._pool_name,+ )+ accepted[name] = config+ for name, config in new_configs.items():+ validate_no_legacy_scalar_lora_id(name=name, config=config)+async with self._get_load_admission_lock():removed = set(self._configs) - set(new_configs)changed = {diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex 1ebc61dac..e3a5ff3ad 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -46,6 +46,7 @@ from sie_server.ipc_types import (ProcessScoreBatchRequest,RawOutput,ReadinessState,+ ReplaceModelConfigEntry,ReplaceModelConfigsRequest,ReplaceModelConfigsResponse,ScoreBatchItem,@@ -507,6 +508,23 @@ def _wrap_encode_output(output: dict, config: Any) -> dict:return wrapped+def _parse_exported_model_config(entry: ReplaceModelConfigEntry) -> ModelConfig:+ if not entry.model_config.strip():+ msg = "model_config is required"+ raise ValueError(msg)++ raw = yaml.safe_load(entry.model_config)+ if not isinstance(raw, dict):+ msg = "model_config must decode to a YAML mapping"+ raise ValueError(msg)++ model_config = ModelConfig(**raw)+ if entry.model_id and model_config.sie_id != entry.model_id:+ msg = f"model_id mismatch: export={entry.model_id!r} config={model_config.sie_id!r}"+ raise ValueError(msg)+ return model_config++# ---------------------------------------------------------------------------# QueueExecutor# ---------------------------------------------------------------------------@@ -606,29 +624,32 @@ class QueueExecutor:return compute_bundle_config_hash_cached(self._registry, bundle_id)async def replace_model_configs(self, req: ReplaceModelConfigsRequest) -> ReplaceModelConfigsResponse:- """Replace the bundle-scoped registry view from a full export snapshot."""+ """Replace the bundle-scoped registry view from a full export snapshot.++ An entry the model-config schema rejects is logged, and that model keeps+ its current registry entries, if any. The returned hash covers what the+ registry then holds; the sidecar advertises it only when it equals the+ control-plane hash.+ """if not req.bundle_id:msg = "bundle_id is required"raise ValueError(msg)configs: list[ModelConfig] = []+ rejected: set[str] = set()for entry in req.models:- if not entry.model_config.strip():- msg = "model_config is required"- raise ValueError(msg)-- raw = yaml.safe_load(entry.model_config)- if not isinstance(raw, dict):- msg = "model_config must decode to a YAML mapping"- raise ValueError(msg)-- model_config = ModelConfig(**raw)- if entry.model_id and model_config.sie_id != entry.model_id:- msg = f"model_id mismatch: export={entry.model_id!r} config={model_config.sie_id!r}"- raise ValueError(msg)- configs.append(model_config)-- invalidated = await self._registry.replace_configs_async(configs)+ try:+ configs.append(_parse_exported_model_config(entry))+ except (TypeError, ValueError, yaml.YAMLError) as exc:+ logger.warning(+ "Rejected exported model config %r for bundle %s; keeping its current config, if any: %s",+ entry.model_id,+ req.bundle_id,+ exc,+ )+ rejected.add(entry.model_id)++ invalidated = await self._registry.replace_configs_async(configs, retained_models=rejected)for model_id in invalidated:self.invalidate_model_descriptor(model_id)bundle_hash = compute_bundle_config_hash_cached(self._registry, req.bundle_id)diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex f0e2f26c8..be32c0a7a 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -1473,6 +1473,131 @@ profiles:assert not registry.has_model("default/model")assert registry.has_model("tenant/model")+ @pytest.mark.asyncio+ async def test_replace_model_configs_keeps_rejected_models_and_applies_the_rest(+ self, caplog: pytest.LogCaptureFixture+ ) -> None:+ def model_yaml(model_id: str, *, max_batch_tokens: int = 4096, profile_extra: 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: {max_batch_tokens}+{profile_extra}"""++ def request(epoch: int, entries: list[tuple[str, str]]) -> ReplaceModelConfigsRequest:+ return ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=epoch,+ bundle_config_hash="",+ models=[ReplaceModelConfigEntry(model_id=mid, model_config=body) for mid, body in entries],+ )++ registry = ModelRegistry(models_dir=None)+ executor = QueueExecutor(registry)+ await executor.replace_model_configs(+ request(+ 7,+ [(model_id, model_yaml(model_id)) for model_id in ("kept/model", "broken/model", "stale/model")],+ )+ )+ previous_broken = registry.get_config("broken/model")+ registry._loaded["broken/model"] = MagicMock()+ registry._do_unload = AsyncMock()++ with caplog.at_level("WARNING", logger="sie_server.queue_executor"):+ resp = await executor.replace_model_configs(+ request(+ 8,+ [+ ("kept/model", model_yaml("kept/model", max_batch_tokens=8192)),+ ("broken/model", model_yaml("broken/model", profile_extra=" max_output_token: 512")),+ ("renamed/model", model_yaml("other/model")),+ ("empty/model", ""),+ ("list/model", "- not\n- a mapping\n"),+ ],+ )+ )++ assert resp.applied is True+ assert resp.applied_models == ["broken/model", "kept/model"]+ assert registry.get_config("kept/model").profiles["default"].max_batch_tokens == 8192+ assert registry.get_config("broken/model") is previous_broken+ registry._do_unload.assert_not_awaited()+ assert not registry.has_model("stale/model")+ assert not registry.has_model("other/model")++ reference = QueueExecutor(ModelRegistry(models_dir=None))+ expected = await reference.replace_model_configs(+ request(+ 8,+ [+ ("kept/model", model_yaml("kept/model", max_batch_tokens=8192)),+ ("broken/model", model_yaml("broken/model")),+ ],+ )+ )+ assert expected.bundle_config_hash+ assert resp.bundle_config_hash == expected.bundle_config_hash++ rejected = [+ record.getMessage() for record in caplog.records if "Rejected exported model" in record.getMessage()+ ]+ assert len(rejected) == 4+ assert "'broken/model'" in rejected[0]+ assert "max_output_token" in rejected[0]+ assert "model_id mismatch" in rejected[1]++ @pytest.mark.asyncio+ async def test_replace_model_configs_keeps_profile_variants_of_a_rejected_model(self) -> None:+ def request(epoch: int, model_config: str) -> ReplaceModelConfigsRequest:+ return ReplaceModelConfigsRequest(+ bundle_id="sglang",+ epoch=epoch,+ bundle_config_hash="",+ models=[ReplaceModelConfigEntry(model_id="Qwen/Qwen3.6-27B", model_config=model_config)],+ )++ registry = ModelRegistry(models_dir=None)+ executor = QueueExecutor(registry)+ await executor.replace_model_configs(request(7, _qwen_profile_variant_yaml()))+ previous = {name: registry.get_config(name) for name in ("Qwen/Qwen3.6-27B", "Qwen/Qwen3.6-27B:rtx-pro-6000")}++ resp = await executor.replace_model_configs(request(8, "unknown_field: 1\n" + _qwen_profile_variant_yaml()))++ assert resp.applied_models == sorted(previous)+ assert all(registry.get_config(name) is config for name, config in previous.items())++ @pytest.mark.asyncio+ async def test_replace_model_configs_valid_entry_wins_over_a_rejected_duplicate(self) -> None:+ def request(epoch: int, model_configs: list[str]) -> ReplaceModelConfigsRequest:+ return ReplaceModelConfigsRequest(+ bundle_id="sglang",+ epoch=epoch,+ bundle_config_hash="",+ models=[+ ReplaceModelConfigEntry(model_id="Qwen/Qwen3.6-27B", model_config=model_config)+ for model_config in model_configs+ ],+ )++ registry = ModelRegistry(models_dir=None)+ executor = QueueExecutor(registry)+ await executor.replace_model_configs(request(7, [_qwen_profile_variant_yaml()]))++ resp = await executor.replace_model_configs(+ request(8, ["unknown_field: 1\n" + _qwen_profile_variant_yaml(), _qwen_default_only_yaml()])+ )++ assert resp.applied_models == ["Qwen/Qwen3.6-27B"]+ assert not registry.has_model("Qwen/Qwen3.6-27B:rtx-pro-6000")+# -----------------------------------------------------------------------------# SetPinnedModelsdiff --git a/tools/ci/tests/test_helm_render.py b/tools/ci/tests/test_helm_render.pyindex ca53decbf..24e68d5f6 100644--- a/tools/ci/tests/test_helm_render.py+++ b/tools/ci/tests/test_helm_render.py@@ -11,9 +11,21 @@ from tools.mise_tasks import helmROOT = Path(__file__).resolve().parents[3]WORKER_TEMPLATE = "templates/worker-statefulset.yaml"+KEDA_APPLY_TEMPLATE = "templates/keda-scaledobject.yaml"+KEDA_CLEANUP_TEMPLATE = "templates/keda-lifecycle.yaml"+AUTOSCALING_VALUES = {+ "autoscaling": {"enabled": True},+ "observability": {+ "otel": {"collector": {"prometheus": {"networkPolicy": {"scrapeNamespaceNames": ["monitoring"]}}}}+ },+}def render_workers(tmp_path: Path, values: dict) -> subprocess.CompletedProcess[str]:+ return render_template(tmp_path, values, WORKER_TEMPLATE)+++def render_template(tmp_path: Path, values: dict, template: str) -> subprocess.CompletedProcess[str]:values_file = tmp_path / "values.yaml"values_file.write_text(yaml.safe_dump(values), encoding="utf-8")return subprocess.run(@@ -27,7 +39,7 @@ def render_workers(tmp_path: Path, values: dict) -> subprocess.CompletedProcess[str(helm.CHART_DIR),"--namespace","sie",- *helm.validation_args(["-f", str(values_file), "--show-only", WORKER_TEMPLATE]),+ *helm.validation_args(["-f", str(values_file), "--show-only", template]),],cwd=ROOT,capture_output=True,@@ -109,3 +121,34 @@ def test_readme_device_group_example_renders(tmp_path: Path) -> None:]assert worker["resources"]["limits"]["nvidia.com/gpu"] == str(pool["gpu"]["count"])assert worker["resources"]["limits"]["memory"] == pool["resources"]["limits"]["memory"]+++def hook_events(tmp_path: Path, values: dict, template: str) -> dict[tuple[str, str], set[str]]:+ result = render_template(tmp_path, values, template)+ assert result.returncode == 0, result.stderr+ return {+ (doc["kind"], doc["metadata"]["name"]): set(doc["metadata"]["annotations"]["helm.sh/hook"].split(","))+ for doc in yaml.safe_load_all(result.stdout)+ if doc and "helm.sh/hook" in doc["metadata"].get("annotations", {})+ }+++def test_scaledobject_apply_hook_also_runs_on_rollback(tmp_path: Path) -> None:+ hooks = hook_events(tmp_path, AUTOSCALING_VALUES, KEDA_APPLY_TEMPLATE)++ assert sorted(kind for kind, _ in hooks) == ["Job", "Role", "RoleBinding", "ServiceAccount"]+ assert all(events == {"post-install", "post-upgrade", "post-rollback"} for events in hooks.values()), hooks+++ ("values", "expected"),+ [+ ({}, {"pre-upgrade", "pre-rollback", "pre-delete"}),+ (AUTOSCALING_VALUES, {"pre-delete"}),+ ],+)+def test_scaledobject_cleanup_hook_events(tmp_path: Path, values: dict, expected: set[str]) -> None:+ hooks = hook_events(tmp_path, values, KEDA_CLEANUP_TEMPLATE)++ assert sorted(kind for kind, _ in hooks) == ["Job", "Role", "RoleBinding", "ServiceAccount"]+ assert all(events == expected for events in hooks.values()), hooksdiff --git a/uv.lock b/uv.lockindex 7db0228a4..56959c560 100644--- a/uv.lock+++ b/uv.lock@@ -4508,6 +4508,7 @@ version = "0.8.3"source = { editable = "packages/sie_config" }dependencies = [{ name = "fastapi" },+ { name = "jsonschema" },{ name = "nats-py" },{ name = "opentelemetry-api" },{ name = "opentelemetry-exporter-otlp-proto-grpc" },@@ -4538,6 +4539,7 @@ dev = [requires-dist = [{ name = "fastapi", specifier = ">=0.115,<1" },{ name = "google-cloud-storage", marker = "extra == 'gcs'", specifier = ">=2.18,<3" },+ { name = "jsonschema", specifier = ">=4,<5" },{ name = "nats-py", specifier = ">=2.9,<3" },{ name = "opentelemetry-api", specifier = ">=1.28,<2" },{ name = "opentelemetry-exporter-otlp-proto-grpc", specifier = ">=1.28,<2" },