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(gateway): keep other bundle models routable while workers predate a new adapter (#419)
Krisztian Gajdara6eb6bbcf02d
diff --git a/deploy/helm/sie-cluster/files/dashboards/queue-routing.json b/deploy/helm/sie-cluster/files/dashboards/queue-routing.jsonindex bd33989dd..494a877a1 100644--- a/deploy/helm/sie-cluster/files/dashboards/queue-routing.json+++ b/deploy/helm/sie-cluster/files/dashboards/queue-routing.json@@ -1028,7 +1028,7 @@},"id": 70,"title": "Gateway Config, Queue, and Provisioning Event Rate",- "description": "Bounded gateway config operations, logical queue publishes/result waits, durability events, provisioning responses, and per-lane queue admission decisions. A lane_admission outcome of shed_shadow is the decision the per-lane check would have taken with SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE on; it never changes admission, so it is how the shadow period is read before the flag is flipped.",+ "description": "Bounded gateway config operations, logical queue publishes/result waits, durability events, provisioning responses, unsupported-model lane exclusions, and per-lane queue admission decisions. An unsupported-model exclusion is a lane passed over because a worker in it reports that it cannot serve the requested model, for example during a rollout that adds adapters to its bundle. A lane_admission outcome of shed_shadow is the decision the per-lane check would have taken with SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE on; it never changes admission, so it is how the shadow period is read before the flag is flipped.","type": "timeseries","fieldConfig": {"defaults": {@@ -1081,6 +1081,11 @@"expr": "sum by (pool, machine_profile, bundle, outcome) (rate(sie_gateway_queue_lane_admission_decisions_total{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"}[$rate_window]))","legendFormat": "lane admission {{pool}}/{{machine_profile}}/{{bundle}} / {{outcome}}","refId": "F"+ },+ {+ "expr": "sum(rate(sie_gateway_routing_unsupported_model_exclusions_total{namespace=\"$namespace\", service=\"$collector\", endpoint=\"prometheus\", producer_service=\"sie-gateway\"}[$rate_window]))",+ "legendFormat": "unsupported-model lane exclusions",+ "refId": "G"}]},diff --git a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl b/deploy/helm/sie-cluster/templates/_otel-collector-config.tplindex 166792e0f..d513ef6f9 100644--- a/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl+++ b/deploy/helm/sie-cluster/templates/_otel-collector-config.tpl@@ -89,7 +89,7 @@ processors:error_mode: propagatemetrics:metric:- - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]lane_admission[.]decisions|sie[.]gateway[.]queue[.]worker_pool[.]events|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pool[.]pinned_model[.]loaded|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]capacity[.]snapshot[.]timestamp|sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'+ - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]lane_admission[.]decisions|sie[.]gateway[.]queue[.]worker_pool[.]events|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]routing[.]unsupported_model_exclusions|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pool[.]pinned_model[.]loaded|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]capacity[.]snapshot[.]timestamp|sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'- 'resource.attributes["service.name"] != "sie-gateway"'filter/prometheus_application_contract:error_mode: propagate@@ -137,6 +137,7 @@ processors:- 'set(unit, "By") where IsMatch(name, "^(sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]worker[.]ipc[.]response[.]reconstructed[.]size|sie[.]worker[.]ipc[.]response[.]chunk[.]reserved|sie[.]worker[.]result[.]chunk[.]size)$")'- 'set(unit, "{event}") where IsMatch(name, "^(sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]worker_pool[.]events|sie[.]gateway[.]generation[.]events)$")'- 'set(unit, "{response}") where IsMatch(name, "^(sie[.]gateway[.]provisioning[.]responses|sie[.]worker[.]generation[.]model_loading[.]responses)$")'+ - 'set(unit, "{exclusion}") where name == "sie.gateway.routing.unsupported_model_exclusions"'- 'set(unit, "{token}") where IsMatch(name, "^(sie[.]gateway[.]generation[.]tokens|sie[.]worker[.]generation[.]tokens|sie[.]worker[.]generation[.]kv[.]reserved|sie[.]worker[.]generation[.]kv[.]budget)$")'- 'set(unit, "{invocation}") where IsMatch(name, "^(sie[.]dispatcher[.]invocations|sie[.]dispatcher[.]inflight)$")'- 'set(unit, "{stage}") where IsMatch(name, "^(sie[.]dispatcher[.]sealed[.]stage)$")'@@ -171,6 +172,7 @@ processors:- 'keep_keys(attributes, ["event", "outcome"]) where metric.name == "sie.gateway.queue.events"'- 'keep_keys(attributes, ["pool", "event"]) where metric.name == "sie.gateway.queue.worker_pool.events"'- 'keep_keys(attributes, ["surface", "http.status_code"]) where metric.name == "sie.gateway.provisioning.responses"'+ - 'keep_keys(attributes, []) where metric.name == "sie.gateway.routing.unsupported_model_exclusions"'- 'keep_keys(attributes, ["event", "reason", "outcome"]) where metric.name == "sie.gateway.generation.events"'- 'keep_keys(attributes, ["operation"]) where IsMatch(metric.name, "^(sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot)$")'- 'keep_keys(attributes, ["operation", "token.kind"]) where metric.name == "sie.gateway.generation.tokens"'@@ -282,7 +284,7 @@ processors:error_mode: propagatemetrics:metric:- - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]lane_admission[.]decisions|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'+ - 'not IsMatch(name, "^(sie[.]gateway[.]requests|sie[.]gateway[.]request[.]duration|sie[.]gateway[.]admission[.]decisions|sie[.]gateway[.]dispatches|sie[.]gateway[.]dispatch[.]duration|sie[.]gateway[.]config[.]applied_epoch|sie[.]gateway[.]config[.]operations|sie[.]gateway[.]config[.]bootstrap[.]degraded|sie[.]gateway[.]messaging[.]client[.]ready|sie[.]gateway[.]queue[.]publishes|sie[.]gateway[.]queue[.]publish[.]duration|sie[.]gateway[.]queue[.]publish[.]items|sie[.]gateway[.]queue[.]result_waits|sie[.]gateway[.]queue[.]result_wait[.]duration|sie[.]gateway[.]queue[.]result_chunks[.]received|sie[.]gateway[.]queue[.]result_chunk[.]bytes_received|sie[.]gateway[.]queue[.]result_chunk[.]rejections|sie[.]gateway[.]queue[.]result_chunk[.]transfers_completed|sie[.]gateway[.]queue[.]result_chunk[.]duplicates|sie[.]gateway[.]queue[.]result_chunk[.]retry_replacements|sie[.]gateway[.]queue[.]result_chunk[.]stale_retries|sie[.]gateway[.]queue[.]result_chunk[.]reserved_bytes|sie[.]gateway[.]queue[.]events|sie[.]gateway[.]queue[.]lane_admission[.]decisions|sie[.]gateway[.]provisioning[.]responses|sie[.]gateway[.]routing[.]unsupported_model_exclusions|sie[.]gateway[.]generation[.]events|sie[.]gateway[.]generation[.]ttft|sie[.]gateway[.]generation[.]tpot|sie[.]gateway[.]generation[.]tokens|sie[.]gateway[.]pending_demand|sie[.]gateway[.]lane[.]queue[.]depth|sie[.]gateway[.]lane[.]queue[.]snapshot[.]timestamp|sie[.]gateway[.]active_lease[.]gpus|sie[.]gateway[.]pool[.]warm_floor|sie[.]gateway[.]rejected[.]requests|sie[.]gateway[.]key_snapshot[.]polls|sie[.]gateway[.]settlement[.]confirms|sie[.]gateway[.]settlement[.]confirm[.]duration)$")'- 'resource.attributes["service.name"] != "sie-gateway"'filter/remote_application_contract:error_mode: propagatediff --git a/packages/sie_config/src/sie_config/config_api.py b/packages/sie_config/src/sie_config/config_api.pyindex ba789d723..ad131f6dd 100644--- a/packages/sie_config/src/sie_config/config_api.py+++ b/packages/sie_config/src/sie_config/config_api.py@@ -837,6 +837,7 @@ async def add_model(request: Request) -> Response:bundle_id: all_bundle_pool_config_hashes.get(bundle_id, {}) for bundle_id in affected_bundles}model_pool = model_registry.get_model_pool_name(model_id)+ bundle_adapters = model_registry.get_bundle_adapters(affected_bundles)nats_publish_failed = Falsepartial_publish_failed_bundles: list[str] = []@@ -852,6 +853,7 @@ async def add_model(request: Request) -> Response:model_config_yaml=config_yaml,model_pool=model_pool,bundle_pool_config_hashes=bundle_pool_config_hashes,+ bundle_adapters=bundle_adapters,))except PartialPublishError as e:@@ -1118,6 +1120,7 @@ async def replace_model(request: Request, model_id: str) -> Response:bundle_id: all_bundle_pool_config_hashes.get(bundle_id, {}) for bundle_id in affected_bundles}model_pool = model_registry.get_model_pool_name(model_id)+ bundle_adapters = model_registry.get_bundle_adapters(affected_bundles)nats_publish_failed = Falsepartial_publish_failed_bundles: list[str] = []@@ -1133,6 +1136,7 @@ async def replace_model(request: Request, model_id: str) -> Response:model_config_yaml=config_yaml,model_pool=model_pool,bundle_pool_config_hashes=bundle_pool_config_hashes,+ bundle_adapters=bundle_adapters,))except PartialPublishError as e:@@ -1646,6 +1650,7 @@ async def export_snapshot(request: Request) -> Response:for bundle_id in model_registry.list_bundles()}bundle_pool_config_hashes = model_registry.compute_bundle_pool_config_hashes()+ bundle_adapters = model_registry.get_bundle_adapters()snapshot = {"snapshot_version": 1,@@ -1653,6 +1658,7 @@ async def export_snapshot(request: Request) -> Response:"generated_at": datetime.now(UTC).isoformat(),"bundle_config_hashes": bundle_config_hashes,"bundle_pool_config_hashes": bundle_pool_config_hashes,+ "bundle_adapters": bundle_adapters,"models": models,}return Response(content=orjson.dumps(snapshot), media_type="application/json")diff --git a/packages/sie_config/src/sie_config/model_registry.py b/packages/sie_config/src/sie_config/model_registry.pyindex f4d8dc828..c0521fe5b 100644--- a/packages/sie_config/src/sie_config/model_registry.py+++ b/packages/sie_config/src/sie_config/model_registry.py@@ -1034,6 +1034,16 @@ class ModelRegistry:with self._lock:return self._bundles.get(bundle)+ def get_bundle_adapters(self, bundle_ids: list[str] | None = None) -> dict[str, list[str]]:+ """Return the adapter-module list of each requested known bundle.++ These are the lists ``compute_bundle_config_hash`` scopes by, so a worker+ that hashes the configs it received with them reproduces this hash.+ """+ with self._lock:+ names = list(self._bundles) if bundle_ids is None else bundle_ids+ return {name: list(self._bundles[name].adapters) for name in names if name in self._bundles}+def get_models_for_bundle(self, bundle: str) -> list[str]:"""Get all models that can be served by a bundle.diff --git a/packages/sie_config/src/sie_config/nats_publisher.py b/packages/sie_config/src/sie_config/nats_publisher.pyindex 46dc7477d..fa2543a70 100644--- a/packages/sie_config/src/sie_config/nats_publisher.py+++ b/packages/sie_config/src/sie_config/nats_publisher.py@@ -240,6 +240,7 @@ class NatsPublisher:model_config_yaml: str,model_pool: str = "default",bundle_pool_config_hashes: dict[str, dict[str, str]] | None = None,+ bundle_adapters: dict[str, list[str]] | None = None,) -> None:"""Publish config change notifications to NATS.@@ -254,7 +255,8 @@ class NatsPublisher:set of fields that ``sie_gateway`` and worker sidecars expect(``router_id``, ``bundle_id``, ``epoch``, ``bundle_config_hash``,``model_id``, ``profiles_added``, ``model_config``,- ``affected_bundles``, ``pool``, ``bundle_pool_config_hashes``).+ ``affected_bundles``, ``pool``, ``bundle_pool_config_hashes``,+ ``bundle_adapters``).See ``packages/sie_gateway/src/nats/manager.rs::ConfigNotification``.Args:@@ -266,6 +268,7 @@ class NatsPublisher:model_config_yaml: Full model config YAML content.model_pool: Canonical pool assignment for the changed model.bundle_pool_config_hashes: Nested bundle_id -> pool -> hash map.+ bundle_adapters: bundle_id -> adapter modules the hashes were scoped by.Raises:RuntimeError: If NATS is not connected.@@ -294,6 +297,7 @@ class NatsPublisher:nc = cast("nats.NATS", self._nc)normalized_pool = model_pool.strip().lower() or "default"pool_hashes = bundle_pool_config_hashes or {}+ adapters_by_bundle = bundle_adapters or {}# Publish each bundle delta individually, collecting failures# rather than short-circuiting on the first exception. If we@@ -315,6 +319,7 @@ class NatsPublisher:"affected_bundles": affected_bundles,"pool": normalized_pool,"bundle_pool_config_hashes": pool_hashes,+ "bundle_adapters": adapters_by_bundle,}encoded = orjson.dumps(payload)diff --git a/packages/sie_config/tests/test_config_api.py b/packages/sie_config/tests/test_config_api.pyindex 0810e7bc3..a8ce9bdaf 100644--- a/packages/sie_config/tests/test_config_api.py+++ b/packages/sie_config/tests/test_config_api.py@@ -752,6 +752,7 @@ class TestConfigAPIExport:"default")assert data["bundle_pool_config_hashes"]["default"]["default"] == data["bundle_config_hashes"]["default"]+ assert data["bundle_adapters"] == {"default": ["sie_server.adapters.bert_flash"]}assert len(data["models"]) == 1assert data["models"][0]["model_id"] == "test/model"assert data["models"][0]["affected_bundles"] == ["default"]@@ -1093,6 +1094,9 @@ class TestConfigAPIExportNoConfigStore:assert set(parsed.get("profiles", {}).keys()) == {"default", "fast"}, (f"NATS delta must carry merged profiles; got {list(parsed.get('profiles', {}).keys())}")+ assert last_call.kwargs["affected_bundles"] == ["default"]+ assert last_call.kwargs["bundle_adapters"] == self.app.state.model_registry.get_bundle_adapters(["default"])+ assert last_call.kwargs["bundle_adapters"]["default"]class TestConfigAPIExportAuth:diff --git a/packages/sie_config/tests/test_nats_publisher.py b/packages/sie_config/tests/test_nats_publisher.pyindex 578e4523f..889b1dd6b 100644--- a/packages/sie_config/tests/test_nats_publisher.py+++ b/packages/sie_config/tests/test_nats_publisher.py@@ -155,6 +155,7 @@ class TestNatsPublisherPublish:"epoch","bundle_config_hash","bundle_pool_config_hashes",+ "bundle_adapters","model_id","profiles_added","model_config",@@ -172,6 +173,7 @@ class TestNatsPublisherPublish:assert payload["affected_bundles"] == ["default", "sglang"]assert payload["pool"] == "default"assert payload["bundle_pool_config_hashes"] == {}+ assert payload["bundle_adapters"] == {}@pytest.mark.asyncioasync def test_publish_bundle_subject_carries_its_own_hash(self) -> None:@@ -227,6 +229,27 @@ class TestNatsPublisherPublish:assert payload["bundle_config_hash"] == "global-hash"assert payload["bundle_pool_config_hashes"]["candle"]["customer-a"] == "tenant-hash"+ @pytest.mark.asyncio+ async def test_publish_payload_carries_the_bundle_adapters_the_hashes_used(self) -> None:+ publisher = NatsPublisher()+ mock_nc = AsyncMock()+ mock_nc.is_connected = True+ publisher._nc = mock_nc+ publisher._connected = True+ adapters = {"default": ["sie_server.adapters.bert_flash", "sie_server.adapters.laya.adapter"]}+ await publisher.publish_config_notification(+ model_id="org/model",+ profiles_added=["default"],+ affected_bundles=["default"],+ bundle_config_hashes={"default": "hash"},+ epoch=9,+ model_config_yaml="yaml",+ bundle_adapters=adapters,+ )++ for call in mock_nc.publish.call_args_list:+ assert json.loads(call.args[1].decode())["bundle_adapters"] == adapters+@pytest.mark.asyncioasync def test_publish_all_payload_matches_paired_bundle_payload(self) -> None:"""The payload sent to _all for a given bundle is byte-identical to thediff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 73e34d395..c8459598c 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -36,7 +36,8 @@ Key terms used throughout this document:- **Pool**: an operational routing group of workers managed by the gateway. Answers "which compatible workers should this request be queued to right now?". Pools are a runtime concept stored in Kubernetes.- **Config store**: `sie-config`'s backing store for persisted state. Per-model YAML files plus a plain-text monotonic `epoch` counter, laid out as `{base}/models/{id-with-/-as-__}.yaml` and `{base}/epoch`. The backend is selected by the `SIE_CONFIG_STORE_DIR` scheme: a local path (default — backed by an opt-in PVC in Helm), `s3://…`, or `gs://…`.- **Config epoch**: a monotonic integer. Every `sie-config` write that creates new profiles bumps it by one. The gateway tracks it locally as `ConfigEpoch` for drift detection.-- **`bundle_config_hash`**: a content hash over each model's immutable weights revision and routable-profile fields (`adapter_path`, `max_batch_tokens`, `compute_precision`, `adapter_options`) for every model whose adapters match a bundle. Used by admin tooling and workers to tell whether a worker's local registry and weights identity match the gateway's expected config for this bundle.+- **`bundle_config_hash`**: a content hash over each model's immutable weights revision and routable-profile fields (`adapter_path`, `max_batch_tokens`, `compute_precision`, `adapter_options`) for every model whose adapters match a bundle. Used by admin tooling and workers to tell whether a worker's local registry and weights identity match the gateway's expected config for this bundle. Every service scopes the hash by `sie-config`'s bundle definition, so it identifies the config a worker received, not the adapter code in the worker's image (§7).+- **`unsupported_models`**: the routable model ids (`model` or `model:profile`) covered by a worker's `bundle_config_hash` that the worker cannot serve, for example because its image predates an adapter that `sie-config` added to the bundle. Workers report it in their heartbeat; it is empty in steady state.## 2. Inference Request Path@@ -57,7 +58,7 @@ Rules enforced on the inference path:- Ordinary encode, score, and extract use pool-queue dispatch; capped logical batch pools and generation use worker direct-dispatch. Both paths use JetStream, with no direct-HTTP fallback. `src/handlers/proxy.rs` is the JetStream submission handler despite its name.- If the queue transport is unavailable (no usable NATS client at init), the gateway returns `503`. It does not fall back to direct mode.- Unknown model ids fast-fail with `404` whenever the in-memory `ModelRegistry` has been populated (either by the filesystem seed or by a successful bootstrap / delta from `sie-config`). In the pre-bootstrap edge case where the registry is still empty — no seed, no export applied yet — the proxy falls back to the caller-supplied bundle (or `"default"`) so an unseeded gateway can still publish work to a cold pool that a caller pinned via `X-SIE-Pool`. Once any model is registered, this fallback is disabled and the 404 contract applies.-- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. Explicit `X-SIE-Pool` selects a logical pool; the gateway publishes to that pool's backing queue pool (`PoolSpec.queue_pool`, default `default`) and stamps the logical pool into the work item as `admission_pool`. Deliveries whose hash is not the worker-sidecar's current hash, or logical pools that do not assign that worker, are NAKed before backend IPC. Successful non-streaming results echo the execution hash; the gateway emits `X-SIE-Model-Revision` only when every successful result matches the hash and immutable revision captured atomically at routing time. The header value is the lowercase 64-hex executed bundle/config SHA-256, not the catalog weights revision (for example, a 40-hex Hugging Face commit). Buffered generation also follows this rule even though it internally collects worker chunks. True SSE responses (`stream: true`) always omit the header because headers precede the terminal result. Successful terminal SSE events may instead carry the worker-origin `execution_identity_sha256` / `execution_binding_sha256` pair, both lowercase 64-hex digests; absence remains valid for older or self-hosted deployments and does not attest execution. These digests are distinct from both the weights revision and the bundle/config hash.+- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. For the requested model, a lane (`pool`, `machine_profile`, `bundle`) is eligible only when no such worker in it lists the model in `unsupported_models`: every worker of a lane consumes the lane subject, so a worker that cannot serve the model would otherwise receive its items and NAK them, spending JetStream delivery attempts. Worker-direct rings (generation and capped logical pools) exclude workers that list the model. When every lane is excluded the gateway returns the `503 PROVISIONING` contract below and counts the exclusion in `sie.gateway.routing.unsupported_model_exclusions`. Explicit `X-SIE-Pool` selects a logical pool; the gateway publishes to that pool's backing queue pool (`PoolSpec.queue_pool`, default `default`) and stamps the logical pool into the work item as `admission_pool`. Deliveries whose hash is not the worker-sidecar's current hash, whose model the worker lists in `unsupported_models`, or whose logical pool does not assign that worker, are NAKed before backend IPC. Successful non-streaming results echo the execution hash; the gateway emits `X-SIE-Model-Revision` only when every successful result matches the hash and immutable revision captured atomically at routing time. The header value is the lowercase 64-hex executed bundle/config SHA-256, not the catalog weights revision (for example, a 40-hex Hugging Face commit). Buffered generation also follows this rule even though it internally collects worker chunks. True SSE responses (`stream: true`) always omit the header because headers precede the terminal result. Successful terminal SSE events may instead carry the worker-origin `execution_identity_sha256` / `execution_binding_sha256` pair, both lowercase 64-hex digests; absence remains valid for older or self-hosted deployments and does not attest execution. These digests are distinct from both the weights revision and the bundle/config hash.- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway records pending demand for KEDA and returns a retryable `503` provisioning response with `Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. SIE-native surfaces use the SDK retry envelope (`{"error":{"code","message"}}`); OpenAI-compatible surfaces (`/v1/generate`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`) use the OpenAI error envelope, because standard OpenAI clients parse 2xx as successful model output. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.- On no-consumer conditions for the JetStream publish, the gateway treats the miss as the same pre-execution provisioning state and returns the same retryable `503 PROVISIONING` contract (`Retry-After: 60`, `X-SIE-Error-Code: PROVISIONING`, and surface-specific error envelope). On backpressure conditions the gateway returns `503` with `Retry-After: 5`. Backpressure is evaluated twice: pool-wide against the `WORK_POOL_{pool}` stream's pending count (`SIE_GATEWAY_MAX_STREAM_PENDING`), and per lane (`pool`/`machine_profile`/`bundle`) against a gateway-local in-flight work-item count (`SIE_GATEWAY_MAX_LANE_IN_FLIGHT_ITEMS`). The per-lane decision is always computed and recorded on `sie.gateway.queue.lane_admission.decisions`, but it only sheds when `SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE` is set; with the flag off (the default) the pool-wide check is the sole gate. Both sheds produce the same `503` contract and both record pending demand for the exact physical lane so KEDA scales it.- On queue result timeouts the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5`. This means the gateway accepted and published the work item, but no worker result reached the gateway before `SIE_GATEWAY_REQUEST_TIMEOUT`; it must not be collapsed into worker-emitted `MODEL_LOADING`, which remains a separate retryable `503 MODEL_LOADING` signal.@@ -236,7 +237,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`. 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.+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, and it commits the worker's `unsupported_models` together with that hash (§7).Response shape:@@ -254,6 +255,7 @@ Response shape:"total_eligible_workers": 3,"acked_workers": ["worker-1", "worker-2", "worker-3"],"pending_workers": [],+ "unsupported_workers": [],"acked": true}],@@ -265,6 +267,7 @@ Computation rules:- **Per-replica only.** The endpoint reports the worker registry state on this specific gateway pod. Fleet-wide readiness is the union across replicas; admin tooling fans out.- **Case-sensitive bundle match.** A worker is counted as eligible only if `worker.bundle == bundle_id` exactly. Workers whose `bundle` field does not match exactly are skipped entirely — they contribute to neither `total_eligible_workers` nor `pending_workers`. The expected hash is computed against the canonical bundle ID from the registry, and the fleet is case-consistent in practice.+- **Per-model support.** A worker that reports the expected hash but lists the model, or one of its `model:profile` routes, in `unsupported_models` is reported in `unsupported_workers`, not `acked_workers`, and keeps `acked` false. During a rollout that adds an adapter to a bundle, workers on the earlier image appear here for the models that use the new adapter while they keep serving every other model.- **Healthy-only.** Unhealthy workers (per `worker.healthy()`) are skipped entirely; they contribute to neither `total_eligible_workers` nor either worker list.- **Zero-bundle models.** A model with no routable bundles is reported as `all_bundles_acked: false` and `no_bundles: true`. Returning `true` for "nothing to ack" would silently tell admin tooling "fully deployed" when there is nothing deployed.- **`config_epoch` field.** Surfaces the gateway's local `ConfigEpoch` so callers can tell whether this replica has caught up to a recent write (`config_epoch` lower than the write's returned epoch means this replica is still catching up).@@ -273,6 +276,10 @@ Computation rules:`bundle_config_hash` is computed independently by `sie-config`, the gateway, and workers. The `sie-config` export/epoch surface keeps the global per-bundle hash for bootstrap and drift detection, while export snapshots and live NATS deltas also carry per-bundle/per-pool hashes for worker convergence. Worker sidecars apply only models whose top-level `pool` matches their own `SIE_POOL`, then advertise that pool-scoped hash. Gateway hot routing/readiness compares workers against the hash for the same materialized scope the worker serves: the default pool scope for unfiltered workers, or the named physical queue-pool scope for workers filtered by `SIE_POOL`. Logical API pools may draw from a different backing queue pool via `PoolSpec.queue_pool`; for the admin-tooling readiness flow to work, gateway and worker hashes must be byte-identical for that backing bundle/pool scope. A model config's top-level `pool` must therefore match the physical queue scope that will materialize it; dynamic logical pools backed by `default` should use default-scoped model configs unless a dedicated worker queue exists.+A model belongs to a bundle's hash when one of its profiles resolves to an adapter module in that bundle's `adapters` list. All three services use `sie-config`'s list for this. `sie-config` sends it as `bundle_adapters` (bundle id to adapter modules) with every export snapshot and live delta, and the worker sidecar forwards the list for its bundle over backend IPC (`ApplyModelConfig` / `ReplaceModelConfigs`). The Python worker then hashes the configs it received with that list, so a worker whose image predates an adapter still reproduces the control-plane hash. A worker that has not yet received a list, or whose `sie-config` does not send one, uses the list in its image's bundle file, as before. When the worker's schema rejects an export entry, the worker hashes the received entry's routable fields, so the hash still identifies what the control plane sent.++Hash equality therefore no longer implies that the worker can serve every model it covers. The worker reports the routable ids it cannot serve as `unsupported_models`: those whose adapter module is in the control-plane list but not in its image's bundle file, and those whose export entry its schema rejected when the config it retains differs in hashed fields (or it has none). The sidecar commits the list together with the hash, publishes it in its heartbeat (omitted when empty), and NAKs work for a listed model before backend IPC. The gateway routes a model to a worker only when the hash matches and the model is not listed (§2). A worker that sends no list serves every model its hash covers: before this field existed, workers hashed with their image's adapter list, so a matching hash already implied that the image contains every covered adapter. The same holds for a hash that reaches a heartbeat without a list today. Backend IPC `Ping` carries no list, so the Python worker's `Ping` hash stays scoped by its image's bundle file, and a sidecar adopts it only while it has committed no config (at startup, including a sidecar restart next to a running worker). The gateway accepts at most 1024 ids per heartbeat. A worker that reports more is routed no model until it reports fewer, because a dropped id would otherwise read as supported. The Candle worker reports no list. It echoes the control-plane hash only after it has parsed and applied every entry of the export or delta, so an echoed hash implies full support. An entry it cannot parse fails the whole apply: the worker keeps its previous hash and the sidecar does not advance, so the bundle is held on that worker as before.+The hash is a SHA-256 over a JSON-serialized, sort-keys representation of a structured object. The outer shape is an array of models, each with `sie_id`, `revision`, and `profiles: [{name, config: {...4 fields...}}]`. `revision` is the immutable `hf_revision` commit SHA, or null for package-backed/unpinned development models. The inner `config` for each profile is strictly the four routable-profile fields: `adapter_path`, `max_batch_tokens`, `compute_precision`, `adapter_options`. Any field outside that whitelist is excluded from the hash so that non-routable edits (e.g. comments, description-style metadata) cannot unnecessarily invalidate worker acks. Python uses `orjson.dumps(..., OPT_SORT_KEYS)`; Rust mirrors this via `serde_json::to_vec` over `BTreeMap`-backed canonical types.`adapter_options` is canonicalized before hashing:@@ -305,7 +312,7 @@ Per-subject transport:| Non-generation request abandonment | `work_cancel.{router_id}.{request_id}` | NATS Core | Best-effort request-wide signal emitted when the gateway abandons encode/score/extract work, including when a publish ACK fails and the stored item's fate is unknown. Active sidecars retain bounded namespaced tombstones and ACK-drop matching work before backend IPC. The signal is not replayed to disconnected or restarted workers, and static inference already past IPC is not preempted. || Inference results | `_INBOX.{router_id}.{request_id}` | NATS Core | Gateway is waiting synchronously; a brief blip after publish but before delivery means the result is lost and the client may retry (the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5` — see §2). Result payload is msgpack. || Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Gateway durability comes from the snapshot/export path (section 4), not the bus. JSON payload (control plane, not hot path). The gateway subscribes on `_all`; worker-sidecar containers subscribe on their bundle subject and apply through backend IPC. |-| Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`) and supervises the subscriber task: reconnects normally resume in `async-nats`, but a terminated subscription stream is recreated with bounded backoff because there is no full-state health poller. Worker-sidecar containers publish this heartbeat and include the latest bundle hash after successful config apply. Helm sidecar deployments set `health_mode=nats`; the gateway binary default remains `ws` so standalone/test deployments can use the Python WebSocket path. |+| Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`) and supervises the subscriber task: reconnects normally resume in `async-nats`, but a terminated subscription stream is recreated with bounded backoff because there is no full-state health poller. Worker-sidecar containers publish this heartbeat and include the latest bundle hash after successful config apply, plus `unsupported_models` when that hash covers models the worker cannot serve. `packages/wire-fixtures/worker_status.json` pins the heartbeat field set for the sidecar and the gateway. Helm sidecar deployments set `health_mode=nats`; the gateway binary default remains `ws` so standalone/test deployments can use the Python WebSocket path. || DLQ advisories | `$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>` | NATS Core (advisory) | JetStream emits these; gateway replicas subscribe in `queue/dlq.rs` and publish to `DEAD_LETTERS` with a deterministic `Nats-Msg-Id`, so JetStream dedupes replica fan-out. || DLQ storage | `sie.dlq.{model_token}` | JetStream | Single stream `DEAD_LETTERS` (Limits retention, 24 h `max_age`) captures `sie.dlq.>`. Storage and replicas track the work-queue setting (`SIE_STREAM_STORAGE` / `SIE_STREAM_REPLICAS`, memory/1 by default), so a memory-backed DLQ is erased by the same broker restart that erases the work it recorded. `model_token` is derived from the advisory's original work subject by taking the model segment and replacing `/` with `_`. |@@ -405,6 +412,7 @@ The `ConfigNotification` JSON payload carries the following fields, verified aga- `bundle_pool_config_hashes` — nested `bundle_id -> pool -> hash` map used by gateways and sidecars to compare worker acks against the same pool-scoped bundle projection the worker applied.- `profiles_added` — list of profile names created by this write.- `model_config` — raw YAML string of the full model config.+- `bundle_adapters` — `bundle_id -> [adapter module]` for the affected bundles: the lists the hashes in this message were scoped by (§7). The export snapshot carries the same map for every bundle. Older `sie-config` versions omit it.- `affected_bundles` — list of every bundle affected by this write. Each affected bundle receives its own message, so a `_all` subscriber sees N messages per write with their respective `bundle_id` / `bundle_config_hash` populated.### 8.4 Serialization formats@@ -469,6 +477,8 @@ The gateway has no persistent config store. `SIE_CONFIG_STORE_DIR` and `SIE_CONF7. **Bundles are filesystem-only on `sie-config`.** There is no bundle-write API. Bundles change by redeploying the `sie-config` image (and the worker image, since adapters referenced in a bundle live in the worker). The gateway no longer bakes bundles — it fetches them from `sie-config` at bootstrap and re-fetches on any `bundles_hash` drift (§4.2) — so a bundle addition propagates to running gateway replicas within one `DEFAULT_POLL_INTERVAL` without a gateway redeploy. The natural deploy order is `sie-config` first (so the new bundle is advertised), then workers for the new bundle (so routable instances exist when the gateway learns about the bundle).+ A release can also add an adapter to an existing bundle. Once the new `sie-config` is running, a worker still on the earlier image reports the new bundle hash with the new adapter's models in `unsupported_models` (§7), so it keeps serving every other model of the bundle. A new adapter's models become routable in a lane once every worker in that lane that reports the hash can serve them, typically when the rollout has replaced the earlier workers; until then they get the retryable `503 PROVISIONING` response. This needs the earlier workers to run a release that already reports `unsupported_models`. Workers from before that release hash with their image's adapter list, so while they remain, the whole bundle is routable only on upgraded workers, as before. The first release with `unsupported_models` therefore protects the upgrade to the release after it, not its own upgrade. A release that removes an adapter from a bundle needs no special handling: `sie-config` stops exporting that adapter's models to the bundle, and workers of either image reproduce the hash.+Side effect of this design: `sie-config` is a **cold-start** dependency for gateway replicas.- A fresh replica that cannot reach `sie-config` starts with zero bundles AND zero models.diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 70c66ac11..bbd869224 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -2185,6 +2185,13 @@"total_eligible_workers": {"minimum": 0,"type": "integer"+ },+ "unsupported_workers": {+ "description": "Workers that report the expected hash but cannot serve this model, for\nexample during a rollout that adds its adapter to the bundle.",+ "items": {+ "type": "string"+ },+ "type": "array"}},"required": [@@ -3966,6 +3973,17 @@"format": "int32","type": "integer"},+ "unsupported_models": {+ "description": "Models covered by `bundle_config_hash` that this worker cannot serve,\nfor example during a rollout that adds adapters to its bundle. The\ngateway does not route these models to it. Omitted when empty.",+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ "unsupported_models_overflow": {+ "description": "The worker reported more unsupported models than the gateway accepts\n(1024), so no model is routed to it. Omitted when false.",+ "type": "boolean"+ },"url": {"type": "string"}diff --git a/packages/sie_gateway/src/discovery/nats_health.rs b/packages/sie_gateway/src/discovery/nats_health.rsindex 9788fdc91..e359aa206 100644--- a/packages/sie_gateway/src/discovery/nats_health.rs+++ b/packages/sie_gateway/src/discovery/nats_health.rs@@ -315,6 +315,7 @@ mod tests {memory_total_bytes: None,saturated: false,terminated: false,+ unsupported_models: Vec::new(),}}diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex 675cf9947..60a948f0a 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -190,6 +190,17 @@ async fn compute_model_status(// misreport, so `no_bundles` makes the distinction explicit and// `all_bundles_acked` stays false.let mut all_acked = !model_info.bundles.is_empty();+ // The queried route and, for a base model, each of its profile routes.+ let mut route_ids = vec![model_info.name.clone()];+ if model_info.canonical_profile == "default" {+ route_ids.extend(+ model_info+ .profile_names+ .iter()+ .filter(|profile| profile.as_str() != "default")+ .map(|profile| format!("{}:{profile}", model_info.name)),+ );+ }let model_pool = model_info.pool.as_deref().unwrap_or("default");let pending_generation = state.work_publisher@@ -205,6 +216,8 @@ async fn compute_model_status(let mut total_eligible = 0usize;let mut acked_workers: Vec<String> = Vec::new();let mut pending_workers: Vec<String> = Vec::new();+ // Acked the hash but reported that they cannot serve this model.+ let mut unsupported_workers: Vec<String> = Vec::new();for worker in workers.values() {// Exact bundle-name match. `compute_bundle_config_hash` hashes@@ -224,13 +237,18 @@ async fn compute_model_status(}total_eligible += 1;if !expected.is_empty() && worker.bundle_config_hash == expected {- acked_workers.push(worker.name.clone());+ if route_ids.iter().all(|route| worker.supports_model(route)) {+ acked_workers.push(worker.name.clone());+ } else {+ unsupported_workers.push(worker.name.clone());+ }} else {pending_workers.push(worker.name.clone());}}- let bundle_acked = total_eligible > 0 && pending_workers.is_empty();+ let bundle_acked =+ total_eligible > 0 && pending_workers.is_empty() && unsupported_workers.is_empty();if !bundle_acked {all_acked = false;}@@ -242,6 +260,7 @@ async fn compute_model_status("total_eligible_workers": total_eligible,"acked_workers": acked_workers,"pending_workers": pending_workers,+ "unsupported_workers": unsupported_workers,"acked": bundle_acked,}));}@@ -733,23 +752,29 @@ mod tests {/// Helper: seed a model into the registry so status tests have a target.fn seed_model(state: &AppState, model_id: &str) {+ seed_model_with_profiles(state, model_id, &["default"]);+ }++ fn seed_model_with_profiles(state: &AppState, model_id: &str, profile_names: &[&str]) {use crate::types::model::{ModelConfig, ProfileConfig};let mut profiles = HashMap::new();- profiles.insert(- "default".to_string(),- ProfileConfig {- kv_budget_tokens: None,- max_output_tokens: None,- grammar_profile: None,- chat_template_kwargs: None,- adapter_path: Some("module:Adapter".to_string()),- max_batch_tokens: Some(4096),- compute_precision: None,- adapter_options: None,- extends: None,- },- );+ for profile_name in profile_names {+ profiles.insert(+ (*profile_name).to_string(),+ ProfileConfig {+ kv_budget_tokens: None,+ max_output_tokens: None,+ grammar_profile: None,+ chat_template_kwargs: None,+ adapter_path: Some("module:Adapter".to_string()),+ max_batch_tokens: Some(4096),+ compute_precision: None,+ adapter_options: None,+ extends: None,+ },+ );+ }state.model_registry.add_model_config(ModelConfig {@@ -842,6 +867,7 @@ mod tests {pool_name: "default".into(),saturated: false,terminated: false,+ unsupported_models: Vec::new(),}}@@ -885,6 +911,97 @@ mod tests {assert!(bundle["pending_workers"].as_array().unwrap().is_empty());}+ #[tokio::test]+ async fn test_model_status_separates_workers_that_cannot_serve_the_model() {+ let bundles_dir = tempfile::TempDir::new().unwrap();+ let models_dir = tempfile::TempDir::new().unwrap();+ let (app, state) = build_test_router_with_state(&bundles_dir, &models_dir).await;+ seed_model(&state, "BAAI/bge-m3");+ let expected_hash = state+ .model_registry+ .compute_bundle_config_hash_for_pool("default", "default");++ let mut earlier = worker_msg("worker-earlier", "default", &expected_hash);+ earlier.unsupported_models = vec!["BAAI/bge-m3".into()];+ state+ .registry+ .update_worker("http://worker-earlier:8080", earlier)+ .await;+ state+ .registry+ .update_worker(+ "http://worker-current:8080",+ worker_msg("worker-current", "default", &expected_hash),+ )+ .await;++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/configs/models/BAAI/bge-m3/status")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let parsed: serde_json::Value =+ serde_json::from_slice(&body_bytes(response).await).unwrap();+ assert_eq!(parsed["all_bundles_acked"], false);+ let bundle = &parsed["bundles"][0];+ assert_eq!(bundle["total_eligible_workers"], 2);+ assert_eq!(+ bundle["acked_workers"],+ serde_json::json!(["worker-current"])+ );+ assert_eq!(+ bundle["unsupported_workers"],+ serde_json::json!(["worker-earlier"])+ );+ assert!(bundle["pending_workers"].as_array().unwrap().is_empty());+ assert_eq!(bundle["acked"], false);+ }++ #[tokio::test]+ async fn test_model_status_counts_an_unsupported_profile_route() {+ let bundles_dir = tempfile::TempDir::new().unwrap();+ let models_dir = tempfile::TempDir::new().unwrap();+ let (app, state) = build_test_router_with_state(&bundles_dir, &models_dir).await;+ seed_model_with_profiles(&state, "BAAI/bge-m3", &["default", "fast"]);+ let expected_hash = state+ .model_registry+ .compute_bundle_config_hash_for_pool("default", "default");++ let mut earlier = worker_msg("worker-earlier", "default", &expected_hash);+ earlier.unsupported_models = vec!["BAAI/bge-m3:fast".into()];+ state+ .registry+ .update_worker("http://worker-earlier:8080", earlier)+ .await;++ let response = app+ .oneshot(+ Request::builder()+ .uri("/v1/configs/models/BAAI/bge-m3/status")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let parsed: serde_json::Value =+ serde_json::from_slice(&body_bytes(response).await).unwrap();+ let bundle = &parsed["bundles"][0];+ assert!(bundle["acked_workers"].as_array().unwrap().is_empty());+ assert_eq!(+ bundle["unsupported_workers"],+ serde_json::json!(["worker-earlier"])+ );+ assert_eq!(bundle["acked"], false);+ }+#[tokio::test]async fn test_model_status_reports_pending_for_stale_hash() {let bundles_dir = tempfile::TempDir::new().unwrap();diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 01fe62512..d255d42da 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -693,6 +693,7 @@ mod route_tests {pool_name: String::new(),saturated: false,terminated: false,+ unsupported_models: Vec::new(),}}diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 4b34b3c4b..ebcdbf1aa 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -645,6 +645,7 @@ async fn apply_model_pool_default(/// `X-SIE-MACHINE-PROFILE`. Before the fix this branch only fired when/// `gpu` was non-empty, which turned a normal cold start into a queue/// timeout for default-routing clients.+#[cfg(test)]async fn resolve_effective_pool(registry: &WorkerRegistry,pool_manager: Option<&PoolManager>,@@ -653,6 +654,38 @@ async fn resolve_effective_pool(pool_name: &str,bundle_config_hash: &str,) -> PoolLookup {+ resolve_effective_pool_for_model(+ registry,+ pool_manager,+ bundle,+ gpu,+ pool_name,+ bundle_config_hash,+ "",+ )+ .await+}++/// [`resolve_effective_pool`] for one model: a lane in which a worker that+/// reports the expected hash cannot serve `model` is not eligible (see+/// [`WorkerRegistry::resolve_queue_route_for_model`]).+async fn resolve_effective_pool_for_model(+ registry: &WorkerRegistry,+ pool_manager: Option<&PoolManager>,+ bundle: &str,+ gpu: &str,+ pool_name: &str,+ bundle_config_hash: &str,+ model: &str,+) -> PoolLookup {+ let resolve_route = |gpu: &str, pool: &str| {+ let lookup =+ registry.resolve_queue_route_for_model(bundle, gpu, pool, bundle_config_hash, model);+ if lookup.excluded_unsupported {+ telemetry::record_unsupported_model_route_exclusion();+ }+ lookup.route+ };if !pool_name.is_empty() {let normalized_pool = normalize_pool_name(pool_name);let Some(queue_pool) = queue_pool_for_request(pool_manager, pool_name).await else {@@ -676,9 +709,7 @@ async fn resolve_effective_pool(} else {""};- let route = registry- .resolve_queue_route_in_pool(bundle, lookup_gpu, &queue_pool, bundle_config_hash)- .await;+ let route = resolve_route(lookup_gpu, &queue_pool);let pending_demand_profiles = if route.is_none() {profiles} else {@@ -700,9 +731,7 @@ async fn resolve_effective_pool(let configured_profile = profiles.into_iter().find(|profile| profile.eq_ignore_ascii_case(gpu));- let route = registry- .resolve_queue_route_in_pool(bundle, gpu, &queue_pool, bundle_config_hash)- .await;+ let route = resolve_route(gpu, &queue_pool);let exact_gpu_match = route.is_some();return PoolLookup {resolution: match route {@@ -722,9 +751,7 @@ async fn resolve_effective_pool(// Primary lookup. Folds the "was the exact tuple routable?"// question into the same registry load we use to pick a pool.- let primary = registry- .resolve_queue_route_in_pool(bundle, gpu, DEFAULT_POOL_NAME, bundle_config_hash)- .await;+ let primary = resolve_route(gpu, DEFAULT_POOL_NAME);let exact_gpu_match = !gpu.is_empty() && primary.is_some();let resolution = match primary {@@ -2366,13 +2393,14 @@ async fn proxy_request_inner(// it holds the caller's GPU preference when no exact-tuple worker was// registered, or, for a cold gpu-agnostic request, every machine profile// the pool can provision so each candidate lane can scale from zero.- let lookup = resolve_effective_pool(+ let lookup = resolve_effective_pool_for_model(&state.registry,Some(&state.pool_manager),&bundle,&gpu,&pool_name,&bundle_config_hash,+ &dispatch_model,).await;let demand_pool = lookup.demand_pool.clone();@@ -6852,13 +6880,14 @@ async fn resolve_generation_route(.map(|info| info.engine).unwrap_or_else(|| crate::types::bundle::DEFAULT_ENGINE.to_string()),};- let lookup = resolve_effective_pool(+ let lookup = resolve_effective_pool_for_model(&state.registry,Some(&state.pool_manager),&bundle,&gpu,&pool_name,&bundle_config_hash,+ dispatch_model,).await;let demand_pool = lookup.demand_pool.clone();@@ -16944,6 +16973,7 @@ mod tests {memory_total_bytes: None,saturated: false,terminated: false,+ unsupported_models: Vec::new(),},).await;@@ -20954,6 +20984,7 @@ mod tests {memory_total_bytes: None,saturated: false,terminated: false,+ unsupported_models: Vec::new(),}}@@ -21375,6 +21406,33 @@ mod tests {assert!(!out.exact_gpu_match);}+ #[tokio::test]+ async fn test_resolve_effective_pool_provisions_a_model_its_lane_cannot_serve() {+ let reg = pool_registry();+ let mut earlier = worker_msg("default", "l4-spot", "default");+ earlier.bundle_config_hash = "h1".into();+ earlier.unsupported_models = vec!["org/new-family".into()];+ reg.update_worker("http://w1:8080", earlier).await;++ let served =+ resolve_effective_pool_for_model(®, None, "default", "", "", "h1", "BAAI/bge-m3")+ .await;+ assert!(matches!(served.resolution, PoolResolution::Route(_)));++ let excluded = resolve_effective_pool_for_model(+ ®,+ None,+ "default",+ "l4-spot",+ "",+ "h1",+ "org/new-family",+ )+ .await;+ assert_eq!(excluded.resolution, PoolResolution::Provisioning);+ assert!(!excluded.exact_gpu_match);+ }+#[tokio::test]async fn test_resolve_effective_pool_pinned_pool_provisions_when_hash_mismatch() {let reg = pool_registry();diff --git a/packages/sie_gateway/src/nats/manager.rs b/packages/sie_gateway/src/nats/manager.rsindex 92a34dc84..a95ed7c32 100644--- a/packages/sie_gateway/src/nats/manager.rs+++ b/packages/sie_gateway/src/nats/manager.rs@@ -856,6 +856,7 @@ profiles:"bundle_config_hash": "x","model_id": "unknown/model","future_field_we_dont_know_about": 42,+ "bundle_adapters": {"default": ["sie_server.adapters.sentence_transformer"]},"model_config": ""}"#;let parsed: ConfigNotification = serde_json::from_str(json).unwrap();diff --git a/packages/sie_gateway/src/observability/metrics.rs b/packages/sie_gateway/src/observability/metrics.rsindex 5684e8b10..3c905e411 100644--- a/packages/sie_gateway/src/observability/metrics.rs+++ b/packages/sie_gateway/src/observability/metrics.rs@@ -61,6 +61,8 @@ pub const QUEUE_EVENTS_METRIC_NAME: &str = "sie.gateway.queue.events";pub const QUEUE_LANE_ADMISSION_DECISIONS_METRIC_NAME: &str ="sie.gateway.queue.lane_admission.decisions";pub const PROVISIONING_RESPONSES_METRIC_NAME: &str = "sie.gateway.provisioning.responses";+pub const ROUTING_UNSUPPORTED_MODEL_EXCLUSIONS_METRIC_NAME: &str =+ "sie.gateway.routing.unsupported_model_exclusions";pub const GENERATION_EVENTS_METRIC_NAME: &str = "sie.gateway.generation.events";pub const GENERATION_TTFT_METRIC_NAME: &str = "sie.gateway.generation.ttft";pub const GENERATION_TPOT_METRIC_NAME: &str = "sie.gateway.generation.tpot";@@ -820,6 +822,7 @@ struct GatewayTelemetry {queue_events: Counter<u64>,queue_lane_admission_decisions: Counter<u64>,provisioning_responses: Counter<u64>,+ routing_unsupported_model_exclusions: Counter<u64>,generation_events: Counter<u64>,generation_ttft: Histogram<f64>,generation_tpot: Histogram<f64>,@@ -1089,6 +1092,13 @@ impl GatewayTelemetry {).with_unit("{response}").build(),+ routing_unsupported_model_exclusions: meter+ .u64_counter(ROUTING_UNSUPPORTED_MODEL_EXCLUSIONS_METRIC_NAME)+ .with_description(+ "Count of queue-lane resolutions that passed over a lane because a worker in it cannot serve the requested model.",+ )+ .with_unit("{exclusion}")+ .build(),generation_events: meter.u64_counter(GENERATION_EVENTS_METRIC_NAME).with_description(@@ -1334,6 +1344,10 @@ impl GatewayTelemetry {);}+ fn record_unsupported_model_route_exclusion(&self) {+ self.routing_unsupported_model_exclusions.add(1, &[]);+ }+fn record_provisioning_response(&self, surface: ProvisioningSurface, status: u16) {let status = if (100..=599).contains(&status) {status@@ -1994,6 +2008,21 @@ pub fn record_queue_event(event: QueueEvent, outcome: QueueEventOutcome) {}}+fn record_unsupported_model_route_exclusion_to(target: Option<&GatewayTelemetry>) -> bool {+ let Some(target) = target else {+ return false;+ };+ target.record_unsupported_model_route_exclusion();+ true+}++/// Count one queue-lane resolution that passed over a lane because a worker+/// in it reported that it cannot serve the requested model. The counter+/// carries no attributes, so model ids never become metric dimensions.+pub fn record_unsupported_model_route_exclusion() {+ let _ = record_unsupported_model_route_exclusion_to(telemetry());+}+fn record_provisioning_response_to(target: Option<&GatewayTelemetry>,surface: ProvisioningSurface,@@ -2230,6 +2259,36 @@ mod tests {(telemetry, exporter, provider)}+ #[test]+ fn unsupported_model_route_exclusions_export_one_attribute_free_counter() {+ assert!(!record_unsupported_model_route_exclusion_to(None));++ let (telemetry, exporter, provider) = metric_points();+ assert!(record_unsupported_model_route_exclusion_to(Some(+ &telemetry+ )));+ assert!(record_unsupported_model_route_exclusion_to(Some(+ &telemetry+ )));++ provider.force_flush().expect("force_flush");+ let resource_metrics = exporter.get_finished_metrics().expect("finished metrics");+ let metric = resource_metrics+ .iter()+ .flat_map(|resource| resource.scope_metrics())+ .flat_map(|scope| scope.metrics())+ .find(|metric| metric.name() == ROUTING_UNSUPPORTED_MODEL_EXCLUSIONS_METRIC_NAME)+ .expect("exclusion counter exported");+ assert_eq!(metric.unit(), "{exclusion}");+ let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data() else {+ panic!("exclusion counter must be a u64 sum");+ };+ let points: Vec<_> = sum.data_points().collect();+ assert_eq!(points.len(), 1);+ assert_eq!(points[0].value(), 2);+ assert_eq!(points[0].attributes().count(), 0);+ }+#[test]fn dispatch_contract_exports_one_counter_and_histogram_observation() {let (telemetry, exporter, provider) = metric_points();diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex a89e84d4c..2c443b4bf 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -2797,6 +2797,10 @@ pub struct ModelAckBundleStatus {pub total_eligible_workers: usize,pub acked_workers: Vec<String>,pub pending_workers: Vec<String>,+ /// Workers that report the expected hash but cannot serve this model, for+ /// example during a rollout that adds its adapter to the bundle.+ #[serde(default)]+ pub unsupported_workers: Vec<String>,pub acked: bool,}diff --git a/packages/sie_gateway/src/state/config_bootstrap.rs b/packages/sie_gateway/src/state/config_bootstrap.rsindex 1e3dc6db1..86e907f26 100644--- a/packages/sie_gateway/src/state/config_bootstrap.rs+++ b/packages/sie_gateway/src/state/config_bootstrap.rs@@ -982,6 +982,7 @@ mod tests {"generated_at": "2026-04-17T00:00:00Z","bundle_config_hashes": {"default": "control-plane-hash"},"bundle_pool_config_hashes": {"default": {"default": "control-plane-pool-hash"}},+ "bundle_adapters": {"default": ["sie_server.adapters.sentence_transformer"]},"models": [{"model_id": "test/model",diff --git a/packages/sie_gateway/src/state/worker_registry.rs b/packages/sie_gateway/src/state/worker_registry.rsindex e6f6fe9ea..dba9369f5 100644--- a/packages/sie_gateway/src/state/worker_registry.rs+++ b/packages/sie_gateway/src/state/worker_registry.rs@@ -8,6 +8,7 @@ use tokio::sync::RwLock;use crate::routing::hrw::{RingEntry, RingSnapshot};use crate::state::pool_manager::normalize_pool_name;+use crate::types::worker::MAX_UNSUPPORTED_MODELS;use crate::types::{ClusterStatus, ModelInfo, WorkerHealth, WorkerInfo, WorkerState, WorkerStatusMessage,};@@ -77,6 +78,15 @@ pub struct QueueRoute {pub machine_profile: String,}+/// Result of resolving a queue lane for one model.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct QueueRouteLookup {+ pub route: Option<QueueRoute>,+ /// A lane was passed over because a worker in it that reports the+ /// expected hash cannot serve the model.+ pub excluded_unsupported: bool,+}+/// Pre-computed snapshot of healthy workers, indexed by bundle./// Rebuilt on every worker state change and swapped atomically via Arc.#[derive(Default)]@@ -205,6 +215,8 @@ impl WorkerRegistry {last_heartbeat: Instant::now(),pool_name: String::new(),saturated: false,+ unsupported_models: Arc::from([]),+ unsupported_overflow: false,});let was_healthy = w.healthy();@@ -223,6 +235,23 @@ impl WorkerRegistry {msg.bundle.clone()};w.bundle_config_hash = msg.bundle_config_hash.clone();+ let overflow = msg.unsupported_models.len() > MAX_UNSUPPORTED_MODELS;+ if overflow && !w.unsupported_overflow {+ tracing::warn!(+ worker = %w.name,+ reported = msg.unsupported_models.len(),+ max = MAX_UNSUPPORTED_MODELS,+ "worker reported more unsupported models than the gateway accepts; \+ routing no model to it until it reports fewer"+ );+ }+ w.unsupported_overflow = overflow;+ w.unsupported_models = msg+ .unsupported_models+ .iter()+ .take(MAX_UNSUPPORTED_MODELS)+ .cloned()+ .collect();w.machine_profile = msg.machine_profile.clone();w.pool_name = msg.pool_name.clone();w.models = msg.loaded_models.clone();@@ -342,8 +371,9 @@ impl WorkerRegistry {}/// Dispatch-eligible workers for a `(model, pool, machine_profile, bundle)` —- /// healthy, not saturated, with `model` in `loaded_models`, a matching- /// bundle config hash, and the full queue lane matching. Pool /+ /// healthy, not saturated, with `model` in `loaded_models` and not in+ /// `unsupported_models`, a matching bundle config hash, and the full+ /// queue lane matching. Pool //// machine-profile / bundle matches are case-insensitive to mirror/// [`resolve_queue_route_matching`]. Used by the proxy to build/// per-request HRW snapshots.@@ -404,6 +434,7 @@ impl WorkerRegistry {&& w.machine_profile.eq_ignore_ascii_case(machine_profile)&& bundle_config_hash_matches(&w.bundle_config_hash, bundle_config_hash)&& w.models.iter().any(|m| m.eq_ignore_ascii_case(model))+ && w.supports_model(model)}).cloned().collect()@@ -483,6 +514,7 @@ impl WorkerRegistry {bundle_config_hash,Some(admitted_worker_names),);+ workers.retain(|w| w.supports_model(model));workers.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.url.cmp(&b.url)));let before = workers.len();workers.dedup_by(|a, b| a.name == b.name);@@ -627,7 +659,8 @@ impl WorkerRegistry {gpu: &str,bundle_config_hash: &str,) -> Option<String> {- self.resolve_queue_route_matching(bundle, gpu, None, bundle_config_hash)+ self.resolve_queue_route_matching(bundle, gpu, None, bundle_config_hash, "")+ .route.map(|route| route.pool_name)}@@ -646,6 +679,7 @@ impl WorkerRegistry {}/// Resolve a concrete queue lane, constrained to a specific logical pool.+ #[cfg(test)]pub async fn resolve_queue_route_in_pool(&self,bundle: &str,@@ -653,7 +687,25 @@ impl WorkerRegistry {pool_name: &str,bundle_config_hash: &str,) -> Option<QueueRoute> {- self.resolve_queue_route_matching(bundle, gpu, Some(pool_name), bundle_config_hash)+ self.resolve_queue_route_matching(bundle, gpu, Some(pool_name), bundle_config_hash, "")+ .route+ }++ /// Resolve a concrete queue lane for `model`, constrained to a logical pool.+ ///+ /// Every worker of a lane consumes the lane subject, so a lane is eligible+ /// only when no worker in it that reports the expected hash lists `model`+ /// in `unsupported_models`. Otherwise such a worker would receive the+ /// model's items and NAK them, spending JetStream delivery attempts.+ pub fn resolve_queue_route_for_model(+ &self,+ bundle: &str,+ gpu: &str,+ pool_name: &str,+ bundle_config_hash: &str,+ model: &str,+ ) -> QueueRouteLookup {+ self.resolve_queue_route_matching(bundle, gpu, Some(pool_name), bundle_config_hash, model)}fn resolve_queue_route_matching(@@ -662,7 +714,8 @@ impl WorkerRegistry {gpu: &str,pool_name: Option<&str>,bundle_config_hash: &str,- ) -> Option<QueueRoute> {+ model: &str,+ ) -> QueueRouteLookup {let snap = self.snapshot.load();// `by_bundle` is keyed with `w.bundle.to_lowercase()` in@@ -677,8 +730,12 @@ impl WorkerRegistry {let bundle_lower = bundle.to_lowercase();// Use pre-computed by_bundle index for efficient lock-free lookup- let candidates = snap.by_bundle.get(&bundle_lower)?;+ let Some(candidates) = snap.by_bundle.get(&bundle_lower) else {+ return QueueRouteLookup::default();+ };+ let mut eligible: Vec<&WorkerState> = Vec::new();+ let mut unsupporting: Vec<&WorkerState> = Vec::new();for w in candidates {if w.pool_name.is_empty() {continue;@@ -697,12 +754,27 @@ impl WorkerRegistry {if !bundle_config_hash_matches(&w.bundle_config_hash, bundle_config_hash) {continue;}- return Some(QueueRoute {+ if model.is_empty() || w.supports_model(model) {+ eligible.push(w);+ } else {+ unsupporting.push(w);+ }+ }+ let same_lane = |a: &WorkerState, b: &WorkerState| {+ a.pool_name.eq_ignore_ascii_case(&b.pool_name)+ && a.machine_profile.eq_ignore_ascii_case(&b.machine_profile)+ };+ let route = eligible+ .into_iter()+ .find(|w| !unsupporting.iter().any(|u| same_lane(u, w)))+ .map(|w| QueueRoute {pool_name: normalize_pool_name(&w.pool_name),machine_profile: w.machine_profile.clone(),});+ QueueRouteLookup {+ route,+ excluded_unsupported: !unsupporting.is_empty(),}- None}pub async fn get_models(&self) -> HashMap<String, Vec<String>> {@@ -783,6 +855,8 @@ impl WorkerRegistry {healthy: w.healthy(),bundle: w.bundle.clone(),bundle_config_hash: w.bundle_config_hash.clone(),+ unsupported_models: w.unsupported_models.to_vec(),+ unsupported_models_overflow: w.unsupported_overflow,});if w.healthy() {@@ -877,6 +951,7 @@ mod tests {memory_total_bytes: None,saturated: false,terminated: false,+ unsupported_models: Vec::new(),}}@@ -1132,6 +1207,7 @@ mod tests {memory_total_bytes: Some(8000),saturated: false,terminated: false,+ unsupported_models: Vec::new(),};reg.update_worker("http://w1:8080", msg).await;@@ -1167,6 +1243,7 @@ mod tests {memory_total_bytes: None,saturated: false,terminated: false,+ unsupported_models: Vec::new(),};reg.update_worker("http://w1:8080", msg).await;@@ -1739,6 +1816,7 @@ mod tests {memory_total_bytes: None,saturated,terminated: false,+ unsupported_models: Vec::new(),}}@@ -2024,4 +2102,190 @@ mod tests {reg.mark_unhealthy("http://w:8080").await;assert_eq!(count.load(Ordering::SeqCst), 1);}++ // ── per-model support within one bundle config hash ────────────++ /// Laya and GLiFormer route ids that an earlier default-bundle image+ /// reports as unsupported once the control plane adds their adapters.+ const ADDED_FAMILY_ROUTES: [&str; 5] = [+ "convaiinnovations/laya",+ "convaiinnovations/laya-multilingual",+ "convaiinnovations/laya-typed-decisions",+ "knowledgator/gliformer-base-v1",+ "knowledgator/gliformer-large-v1",+ ];++ async fn lane_worker(+ reg: &WorkerRegistry,+ name: &str,+ machine_profile: &str,+ hash: &str,+ loaded: &[&str],+ unsupported: &[&str],+ ) {+ let mut msg = make_dispatch_msg(true, false, "default", loaded).await;+ msg.name = name.into();+ msg.machine_profile = machine_profile.into();+ msg.bundle_config_hash = hash.into();+ msg.unsupported_models = unsupported.iter().map(|m| (*m).into()).collect();+ reg.update_worker(&format!("http://{name}:8080"), msg).await;+ }++ fn route(reg: &WorkerRegistry, gpu: &str, hash: &str, model: &str) -> QueueRouteLookup {+ reg.resolve_queue_route_for_model("default", gpu, "default", hash, model)+ }++ #[tokio::test]+ async fn test_earlier_image_keeps_other_models_routable_when_the_bundle_gains_adapters() {+ let reg = registry();+ lane_worker(®, "old-0", "l4", "h-083", &[], &ADDED_FAMILY_ROUTES).await;++ for model in ["BAAI/bge-m3", "urchade/gliner_multi-v2.1"] {+ let lookup = route(®, "", "h-083", model);+ assert_eq!(+ lookup.route.map(|r| r.machine_profile).as_deref(),+ Some("l4"),+ "{model} must stay routable on the earlier image"+ );+ assert!(!lookup.excluded_unsupported);+ }+ for model in ADDED_FAMILY_ROUTES {+ let lookup = route(®, "", "h-083", model);+ assert!(+ lookup.route.is_none(),+ "{model} must not reach the earlier image"+ );+ assert!(lookup.excluded_unsupported);+ }+ assert!(route(®, "", "h-083", "Convaiinnovations/LAYA")+ .route+ .is_none());++ // The same worker before this change hashed with its image's adapter+ // list, so it advertised a different hash and served nothing.+ let before = registry();+ lane_worker(&before, "old-0", "l4", "h-082-image-scope", &[], &[]).await;+ assert!(route(&before, "", "h-083", "BAAI/bge-m3").route.is_none());+ }++ #[tokio::test]+ async fn test_mixed_lane_is_not_eligible_for_a_model_one_worker_cannot_serve() {+ let reg = registry();+ lane_worker(®, "old-0", "l4", "h1", &[], &["org/new-family"]).await;+ lane_worker(®, "new-0", "l4", "h1", &[], &[]).await;+ lane_worker(®, "new-1", "a100", "h1", &[], &[]).await;++ let lookup = route(®, "", "h1", "org/new-family");+ assert_eq!(+ lookup.route.map(|r| r.machine_profile).as_deref(),+ Some("a100")+ );+ assert!(lookup.excluded_unsupported);+ assert!(route(®, "l4", "h1", "org/new-family").route.is_none());+ assert!(route(®, "l4", "h1", "org/kept").route.is_some());+ }++ #[tokio::test]+ async fn test_workers_without_the_field_or_the_hash_do_not_block_a_model() {+ let reg = registry();+ // A worker that predates the field serves everything its hash covers.+ lane_worker(®, "older", "l4", "h1", &[], &[]).await;+ // A worker on another hash does not consume this hash's work.+ lane_worker(®, "stale", "l4", "h0", &[], &["org/new-family"]).await;++ let lookup = route(®, "l4", "h1", "org/new-family");+ assert!(lookup.route.is_some());+ assert!(!lookup.excluded_unsupported);+ }++ #[tokio::test]+ async fn test_worker_direct_rings_exclude_workers_that_cannot_serve_the_model() {+ let reg = registry();+ lane_worker(+ ®,+ "old-0",+ "l4",+ "h1",+ &["org/new-family"],+ &["org/new-family"],+ )+ .await;+ lane_worker(®, "new-0", "l4", "h1", &["org/new-family"], &[]).await;++ let direct: Vec<String> = reg+ .dispatch_workers_for("org/new-family", "default", "l4", "default", "h1")+ .into_iter()+ .map(|w| w.name)+ .collect();+ assert_eq!(direct, ["new-0"]);++ let admitted: HashSet<String> = ["old-0".to_string(), "new-0".to_string()].into();+ let lazy = reg.lazy_lane_ring_snapshot_for_admitted(+ "org/new-family",+ "default",+ "l4",+ "default",+ "h1",+ &admitted,+ );+ assert_eq!(lazy.len(), 1);+ let kept = reg.lazy_lane_ring_snapshot_for_admitted(+ "org/kept", "default", "l4", "default", "h1", &admitted,+ );+ assert_eq!(kept.len(), 2);+ }++ #[tokio::test]+ async fn test_oversized_unsupported_list_fails_closed_and_is_capped() {+ let reg = registry();+ let oversized: Vec<String> = (0..=MAX_UNSUPPORTED_MODELS)+ .map(|i| format!("org/model-{i}"))+ .collect();+ let mut msg = make_dispatch_msg(true, false, "default", &["org/kept"]).await;+ msg.name = "flooded".into();+ msg.bundle_config_hash = "h1".into();+ msg.unsupported_models = oversized;+ reg.update_worker("http://flooded:8080", msg).await;++ let workers = reg.workers().await;+ let flooded = &workers["http://flooded:8080"];+ assert!(flooded.unsupported_overflow);+ assert_eq!(flooded.unsupported_models.len(), MAX_UNSUPPORTED_MODELS);+ assert!(!flooded.supports_model("org/kept"));+ assert!(route(®, "", "h1", "org/kept").route.is_none());+ let status = reg.get_cluster_status().await;+ assert!(status.workers[0].unsupported_models_overflow);++ lane_worker(®, "flooded", "l4", "h1", &["org/kept"], &["org/other"]).await;+ let recovered = reg.workers().await;+ let flooded = &recovered["http://flooded:8080"];+ assert!(!flooded.unsupported_overflow);+ assert!(flooded.supports_model("org/kept"));+ }++ #[tokio::test]+ async fn test_cluster_status_reports_unsupported_models() {+ let reg = registry();+ lane_worker(®, "old-0", "l4", "h1", &[], &["org/new-family"]).await;+ lane_worker(®, "new-0", "l4", "h1", &[], &[]).await;++ let status = reg.get_cluster_status().await;+ let by_name: HashMap<_, _> = status+ .workers+ .iter()+ .map(|w| (w.name.as_str(), w.unsupported_models.clone()))+ .collect();+ assert_eq!(by_name["old-0"], ["org/new-family"]);+ assert!(by_name["new-0"].is_empty());+ let json = serde_json::to_value(&status).unwrap();+ let workers = json["workers"].as_array().unwrap();+ assert_eq!(+ workers+ .iter()+ .filter(|w| w.get("unsupported_models").is_some())+ .count(),+ 1,+ "the field is omitted for workers that serve every model"+ );+ }}diff --git a/packages/sie_gateway/src/types/worker.rs b/packages/sie_gateway/src/types/worker.rsindex cb9303e7f..8c3eda4bd 100644--- a/packages/sie_gateway/src/types/worker.rs+++ b/packages/sie_gateway/src/types/worker.rs@@ -1,4 +1,5 @@use serde::{Deserialize, Serialize};+use std::sync::Arc;use std::time::Instant;use utoipa::ToSchema;@@ -44,13 +45,34 @@ pub struct WorkerState {/// worker side (90/70 thresholds); the gateway just consumes the/// bool.pub saturated: bool,+ /// Routable model ids covered by `bundle_config_hash` that this worker+ /// reported it cannot serve. Empty for workers that predate the field.+ /// Shared so snapshot rebuilds do not copy it.+ pub unsupported_models: Arc<[String]>,+ /// The worker reported more than [`MAX_UNSUPPORTED_MODELS`] ids. It is+ /// then treated as unable to serve any model, because a dropped id would+ /// otherwise read as supported.+ pub unsupported_overflow: bool,}+/// Upper bound on the `unsupported_models` one heartbeat may carry.+pub const MAX_UNSUPPORTED_MODELS: usize = 1024;+impl WorkerState {pub fn healthy(&self) -> bool {self.health == WorkerHealth::Healthy}+ /// Whether this worker can serve `model` under its advertised config.+ /// A worker that sends no list serves every model its hash covers.+ pub fn supports_model(&self, model: &str) -> bool {+ !self.unsupported_overflow+ && !self+ .unsupported_models+ .iter()+ .any(|unsupported| unsupported.eq_ignore_ascii_case(model))+ }+/// Eligible for dispatch: healthy, with at least one ready slot, and not saturated./// Saturated workers stay in the registry (so the pool fallback/// still drains to them via the bundle index) but are excluded@@ -95,6 +117,15 @@ pub struct WorkerInfo {pub healthy: bool,pub bundle: String,pub bundle_config_hash: String,+ /// Models covered by `bundle_config_hash` that this worker cannot serve,+ /// for example during a rollout that adds adapters to its bundle. The+ /// gateway does not route these models to it. Omitted when empty.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub unsupported_models: Vec<String>,+ /// The worker reported more unsupported models than the gateway accepts+ /// (1024), so no model is routed to it. Omitted when false.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub unsupported_models_overflow: bool,}#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]@@ -208,6 +239,12 @@ pub struct WorkerStatusMessage {/// unhealthy. Defaults to false for older workers.#[serde(default)]pub terminated: bool,+ /// Routable model ids (`model` or `model:profile`) covered by+ /// `bundle_config_hash` that the worker cannot serve. Absent from+ /// workers that predate the field, which serve every model their hash+ /// covers.+ #[serde(default)]+ pub unsupported_models: Vec<String>,}#[derive(Debug, Clone, Deserialize)]@@ -251,6 +288,8 @@ mod tests {last_heartbeat: Instant::now(),pool_name: String::new(),saturated: false,+ unsupported_models: Arc::from([]),+ unsupported_overflow: false,}}@@ -283,6 +322,85 @@ mod tests {assert!(msg.saturated);}+ #[test]+ fn test_worker_status_message_matches_the_worker_status_wire_fixture() {+ let fixture: serde_json::Value =+ serde_json::from_str(include_str!("../../../wire-fixtures/worker_status.json"))+ .expect("worker_status fixture parses");+ let example = &fixture["example"];+ let msg: WorkerStatusMessage =+ serde_json::from_value(example.clone()).expect("example parses");+ assert_eq!(msg.name, example["name"]);+ assert_eq!(msg.ready, example["ready"]);+ assert_eq!(msg.terminated, example["terminated"]);+ assert_eq!(msg.gpu_count, example["gpu_count"]);+ assert_eq!(+ msg.total_gpu_slots,+ example["total_gpu_slots"].as_i64().map(|v| v as i32)+ );+ assert_eq!(+ msg.ready_gpu_slots,+ example["ready_gpu_slots"].as_i64().map(|v| v as i32)+ );+ assert_eq!(msg.machine_profile, example["machine_profile"]);+ assert_eq!(msg.pool_name, example["pool_name"]);+ assert_eq!(msg.bundle, example["bundle"]);+ assert_eq!(msg.bundle_config_hash, example["bundle_config_hash"]);+ assert_eq!(+ serde_json::json!(msg.loaded_models),+ example["loaded_models"]+ );+ assert_eq!(+ msg.queue_depth,+ example["queue_depth"].as_i64().map(|v| v as i32)+ );+ assert_eq!(msg.pending_cost, example["pending_cost"].as_i64());+ assert_eq!(+ msg.inflight_batches,+ example["inflight_batches"].as_i64().map(|v| v as i32)+ );+ assert_eq!(msg.saturated, example["saturated"]);+ assert_eq!(+ serde_json::json!(msg.unsupported_models),+ example["unsupported_models"]+ );+ let fields: Vec<&str> = fixture["fields"]+ .as_array()+ .expect("fields")+ .iter()+ .map(|field| field.as_str().expect("field name"))+ .collect();+ assert_eq!(+ fields.len(),+ example.as_object().expect("example object").len(),+ "the example must carry every published field"+ );++ let mut older = example.clone();+ for field in fixture["omitted_when_empty"]+ .as_object()+ .expect("omitted")+ .keys()+ {+ older.as_object_mut().unwrap().remove(field);+ }+ let older: WorkerStatusMessage =+ serde_json::from_value(older).expect("older worker parses");+ assert!(older.unsupported_models.is_empty());+ }++ #[test]+ fn test_worker_supports_model_ignores_ascii_case_and_defaults_to_all() {+ let mut w = make_worker(WorkerHealth::Healthy, 0, 0);+ assert!(w.supports_model("org/new"));+ w.unsupported_models = vec!["Org/New".to_string(), "org/model:fast".to_string()].into();+ assert!(!w.supports_model("org/new"));+ assert!(!w.supports_model("org/model:fast"));+ assert!(w.supports_model("org/model"));+ w.unsupported_overflow = true;+ assert!(!w.supports_model("org/model"));+ }+#[test]fn test_worker_status_message_deserialize_terminated_true() {let json = r#"{"ready": false, "terminated": true}"#;diff --git a/packages/sie_server/src/sie_server/api/ws.py b/packages/sie_server/src/sie_server/api/ws.pyindex 64a00f379..68169551d 100644--- a/packages/sie_server/src/sie_server/api/ws.py+++ b/packages/sie_server/src/sie_server/api/ws.py@@ -8,9 +8,9 @@ import loggingimport osimport timeimport weakref-from collections.abc import Mapping+from collections.abc import Collection, Mappingfrom pathlib import Path-from typing import TYPE_CHECKING, Any, Protocol, cast+from typing import TYPE_CHECKING, Any, NamedTuple, Protocol, castimport orjsonimport yaml@@ -298,7 +298,7 @@ def _resolved_profile_for_hash(config: object, profile_name: str, seen: set[str]return resolved-def _is_synthetic_profile_variant(config: ServerModelConfig, configs: dict[str, ServerModelConfig]) -> bool:+def _is_synthetic_profile_variant(config: ServerModelConfig, configs: Mapping[str, ServerModelConfig]) -> bool:source = config.synthetic_profile_variant_sourceif source is None:return False@@ -327,35 +327,27 @@ def _profile_config_for_hash(config: ServerModelConfig, profile_name: str) -> direturn _resolved_profile_for_hash(config, profile_name)-def _compute_bundle_config_hash(registry: ModelRegistry, bundle_id: str) -> str:- """Compute SHA-256 hash of model configs assigned to this worker's bundle.+_ProfileHashes = dict[str, dict[str, object | None]]+_HashEntry = tuple[object, _ProfileHashes]- The hash covers serialized model configs (sie_id + profiles) for models- routable to the given bundle. Bundle metadata is excluded (immutable at- runtime).- Args:- registry: The model registry.- bundle_id: The bundle identifier to scope configs to.+class BundleConfigView(NamedTuple):+ """What a worker advertises for one bundle after a config apply."""- Returns:- Hex-encoded SHA-256 hash string, or empty string if no configs.- """- configs = registry.get_configs_snapshot(bundle_id)- if not configs:- return ""+ bundle_config_hash: str+ unsupported_models: list[str]- # Deterministic serialization matching gateway's compute_bundle_config_hash:- # both sides hash [{"sie_id": name, "profiles": [{name, config}]}]- # where config contains resolved routable fields: adapter_path,- # max_batch_tokens, compute_precision, adapter_options.- bundle_adapters = _bundle_adapter_modules(bundle_id)- items_by_model: dict[str, dict[str, dict[str, object | None]]] = {}++def _registry_hash_entries(+ configs: Mapping[str, ServerModelConfig],+ scope: frozenset[str],+) -> dict[str, _HashEntry]:+ items_by_model: dict[str, _ProfileHashes] = {}revisions_by_model: dict[str, str | None] = {}for config in sorted(configs.values(), key=lambda c: c.sie_id):if _is_synthetic_profile_variant(config, configs):continue- if not _model_has_bundle_adapter(config, bundle_adapters):+ if not _model_has_bundle_adapter(config, scope):continuebase_id = config.sie_id@@ -367,31 +359,144 @@ def _compute_bundle_config_hash(registry: ModelRegistry, bundle_id: str) -> str:profiles_for_model = items_by_model.setdefault(base_id, {})for pname in sorted(profile_name_map):- if not _profile_matches_bundle(config, pname, bundle_adapters):+ if not _profile_matches_bundle(config, pname, scope):continueprofiles_for_model[profile_name_map[pname]] = _profile_config_for_hash(config, pname)- items = []- for model_id in sorted(items_by_model):- profiles = items_by_model[model_id]- if not profiles:- continue- profiles_for_hash = [{"name": pname, "config": profiles[pname]} for pname in sorted(profiles)]- items.append(- {- "sie_id": model_id,- "revision": revisions_by_model[model_id],- "profiles": profiles_for_hash,- }- )+ return {+ model_id: (revisions_by_model[model_id], profiles) for model_id, profiles in items_by_model.items() if profiles+ }++def _received_hash_entry(+ model_id: str,+ raw: Mapping[str, Any],+ scope: frozenset[str],+) -> tuple[_HashEntry | None, list[tuple[str, str | None]]] | None:+ """Project a received raw config the same way as a parsed one.++ Returns the hash entry (``None`` when no profile is in scope) and the+ routable id and adapter module of every profile, or ``None`` when the raw+ config cannot be projected.+ """+ profiles_raw = raw.get("profiles")+ if not isinstance(profiles_raw, Mapping) or not profiles_raw:+ return None+ profiles: _ProfileHashes = {}+ routes: list[tuple[str, str | None]] = []+ try:+ for pname in sorted(str(name) for name in profiles_raw):+ resolved = _resolved_profile_for_hash(raw, pname)+ adapter_path = resolved.get("adapter_path")+ module = _adapter_module(adapter_path) if isinstance(adapter_path, str) else None+ routes.append((model_id if pname == "default" else f"{model_id}:{pname}", module))+ if module is not None and module in scope:+ profiles[pname] = resolved+ except (TypeError, ValueError, AttributeError):+ return None+ entry = (raw.get("hf_revision"), profiles) if profiles else None+ return entry, routes+++def _serialize_hash_entries(entries: Mapping[str, _HashEntry]) -> str:+ # Deterministic serialization matching gateway's compute_bundle_config_hash:+ # both sides hash [{"sie_id": name, "profiles": [{name, config}]}]+ # where config contains resolved routable fields: adapter_path,+ # max_batch_tokens, compute_precision, adapter_options.+ items = [+ {+ "sie_id": model_id,+ "revision": entries[model_id][0],+ "profiles": [+ {"name": pname, "config": entries[model_id][1][pname]} for pname in sorted(entries[model_id][1])+ ],+ }+ for model_id in sorted(entries)+ ]if not items:return ""-serialized = orjson.dumps(items, option=orjson.OPT_SORT_KEYS)return hashlib.sha256(serialized).hexdigest()+def compute_bundle_config_view(+ registry: ModelRegistry,+ bundle_id: str,+ *,+ control_plane_adapters: Collection[str] | None = None,+ rejected_configs: Mapping[str, Mapping[str, Any]] | None = None,+) -> BundleConfigView:+ """Compute the bundle config hash and the unsupported model ids for a bundle.++ The hash is scoped by ``control_plane_adapters``, the adapter list of the+ control-plane bundle definition the configs arrived with, so it identifies+ the config the worker received. Without one, the adapter list in this+ image's bundle file is used. For a model whose latest received entry this+ worker's schema rejected, the received entry is hashed.++ ``unsupported_models`` lists the routable ids (``model`` or+ ``model:profile``) in that scope that this worker cannot serve: the adapter+ module is not in this image's bundle file, or the entry was rejected and the+ registry holds no config with the same hashed fields.++ Raises:+ BundleMetadataUnavailableError: This image's bundle file is missing.+ """+ configs = registry.get_configs_snapshot(bundle_id)+ rejected = rejected_configs or {}+ if not configs and not rejected:+ return BundleConfigView("", [])++ image_adapters = _bundle_adapter_modules(bundle_id)+ scope = frozenset(control_plane_adapters) if control_plane_adapters is not None else image_adapters+ entries = _registry_hash_entries(configs, scope)+ unsupported: set[str] = set()+ replaced: set[str] = set()+ for model_id, raw in rejected.items():+ received = _received_hash_entry(model_id, raw, scope)+ if received is None:+ continue+ received_entry, received_routes = received+ if entries.get(model_id) == received_entry:+ continue+ replaced.add(model_id)+ if received_entry is None:+ entries.pop(model_id, None)+ else:+ entries[model_id] = received_entry+ unsupported.update(route for route, module in received_routes if module is not None and module in scope)++ for name, config in configs.items():+ if _config_base_name(name, config) in replaced:+ continue+ module = _adapter_module(config.resolve_profile("default").adapter_path)+ if module is not None and module in scope and module not in image_adapters:+ unsupported.add(name)++ return BundleConfigView(_serialize_hash_entries(entries), sorted(unsupported))+++def _config_base_name(name: str, config: ServerModelConfig) -> str:+ source = config.synthetic_profile_variant_source+ return source[0] if source is not None else name+++def _compute_bundle_config_hash(registry: ModelRegistry, bundle_id: str) -> str:+ """Compute SHA-256 hash of model configs assigned to this worker's bundle.++ The hash covers serialized model configs (sie_id + profiles) for models+ routable to the given bundle, scoped by this image's bundle file.++ Args:+ registry: The model registry.+ bundle_id: The bundle identifier to scope configs to.++ Returns:+ Hex-encoded SHA-256 hash string, or empty string if no configs.+ """+ return compute_bundle_config_view(registry, bundle_id).bundle_config_hash++# Cache of bundle config hashes. Populated by _compute_bundle_config_hash# and invalidated when the corresponding registry is mutated. The cache is# scoped per registry so test/sidecar registry instances with the same versiondiff --git a/packages/sie_server/src/sie_server/ipc_types.py b/packages/sie_server/src/sie_server/ipc_types.pyindex 0934dd031..35d7be96b 100644--- a/packages/sie_server/src/sie_server/ipc_types.py+++ b/packages/sie_server/src/sie_server/ipc_types.py@@ -181,12 +181,18 @@ class ApplyModelConfigRequest(msgspec.Struct):bundle_config_hash: strmodel_config: strprofiles_added: list[str] = msgspec.field(default_factory=list)+ # Adapter modules of the control-plane bundle definition that+ # ``bundle_config_hash`` was scoped by. ``None`` when the control plane+ # did not send one; the worker then uses its image's bundle file.+ bundle_adapters: list[str] | None = Noneclass ApplyModelConfigResponse(msgspec.Struct):applied: boolbundle_config_hash: strconfig_version: int = 0+ # Routable model ids in the bundle scope this worker cannot serve.+ unsupported_models: list[str] = msgspec.field(default_factory=list)class ReplaceModelConfigEntry(msgspec.Struct):@@ -199,6 +205,7 @@ class ReplaceModelConfigsRequest(msgspec.Struct):epoch: intbundle_config_hash: strmodels: list[ReplaceModelConfigEntry]+ bundle_adapters: list[str] | None = Noneclass ReplaceModelConfigsResponse(msgspec.Struct):@@ -207,6 +214,7 @@ class ReplaceModelConfigsResponse(msgspec.Struct):config_version: int = 0applied_models: list[str] = msgspec.field(default_factory=list)applied_profiles: list[str] = msgspec.field(default_factory=list)+ unsupported_models: list[str] = msgspec.field(default_factory=list)# -----------------------------------------------------------------------------diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.pyindex bf3141c67..5d0963e8f 100644--- a/packages/sie_server/src/sie_server/queue_executor.py+++ b/packages/sie_server/src/sie_server/queue_executor.py@@ -14,7 +14,12 @@ import yamlfrom sie_sdk._msgpack import packb as pack_msgpackfrom sie_server.adapters.errors import InputTooLongError-from sie_server.api.ws import compute_bundle_config_hash_cached+from sie_server.api.ws import (+ BundleConfigView,+ BundleMetadataUnavailableError,+ compute_bundle_config_hash_cached,+ compute_bundle_config_view,+)from sie_server.config.model import ModelConfigfrom sie_server.core.encode_pipeline import EncodePipeline, resolve_encode_output_typesfrom sie_server.core.extract_cost import (@@ -510,6 +515,17 @@ def _wrap_encode_output(output: dict, config: Any) -> dict:return wrapped+def _rejected_entry_mapping(entry: ReplaceModelConfigEntry, model_id: str) -> dict[str, Any] | None:+ """Return a rejected export entry as a mapping for hashing, if it names ``model_id``."""+ try:+ raw = yaml.safe_load(entry.model_config) if entry.model_config.strip() else None+ except yaml.YAMLError:+ return None+ if not isinstance(raw, dict) or raw.get("sie_id", model_id) != model_id:+ return None+ return raw++def _parse_exported_model_config(entry: ReplaceModelConfigEntry) -> ModelConfig:if not entry.model_config.strip():msg = "model_config is required"@@ -571,6 +587,13 @@ class QueueExecutor:# :meth:`invalidate_model_descriptor` when a model is unloaded# or hot-reloaded.self._descriptor_cache: dict[str, ModelDescriptor] = {}+ # Per bundle: the control-plane adapter list the latest config arrived+ # with, and the raw entries of the latest export this worker's schema+ # rejected. Both feed ``bundle_config_view``.+ self._control_plane_adapters: dict[str, frozenset[str]] = {}+ self._rejected_configs: dict[str, dict[str, dict[str, Any]]] = {}+ self._view_state_version = 0+ self._view_cache: dict[str, tuple[tuple[int, int], BundleConfigView]] = {}@propertydef registry(self) -> ModelRegistry:@@ -590,6 +613,36 @@ class QueueExecutor:"""self._descriptor_cache.pop(model_id, None)+ def bundle_config_view(self, bundle_id: str) -> BundleConfigView:+ """Return the advertised hash and unsupported model ids for ``bundle_id``."""+ key = (int(getattr(self._registry, "_config_version", 0)), self._view_state_version)+ cached = self._view_cache.get(bundle_id)+ if cached is not None and cached[0] == key:+ return cached[1]+ try:+ view = compute_bundle_config_view(+ self._registry,+ bundle_id,+ control_plane_adapters=self._control_plane_adapters.get(bundle_id),+ rejected_configs=self._rejected_configs.get(bundle_id),+ )+ except BundleMetadataUnavailableError:+ logger.exception(+ "Unable to load bundle metadata for %s; returning empty bundle_config_hash to avoid widened hash scope",+ bundle_id,+ )+ return BundleConfigView("", [])+ self._view_cache[bundle_id] = (key, view)+ return view++ def _record_control_plane_adapters(self, bundle_id: str, adapters: list[str] | None) -> None:+ if adapters is None:+ return+ scope = frozenset(adapter for adapter in adapters if adapter)+ if self._control_plane_adapters.get(bundle_id) != scope:+ self._control_plane_adapters[bundle_id] = scope+ self._view_state_version += 1+async def apply_model_config(self, req: ApplyModelConfigRequest) -> ApplyModelConfigResponse:"""Validate and add a bundle-scoped config delta to the local registry."""if not req.bundle_id:@@ -598,6 +651,7 @@ class QueueExecutor:if not req.model_config.strip():msg = "model_config is required"raise ValueError(msg)+ self._record_control_plane_adapters(req.bundle_id, req.bundle_adapters)raw = yaml.safe_load(req.model_config)if not isinstance(raw, dict):@@ -612,15 +666,24 @@ class QueueExecutor:updated_model_ids = await self._registry.add_config_async(model_config)for model_id in updated_model_ids:self.invalidate_model_descriptor(model_id)- bundle_hash = compute_bundle_config_hash_cached(self._registry, req.bundle_id)+ if self._rejected_configs.get(req.bundle_id, {}).pop(model_config.sie_id, None) is not None:+ self._view_state_version += 1+ view = self.bundle_config_view(req.bundle_id)return ApplyModelConfigResponse(applied=True,- bundle_config_hash=bundle_hash,+ bundle_config_hash=view.bundle_config_hash,config_version=int(getattr(self._registry, "_config_version", 0)),+ unsupported_models=view.unsupported_models,)def compute_bundle_config_hash(self, bundle_id: str) -> str:- """Return the local registry hash for ``bundle_id``."""+ """Return the registry hash for ``bundle_id``, scoped by this image's bundle file.++ ``Ping`` reports this hash without ``unsupported_models``, and a sidecar+ with no committed state advertises it. A hash that travels without that+ list must imply that this image serves every model it covers, so it is+ never scoped by the control-plane adapter list.+ """if not bundle_id:return ""return compute_bundle_config_hash_cached(self._registry, bundle_id)@@ -632,16 +695,20 @@ class QueueExecutor:that model keeps its current registry entries, if any. An invalid entrywithout an identifiable model, duplicate valid model IDs, and cross-modelpool conflicts reject the whole snapshot before any registry mutation.- The returned hash covers what the registry- then holds; the sidecar advertises it only when it equals the- control-plane hash.+ The returned hash covers the received entries, scoped by the+ control-plane adapter list when the request carries one; a rejected+ model whose retained config differs in hashed fields is reported in+ ``unsupported_models``. The sidecar advertises the hash only when it+ equals the control-plane hash."""if not req.bundle_id:msg = "bundle_id is required"raise ValueError(msg)+ self._record_control_plane_adapters(req.bundle_id, req.bundle_adapters)configs: list[ModelConfig] = []rejected: set[str] = set()+ rejected_configs: dict[str, dict[str, Any]] = {}for entry in req.models:model_id = entry.model_idtry:@@ -661,11 +728,18 @@ class QueueExecutor:exc,)rejected.add(model_id)+ if (raw := _rejected_entry_mapping(entry, model_id)) is not None:+ rejected_configs[model_id] = rawinvalidated = 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)+ accepted_ids = {config.sie_id for config in configs}+ self._rejected_configs[req.bundle_id] = {+ model_id: raw for model_id, raw in rejected_configs.items() if model_id not in accepted_ids+ }+ self._view_state_version += 1+ view = self.bundle_config_view(req.bundle_id)applied_configs = self._registry.get_configs_snapshot(req.bundle_id)applied_models = sorted(applied_configs)applied_profiles = sorted(@@ -676,10 +750,11 @@ class QueueExecutor:)return ReplaceModelConfigsResponse(applied=True,- bundle_config_hash=bundle_hash,+ bundle_config_hash=view.bundle_config_hash,config_version=int(getattr(self._registry, "_config_version", 0)),applied_models=applied_models,applied_profiles=applied_profiles,+ unsupported_models=view.unsupported_models,)async def set_pinned_models(self, req: SetPinnedModelsRequest) -> SetPinnedModelsResponse:diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex 62b35c1c6..5fce75af9 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -17,6 +17,7 @@ import msgpackimport msgspecimport numpy as npimport pytest+import sie_server.api.ws as ws_moduleimport sie_server.ipc_server as ipc_server_moduleimport yamlfrom sie_config.model_registry import ModelRegistry as ConfigModelRegistry@@ -1743,6 +1744,280 @@ profiles:assert not registry.has_model("Qwen/Qwen3.6-27B:rtx-pro-6000")+# -----------------------------------------------------------------------------+# Bundle config view: control-plane hash scope and unsupported models+# -----------------------------------------------------------------------------++_ADAPTERS_ADDED_IN_LATER_IMAGE = frozenset(+ {"sie_server.adapters.laya.adapter", "sie_server.adapters.gliformer.adapter"}+)+++def _default_bundle_export() -> tuple[list[ReplaceModelConfigEntry], list[str], str]:+ """Export the shipped catalog for the default bundle the way the sidecar forwards it."""+ root = _repo_root()+ config_registry = ConfigModelRegistry(root / "packages/sie_server/bundles", root / "packages/sie_server/models")+ entries = [+ ReplaceModelConfigEntry(+ model_id=model_id,+ model_config=yaml.safe_dump(config_registry.get_full_config(model_id), sort_keys=False),+ )+ for model_id in config_registry.list_models()+ if "default" in config_registry.get_model_export_bundles(model_id)+ and config_registry.get_model_pool_name(model_id) == "default"+ ]+ adapters = config_registry.get_bundle_adapters(["default"])["default"]+ return entries, adapters, config_registry.compute_bundle_config_hash_for_pool("default", "default")+++def _route_ids_using(entries: list[ReplaceModelConfigEntry], modules: frozenset[str]) -> list[str]:+ routes = []+ for entry in entries:+ for profile_name, profile in yaml.safe_load(entry.model_config)["profiles"].items():+ adapter_path = profile.get("adapter_path") or ""+ if adapter_path.split(":", maxsplit=1)[0] in modules:+ routes.append(entry.model_id if profile_name == "default" else f"{entry.model_id}:{profile_name}")+ return sorted(routes)+++def _earlier_image(monkeypatch: pytest.MonkeyPatch, adapters: list[str]) -> None:+ earlier = frozenset(adapters) - _ADAPTERS_ADDED_IN_LATER_IMAGE+ monkeypatch.setattr(ws_module, "_bundle_adapter_modules", lambda bundle_id: earlier)+++def _sentence_transformer_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}"""+++class TestBundleConfigView:+ @pytest.mark.asyncio+ async def test_earlier_image_keeps_the_control_plane_hash_when_the_bundle_gains_adapters(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ entries, adapters, control_plane_hash = _default_bundle_export()+ added_routes = _route_ids_using(entries, _ADAPTERS_ADDED_IN_LATER_IMAGE)+ assert frozenset(adapters) >= _ADAPTERS_ADDED_IN_LATER_IMAGE+ assert added_routes+ _earlier_image(monkeypatch, adapters)++ def request(bundle_adapters: list[str] | None) -> ReplaceModelConfigsRequest:+ return ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=1,+ bundle_config_hash=control_plane_hash,+ models=entries,+ bundle_adapters=bundle_adapters,+ )++ image_scoped = await QueueExecutor(ModelRegistry(models_dir=None)).replace_model_configs(request(None))+ assert image_scoped.bundle_config_hash != control_plane_hash+ assert image_scoped.unsupported_models == []++ resp = await QueueExecutor(ModelRegistry(models_dir=None)).replace_model_configs(request(adapters))+ assert resp.bundle_config_hash == control_plane_hash+ assert resp.unsupported_models == added_routes++ monkeypatch.undo()+ current = await QueueExecutor(ModelRegistry(models_dir=None)).replace_model_configs(request(adapters))+ assert current.bundle_config_hash == control_plane_hash+ assert current.unsupported_models == []++ @pytest.mark.asyncio+ async def test_delta_scope_follows_the_control_plane_and_reports_unsupported_models(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ entries, adapters, control_plane_hash = _default_bundle_export()+ _earlier_image(monkeypatch, adapters)+ executor = QueueExecutor(ModelRegistry(models_dir=None))+ laya = next(entry for entry in entries if entry.model_id == "convaiinnovations/laya")+ others = [entry for entry in entries if entry.model_id != laya.model_id]+ await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=1,+ bundle_config_hash="",+ models=others,+ bundle_adapters=adapters,+ )+ )++ resp = await executor.apply_model_config(+ ApplyModelConfigRequest(+ bundle_id="default",+ model_id=laya.model_id,+ epoch=2,+ bundle_config_hash=control_plane_hash,+ model_config=laya.model_config,+ bundle_adapters=adapters,+ )+ )++ assert resp.bundle_config_hash == control_plane_hash+ assert laya.model_id in resp.unsupported_models++ @pytest.mark.asyncio+ async def test_ping_after_a_sidecar_restart_never_reports_the_scoped_hash_without_its_list(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ entries, adapters, control_plane_hash = _default_bundle_export()+ _earlier_image(monkeypatch, adapters)+ registry = ModelRegistry(models_dir=None)+ executor = QueueExecutor(registry)+ applied = await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="default",+ epoch=1,+ bundle_config_hash=control_plane_hash,+ models=entries,+ bundle_adapters=adapters,+ )+ )+ assert applied.bundle_config_hash == control_plane_hash+ assert applied.unsupported_models++ # A restarted sidecar has no committed state and adopts the Ping hash,+ # which carries no unsupported models.+ sock = _short_sock_path()+ srv = IpcServer(sock, executor, worker_id="worker-test", stale_after_ms=10_000, bundle_id="default")+ await srv.start()+ try:+ client = await _Client.connect(sock)+ try:+ ping = await client.rpc("Ping", {"timestamp_ms": 1.0})+ finally:+ await client.close()+ finally:+ await srv.stop(drain_timeout_s=1.0)++ assert ping["ok"] is True+ assert "unsupported_models" not in ping["body"]+ assert ping["body"]["bundle_config_hash"] != control_plane_hash+ assert ping["body"]["bundle_config_hash"] == compute_bundle_config_hash_cached(registry, "default")++ @pytest.mark.asyncio+ async def test_rejected_entries_keep_the_hash_and_are_reported_unless_their_hashed_fields_match(self) -> None:+ 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],+ bundle_adapters=["sie_server.adapters.sentence_transformer"],+ )++ newer_field = " newer_schema_field: 1"+ executor = QueueExecutor(ModelRegistry(models_dir=None))+ await executor.replace_model_configs(+ request(7, [(mid, _sentence_transformer_yaml(mid)) for mid in ("served/same", "served/changed")])+ )++ resp = await executor.replace_model_configs(+ request(+ 8,+ [+ ("served/same", _sentence_transformer_yaml("served/same", profile_extra=newer_field)),+ (+ "served/changed",+ _sentence_transformer_yaml("served/changed", max_batch_tokens=8192, profile_extra=newer_field),+ ),+ ("added/model", _sentence_transformer_yaml("added/model", profile_extra=newer_field)),+ ],+ )+ )++ reference = await QueueExecutor(ModelRegistry(models_dir=None)).replace_model_configs(+ request(+ 8,+ [+ ("served/same", _sentence_transformer_yaml("served/same")),+ ("served/changed", _sentence_transformer_yaml("served/changed", max_batch_tokens=8192)),+ ("added/model", _sentence_transformer_yaml("added/model")),+ ],+ )+ )+ assert reference.bundle_config_hash+ assert resp.bundle_config_hash == reference.bundle_config_hash+ assert resp.unsupported_models == ["added/model", "served/changed"]+ assert reference.unsupported_models == []++ accepted = await executor.apply_model_config(+ ApplyModelConfigRequest(+ bundle_id="default",+ model_id="added/model",+ epoch=9,+ bundle_config_hash="",+ model_config=_sentence_transformer_yaml("added/model"),+ )+ )+ assert accepted.bundle_config_hash == reference.bundle_config_hash+ assert accepted.unsupported_models == ["served/changed"]++ @pytest.mark.asyncio+ async def test_rejected_per_model_options_are_reported_when_hashed_fields_change(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)],+ )++ executor = QueueExecutor(ModelRegistry(models_dir=None))+ served = await executor.replace_model_configs(request(7, _qwen_profile_variant_yaml()))++ schema_only = await executor.replace_model_configs(+ request(8, "unknown_field: 1\n" + _qwen_profile_variant_yaml())+ )+ assert schema_only.unsupported_models == []+ assert schema_only.bundle_config_hash == served.bundle_config_hash++ legacy_lora = await executor.replace_model_configs(request(9, _qwen_invalid_legacy_lora_yaml()))+ assert legacy_lora.unsupported_models+ assert all(model.startswith("Qwen/Qwen3.6-27B") for model in legacy_lora.unsupported_models)+ assert legacy_lora.bundle_config_hash != served.bundle_config_hash++ @pytest.mark.asyncio+ async def test_unsupported_models_roundtrip_over_ipc(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ws_module, "_bundle_adapter_modules", lambda bundle_id: frozenset())+ executor = QueueExecutor(ModelRegistry(models_dir=None))+ sock = _short_sock_path()+ srv = IpcServer(sock, executor, worker_id="worker-test", stale_after_ms=10_000)+ await srv.start()+ try:+ client = await _Client.connect(sock)+ try:+ resp = await client.rpc(+ "ApplyModelConfig",+ {+ "bundle_id": "default",+ "model_id": "new/model",+ "epoch": 3,+ "bundle_config_hash": "",+ "profiles_added": ["default"],+ "model_config": _sentence_transformer_yaml("new/model"),+ "bundle_adapters": ["sie_server.adapters.sentence_transformer"],+ },+ )+ assert resp["ok"] is True+ assert resp["body"]["unsupported_models"] == ["new/model"]+ assert resp["body"]["bundle_config_hash"]+ finally:+ await client.close()+ finally:+ await srv.stop(drain_timeout_s=1.0)++# -----------------------------------------------------------------------------# SetPinnedModels# -----------------------------------------------------------------------------diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.mdindex 9ff7f713a..6b872b8e7 100644--- a/packages/sie_server_sidecar/docs/architecture-guide.md+++ b/packages/sie_server_sidecar/docs/architecture-guide.md@@ -446,8 +446,9 @@ cover the finite domain of every sidecar stream so valid labels do not enter`otel.metric.overflow`.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. It also mirrors the latest `loaded_models` list reported by+emits worker identity, bundle, machine profile, readiness, the current+bundle config hash, and, when non-empty, the `unsupported_models` committed+with that hash. It also mirrors the latest `loaded_models` list reported bythe backend IPC heartbeat so gateway pool/model gauges reflect live residency inNATS health mode.@@ -465,15 +466,23 @@ sie.config.models.{bundle}Each notification is checked for trusted producer, bundle, epoch, and payloadsize. Accepted deltas are forwarded to the colocated backend through-`ApplyModelConfig`. The backend returns the applied bundle config hash. The-sidecar stores that hash in `ConfigApplyState` only when it exactly matches a-non-empty control-plane hash. A mismatch or missing backend proof does not+`ApplyModelConfig`, together with the notification's `bundle_adapters` list for+this bundle when `sie-config` sends one. The backend returns the applied bundle+config hash and `unsupported_models`, the routable ids that hash covers but the+backend cannot serve. The sidecar stores the hash and the list together in+`ConfigApplyState` only when the hash exactly matches a non-empty control-plane+hash. Before anything is committed, the sidecar adopts the backend's IPC `Ping`+hash, which never replaces a committed pair. `Ping` carries no list, so its hash+must imply full support: the Python worker scopes it by its image's bundle file,+and the Candle worker returns a hash it echoed only after applying every entry.+A mismatch or missing backend proof does notadvance the epoch, advertised hash, or loaded-model state, leaving the workerquarantined from hash-bound work until reconciliation succeeds.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 the backend through `ReplaceModelConfigs`.+exports are sent to the backend through `ReplaceModelConfigs`, with the+export's `bundle_adapters` list for this bundle.Export reconciliation skips unchanged periodic exports. Exports older than thelocal epoch are skipped unless the reconciler is handling an epoch-rewind@@ -486,7 +495,12 @@ expected bundle config hash for the resolved pool and bundle. Config mutationtakes an exclusive execution barrier and backend inference takes a sharedbarrier. Immediately before execution the dispatcher requires an exact matchwith the worker's current hash; old hashes are NAKed rather than executed-against newer weights. Successful non-streaming results echo that stable+against newer weights. Work for a model in the current `unsupported_models`+list is NAKed at intake, again immediately before each readiness probe, and at+that barrier, before backend IPC, so the dispatcher never asks the backend to+load or run such a model. The backend's own eager load of pinned models does+not consult the list. These NAKs are counted with reason `model_unsupported`.+Successful non-streaming results echo that stableexecution hash so the gateway can bind response provenance to the exact workerexecution. Empty hashes remain accepted only for legacy, non-attested traffic.diff --git a/packages/sie_server_sidecar/src/backend/adapter_pool.rs b/packages/sie_server_sidecar/src/backend/adapter_pool.rsindex 50fcfc4c9..86c7aeb61 100644--- a/packages/sie_server_sidecar/src/backend/adapter_pool.rs+++ b/packages/sie_server_sidecar/src/backend/adapter_pool.rs@@ -696,6 +696,7 @@ fn merge_apply_model_config_response(resp.bundle_config_hash,);existing.config_version = existing.config_version.max(resp.config_version);+ merge_unsupported_models(&mut existing.unsupported_models, resp.unsupported_models);}fn merge_replace_model_configs_response(@@ -713,6 +714,7 @@ fn merge_replace_model_configs_response(resp.bundle_config_hash,);existing.config_version = existing.config_version.max(resp.config_version);+ merge_unsupported_models(&mut existing.unsupported_models, resp.unsupported_models);let mut existing_models = existing.applied_models.clone();let mut new_models = resp.applied_models;@@ -745,6 +747,13 @@ fn merge_replace_model_configs_response(}}+/// A model is unsupported on the pod when any child cannot serve it.+fn merge_unsupported_models(existing: &mut Vec<String>, next: Vec<String>) {+ existing.extend(next);+ existing.sort();+ existing.dedup();+}+fn merge_bundle_hash(applied: &mut bool, existing_hash: &mut String, next_hash: String) {if existing_hash.is_empty() {*existing_hash = next_hash;@@ -1189,6 +1198,46 @@ mod tests {assert_eq!(placement(&pool, "model-a"), None);}+ #[test]+ fn config_merges_union_unsupported_models_across_children() {+ let mut applied = None;+ for unsupported in [+ vec!["b".to_string(), "a".to_string()],+ vec!["a".to_string()],+ ] {+ merge_apply_model_config_response(+ &mut applied,+ ApplyModelConfigResponse {+ unsupported_models: unsupported,+ applied: true,+ bundle_config_hash: "h1".into(),+ config_version: 1,+ },+ );+ }+ let applied = applied.expect("combined apply");+ assert!(applied.applied);+ assert_eq!(applied.unsupported_models, ["a", "b"]);++ let mut replaced = None;+ for unsupported in [Vec::new(), vec!["c".to_string()]] {+ merge_replace_model_configs_response(+ &mut replaced,+ ReplaceModelConfigsResponse {+ unsupported_models: unsupported,+ applied: true,+ bundle_config_hash: "h1".into(),+ config_version: 1,+ applied_models: vec!["c".into()],+ applied_profiles: vec!["default".into()],+ },+ );+ }+ let replaced = replaced.expect("combined replace");+ assert!(replaced.applied);+ assert_eq!(replaced.unsupported_models, ["c"]);+ }+#[test]fn apply_config_merge_preserves_any_child_rejection() {let mut combined = None;@@ -1196,6 +1245,7 @@ mod tests {merge_apply_model_config_response(&mut combined,ApplyModelConfigResponse {+ unsupported_models: Vec::new(),applied: false,bundle_config_hash: "h1".into(),config_version: 1,@@ -1204,6 +1254,7 @@ mod tests {merge_apply_model_config_response(&mut combined,ApplyModelConfigResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "h1".into(),config_version: 2,@@ -1223,6 +1274,7 @@ mod tests {merge_apply_model_config_response(&mut combined,ApplyModelConfigResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "h1".into(),config_version: 1,@@ -1231,6 +1283,7 @@ mod tests {merge_apply_model_config_response(&mut combined,ApplyModelConfigResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "h2".into(),config_version: 1,@@ -1247,6 +1300,7 @@ mod tests {merge_replace_model_configs_response(&mut combined,ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "h1".into(),config_version: 1,@@ -1257,6 +1311,7 @@ mod tests {merge_replace_model_configs_response(&mut combined,ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "h1".into(),config_version: 1,@@ -1285,6 +1340,7 @@ mod tests {merge_replace_model_configs_response(&mut combined,ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "h1".into(),config_version: 1,diff --git a/packages/sie_server_sidecar/src/config_reconciler.rs b/packages/sie_server_sidecar/src/config_reconciler.rsindex c426b4e9d..635361efe 100644--- a/packages/sie_server_sidecar/src/config_reconciler.rs+++ b/packages/sie_server_sidecar/src/config_reconciler.rs@@ -61,6 +61,10 @@ struct ExportSnapshot {bundle_config_hashes: HashMap<String, String>,#[serde(default)]bundle_pool_config_hashes: HashMap<String, HashMap<String, String>>,+ /// Adapter modules each bundle's hash was scoped by. Absent from older+ /// control planes.+ #[serde(default)]+ bundle_adapters: HashMap<String, Vec<String>>,#[serde(default)]models: Vec<ExportedModel>,}@@ -260,6 +264,7 @@ fn drift_reason(fn compute_export_signature(bundle: &str,bundle_config_hash: Option<&str>,+ bundle_adapters: Option<&[String]>,models: &[ReplaceModelConfigEntry],) -> blake3::Hash {fn update_len_prefixed(hasher: &mut blake3::Hasher, value: &str) {@@ -270,6 +275,18 @@ fn compute_export_signature(let mut hasher = blake3::Hasher::new();update_len_prefixed(&mut hasher, bundle);update_len_prefixed(&mut hasher, bundle_config_hash.unwrap_or_default());+ match bundle_adapters {+ Some(adapters) => {+ hasher.update(&[1]);+ hasher.update(&(adapters.len() as u64).to_le_bytes());+ for adapter in adapters {+ update_len_prefixed(&mut hasher, adapter);+ }+ }+ None => {+ hasher.update(&[0]);+ }+ }let mut entries: Vec<(&str, &str)> = models.iter()@@ -546,6 +563,7 @@ where),None => snapshot.bundle_config_hashes.get(scope.bundle).cloned(),};+ let bundle_adapters = snapshot.bundle_adapters.get(scope.bundle).cloned();for model in snapshot.models {if !model.targets_bundle(scope.bundle) || !model.targets_pool(&normalized_pool) {skipped += 1;@@ -590,6 +608,7 @@ whereSome(compute_export_signature(scope.bundle,control_plane_hash.as_deref(),+ bundle_adapters.as_deref(),&exported_models,))} else {@@ -622,6 +641,7 @@ whereepoch: snapshot.epoch,bundle_config_hash: control_plane_hash.clone().unwrap_or_default(),models: exported_models,+ bundle_adapters,};let resp = match apply(req, snapshot.epoch).await {Ok(Some(resp)) => resp,@@ -694,8 +714,12 @@ whereexport_signature: None,};};- let state_updated =- state.mark_export_reconciled(snapshot.epoch, Some(applied_hash), options.force_epoch);+ let state_updated = state.mark_export_reconciled(+ snapshot.epoch,+ Some(applied_hash),+ resp.unsupported_models.clone(),+ options.force_epoch,+ );if state_updated {// Activate only the catalog belonging to the trusted, committed// worker state. Cardinality overflow remains fail-open for serving.@@ -878,9 +902,86 @@ mod tests {);}+ #[tokio::test]+ async fn export_reconcile_forwards_bundle_adapters_and_commits_unsupported_models() {+ let adapters = vec!["pkg.old".to_string(), "pkg.new".to_string()];+ let snapshot = ExportSnapshot {+ bundle_adapters: HashMap::from([+ ("default".to_string(), adapters.clone()),+ ("vision".to_string(), vec!["pkg.vision".to_string()]),+ ]),+ epoch: 7,+ bundle_config_hashes: HashMap::from([("default".to_string(), "hash-7".to_string())]),+ bundle_pool_config_hashes: HashMap::new(),+ models: vec![+ exported_model("kept/model", &["default"]),+ exported_model("new/model", &["default"]),+ ],+ };+ let state = ConfigApplyState::new("old".into());+ let requests = Arc::new(Mutex::new(Vec::new()));++ let outcome = reconcile_export_snapshot(+ snapshot,+ scope("default", "default"),+ &state,+ &SidecarTelemetry::for_tests(&[]),+ reconcile_options("test"),+ {+ let requests = Arc::clone(&requests);+ move |req, _epoch| {+ let requests = Arc::clone(&requests);+ async move {+ requests.lock().await.push(req);+ Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: vec!["new/model".into()],+ applied: true,+ bundle_config_hash: "hash-7".into(),+ config_version: 7,+ applied_models: vec!["kept/model".into(), "new/model".into()],+ applied_profiles: vec!["default".into()],+ }))+ }+ }+ },+ )+ .await;++ assert!(outcome.state_updated);+ assert_eq!(+ requests.lock().await[0].bundle_adapters.as_deref(),+ Some(adapters.as_slice())+ );+ assert!(state.accepts_work("hash-7", "kept/model"));+ assert!(!state.accepts_work("hash-7", "new/model"));+ }++ #[test]+ fn export_signature_changes_with_the_bundle_adapters() {+ let models = vec![ReplaceModelConfigEntry {+ model_id: "m".into(),+ model_config: "sie_id: m\n".into(),+ }];+ let without = compute_export_signature("default", Some("h"), None, &models);+ let one = compute_export_signature("default", Some("h"), Some(&["a".to_string()]), &models);+ let two = compute_export_signature(+ "default",+ Some("h"),+ Some(&["a".to_string(), "b".to_string()]),+ &models,+ );+ assert_ne!(without, one);+ assert_ne!(one, two);+ assert_eq!(+ one,+ compute_export_signature("default", Some("h"), Some(&["a".to_string()]), &models)+ );+ }+#[tokio::test]async fn export_reconcile_applies_target_bundle_and_updates_epoch_hash() {let snapshot = ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 7,bundle_config_hashes: HashMap::new(),bundle_pool_config_hashes: HashMap::new(),@@ -906,6 +1007,7 @@ mod tests {async move {applied.lock().await.push(req);Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "hash-7".into(),config_version: 7,@@ -951,6 +1053,7 @@ mod tests {#[tokio::test]async fn export_reconcile_filters_pool_and_uses_pool_hash() {let snapshot = ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 13,bundle_config_hashes: HashMap::from([("candle".to_string(),@@ -985,6 +1088,7 @@ mod tests {async move {applied.lock().await.push(req);Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "default-pool-hash".into(),config_version: 13,@@ -1018,6 +1122,7 @@ mod tests {#[tokio::test]async fn export_reconcile_partial_failure_does_not_advance_state() {let snapshot = ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 8,bundle_config_hashes: HashMap::new(),bundle_pool_config_hashes: HashMap::new(),@@ -1040,6 +1145,7 @@ mod tests {Err(IpcError::Server("apply failed".into()))} else {Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "hash-8".into(),config_version: 8,@@ -1068,6 +1174,7 @@ mod tests {#[tokio::test]async fn export_reconcile_rejected_replace_does_not_change_telemetry_catalog() {let snapshot = ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 8,bundle_config_hashes: HashMap::new(),bundle_pool_config_hashes: HashMap::new(),@@ -1084,6 +1191,7 @@ mod tests {reconcile_options("test"),|_req, _epoch| async move {Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: false,bundle_config_hash: "hash-8".into(),config_version: 8,@@ -1103,6 +1211,7 @@ mod tests {#[tokio::test]async fn export_reconcile_forced_epoch_rewind_only_after_success() {let snapshot = ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 3,bundle_config_hashes: HashMap::new(),bundle_pool_config_hashes: HashMap::new(),@@ -1123,6 +1232,7 @@ mod tests {},|_req, _epoch| async move {Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "hash-3".into(),config_version: 3,@@ -1146,6 +1256,7 @@ mod tests {#[tokio::test]async fn export_reconcile_rejects_control_plane_worker_hash_mismatch() {let snapshot = ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 11,bundle_config_hashes: HashMap::from([("default".to_string(),@@ -1165,6 +1276,7 @@ mod tests {reconcile_options("test"),|_req, _epoch| async move {Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "python-hash".into(),config_version: 11,@@ -1186,6 +1298,7 @@ mod tests {#[tokio::test]async fn export_reconcile_replaces_with_empty_bundle_snapshot() {let snapshot = ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 12,bundle_config_hashes: HashMap::from([("default".to_string(), String::new())]),bundle_pool_config_hashes: HashMap::new(),@@ -1208,6 +1321,7 @@ mod tests {async move {replace_calls.lock().await.push(req);Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: String::new(),config_version: 12,@@ -1241,6 +1355,7 @@ mod tests {let initial = reconcile_export_snapshot(ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 0,bundle_config_hashes: HashMap::from([("default".to_string(),@@ -1260,6 +1375,7 @@ mod tests {async move {replace_calls.lock().await.push(req);Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "control-hash".into(),config_version: 1,@@ -1275,6 +1391,7 @@ mod tests {let unchanged = reconcile_export_snapshot(ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 0,bundle_config_hashes: HashMap::from([("default".to_string(),@@ -1297,6 +1414,7 @@ mod tests {async move {replace_calls.lock().await.push(req);Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "control-hash".into(),config_version: 2,@@ -1323,6 +1441,7 @@ mod tests {let initial = reconcile_export_snapshot(ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 0,bundle_config_hashes: HashMap::from([("default".to_string(),@@ -1346,6 +1465,7 @@ mod tests {async move {replace_calls.lock().await.push(req);Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "stable-routing-hash".into(),config_version: 1,@@ -1361,6 +1481,7 @@ mod tests {let changed = reconcile_export_snapshot(ExportSnapshot {+ bundle_adapters: HashMap::new(),epoch: 0,bundle_config_hashes: HashMap::from([("default".to_string(),@@ -1392,6 +1513,7 @@ mod tests {.collect();replace_calls.lock().await.push(req);Ok(Some(ReplaceModelConfigsResponse {+ unsupported_models: Vec::new(),applied: true,bundle_config_hash: "stable-routing-hash".into(),config_version: 2,diff --git a/packages/sie_server_sidecar/src/config_subscriber.rs b/packages/sie_server_sidecar/src/config_subscriber.rsindex 72c87a97f..ef2053ad1 100644--- a/packages/sie_server_sidecar/src/config_subscriber.rs+++ b/packages/sie_server_sidecar/src/config_subscriber.rs@@ -20,7 +20,9 @@ use tokio::time::{sleep, Duration};use tracing::{debug, info, warn};use crate::backend::AdapterWorkerPool;-use crate::health_publisher::{SharedBundleConfigHash, SharedLoadedModels};+use crate::health_publisher::{+ SharedBundleConfigHash, SharedLoadedModels, SharedUnsupportedModels,+};use crate::ipc_client::IpcError;use crate::ipc_types::{ApplyModelConfigRequest, ReplaceModelConfigsRequest, ReplaceModelConfigsResponse,@@ -43,6 +45,9 @@ pub const DEFAULT_TRUSTED_PRODUCERS: &[&str] = &["sie-config"];pub struct ConfigApplyState {epoch: AtomicU64,bundle_config_hash: SharedBundleConfigHash,+ /// Routable model ids covered by `bundle_config_hash` that the backend+ /// cannot serve. Committed together with the hash.+ unsupported_models: SharedUnsupportedModels,loaded_models: SharedLoadedModels,/// Config mutation is exclusive while inference takes a shared guard./// This binds each execution to one stable backend registry revision.@@ -54,6 +59,7 @@ impl ConfigApplyState {Self {epoch: AtomicU64::new(0),bundle_config_hash: Arc::new(RwLock::new(initial_bundle_config_hash)),+ unsupported_models: Arc::new(RwLock::new(Vec::new())),loaded_models: Arc::new(RwLock::new(Vec::new())),execution_barrier: AsyncRwLock::new(()),}@@ -71,6 +77,25 @@ impl ConfigApplyState {Arc::clone(&self.loaded_models)}+ pub fn unsupported_models(&self) -> SharedUnsupportedModels {+ Arc::clone(&self.unsupported_models)+ }++ pub fn model_is_unsupported(&self, model_id: &str) -> bool {+ self.unsupported_models+ .read()+ .expect("unsupported models lock poisoned")+ .iter()+ .any(|unsupported| unsupported.eq_ignore_ascii_case(model_id))+ }++ /// Whether this worker may execute `model_id` under `expected_hash`: the+ /// hash is its current one and the model is not among those it reported+ /// it cannot serve.+ pub fn accepts_work(&self, expected_hash: &str, model_id: &str) -> bool {+ self.accepts_bundle_config_hash(expected_hash) && !self.model_is_unsupported(model_id)+ }+pub fn current_bundle_config_hash(&self) -> String {self.bundle_config_hash.read()@@ -111,7 +136,8 @@ impl ConfigApplyState {self.epoch.store(epoch, Ordering::Release);}- pub fn set_bundle_hash(&self, hash: String) {+ #[cfg(test)]+ pub(crate) fn set_bundle_hash(&self, hash: String) {let mut guard = self.bundle_config_hash.write()@@ -119,6 +145,46 @@ impl ConfigApplyState {*guard = hash;}+ /// Adopt the backend's `Ping` hash while no hash has been committed. That+ /// hash is scoped by the backend image and carries no+ /// `unsupported_models`, so it must never replace a committed pair.+ pub fn adopt_backend_hash_if_unset(&self, hash: &str) -> bool {+ if hash.is_empty() {+ return false;+ }+ let mut guard = self+ .bundle_config_hash+ .write()+ .expect("bundle config hash lock poisoned");+ if !guard.is_empty() {+ return false;+ }+ *guard = hash.to_string();+ true+ }++ /// Commit a hash and its unsupported models as one pair. Lock order is+ /// hash, then list, matching the heartbeat encoder, so a heartbeat never+ /// pairs one apply's hash with another apply's list.+ fn set_applied_view(&self, hash: String, unsupported_models: Vec<String>) {+ let mut unsupported: Vec<String> = unsupported_models+ .into_iter()+ .map(|model| model.trim().to_string())+ .filter(|model| !model.is_empty())+ .collect();+ unsupported.sort();+ unsupported.dedup();+ let mut hash_guard = self+ .bundle_config_hash+ .write()+ .expect("bundle config hash lock poisoned");+ *self+ .unsupported_models+ .write()+ .expect("unsupported models lock poisoned") = unsupported;+ *hash_guard = hash;+ }+pub fn set_loaded_models<I>(&self, models: I)whereI: IntoIterator<Item = String>,@@ -153,9 +219,14 @@ impl ConfigApplyState {guard.sort();}- fn mark_applied(&self, epoch: u64, bundle_config_hash: String) {+ fn mark_applied(+ &self,+ epoch: u64,+ bundle_config_hash: String,+ unsupported_models: Vec<String>,+ ) {if epoch == 0 {- self.set_bundle_hash(bundle_config_hash);+ self.set_applied_view(bundle_config_hash, unsupported_models);return;}@@ -166,7 +237,7 @@ impl ConfigApplyState {.compare_exchange(current, epoch, Ordering::AcqRel, Ordering::Acquire){Ok(_) => {- self.set_bundle_hash(bundle_config_hash);+ self.set_applied_view(bundle_config_hash, unsupported_models);return;}Err(observed) => current = observed,@@ -178,6 +249,7 @@ impl ConfigApplyState {&self,epoch: u64,bundle_config_hash: Option<String>,+ unsupported_models: Vec<String>,force_epoch: bool,) -> bool {if force_epoch {@@ -190,7 +262,7 @@ impl ConfigApplyState {self.set_epoch_max(epoch);}if let Some(hash) = bundle_config_hash {- self.set_bundle_hash(hash);+ self.set_applied_view(hash, unsupported_models);}true}@@ -217,6 +289,10 @@ pub struct ConfigNotification {pub affected_bundles: Vec<String>,#[serde(default)]pub pool: Option<String>,+ /// Adapter modules each bundle's hash was scoped by. Absent from older+ /// control planes.+ #[serde(default)]+ pub bundle_adapters: HashMap<String, Vec<String>>,}fn env_bool(name: &str) -> bool {@@ -695,6 +771,10 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotbundle_config_hash: notification_bundle_hash_for_pool(¬ification, runtime.pool.as_str()),profiles_added: notification.profiles_added.clone(),model_config: notification.model_config.clone(),+ bundle_adapters: notification+ .bundle_adapters+ .get(¬ification.bundle_id)+ .cloned(),};let resp = match apply_via_ipc_with_retry(@@ -749,7 +829,7 @@ async fn apply_notification(runtime: &SubscriberRuntime, notification: ConfigNotreturn;};- state.mark_applied(notification.epoch, applied_hash);+ state.mark_applied(notification.epoch, applied_hash, resp.unsupported_models);// Telemetry catalog overflow/mismatch is fail-open for serving and the// facade emits at most one process-local warning before collapsing the// affected pair to `other`. Activate it only after the trusted hash and@@ -779,6 +859,7 @@ mod tests {model_id: &str,) -> ConfigNotification {ConfigNotification {+ bundle_adapters: HashMap::new(),producer_id: producer_id.to_string(),bundle_id: bundle_id.to_string(),epoch: 1,@@ -792,6 +873,80 @@ mod tests {}}+ /// Fake backend that records every request body and answers config+ /// applies with `reply`.+ fn spawn_recording_apply_server(+ listener: UnixListener,+ requests: Arc<Mutex<Vec<serde_json::Value>>>,+ reply: serde_json::Value,+ ) -> JoinHandle<()> {+ tokio::spawn(async move {+ loop {+ let Ok((mut stream, _addr)) = listener.accept().await else {+ break;+ };+ let requests = Arc::clone(&requests);+ let reply = reply.clone();+ tokio::spawn(async move {+ loop {+ let mut len_buf = [0_u8; 4];+ if stream.read_exact(&mut len_buf).await.is_err() {+ break;+ }+ let mut frame = vec![0_u8; u32::from_be_bytes(len_buf) as usize];+ if stream.read_exact(&mut frame).await.is_err() {+ break;+ }+ let raw: serde_json::Value =+ rmp_serde::from_slice(&frame).expect("decode request envelope");+ requests+ .lock()+ .await+ .push(raw.get("body").cloned().unwrap_or_default());+ let response = serde_json::json!({+ "version": crate::ipc_types::IPC_VERSION,+ "request_id": raw.get("request_id").cloned().unwrap_or_default(),+ "ok": true,+ "body": reply,+ });+ let bytes =+ rmp_serde::to_vec_named(&response).expect("encode response envelope");+ stream+ .write_all(&(bytes.len() as u32).to_be_bytes())+ .await+ .expect("write response length");+ stream.write_all(&bytes).await.expect("write response");+ }+ });+ }+ })+ }++ async fn apply_against_fake_backend(+ notification: ConfigNotification,+ reply: serde_json::Value,+ ) -> (Arc<ConfigApplyState>, serde_json::Value) {+ let tmp = tempfile::tempdir().expect("tempdir");+ let socket_path = tmp.path().join("ipc.sock");+ let listener = UnixListener::bind(&socket_path).expect("bind fake ipc socket");+ let requests = Arc::new(Mutex::new(Vec::new()));+ let server = spawn_recording_apply_server(listener, Arc::clone(&requests), reply);+ let state = Arc::new(ConfigApplyState::new(String::new()));+ let runtime = SubscriberRuntime {+ bundle: "default".to_string(),+ pool: "default".to_string(),+ trusted_producers: vec!["sie-config".to_string()],+ ipc: AdapterWorkerPool::new(&[socket_path], 1, 1, 1, Arc::new(RuntimeState::new())),+ state: Arc::clone(&state),+ telemetry: SidecarTelemetry::for_tests(&[]),+ shutdown: Arc::new(Shutdown::new()),+ };+ apply_notification(&runtime, notification).await;+ server.abort();+ let request = requests.lock().await.first().cloned().expect("one apply");+ (state, request)+ }+fn spawn_conditional_apply_server(listener: UnixListener,models: Arc<Mutex<Vec<String>>>,@@ -876,6 +1031,7 @@ mod tests {#[test]fn notification_targets_bundle_requires_payload_bundle_match() {let mut notification = ConfigNotification {+ bundle_adapters: HashMap::new(),producer_id: "sie-config".into(),bundle_id: "default".into(),epoch: 1,@@ -896,6 +1052,7 @@ mod tests {#[test]fn notification_targets_pool_and_selects_pool_hash() {let notification = ConfigNotification {+ bundle_adapters: HashMap::new(),producer_id: "sie-config".into(),bundle_id: "candle".into(),epoch: 1,@@ -967,14 +1124,15 @@ mod tests {#[test]fn apply_state_tracks_epoch_monotonically_and_hash() {let state = ConfigApplyState::new("initial".into());- state.mark_applied(10, "h10".into());- state.mark_applied(7, "h7".into());+ state.mark_applied(10, "h10".into(), Vec::new());+ state.mark_applied(7, "h7".into(), vec!["late/model".into()]);assert_eq!(state.epoch(), 10);assert_eq!(state.bundle_config_hash().read().unwrap().as_str(),"h10","stale apply results must not roll the advertised hash backward");+ assert!(!state.model_is_unsupported("late/model"));}#[test]@@ -987,7 +1145,7 @@ mod tests {#[test]fn epoch_zero_apply_updates_hash_without_advancing_epoch() {let state = ConfigApplyState::new("initial".into());- state.mark_applied(0, "h0".into());+ state.mark_applied(0, "h0".into(), Vec::new());assert_eq!(state.epoch(), 0);assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "h0");}@@ -995,7 +1153,7 @@ mod tests {#[test]fn live_apply_can_clear_bundle_hash() {let state = ConfigApplyState::new("old".into());- state.mark_applied(4, String::new());+ state.mark_applied(4, String::new(), Vec::new());assert_eq!(state.epoch(), 4);assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "");}@@ -1003,7 +1161,7 @@ mod tests {#[test]fn export_reconcile_can_clear_bundle_hash() {let state = ConfigApplyState::new("old".into());- assert!(state.mark_export_reconciled(4, Some(String::new()), false));+ assert!(state.mark_export_reconciled(4, Some(String::new()), Vec::new(), false));assert_eq!(state.epoch(), 4);assert_eq!(state.bundle_config_hash().read().unwrap().as_str(), "");}@@ -1030,12 +1188,79 @@ mod tests {assert!(state.accepts_bundle_config_hash("h0"));assert!(!state.accepts_bundle_config_hash("h1"));- state.mark_applied(1, "h1".into());+ state.mark_applied(1, "h1".into(), Vec::new());assert!(!state.accepts_bundle_config_hash("h0"));assert!(state.accepts_bundle_config_hash("h1"));assert!(!state.accepts_bundle_config_hash("missing"));}+ #[test]+ fn backend_ping_hash_is_adopted_only_while_nothing_is_committed() {+ let state = ConfigApplyState::new(String::new());+ assert!(!state.adopt_backend_hash_if_unset(""));+ assert!(state.adopt_backend_hash_if_unset("image-scoped"));+ assert_eq!(state.current_bundle_config_hash(), "image-scoped");++ state.mark_applied(1, "control-plane".into(), vec!["org/new".into()]);+ assert!(!state.adopt_backend_hash_if_unset("image-scoped"));+ assert_eq!(state.current_bundle_config_hash(), "control-plane");+ assert!(state.model_is_unsupported("org/new"));+ }++ #[test]+ fn applied_view_waits_for_a_heartbeat_that_holds_the_hash() {+ let state = Arc::new(ConfigApplyState::new("h0".into()));+ let hash = state.bundle_config_hash();+ let unsupported = state.unsupported_models();+ let heartbeat = hash.read().unwrap();+ let writer_state = Arc::clone(&state);+ let writer = std::thread::spawn(move || {+ writer_state.mark_applied(1, "h1".into(), vec!["org/new".into()]);+ });++ std::thread::sleep(Duration::from_millis(50));+ assert!(+ unsupported.read().unwrap().is_empty(),+ "the list must not change while a heartbeat holds the hash it pairs with"+ );+ drop(heartbeat);+ writer.join().unwrap();+ assert_eq!(hash.read().unwrap().as_str(), "h1");+ assert_eq!(unsupported.read().unwrap().as_slice(), ["org/new"]);+ }++ #[test]+ fn unsupported_models_commit_with_the_hash_and_gate_work() {+ let state = ConfigApplyState::new("h0".into());+ assert!(state.accepts_work("h0", "org/new"));++ state.mark_applied(+ 1,+ "h1".into(),+ vec![+ " org/new ".into(),+ "org/new".into(),+ String::new(),+ "org/other:fast".into(),+ ],+ );+ assert_eq!(+ state.unsupported_models().read().unwrap().as_slice(),+ ["org/new".to_string(), "org/other:fast".to_string()]+ );+ assert!(!state.accepts_work("h1", "org/new"));+ assert!(!state.accepts_work("h1", "ORG/New"));+ assert!(!state.accepts_work("h1", "org/other:fast"));+ assert!(state.accepts_work("h1", "org/other"));+ assert!(state.accepts_work("", "org/kept"));+ assert!(!state.accepts_work("h0", "org/kept"));++ assert!(!state.mark_export_reconciled(0, Some("h-stale".into()), Vec::new(), false));+ assert!(state.model_is_unsupported("org/new"));+ assert!(state.mark_export_reconciled(2, Some("h2".into()), Vec::new(), false));+ assert!(state.accepts_work("h2", "org/new"));+ }+#[tokio::test]async fn config_write_waits_for_inflight_execution_guard() {let state = Arc::new(ConfigApplyState::new("h0".into()));@@ -1133,6 +1358,66 @@ mod tests {server.abort();}+ #[tokio::test]+ async fn delta_forwards_the_control_plane_adapters_and_commits_unsupported_models() {+ let mut delta = notification("sie-config", "default", None, "org/new-family");+ delta.bundle_adapters = HashMap::from([+ (+ "default".to_string(),+ vec!["pkg.old".to_string(), "pkg.new".to_string()],+ ),+ ("other".to_string(), vec!["pkg.other".to_string()]),+ ]);+ let (state, request) = apply_against_fake_backend(+ delta,+ serde_json::json!({+ "applied": true,+ "bundle_config_hash": "hash-1",+ "config_version": 1_u64,+ "unsupported_models": ["org/new-family"],+ }),+ )+ .await;++ assert_eq!(+ request.get("bundle_adapters"),+ Some(&serde_json::json!(["pkg.old", "pkg.new"]))+ );+ assert_eq!(state.current_bundle_config_hash(), "hash-1");+ assert!(!state.accepts_work("hash-1", "org/new-family"));+ assert!(state.accepts_work("hash-1", "org/kept"));+ }++ #[tokio::test]+ async fn older_control_plane_and_backend_keep_the_previous_contract() {+ let (state, request) = apply_against_fake_backend(+ notification("sie-config", "default", None, "org/model"),+ serde_json::json!({+ "applied": true,+ "bundle_config_hash": "hash-1",+ "config_version": 1_u64,+ }),+ )+ .await;++ assert!(request.get("bundle_adapters").is_none());+ assert_eq!(state.current_bundle_config_hash(), "hash-1");+ assert!(state.unsupported_models().read().unwrap().is_empty());+ assert!(state.accepts_work("hash-1", "org/model"));+ }++ #[test]+ fn notification_without_bundle_adapters_parses() {+ let parsed: ConfigNotification = serde_json::from_value(serde_json::json!({+ "router_id": "sie-config",+ "bundle_id": "default",+ "epoch": 3,+ "bundle_config_hash": "h",+ }))+ .expect("older notification parses");+ assert!(parsed.bundle_adapters.is_empty());+ }+#[tokio::test]async fn apply_via_ipc_does_not_eager_ensure_candle_model_ready() {let tmp = tempfile::tempdir().expect("tempdir");@@ -1215,6 +1500,7 @@ mod tests {bundle_config_hash: "hash".to_string(),profiles_added: vec!["candle".to_string()],model_config: "sie_id: topk-io/Iso-ModernColBERT\n".to_string(),+ bundle_adapters: None,},"topk-io/Iso-ModernColBERT",7,diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex c00a880de..17f5831de 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -717,6 +717,12 @@ impl Dispatcher {Fut: std::future::Future<Output = Result<(), String>>,{let model_id = wi.model_id.clone();+ if self.model_is_unsupported(&model_id) {+ return Err(GenerateDispatchError::new(+ "BUNDLE_CONFIG_MISMATCH",+ "worker configuration cannot serve this model",+ ));+ }match self.backend.ensure_model_ready(&model_id).await {Ok(response) => match response.state {ReadinessState::Ready => {}@@ -756,7 +762,7 @@ impl Dispatcher {let _execution_guard = if let Some(state) = self.config_apply_state.as_ref() {let guard = state.lock_execution().await;- if !state.accepts_bundle_config_hash(&wi.bundle_config_hash) {+ if !state.accepts_work(&wi.bundle_config_hash, &wi.model_id) {return Err(GenerateDispatchError::new("BUNDLE_CONFIG_MISMATCH","worker configuration changed before generation execution",@@ -891,6 +897,12 @@ impl Dispatcher {})}+ fn model_is_unsupported(&self, model_id: &str) -> bool {+ self.config_apply_state+ .as_ref()+ .is_some_and(|state| state.model_is_unsupported(model_id))+ }+fn current_bundle_config_hash(&self) -> Option<String> {self.config_apply_state.as_ref()@@ -1126,6 +1138,8 @@ fn classify_cancellation(.then_some(WorkCancellation::BatchDirect)}+/// First work item this worker must not execute under its current config: an+/// unknown bundle config hash, or a model the worker reported it cannot serve.fn unknown_bundle_config_hash<'a>(items: impl IntoIterator<Item = &'a WorkItem>,state: Option<&ConfigApplyState>,@@ -1134,7 +1148,7 @@ fn unknown_bundle_config_hash<'a>(let mut first_unknown: Option<&'a str> = None;let mut count = 0usize;for wi in items {- if !state.accepts_bundle_config_hash(&wi.bundle_config_hash) {+ if !state.accepts_work(&wi.bundle_config_hash, &wi.model_id) {count += 1;if first_unknown.is_none() {first_unknown = Some(wi.bundle_config_hash.as_str());@@ -1259,6 +1273,22 @@ impl Dispatcher {);wi.model_id = subject_model;}+ if self.model_is_unsupported(&wi.model_id) {+ debug!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %wi.model_id,+ "worker cannot serve this model under its current config — NAKing for redelivery"+ );+ nak_one_with_reason(+ &delivery,+ base_delay_ms,+ &self.runtime_state.telemetry,+ "model_unsupported",+ )+ .await;+ continue;+ }if wi.operation != "generate" {self.hold_progress_lease(&wi, &mut delivery);}@@ -1400,6 +1430,21 @@ impl Dispatcher {"generate delivery received");+ if self.model_is_unsupported(&model_id) {+ info!(+ work_item_id = %wi.work_item_id,+ model = %model_id,+ "worker cannot serve this model under its current config — NAKing before readiness"+ );+ nak_msg_with_reason(+ &msg,+ base_delay_ms,+ &self.runtime_state.telemetry,+ "model_unsupported",+ )+ .await;+ return;+ }let readiness_resp = match self.backend.ensure_model_ready(&model_id).await {Ok(r) => r,Err(e) => {@@ -1794,7 +1839,7 @@ impl Dispatcher {// a queued A request can never execute after the worker advances to B.let _execution_guard = if let Some(state) = self.config_apply_state.as_ref() {let guard = state.lock_execution().await;- if !state.accepts_bundle_config_hash(&wi.bundle_config_hash) {+ if !state.accepts_work(&wi.bundle_config_hash, &model_id) {info!(model = %model_id,expected_hash = %wi.bundle_config_hash,@@ -2019,14 +2064,33 @@ impl Dispatcher {/// `EnsureModelReady` for `items`. A parked group's call is bounded by its/// readiness deadline and progress-ACKs the group while it is pending, so/// a slow call neither outlives the deadline nor lets JetStream redeliver- /// the group. `None` when the group was NAKed instead: the deadline passed- /// first, a progress ACK failed, or shutdown requested redelivery.+ /// the group. `None` when the group was NAKed instead: the worker lists the+ /// model in `unsupported_models` (a config commit can add it after+ /// intake), the deadline passed first, a progress ACK failed, or shutdown+ /// requested redelivery.async fn ensure_model_ready_by(&self,model_id: &str,items: &[(WorkItem, Delivery)],ready_deadline: Option<tokio::time::Instant>,) -> Option<Result<crate::ipc_types::EnsureModelReadyResponse, BackendError>> {+ if self.model_is_unsupported(model_id) {+ info!(+ model = %model_id,+ group_size = items.len(),+ "worker cannot serve this model under its current config — NAKing group before readiness"+ );+ for (_, delivery) in items {+ nak_one_with_reason(+ delivery,+ base_nak_delay_ms(),+ &self.runtime_state.telemetry,+ "model_unsupported",+ )+ .await;+ }+ return None;+ }let readiness = self.backend.ensure_model_ready(model_id);let Some(deadline) = ready_deadline else {return Some(readiness.await);@@ -4671,6 +4735,15 @@ async fn nak_msg(msg: &Message,delay_ms: u64,telemetry: &crate::observability::metrics::SidecarTelemetry,+) {+ nak_msg_with_reason(msg, delay_ms, telemetry, "retry").await;+}++async fn nak_msg_with_reason(+ msg: &Message,+ delay_ms: u64,+ telemetry: &crate::observability::metrics::SidecarTelemetry,+ reason: &str,) {let delay = std::time::Duration::from_millis(delay_ms);let result = msg@@ -4679,7 +4752,7 @@ async fn nak_msg(telemetry.nats_operation("nak",if result.is_ok() { "success" } else { "error" },- "retry",+ reason,1,);match result {@@ -6147,6 +6220,108 @@ mod tests {assert!(backend.encoded_models().is_empty());}+ fn dispatcher_listing_unsupported(+ backend: SharedBackend,+ unsupported: &[&str],+ ) -> (Arc<Dispatcher>, Arc<ConfigApplyState>) {+ let state = Arc::new(ConfigApplyState::new(String::new()));+ assert!(state.mark_export_reconciled(+ 1,+ Some("hash-1".into()),+ unsupported.iter().map(|m| (*m).to_string()).collect(),+ false+ ));+ let runtime_state = Arc::new(RuntimeState::new());+ let dispatcher = Arc::new(Dispatcher::new(+ backend,+ adapter_pool_with_runtime_state(Arc::clone(&runtime_state)),+ Arc::new(crate::payload_store::LocalPayloadStore::new(+ None::<PathBuf>,+ )),+ None,+ "worker-test".into(),+ runtime_state,+ Arc::new(Mutex::new(LatencyTracker::new(200, 10))),+ TokenizerRegistry::empty(),+ None,+ None,+ Some(Arc::clone(&state)),+ None,+ BatchCancelState::default(),+ RequestCancelState::new(Duration::from_secs(60)),+ ));+ (dispatcher, state)+ }++ #[tokio::test]+ async fn readiness_rechecks_a_model_listed_after_intake() {+ let backend = LoadingModelBackend::new("org/new-family");+ let (dispatcher, state) = dispatcher_listing_unsupported(backend.clone(), &[]);+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ let items = local_group("new-req", "org/new-family", 0..2, &tx);++ assert!(state.mark_export_reconciled(+ 2,+ Some("hash-2".into()),+ vec!["org/new-family".into()],+ false+ ));+ let readiness = dispatcher+ .ensure_model_ready_by("org/new-family", &items, None)+ .await;++ assert!(readiness.is_none());+ assert_eq!(backend.probes.load(Ordering::SeqCst), 0);+ assert_eq!(retried_slots(&mut rx), [0, 1]);+ }++ #[tokio::test]+ async fn unsupported_model_group_is_naked_before_readiness_or_backend_ipc() {+ let backend = LoadingModelBackend::new("org/new-family");+ let state = Arc::new(ConfigApplyState::new(String::new()));+ assert!(state.mark_export_reconciled(+ 1,+ Some("hash-1".into()),+ vec!["org/new-family".into()],+ false+ ));+ let runtime_state = Arc::new(RuntimeState::new());+ let dispatcher = Arc::new(Dispatcher::new(+ backend.clone(),+ adapter_pool_with_runtime_state(Arc::clone(&runtime_state)),+ Arc::new(crate::payload_store::LocalPayloadStore::new(+ None::<PathBuf>,+ )),+ None,+ "worker-test".into(),+ runtime_state,+ Arc::new(Mutex::new(LatencyTracker::new(200, 10))),+ TokenizerRegistry::empty(),+ None,+ None,+ Some(state),+ None,+ BatchCancelState::default(),+ RequestCancelState::new(Duration::from_secs(60)),+ ));+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();+ let mut items = local_group("new-req", "org/new-family", 0..2, &tx);+ items.extend(local_group("kept-req", "org/kept", 5..6, &tx));+ for (wi, _) in &mut items {+ wi.bundle_config_hash = "hash-1".into();+ }++ dispatcher.dispatch_decoded(items, 3, Instant::now()).await;+ dispatcher+ .join_parked_groups(crate::nats_consumer::redelivery_envelope() * 2)+ .await;++ let retried = retried_slots(&mut rx);+ assert!(retried.contains(&0) && retried.contains(&1));+ assert_eq!(backend.probes.load(Ordering::SeqCst), 0);+ assert_eq!(backend.encoded_models(), ["org/kept"]);+ }+fn retried_slots(rx: &mut tokio::sync::mpsc::UnboundedReceiver<crate::delivery::LocalDeliveryEvent>,) -> Vec<usize> {@@ -6779,6 +6954,23 @@ mod tests {assert_eq!(unknown, Some(("missing-a", 2)));}+ #[test]+ fn unknown_bundle_config_hash_flags_models_the_worker_cannot_serve() {+ let state = ConfigApplyState::new(String::new());+ assert!(state.mark_export_reconciled(1, Some("hash-1".into()), vec!["B".into()], false));++ let mut served = wi("r1", 0, "A", "encode");+ served.bundle_config_hash = "hash-1".into();+ assert!(unknown_bundle_config_hash([&served], Some(&state)).is_none());++ let mut unsupported = wi("r1", 1, "B", "encode");+ unsupported.bundle_config_hash = "hash-1".into();+ assert_eq!(+ unknown_bundle_config_hash([&served, &unsupported], Some(&state)),+ Some(("hash-1", 1))+ );+ }+#[test]fn reply_subject_is_safe_rules() {assert!(reply_subject_is_safe(""));@@ -6861,7 +7053,7 @@ mod tests {.expect("dispatcher.rs must have a production section");let record = concat!("record_work_item_ages", "(");let barrier = concat!("unknown_bundle_config_hash", "(");- let accepts = concat!("accepts_bundle_config_hash", "(");+ let accepts = concat!("accepts_work", "(");// Pair each barrier with the next recording site and require that the// barrier comes first. Five of the six sites sit behind a barrier; thediff --git a/packages/sie_server_sidecar/src/health_publisher.rs b/packages/sie_server_sidecar/src/health_publisher.rsindex 48f6fbc7a..9ec3d7cb3 100644--- a/packages/sie_server_sidecar/src/health_publisher.rs+++ b/packages/sie_server_sidecar/src/health_publisher.rs@@ -28,6 +28,11 @@//! gate on the local [`Readiness`] state so the heartbeat agrees//! with `/readyz`.//!+//! * `unsupported_models` — routable model ids covered by+//! `bundle_config_hash` that this worker cannot serve (for example a model+//! whose adapter module its image lacks). The gateway does not route those+//! models to this worker. Omitted when empty, which is the steady state.+//!//! `loaded_models` and the GPU memory fields are mostly informational, but//! the gateway also uses `loaded_models` as the per-model dispatch readiness//! signal. Backends that need explicit residency, such as Candle, must only@@ -52,6 +57,7 @@ use crate::shutdown::Shutdown;pub type SharedBundleConfigHash = Arc<RwLock<String>>;pub type SharedLoadedModels = Arc<RwLock<Vec<String>>>;+pub type SharedUnsupportedModels = Arc<RwLock<Vec<String>>>;/// Default subject prefix used by the gateway. Workers always/// publish to `sie.health.<worker_id>` because the gateway's@@ -101,6 +107,9 @@ pub struct HealthPublisherConfig {/// model registry epoch. Updated by the config subscriber after a/// successful backend config apply.pub bundle_config_hash: SharedBundleConfigHash,+ /// Models covered by `bundle_config_hash` that the backend cannot serve.+ /// Committed together with the hash by the config subscriber.+ pub unsupported_models: SharedUnsupportedModels,/// Models the colocated backend reports as loaded. Updated by the IPC/// heartbeat, not by config apply.pub loaded_models: SharedLoadedModels,@@ -147,6 +156,8 @@ struct WorkerStatusPayload<'a> {pending_cost: i64,inflight_batches: i32,saturated: bool,+ #[serde(skip_serializing_if = "<[String]>::is_empty")]+ unsupported_models: &'a [String],}fn encode_payload(@@ -169,6 +180,12 @@ fn encode_payload(Some(guard) => guard.as_slice(),None => &[],};+ // Read under the hash guard taken above: the config subscriber writes the+ // hash and this list under the same order, so the pair is consistent.+ let unsupported_models = config+ .unsupported_models+ .read()+ .expect("unsupported models lock poisoned");let configured_slots = config.gpu_count.max(1);let total_gpu_slots = clamp_i64_to_i32(config@@ -217,6 +234,7 @@ fn encode_payload(pending_cost,inflight_batches,saturated,+ unsupported_models: unsupported_models.as_slice(),};serde_json::to_vec(&payload)}@@ -395,6 +413,7 @@ mod tests {machine_profile: "l4".into(),gpu_count: 1,bundle_config_hash: Arc::new(RwLock::new("hash-abc".into())),+ unsupported_models: Arc::new(RwLock::new(Vec::new())),loaded_models: Arc::new(RwLock::new(Vec::new())),runtime_state: Arc::new(RuntimeState::new()),interval: DEFAULT_PUBLISH_INTERVAL,@@ -434,6 +453,7 @@ mod tests {inflight_batches: 0,saturated: false,loaded_models: &[],+ unsupported_models: &[],};serde_json::to_value(&payload).unwrap()};@@ -479,6 +499,7 @@ mod tests {inflight_batches: 0,saturated: false,loaded_models: &[],+ unsupported_models: &[],};serde_json::to_value(&payload).unwrap()};@@ -500,6 +521,52 @@ mod tests {);}+ #[test]+ fn payload_fields_match_the_worker_status_wire_fixture() {+ let fixture: serde_json::Value =+ serde_json::from_str(include_str!("../../wire-fixtures/worker_status.json"))+ .expect("worker_status fixture parses");+ let fields: std::collections::BTreeSet<String> = fixture["fields"]+ .as_array()+ .expect("fields")+ .iter()+ .map(|field| field.as_str().expect("field name").to_string())+ .collect();+ let omitted_when_empty: std::collections::BTreeSet<String> = fixture["omitted_when_empty"]+ .as_object()+ .expect("omitted_when_empty")+ .keys()+ .cloned()+ .collect();+ let keys = |json: &serde_json::Value| -> std::collections::BTreeSet<String> {+ json.as_object()+ .expect("payload object")+ .keys()+ .cloned()+ .collect()+ };++ let c = cfg();+ let steady: serde_json::Value =+ serde_json::from_slice(&encode_payload(&c, true, false).unwrap()).unwrap();+ assert_eq!(+ keys(&steady),+ fields.difference(&omitted_when_empty).cloned().collect()+ );++ let unsupported: Vec<String> =+ serde_json::from_value(fixture["example"]["unsupported_models"].clone())+ .expect("example unsupported_models");+ *c.unsupported_models.write().unwrap() = unsupported;+ let partial: serde_json::Value =+ serde_json::from_slice(&encode_payload(&c, true, false).unwrap()).unwrap();+ assert_eq!(keys(&partial), fields);+ assert_eq!(+ partial["unsupported_models"],+ fixture["example"]["unsupported_models"]+ );+ }+#[test]fn tombstone_payload_marks_not_ready_and_terminated() {let c = cfg();diff --git a/packages/sie_server_sidecar/src/lib.rs b/packages/sie_server_sidecar/src/lib.rsindex c5725c296..d0bb3910c 100644--- a/packages/sie_server_sidecar/src/lib.rs+++ b/packages/sie_server_sidecar/src/lib.rs@@ -554,6 +554,7 @@ pub async fn run(config: WorkerConfig) -> anyhow::Result<()> {machine_profile: config.machine_profile.clone(),gpu_count: config.gpu_count,bundle_config_hash: config_apply_state.bundle_config_hash(),+ unsupported_models: config_apply_state.unsupported_models(),loaded_models: Arc::clone(&loaded_models),runtime_state: Arc::clone(&runtime_state),interval: Duration::from_millis(config.health_publish_interval_ms),@@ -1392,11 +1393,7 @@ fn spawn_heartbeat(.filter(|resp| resp.ready).collect();if let Some(resp) = (ready_children > 0).then(|| successful_ready.first()).flatten() {- if config_apply_state.current_bundle_config_hash().is_empty()- && !resp.bundle_config_hash.is_empty()- {- config_apply_state.set_bundle_hash(resp.bundle_config_hash.clone());- }+ config_apply_state.adopt_backend_hash_if_unset(&resp.bundle_config_hash);let mut merged_loaded_models = Vec::new();for resp in &successful_ready {merged_loaded_models.extend(resp.loaded_models.iter().cloned());diff --git a/packages/sie_server_sidecar/src/observability/metrics.rs b/packages/sie_server_sidecar/src/observability/metrics.rsindex 91319bc05..61ae7d760 100644--- a/packages/sie_server_sidecar/src/observability/metrics.rs+++ b/packages/sie_server_sidecar/src/observability/metrics.rs@@ -2305,6 +2305,7 @@ fn bounded_nats_reason(reason: &str) -> &'static str {"completed" => "completed","retry" => "retry","pool_not_assigned" => "pool_not_assigned",+ "model_unsupported" => "model_unsupported","first_delivery" => "first_delivery","redelivery" => "redelivery","metadata_unavailable" => "metadata_unavailable",diff --git a/packages/sie_server_sidecar/src/protocol/ipc_types.rs b/packages/sie_server_sidecar/src/protocol/ipc_types.rsindex 27ff86f63..2992653d0 100644--- a/packages/sie_server_sidecar/src/protocol/ipc_types.rs+++ b/packages/sie_server_sidecar/src/protocol/ipc_types.rs@@ -320,6 +320,11 @@ pub struct ApplyModelConfigRequest {#[serde(default)]pub profiles_added: Vec<String>,pub model_config: String,+ /// Adapter modules of the control-plane bundle definition that+ /// `bundle_config_hash` was scoped by. Absent when the control plane did+ /// not send one; the worker then uses its image's bundle file.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub bundle_adapters: Option<Vec<String>>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -328,6 +333,11 @@ pub struct ApplyModelConfigResponse {pub bundle_config_hash: String,#[serde(default)]pub config_version: u64,+ /// Routable model ids in the bundle scope the worker cannot serve.+ /// Absent from workers that predate the field, which serve every model+ /// their hash covers.+ #[serde(default)]+ pub unsupported_models: Vec<String>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -342,6 +352,8 @@ pub struct ReplaceModelConfigsRequest {pub epoch: u64,pub bundle_config_hash: String,pub models: Vec<ReplaceModelConfigEntry>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub bundle_adapters: Option<Vec<String>>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -354,6 +366,8 @@ pub struct ReplaceModelConfigsResponse {pub applied_models: Vec<String>,#[serde(default)]pub applied_profiles: Vec<String>,+ #[serde(default)]+ pub unsupported_models: Vec<String>,}// -----------------------------------------------------------------------------diff --git a/packages/wire-fixtures/README.md b/packages/wire-fixtures/README.mdindex 45873ead7..0038d89bc 100644--- a/packages/wire-fixtures/README.md+++ b/packages/wire-fixtures/README.md@@ -29,6 +29,11 @@ executable.score, extract) and for generation, keyed by status, error code, and whethera usable `Retry-After` is present. It also pins how a `Retry-After` value isparsed (delay seconds or an HTTP date; a past date means retry now).+- `worker_status.json` — the worker heartbeat the sidecar publishes on+ `sie.health.<worker_id>`: the exact `fields` it sends, the+ `omitted_when_empty` fields it leaves out when empty, and a fully populated+ `example`. A reader treats a missing field as its default, which is how an+ older worker's heartbeat without `unsupported_models` stays valid.### Why `model_info.json` has two buckets@@ -62,6 +67,11 @@ fixture set. Current consumers:against — match the fixtures), and`packages/sie_ts_sdk/tests/retryClassification.test.ts` (replays every`retry_classification.json` case through the client with a stubbed `fetch`).+- Worker sidecar — `packages/sie_server_sidecar/src/health_publisher.rs`+ (the published key set equals `fields`, minus `omitted_when_empty` when those+ are empty) and gateway — `packages/sie_gateway/src/types/worker.rs` (the+ `example` and an older heartbeat without the omitted fields both parse) load+ `worker_status.json`.- Downstream gateways assert that the members they inject are exactly`settled_charge_fields`, so a gateway that starts publishing a third fieldcannot reach production before every consumer has declared it.diff --git a/packages/wire-fixtures/worker_status.json b/packages/wire-fixtures/worker_status.jsonnew file mode 100644index 000000000..abf30631e--- /dev/null+++ b/packages/wire-fixtures/worker_status.json@@ -0,0 +1,42 @@+{+ "description": "Worker status heartbeat that the worker sidecar publishes on sie.health.<worker_id> and the gateway reads as WorkerStatusMessage. The sidecar publishes exactly `fields`, leaving out an `omitted_when_empty` field whose value is empty. A reader treats every missing field as its default.",+ "fields": [+ "name",+ "ready",+ "terminated",+ "gpu_count",+ "total_gpu_slots",+ "ready_gpu_slots",+ "machine_profile",+ "pool_name",+ "bundle",+ "bundle_config_hash",+ "loaded_models",+ "queue_depth",+ "pending_cost",+ "inflight_batches",+ "saturated",+ "unsupported_models"+ ],+ "omitted_when_empty": {+ "unsupported_models": "Routable model ids (model or model:profile) covered by bundle_config_hash that this worker cannot serve. Workers that predate the field never send it and serve every model their hash covers, so a missing list means empty."+ },+ "example": {+ "name": "worker-l4-0",+ "ready": true,+ "terminated": false,+ "gpu_count": 1,+ "total_gpu_slots": 1,+ "ready_gpu_slots": 1,+ "machine_profile": "l4",+ "pool_name": "default",+ "bundle": "default",+ "bundle_config_hash": "5f1e0b1a3c6d8e2f4a7b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f",+ "loaded_models": ["BAAI/bge-m3"],+ "queue_depth": 2,+ "pending_cost": 4096,+ "inflight_batches": 1,+ "saturated": false,+ "unsupported_models": ["org/new-family", "org/model:new-profile"]+ }+}diff --git a/telemetry/contract.yaml b/telemetry/contract.yamlindex 853a8d220..9d64df8ae 100644--- a/telemetry/contract.yaml+++ b/telemetry/contract.yaml@@ -913,6 +913,7 @@ enums:- completed- retry- pool_not_assigned+ - model_unsupported- first_delivery- redelivery- metadata_unavailable@@ -1690,6 +1691,14 @@ metrics:attributes: gateway_provisioningprometheus_name: sie_gateway_provisioning_responses_totalexport: [prometheus, otlp]+ - name: sie.gateway.routing.unsupported_model_exclusions+ owner: gateway+ facade_event: gateway.unsupported_model_route_exclusion+ type: counter+ unit: "{exclusion}"+ attributes: none+ prometheus_name: sie_gateway_routing_unsupported_model_exclusions_total+ export: [prometheus, otlp]- name: sie.gateway.generation.eventsowner: gatewayfacade_event: gateway.generation_transport_event