Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(server): add a routing block to the model config (#490)

Krisztian Gajdarc02785e6ed70
diff --git a/packages/sie_config/src/sie_config/model_config.schema.json b/packages/sie_config/src/sie_config/model_config.schema.json
index bb740b991..bde61c193 100644
--- a/packages/sie_config/src/sie_config/model_config.schema.json
+++ b/packages/sie_config/src/sie_config/model_config.schema.json
@@ -493,6 +493,111 @@
"title": "ProfileConfig",
"type": "object"
},
+ "RoutingConfig": {
+ "additionalProperties": false,
+ "description": "How a request for the bare model name chooses between the local and the remote profile.\n\n``remote_only`` is the policy of a ``remote_backed`` model: every request is\nserved by its remote profile. Under ``fallback`` the local profile serves,\nand ``fallback_profile`` serves when local capacity refuses for one of\n``triggers`` before it accepts the work. Under ``threshold`` the remote\nprofile serves until demand stays above ``wake_above`` for ``window_s``,\nand serves again once demand stays below ``sleep_below`` for\n``cooldown_s``. A request that names a profile is never routed.",
+ "properties": {
+ "policy": {
+ "enum": [
+ "remote_only",
+ "fallback",
+ "threshold"
+ ],
+ "title": "Policy",
+ "type": "string"
+ },
+ "fallback_profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Fallback Profile"
+ },
+ "triggers": {
+ "anyOf": [
+ {
+ "items": {
+ "enum": [
+ "provisioning",
+ "model_loading",
+ "saturated",
+ "unhealthy"
+ ],
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Triggers"
+ },
+ "wake_above": {
+ "anyOf": [
+ {
+ "exclusiveMinimum": 0,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Wake Above"
+ },
+ "sleep_below": {
+ "anyOf": [
+ {
+ "exclusiveMinimum": 0,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Sleep Below"
+ },
+ "window_s": {
+ "anyOf": [
+ {
+ "exclusiveMinimum": 0,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Window S"
+ },
+ "cooldown_s": {
+ "anyOf": [
+ {
+ "exclusiveMinimum": 0,
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Cooldown S"
+ }
+ },
+ "required": [
+ "policy"
+ ],
+ "title": "RoutingConfig",
+ "type": "object"
+ },
"ScoreTask": {
"additionalProperties": false,
"properties": {},
@@ -611,6 +716,17 @@
"title": "Remote Backed",
"type": "boolean"
},
+ "routing": {
+ "anyOf": [
+ {
+ "$ref": "#/$defs/RoutingConfig"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
"pool": {
"anyOf": [
{
diff --git a/packages/sie_config/tests/test_model_schema.py b/packages/sie_config/tests/test_model_schema.py
index 1ae440532..2c05d7861 100644
--- a/packages/sie_config/tests/test_model_schema.py
+++ b/packages/sie_config/tests/test_model_schema.py
@@ -85,6 +85,21 @@ def test_unknown_keys_are_reported_per_field() -> None:
]
+def test_a_routing_block_passes_and_its_unknown_keys_are_reported() -> None:
+ routing = {"policy": "fallback", "fallback_profile": "remote", "triggers": ["model_loading", "unhealthy"]}
+
+ assert model_config_schema_errors(_model(routing=routing)) == []
+ assert model_config_schema_errors(_model(routing={**routing, "upstream": "team-sie"})) == [
+ {"loc": ["routing", "upstream"], "message": _UNKNOWN}
+ ]
+ assert model_config_schema_errors(_model(routing={**routing, "triggers": ["sometimes"]})) == [
+ {
+ "loc": ["routing", "triggers", 0],
+ "message": "'sometimes' is not one of ['provisioning', 'model_loading', 'saturated', 'unhealthy']",
+ }
+ ]
+
+
@pytest.mark.parametrize(
("field", "value", "loc", "message"),
[
diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rs
index 1b3a7f18d..9670c1975 100644
--- a/packages/sie_gateway/src/types/model.rs
+++ b/packages/sie_gateway/src/types/model.rs
@@ -845,6 +845,36 @@ pool: customer-a
);
}
+ #[test]
+ fn test_model_config_with_a_routing_block_still_parses() {
+ let yaml = r#"
+sie_id: acme/hybrid
+hf_id: acme/hybrid
+routing:
+ policy: fallback
+ fallback_profile: remote
+ triggers: [model_loading, unhealthy]
+profiles:
+ default:
+ adapter_path: "module:Adapter"
+ max_batch_tokens: 4096
+ remote:
+ adapter_path: "sie_server.adapters.remote.sie:SieUpstreamAdapter"
+ max_batch_tokens: 4096
+ adapter_options:
+ loadtime:
+ upstream: team-sie
+ upstream_model: acme/hybrid
+"#;
+ let from_yaml: ModelConfig = serde_yaml::from_str(yaml).unwrap();
+ let value: serde_json::Value = serde_yaml::from_str(yaml).unwrap();
+ let from_json: ModelConfig = serde_json::from_value(value).unwrap();
+ for config in [from_yaml, from_json] {
+ assert_eq!(config.name, "acme/hybrid");
+ assert_eq!(config.profiles.len(), 2);
+ }
+ }
+
#[test]
fn test_profile_output_caps_are_inheritance_resolved_and_route_scoped() {
let raw: serde_yaml::Value = serde_yaml::from_str(
diff --git a/packages/sie_server/src/sie_server/config/model.py b/packages/sie_server/src/sie_server/config/model.py
index 5031cd0bb..ad8fb676a 100644
--- a/packages/sie_server/src/sie_server/config/model.py
+++ b/packages/sie_server/src/sie_server/config/model.py
@@ -588,6 +588,82 @@ def is_remote_adapter_path(adapter_path: str | None) -> bool:
return bool(adapter_path) and adapter_path.startswith(REMOTE_ADAPTER_MODULE_PREFIX)
+RoutingPolicy = Literal["remote_only", "fallback", "threshold"]
+FallbackTrigger = Literal["provisioning", "model_loading", "saturated", "unhealthy"]
+DEFAULT_FALLBACK_TRIGGERS: tuple[FallbackTrigger, ...] = ("provisioning", "model_loading")
+_THRESHOLD_FIELDS = ("wake_above", "sleep_below", "window_s", "cooldown_s")
+
+
+class RoutingConfig(BaseModel):
+ """How a request for the bare model name chooses between the local and the remote profile.
+
+ ``remote_only`` is the policy of a ``remote_backed`` model: every request is
+ served by its remote profile. Under ``fallback`` the local profile serves,
+ and ``fallback_profile`` serves when local capacity refuses for one of
+ ``triggers`` before it accepts the work. Under ``threshold`` the remote
+ profile serves until demand stays above ``wake_above`` for ``window_s``,
+ and serves again once demand stays below ``sleep_below`` for
+ ``cooldown_s``. A request that names a profile is never routed.
+ """
+
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ policy: RoutingPolicy
+ fallback_profile: str | None = None
+ triggers: tuple[FallbackTrigger, ...] | None = None
+ wake_above: float | None = Field(default=None, gt=0)
+ sleep_below: float | None = Field(default=None, gt=0)
+ window_s: float | None = Field(default=None, gt=0)
+ cooldown_s: float | None = Field(default=None, gt=0)
+
+ @property
+ def effective_triggers(self) -> frozenset[FallbackTrigger]:
+ """The triggers that serve through ``fallback_profile``: the declared ones, or the default."""
+ if self.policy != "fallback":
+ return frozenset()
+ return frozenset(self.triggers if self.triggers is not None else DEFAULT_FALLBACK_TRIGGERS)
+
+ @model_validator(mode="after")
+ def validate_policy_fields(self) -> "RoutingConfig":
+ declared_threshold = [name for name in _THRESHOLD_FIELDS if getattr(self, name) is not None]
+ if self.policy == "remote_only":
+ extra = [
+ name
+ for name, value in (("fallback_profile", self.fallback_profile), ("triggers", self.triggers))
+ if value is not None
+ ] + declared_threshold
+ if extra:
+ msg = f"routing policy 'remote_only' takes no other field; remove: {', '.join(extra)}"
+ raise ValueError(msg)
+ return self
+ if not self.fallback_profile:
+ msg = f"routing policy '{self.policy}' must name the remote profile in 'fallback_profile'"
+ raise ValueError(msg)
+ if self.policy == "fallback":
+ if declared_threshold:
+ msg = f"routing policy 'fallback' does not use: {', '.join(declared_threshold)}"
+ raise ValueError(msg)
+ if self.triggers is not None:
+ if not self.triggers:
+ msg = "routing.triggers must name at least one trigger; omit it for the default"
+ raise ValueError(msg)
+ if len(set(self.triggers)) != len(self.triggers):
+ msg = "routing.triggers must not repeat a trigger"
+ raise ValueError(msg)
+ return self
+ if self.triggers is not None:
+ msg = "routing policy 'threshold' does not use 'triggers'"
+ raise ValueError(msg)
+ missing = [name for name in _THRESHOLD_FIELDS if getattr(self, name) is None]
+ if missing:
+ msg = f"routing policy 'threshold' must set: {', '.join(missing)}"
+ raise ValueError(msg)
+ if self.sleep_below is not None and self.wake_above is not None and self.sleep_below >= self.wake_above:
+ msg = "routing.sleep_below must be lower than routing.wake_above"
+ raise ValueError(msg)
+ return self
+
+
class ResolvedProfile(BaseModel):
model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)
@@ -785,6 +861,7 @@ class ModelConfig(BaseModel):
weights_path: Path | None = None
package_backed: bool = False
remote_backed: bool = False
+ routing: RoutingConfig | None = None
pool: str | None = None
inputs: InputModalities = InputModalities()
tasks: Tasks
@@ -873,6 +950,45 @@ class ModelConfig(BaseModel):
raise ValueError(msg)
return self
+ @model_validator(mode="after")
+ def validate_routing(self) -> "ModelConfig":
+ """A routing policy chooses between a local default profile and one remote profile."""
+ routing = self.routing
+ if routing is None:
+ return self
+ if routing.policy == "remote_only":
+ if not self.remote_backed:
+ msg = (
+ "routing policy 'remote_only' is for a model without local weights; "
+ "set 'remote_backed: true' and remove 'hf_id', 'weights_path' and 'package_backed'"
+ )
+ raise ValueError(msg)
+ return self
+ if self.remote_backed:
+ msg = f"a 'remote_backed' model has no local profile, so it cannot use routing policy '{routing.policy}'"
+ raise ValueError(msg)
+ if "default" not in self.profiles or is_remote_adapter_path(self._declared_adapter_path("default")):
+ msg = f"routing policy '{routing.policy}' needs a local 'default' profile"
+ raise ValueError(msg)
+ fallback = routing.fallback_profile
+ if fallback == "default" or fallback not in self.profiles:
+ msg = (
+ f"routing.fallback_profile '{fallback}' must name a non-default profile. "
+ f"Available: {[name for name in self.profiles if name != 'default']}"
+ )
+ raise ValueError(msg)
+ if not is_remote_adapter_path(self._declared_adapter_path(fallback)):
+ msg = f"routing.fallback_profile '{fallback}' must be a remote profile"
+ raise ValueError(msg)
+ return self
+
+ def _declared_adapter_path(self, name: str) -> str | None:
+ profile = self.profiles[name]
+ if profile.adapter_path is not None or profile.extends is None:
+ return profile.adapter_path
+ parent = self.profiles.get(profile.extends)
+ return parent.adapter_path if parent is not None else None
+
def lora_revisions(self) -> dict[str, str | None]:
"""Every LoRA id any profile declares -> its pinned revision (``None`` = unpinned).
diff --git a/packages/sie_server/src/sie_server/config/routing.py b/packages/sie_server/src/sie_server/config/routing.py
new file mode 100644
index 000000000..dfbbb0218
--- /dev/null
+++ b/packages/sie_server/src/sie_server/config/routing.py
@@ -0,0 +1,47 @@
+"""Configuration-load gates for a model's routing block.
+
+``ModelConfig`` checks the shape of the block. These gates refuse a valid
+block that this server does not serve, at the same points that load a model
+config: the models directory, a config added at runtime, and a config snapshot.
+"""
+
+from __future__ import annotations
+
+from sie_server.config.model import ModelConfig
+
+_HYBRID_POLICIES = frozenset({"fallback", "threshold"})
+_EQUIVALENCE_TASKS = ("encode", "score")
+
+
+def hybrid_equivalence_refusal(config: ModelConfig) -> str | None:
+ """Why ``config`` may not serve a primitive from both its local and its remote profile, or ``None``.
+
+ Under ``fallback`` and ``threshold`` one model name is served by two
+ backends. For ``encode`` a difference between them is permanent, because
+ the vectors are stored; for ``score`` it changes the score scale. Both are
+ refused until the remote profile is shown to be equivalent to the local one.
+ """
+ routing = config.routing
+ if routing is None or routing.policy not in _HYBRID_POLICIES:
+ return None
+ tasks = [name for name in _EQUIVALENCE_TASKS if getattr(config.tasks, name) is not None]
+ if not tasks:
+ return None
+ return (
+ f"Model '{config.sie_id}' would serve {' and '.join(tasks)} from both its local profile and remote "
+ f"profile '{routing.fallback_profile}' under routing policy '{routing.policy}'; that is refused until "
+ "the remote profile is shown to be equivalent to the local one"
+ )
+
+
+def validate_model_routing(config: ModelConfig) -> None:
+ """Refuse a routing block this server cannot honour. Raises ``ValueError``."""
+ routing = config.routing
+ if routing is None:
+ return
+ if routing.policy == "threshold":
+ msg = f"Model '{config.sie_id}': routing policy 'threshold' is not available yet"
+ raise ValueError(msg)
+ refusal = hybrid_equivalence_refusal(config)
+ if refusal is not None:
+ raise ValueError(refusal)
diff --git a/packages/sie_server/src/sie_server/core/loader.py b/packages/sie_server/src/sie_server/core/loader.py
index c42af1e31..1ac2afc32 100644
--- a/packages/sie_server/src/sie_server/core/loader.py
+++ b/packages/sie_server/src/sie_server/core/loader.py
@@ -270,6 +270,7 @@ def _expand_profile_variants(configs: dict[str, ModelConfig]) -> None:
variant_updates: dict[str, Any] = {
"sie_id": variant_id,
"profiles": variant_profiles,
+ "routing": None,
}
loadtime = resolved.loadtime if resolved is not None else profile.adapter_options.loadtime
profile_chat_template_kwargs = (
diff --git a/packages/sie_server/src/sie_server/core/registry.py b/packages/sie_server/src/sie_server/core/registry.py
index 6c4403c56..a4dbfd162 100644
--- a/packages/sie_server/src/sie_server/core/registry.py
+++ b/packages/sie_server/src/sie_server/core/registry.py
@@ -30,6 +30,7 @@ from sie_server.adapters.base import ModelAdapter
from sie_server.config.device_groups import resolve_device_group, validate_tensor_parallel_size
from sie_server.config.engine import EngineConfig
from sie_server.config.model import ModelConfig
+from sie_server.config.routing import validate_model_routing
from sie_server.config.upstreams import validate_profile_upstreams
from sie_server.core.disk_cache import DiskCacheConfig, ModelDiskCacheManager
from sie_server.core.hot_reload import HotReloader
@@ -577,6 +578,7 @@ class ModelRegistry:
for name, config in self._configs.items():
validate_no_legacy_scalar_lora_id(name=name, config=config)
validate_profile_upstreams(config)
+ validate_model_routing(config)
self._config_version += 1
@@ -2375,6 +2377,7 @@ class ModelRegistry:
# Multi-LoRA generation (``loadtime.lora_paths``) is unaffected.
validate_no_legacy_scalar_lora_id(name=config.sie_id, config=config)
validate_profile_upstreams(config)
+ validate_model_routing(config)
def _apply_config_entry(self, config: ModelConfig, model_dir: Path | None = None) -> None:
base_id = (
diff --git a/packages/sie_server/src/sie_server/queue_executor.py b/packages/sie_server/src/sie_server/queue_executor.py
index 31dc03673..13cadf7f1 100644
--- a/packages/sie_server/src/sie_server/queue_executor.py
+++ b/packages/sie_server/src/sie_server/queue_executor.py
@@ -21,6 +21,7 @@ from sie_server.api.ws import (
compute_bundle_config_view,
)
from sie_server.config.model import ModelConfig
+from sie_server.config.routing import validate_model_routing
from sie_server.config.upstreams import validate_profile_upstreams
from sie_server.core.encode_pipeline import EncodePipeline, resolve_encode_output_types
from sie_server.core.extract_cost import (
@@ -765,6 +766,7 @@ class QueueExecutor:
for expanded in expand_profile_variants([model_config]).values():
validate_no_legacy_scalar_lora_id(name=expanded.sie_id, config=expanded)
validate_profile_upstreams(expanded)
+ validate_model_routing(expanded)
configs.append(model_config)
except (TypeError, ValueError, yaml.YAMLError) as exc:
if not model_id:
diff --git a/packages/sie_server/tests/config/test_routing_config.py b/packages/sie_server/tests/config/test_routing_config.py
new file mode 100644
index 000000000..f534bad6c
--- /dev/null
+++ b/packages/sie_server/tests/config/test_routing_config.py
@@ -0,0 +1,313 @@
+"""The routing block of a model config and the gates that refuse it at load."""
+
+from __future__ import annotations
+
+import logging
+import re
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any
+
+import pytest
+import yaml
+from pydantic import ValidationError
+from sie_server.config.model import ModelConfig
+from sie_server.config.routing import hybrid_equivalence_refusal, validate_model_routing
+from sie_server.config.upstreams import Upstream, install_upstreams
+from sie_server.core.loader import expand_profile_variants
+from sie_server.core.registry import ModelRegistry
+from sie_server.ipc_types import ReplaceModelConfigEntry, ReplaceModelConfigsRequest
+from sie_server.queue_executor import QueueExecutor
+
+LOCAL_ADAPTER = "sie_server.adapters.fake.adapter:FakeAdapter"
+REMOTE_ADAPTER = "sie_server.adapters.remote.sie:SieUpstreamAdapter"
+FALLBACK = {"policy": "fallback", "fallback_profile": "remote"}
+THRESHOLD = {
+ "policy": "threshold",
+ "fallback_profile": "remote",
+ "wake_above": 2.0,
+ "sleep_below": 0.5,
+ "window_s": 60,
+ "cooldown_s": 300,
+}
+ENCODE = {"encode": {"dense": {"dim": 384}}}
+EXTRACT: dict[str, Any] = {"extract": {}}
+GENERATE = {"generate": {"context_length": 4096, "max_output_tokens": 256}}
+
+
+def local_profile(**extra: Any) -> dict[str, Any]:
+ return {"adapter_path": LOCAL_ADAPTER, "max_batch_tokens": 8192, **extra}
+
+
+def remote_profile(**extra: Any) -> dict[str, Any]:
+ return {
+ "adapter_path": REMOTE_ADAPTER,
+ "max_batch_tokens": 8192,
+ "adapter_options": {"loadtime": {"upstream": "team-sie", "upstream_model": "acme/upstream-model"}},
+ **extra,
+ }
+
+
+def hybrid(
+ *, sie_id: str = "acme/hybrid", tasks: dict[str, Any] | None = None, routing: Any = FALLBACK, **overrides: Any
+) -> dict[str, Any]:
+ spec: dict[str, Any] = {
+ "sie_id": sie_id,
+ "package_backed": True,
+ "tasks": EXTRACT if tasks is None else tasks,
+ "profiles": {"default": local_profile(), "remote": remote_profile()},
+ "routing": routing,
+ }
+ spec.update(overrides)
+ return spec
+
+
+def remote_backed(*, routing: Any = None) -> dict[str, Any]:
+ spec: dict[str, Any] = {
+ "sie_id": "acme/remote",
+ "remote_backed": True,
+ "tasks": ENCODE,
+ "profiles": {"default": remote_profile()},
+ }
+ if routing is not None:
+ spec["routing"] = routing
+ return spec
+
+
[email protected](autouse=True)
+def _upstreams() -> Iterator[None]:
+ install_upstreams(
+ {
+ "team-sie": Upstream.model_validate(
+ {
+ "kind": "sie",
+ "base_url": "http://127.0.0.1:9",
+ "rate_cap": {"requests_per_minute": 60, "max_concurrency": 4},
+ }
+ )
+ }
+ )
+ yield
+ install_upstreams({})
+
+
+def test_a_fallback_model_routes_to_its_remote_profile_on_the_default_triggers() -> None:
+ config = ModelConfig.model_validate(hybrid())
+
+ assert config.routing is not None
+ assert config.routing.policy == "fallback"
+ assert config.routing.fallback_profile == "remote"
+ assert config.routing.effective_triggers == {"provisioning", "model_loading"}
+
+
+def test_declared_triggers_replace_the_default() -> None:
+ config = ModelConfig.model_validate(hybrid(routing={**FALLBACK, "triggers": ["model_loading", "unhealthy"]}))
+
+ assert config.routing is not None
+ assert config.routing.effective_triggers == {"model_loading", "unhealthy"}
+
+
+def test_a_model_without_a_routing_block_is_served_locally() -> None:
+ config = ModelConfig.model_validate(hybrid(routing=None))
+
+ assert config.routing is None
+ assert hybrid_equivalence_refusal(config) is None
+ validate_model_routing(config)
+
+
+ ("routing", "message"),
+ [
+ ({"policy": "fallback"}, "must name the remote profile in 'fallback_profile'"),
+ ({**FALLBACK, "triggers": []}, "must name at least one trigger"),
+ ({**FALLBACK, "triggers": ["model_loading", "model_loading"]}, "must not repeat a trigger"),
+ ({**FALLBACK, "triggers": ["sometimes"]}, "triggers"),
+ ({**FALLBACK, "wake_above": 2.0}, "'fallback' does not use: wake_above"),
+ ({**FALLBACK, "upstream": "team-sie"}, "Extra inputs are not permitted"),
+ ({"policy": "sometimes", "fallback_profile": "remote"}, "policy"),
+ ({**THRESHOLD, "cooldown_s": None}, "'threshold' must set: cooldown_s"),
+ ({**THRESHOLD, "sleep_below": 2.0}, "sleep_below must be lower than routing.wake_above"),
+ ({**THRESHOLD, "window_s": 0}, "greater than 0"),
+ ({**THRESHOLD, "triggers": ["model_loading"]}, "'threshold' does not use 'triggers'"),
+ ({**FALLBACK, "fallback_profile": "default"}, "must name a non-default profile"),
+ ({**FALLBACK, "fallback_profile": "missing"}, "must name a non-default profile"),
+ ],
+ ids=[
+ "no-fallback-profile",
+ "empty-triggers",
+ "repeated-trigger",
+ "unknown-trigger",
+ "threshold-field-under-fallback",
+ "unknown-field",
+ "unknown-policy",
+ "threshold-field-missing",
+ "sleep-not-below-wake",
+ "non-positive-window",
+ "triggers-under-threshold",
+ "default-as-fallback",
+ "unknown-fallback-profile",
+ ],
+)
+def test_an_invalid_routing_block_is_rejected(routing: dict[str, Any], message: str) -> None:
+ with pytest.raises(ValidationError, match=re.escape(message)):
+ ModelConfig.model_validate(hybrid(routing=routing))
+
+
+def test_the_fallback_profile_must_be_a_remote_profile() -> None:
+ profiles = {"default": local_profile(), "remote": remote_profile(), "fast": {"extends": "default"}}
+
+ with pytest.raises(ValidationError, match=r"routing\.fallback_profile 'fast' must be a remote profile"):
+ ModelConfig.model_validate(hybrid(profiles=profiles, routing={**FALLBACK, "fallback_profile": "fast"}))
+
+
+def test_a_fallback_profile_may_inherit_its_remote_adapter() -> None:
+ profiles = {
+ "default": local_profile(),
+ "remote": remote_profile(),
+ "remote-large": {
+ "extends": "remote",
+ "adapter_options": {"loadtime": {"upstream": "team-sie", "upstream_model": "acme/upstream-large"}},
+ },
+ }
+
+ config = ModelConfig.model_validate(
+ hybrid(profiles=profiles, routing={**FALLBACK, "fallback_profile": "remote-large"})
+ )
+
+ assert config.routing is not None
+ assert config.routing.fallback_profile == "remote-large"
+
+
+def test_a_routed_model_needs_a_local_default_profile() -> None:
+ profiles = {"default": remote_profile(), "remote": remote_profile()}
+
+ with pytest.raises(ValidationError, match="needs a local 'default' profile"):
+ ModelConfig.model_validate(hybrid(profiles=profiles))
+
+
+def test_remote_only_is_the_policy_of_a_remote_backed_model() -> None:
+ config = ModelConfig.model_validate(remote_backed(routing={"policy": "remote_only"}))
+
+ assert config.routing is not None
+ assert config.routing.effective_triggers == frozenset()
+ validate_model_routing(config)
+
+
+def test_remote_only_is_refused_for_a_model_with_local_weights() -> None:
+ with pytest.raises(ValidationError, match="set 'remote_backed: true'"):
+ ModelConfig.model_validate(hybrid(routing={"policy": "remote_only"}))
+
+
+ "routing",
+ [
+ {"policy": "remote_only", "fallback_profile": "default"},
+ {"policy": "remote_only", "triggers": ["model_loading"]},
+ {"policy": "remote_only", "wake_above": 2.0},
+ ],
+ ids=["fallback-profile", "triggers", "threshold-field"],
+)
+def test_remote_only_takes_no_other_field(routing: dict[str, Any]) -> None:
+ with pytest.raises(ValidationError, match="'remote_only' takes no other field"):
+ ModelConfig.model_validate(remote_backed(routing=routing))
+
+
[email protected]("routing", [FALLBACK, THRESHOLD], ids=["fallback", "threshold"])
+def test_a_remote_backed_model_has_no_local_profile_to_route_to(routing: dict[str, Any]) -> None:
+ with pytest.raises(ValidationError, match="has no local profile"):
+ ModelConfig.model_validate(remote_backed(routing=routing))
+
+
+def test_profile_variants_carry_no_routing_block() -> None:
+ expanded = expand_profile_variants([ModelConfig.model_validate(hybrid())])
+
+ assert expanded["acme/hybrid"].routing is not None
+ assert expanded["acme/hybrid:remote"].routing is None
+
+
+ ("tasks", "refused"),
+ [
+ (ENCODE, "encode"),
+ ({"score": {}}, "score"),
+ ({**ENCODE, "score": {}}, "encode and score"),
+ ],
+ ids=["encode", "score", "encode-and-score"],
+)
+def test_hybrid_encode_and_score_are_refused(tasks: dict[str, Any], refused: str) -> None:
+ config = ModelConfig.model_validate(hybrid(tasks=tasks))
+
+ refusal = hybrid_equivalence_refusal(config)
+
+ assert refusal is not None
+ assert f"would serve {refused} from both its local profile and remote profile 'remote'" in refusal
+ with pytest.raises(ValueError, match="shown to be equivalent"):
+ validate_model_routing(config)
+
+
+def test_hybrid_extract_is_allowed() -> None:
+ validate_model_routing(ModelConfig.model_validate(hybrid(tasks=EXTRACT)))
+
+
+def test_hybrid_generation_is_allowed() -> None:
+ profiles = {"default": local_profile(kv_budget_tokens=4096), "remote": remote_profile(kv_budget_tokens=4096)}
+
+ validate_model_routing(ModelConfig.model_validate(hybrid(tasks=GENERATE, profiles=profiles)))
+
+
+def test_a_remote_only_model_serves_from_one_backend() -> None:
+ config = ModelConfig.model_validate(remote_backed(routing={"policy": "remote_only"}))
+
+ assert hybrid_equivalence_refusal(config) is None
+
+
+def test_threshold_is_refused_until_it_is_available() -> None:
+ config = ModelConfig.model_validate(hybrid(routing=THRESHOLD))
+
+ with pytest.raises(ValueError, match="routing policy 'threshold' is not available yet"):
+ validate_model_routing(config)
+
+
+def test_a_refused_model_in_the_models_directory_stops_startup(tmp_path: Path) -> None:
+ (tmp_path / "hybrid.yaml").write_text(yaml.safe_dump(hybrid(tasks=ENCODE)), encoding="utf-8")
+
+ with pytest.raises(ValueError, match="shown to be equivalent"):
+ ModelRegistry(models_dir=tmp_path, enable_hot_reload=False)
+
+
+def test_a_refused_model_is_not_added_at_runtime() -> None:
+ registry = ModelRegistry(models_dir=None)
+
+ with pytest.raises(ValueError, match="routing policy 'threshold' is not available yet"):
+ registry.add_config(ModelConfig.model_validate(hybrid(routing=THRESHOLD)))
+
+ assert not registry.has_model("acme/hybrid")
+ assert not registry.has_model("acme/hybrid:remote")
+
+
+async def test_a_config_snapshot_rejects_only_the_refused_entry(caplog: pytest.LogCaptureFixture) -> None:
+ registry = ModelRegistry(models_dir=None)
+ executor = QueueExecutor(registry)
+ caplog.set_level(logging.WARNING, logger="sie_server.queue_executor")
+
+ response = await executor.replace_model_configs(
+ ReplaceModelConfigsRequest(
+ bundle_id="default",
+ epoch=1,
+ bundle_config_hash="",
+ models=[
+ ReplaceModelConfigEntry(
+ model_id="acme/extract", model_config=yaml.safe_dump(hybrid(sie_id="acme/extract"))
+ ),
+ ReplaceModelConfigEntry(
+ model_id="acme/encode", model_config=yaml.safe_dump(hybrid(sie_id="acme/encode", tasks=ENCODE))
+ ),
+ ],
+ )
+ )
+
+ assert registry.has_model("acme/extract")
+ assert registry.has_model("acme/extract:remote")
+ assert not registry.has_model("acme/encode")
+ assert "acme/encode" not in response.applied_models
+ assert "Model 'acme/encode' would serve encode from both" in caplog.text