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): declare openai upstream endpoints and operator request fields (#499)

Krisztian Gajdar2292823f4139
diff --git a/packages/sie_server/src/sie_server/config/upstreams.py b/packages/sie_server/src/sie_server/config/upstreams.py
index 30eac8a80..19b0c3eba 100644
--- a/packages/sie_server/src/sie_server/config/upstreams.py
+++ b/packages/sie_server/src/sie_server/config/upstreams.py
@@ -6,25 +6,33 @@ the server's startup configuration (``--upstreams-file`` or
credential is the name of an environment variable. The value is read when a
request is sent and is never stored on the parsed configuration.
+An upstream of kind ``openai`` declares the endpoints it offers, and the
+operator may set or strip request fields on every call to it. The fields that
+carry the caller's input or that the server reads the answer by can be neither
+set nor stripped.
+
Validation messages never repeat the offending value, because a rejected URL or
a literal credential is exactly what must not reach a log.
"""
from __future__ import annotations
+import copy
import ipaddress
+import json
+import math
import os
import re
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from enum import StrEnum
from pathlib import Path
from types import MappingProxyType
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any
from urllib.parse import urlsplit
import httpx
import yaml
-from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
+from pydantic import BaseModel, ConfigDict, Field, ValidationError, ValidationInfo, field_validator, model_validator
from yaml.constructor import ConstructorError
from sie_server.config.model import UPSTREAM_NAME_PATTERN, is_remote_adapter_path
@@ -38,6 +46,27 @@ REMOTE_SERVING_ENV = "SIE_REMOTE_SERVING"
_ENV_VAR_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,127}$")
_VISIBLE_ASCII = re.compile(r"^[\x21-\x7e]+$")
_DEFAULT_PORTS = {"http": 80, "https": 443}
+_PARAM_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
+_MAX_PARAMS = 32
+_MAX_PARAM_DEPTH = 8
+_MAX_SET_PARAMS_BYTES = 16 << 10
+
+RESERVED_UPSTREAM_PARAMS = frozenset(
+ {
+ "documents",
+ "encoding_format",
+ "input",
+ "messages",
+ "model",
+ "n",
+ "prompt",
+ "query",
+ "stream",
+ "stream_options",
+ "top_n",
+ }
+)
+"""Request fields an operator can neither set nor strip, because the server sends them itself."""
class UpstreamConfigError(ValueError):
@@ -124,6 +153,77 @@ class UpstreamKind(StrEnum):
SIE = "sie"
+class UpstreamEndpoint(StrEnum):
+ """An OpenAI-compatible endpoint that an upstream of kind ``openai`` offers."""
+
+ COMPLETIONS = "completions"
+ CHAT = "chat"
+ EMBEDDINGS = "embeddings"
+ RERANK = "rerank"
+
+
+ENDPOINT_OUTPUTS: Mapping[UpstreamEndpoint, str] = MappingProxyType(
+ {
+ UpstreamEndpoint.COMPLETIONS: "tokens",
+ UpstreamEndpoint.CHAT: "tokens",
+ UpstreamEndpoint.EMBEDDINGS: "dense",
+ UpstreamEndpoint.RERANK: "score",
+ }
+)
+"""The model output each endpoint produces, named as in ``ModelConfig.outputs``."""
+
+
+def _refuse_repeats(items: Sequence[object], *, field: str) -> None:
+ seen: set[str] = set()
+ for item in items:
+ if isinstance(item, str):
+ if item in seen:
+ raise UpstreamConfigError(f"{field} lists the same entry more than once")
+ seen.add(item)
+
+
+def _check_param_name(name: str, *, field: str, action: str) -> None:
+ if not _PARAM_NAME.fullmatch(name):
+ raise UpstreamConfigError(
+ f"{field} names are letters, digits and underscores, at most 64 characters, and do not start with a digit"
+ )
+ if name in RESERVED_UPSTREAM_PARAMS:
+ raise UpstreamConfigError(f"{field} cannot {action} {name!r}, which the server sends itself")
+
+
+def _json_value_problem(value: object) -> str | None:
+ """Why ``value`` is not a bounded JSON value, or ``None``.
+
+ The walk adds up a lower bound of the JSON size, one byte per value plus
+ one per string character or container entry, and stops at the size limit.
+ That keeps it short even when YAML aliases repeat one subtree many times.
+ """
+ pending: list[tuple[object, int]] = [(value, 0)]
+ size = 0
+ while pending:
+ item, depth = pending.pop()
+ size += 1 + (len(item) if isinstance(item, str | dict | list) else 0)
+ if size > _MAX_SET_PARAMS_BYTES:
+ return f"is larger than {_MAX_SET_PARAMS_BYTES} bytes as JSON"
+ if item is None or isinstance(item, bool | int | str):
+ continue
+ if isinstance(item, float):
+ if not math.isfinite(item):
+ return "holds a number that is not finite"
+ continue
+ if not isinstance(item, dict | list):
+ return "holds a value that is not JSON"
+ if depth >= _MAX_PARAM_DEPTH:
+ return f"nests deeper than {_MAX_PARAM_DEPTH} levels"
+ if isinstance(item, dict):
+ if any(not isinstance(key, str) for key in item):
+ return "holds an object key that is not a string"
+ pending.extend((child, depth + 1) for child in item.values())
+ else:
+ pending.extend((child, depth + 1) for child in item)
+ return None
+
+
class RateCap(BaseModel):
"""Per-replica limits on calls to one upstream."""
@@ -145,12 +245,48 @@ class Upstream(BaseModel):
rate_cap: RateCap
proxy_url: str | None = None
"""The only egress proxy used for this upstream. Ambient proxy variables are ignored."""
+ endpoints: frozenset[UpstreamEndpoint] = frozenset()
+ """For kind ``openai``: the endpoints the upstream offers."""
+ set_params: dict[str, Any] = Field(default_factory=dict, repr=False)
+ """For kind ``openai``: request fields added to every call, in place of any value the server sends."""
+ strip_params: frozenset[str] = frozenset()
+ """For kind ``openai``: request fields removed from every call."""
@field_validator("base_url")
@classmethod
def _base_url(cls, value: str) -> str:
return validate_upstream_url(value)
+ @field_validator("endpoints", "strip_params", mode="before")
+ @classmethod
+ def _no_repeats(cls, value: object, info: ValidationInfo) -> object:
+ if isinstance(value, list | tuple):
+ _refuse_repeats(value, field=str(info.field_name))
+ return value
+
+ @field_validator("set_params")
+ @classmethod
+ def _set_params(cls, value: dict[str, Any]) -> dict[str, Any]:
+ if len(value) > _MAX_PARAMS:
+ raise UpstreamConfigError(f"set_params sets at most {_MAX_PARAMS} fields")
+ for name, item in value.items():
+ _check_param_name(name, field="set_params", action="set")
+ problem = _json_value_problem(item)
+ if problem is not None:
+ raise UpstreamConfigError(f"set_params[{name!r}] {problem}")
+ if len(json.dumps(value, separators=(",", ":"))) > _MAX_SET_PARAMS_BYTES:
+ raise UpstreamConfigError(f"set_params is larger than {_MAX_SET_PARAMS_BYTES} bytes as JSON")
+ return value
+
+ @field_validator("strip_params")
+ @classmethod
+ def _strip_params(cls, value: frozenset[str]) -> frozenset[str]:
+ if len(value) > _MAX_PARAMS:
+ raise UpstreamConfigError(f"strip_params strips at most {_MAX_PARAMS} fields")
+ for name in sorted(value):
+ _check_param_name(name, field="strip_params", action="strip")
+ return value
+
@field_validator("proxy_url")
@classmethod
def _proxy_url(cls, value: str | None) -> str | None:
@@ -173,6 +309,34 @@ class Upstream(BaseModel):
raise UpstreamConfigError("proxy_url requires an https base_url")
return self
+ @model_validator(mode="after")
+ def _openai_fields(self) -> Upstream:
+ if self.kind is UpstreamKind.SIE:
+ declared = [name for name in ("endpoints", "set_params", "strip_params") if getattr(self, name)]
+ if declared:
+ raise UpstreamConfigError(f"kind sie takes no {' or '.join(declared)}")
+ elif not self.endpoints:
+ raise UpstreamConfigError("kind openai must declare the endpoints it offers")
+ both = sorted(self.set_params.keys() & self.strip_params)
+ if both:
+ raise UpstreamConfigError(f"set_params and strip_params both name {', '.join(map(repr, both))}")
+ return self
+
+ @property
+ def outputs(self) -> frozenset[str] | None:
+ """The model outputs a remote profile on this upstream can produce. ``None`` when the kind sets no limit."""
+ if self.kind is UpstreamKind.SIE:
+ return None
+ return frozenset(ENDPOINT_OUTPUTS[endpoint] for endpoint in self.endpoints)
+
+ def apply_params(self, body: Mapping[str, Any]) -> dict[str, Any]:
+ """``body`` as one call to this upstream sends it: operator fields set, then stripped."""
+ sent = dict(body)
+ sent.update(copy.deepcopy(self.set_params))
+ for name in self.strip_params:
+ sent.pop(name, None)
+ return sent
+
def api_key(self) -> str | None:
"""Read the credential now. ``None`` when the upstream declares none.
@@ -276,6 +440,10 @@ def upstream_for_serving(name: str) -> Upstream:
def validate_profile_upstreams(config: ModelConfig) -> None:
"""Reject a model whose remote profile names an upstream this server does not define.
+ A remote profile on an ``openai`` upstream is also rejected when the
+ upstream declares no endpoint for any output of the model. A request for
+ an output the upstream cannot produce is refused when it arrives.
+
With remote serving off, every remote profile is refused at load anyway,
so the names are not checked and a stale model does not stop the server.
"""
@@ -285,7 +453,19 @@ def validate_profile_upstreams(config: ModelConfig) -> None:
resolved = config.resolve_profile(profile_name)
if not is_remote_adapter_path(resolved.adapter_path):
continue
- upstream = resolved.loadtime.get("upstream")
- if upstream not in _INSTALLED.upstreams:
- msg = f"Profile '{profile_name}' of '{config.sie_id}' names an undefined upstream {upstream!r}"
+ name = resolved.loadtime.get("upstream")
+ upstream = _INSTALLED.upstreams.get(name) if isinstance(name, str) else None
+ if upstream is None:
+ msg = f"Profile '{profile_name}' of '{config.sie_id}' names an undefined upstream {name!r}"
+ raise ValueError(msg)
+ produced = upstream.outputs
+ if produced is not None and produced.isdisjoint(config.outputs):
+ usable = sorted(endpoint.value for endpoint, output in ENDPOINT_OUTPUTS.items() if output in config.outputs)
+ remedy = (
+ f"declare {' or '.join(usable)}" if usable else "an upstream of kind openai has no endpoint for them"
+ )
+ msg = (
+ f"Profile '{profile_name}' of '{config.sie_id}' names upstream {name!r}, whose endpoints produce "
+ f"none of the model's outputs ({', '.join(config.outputs)}); {remedy}"
+ )
raise ValueError(msg)
diff --git a/packages/sie_server/tests/config/test_openai_upstream_endpoints.py b/packages/sie_server/tests/config/test_openai_upstream_endpoints.py
new file mode 100644
index 000000000..07560e6fe
--- /dev/null
+++ b/packages/sie_server/tests/config/test_openai_upstream_endpoints.py
@@ -0,0 +1,350 @@
+"""Upstreams of kind openai: the endpoints they offer and the request fields an operator sets or strips."""
+
+from __future__ import annotations
+
+import copy
+import datetime
+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.upstreams import (
+ ENDPOINT_OUTPUTS,
+ RESERVED_UPSTREAM_PARAMS,
+ Upstream,
+ UpstreamConfigError,
+ UpstreamEndpoint,
+ install_upstreams,
+ load_upstreams,
+ validate_profile_upstreams,
+)
+from sie_server.core.registry import ModelRegistry
+from sie_server.ipc_types import ReplaceModelConfigEntry, ReplaceModelConfigsRequest
+from sie_server.queue_executor import QueueExecutor
+
+OPENAI_ADAPTER = "sie_server.adapters.remote.openai:OpenAIUpstreamAdapter"
+SIE_ADAPTER = "sie_server.adapters.remote.sie:SieUpstreamAdapter"
+RATE_CAP = {"requests_per_minute": 60, "max_concurrency": 4}
+CANARY = "canary-7d41c2e9"
+DENSE = {"encode": {"dense": {"dim": 8}}}
+GENERATE = {"generate": {"context_length": 8192, "max_output_tokens": 1024}}
+
+
+def openai_upstream(**fields: Any) -> dict[str, Any]:
+ spec: dict[str, Any] = {
+ "kind": "openai",
+ "base_url": "https://host.example.com/v1",
+ "endpoints": ["chat"],
+ "rate_cap": RATE_CAP,
+ }
+ spec.update(fields)
+ return spec
+
+
+def load_one(tmp_path: Path, spec: dict[str, Any]) -> Upstream:
+ path = tmp_path / "upstreams.yaml"
+ path.write_text(yaml.safe_dump({"upstreams": {"open-host": spec}}), encoding="utf-8")
+ return load_upstreams(path)["open-host"]
+
+
+def install(*endpoints: str) -> None:
+ install_upstreams({"open-host": Upstream.model_validate(openai_upstream(endpoints=list(endpoints)))})
+
+
+def remote_model(tasks: dict[str, Any], sie_id: str = "acme/remote", adapter: str = OPENAI_ADAPTER) -> dict[str, Any]:
+ profile: dict[str, Any] = {
+ "adapter_path": adapter,
+ "max_batch_tokens": 8192,
+ "adapter_options": {"loadtime": {"upstream": "open-host", "upstream_model": "org/model"}},
+ }
+ if "generate" in tasks:
+ profile["kv_budget_tokens"] = 65536
+ return {"sie_id": sie_id, "remote_backed": True, "tasks": tasks, "profiles": {"default": profile}}
+
+
+def nested(levels: int) -> Any:
+ value: Any = "leaf"
+ for _ in range(levels):
+ value = {"next": value}
+ return value
+
+
[email protected](autouse=True)
+def _no_upstreams_after() -> Iterator[None]:
+ yield
+ install_upstreams({})
+
+
+def test_the_documented_openai_upstream_parses(tmp_path: Path) -> None:
+ path = tmp_path / "upstreams.yaml"
+ path.write_text(
+ "upstreams:\n"
+ " open-host:\n"
+ " kind: openai\n"
+ " base_url: https://host.example.com/v1\n"
+ " api_key_secret: OPEN_HOST_KEY\n"
+ " endpoints: [completions, chat, embeddings, rerank]\n"
+ " set_params:\n"
+ " provider: {data_collection: deny, zdr: true}\n"
+ " strip_params: [user]\n"
+ " rate_cap: {requests_per_minute: 300, max_concurrency: 16}\n",
+ encoding="utf-8",
+ )
+
+ upstream = load_upstreams(path)["open-host"]
+
+ assert upstream.endpoints == frozenset(UpstreamEndpoint)
+ assert upstream.set_params == {"provider": {"data_collection": "deny", "zdr": True}}
+ assert upstream.strip_params == frozenset({"user"})
+ assert upstream.outputs == frozenset({"tokens", "dense", "score"})
+
+
[email protected]("endpoints", [None, []], ids=["absent", "empty"])
+def test_an_openai_upstream_must_declare_its_endpoints(tmp_path: Path, endpoints: list[str] | None) -> None:
+ spec = openai_upstream(endpoints=endpoints)
+ if endpoints is None:
+ del spec["endpoints"]
+
+ with pytest.raises(UpstreamConfigError, match="kind openai must declare the endpoints it offers"):
+ load_one(tmp_path, spec)
+
+
+ ("fields", "reason"),
+ [
+ ({"endpoints": ["chat", "chat"]}, "endpoints lists the same entry more than once"),
+ ({"endpoints": ["responses"]}, "Input should be 'completions', 'chat', 'embeddings' or 'rerank'"),
+ ({"strip_params": ["user", "user"]}, "strip_params lists the same entry more than once"),
+ ],
+ ids=["repeated-endpoint", "unknown-endpoint", "repeated-strip"],
+)
+def test_a_list_is_never_silently_shortened_or_widened(tmp_path: Path, fields: dict[str, Any], reason: str) -> None:
+ with pytest.raises(UpstreamConfigError, match=re.escape(reason)):
+ load_one(tmp_path, openai_upstream(**fields))
+
+
+ "field",
+ [{"endpoints": ["chat"]}, {"set_params": {"provider": {"zdr": True}}}, {"strip_params": ["user"]}],
+ ids=["endpoints", "set_params", "strip_params"],
+)
+def test_kind_sie_takes_no_openai_field(field: dict[str, Any]) -> None:
+ with pytest.raises(ValidationError, match=f"kind sie takes no {next(iter(field))}"):
+ Upstream.model_validate(
+ {"kind": "sie", "base_url": "https://sie.example.internal", "rate_cap": RATE_CAP, **field}
+ )
+
+
+def test_the_model_and_the_caller_input_are_reserved() -> None:
+ assert {"model", "input", "messages", "prompt", "query", "documents", "stream"} <= RESERVED_UPSTREAM_PARAMS
+
+
[email protected]("name", sorted(RESERVED_UPSTREAM_PARAMS))
+def test_a_field_the_server_sends_itself_can_be_neither_set_nor_stripped(name: str) -> None:
+ with pytest.raises(ValidationError, match=f"set_params cannot set '{name}', which the server sends itself"):
+ Upstream.model_validate(openai_upstream(set_params={name: "x"}))
+ with pytest.raises(ValidationError, match=f"strip_params cannot strip '{name}', which the server sends itself"):
+ Upstream.model_validate(openai_upstream(strip_params=[name]))
+
+
[email protected]("name", ["", "1st", "a-b", "a.b", "$ref", "x" * 65, "naïve"])
+def test_a_field_name_is_an_identifier(name: str) -> None:
+ with pytest.raises(ValidationError, match="set_params names are letters, digits and underscores"):
+ Upstream.model_validate(openai_upstream(set_params={name: 1}))
+ with pytest.raises(ValidationError, match="strip_params names are letters, digits and underscores"):
+ Upstream.model_validate(openai_upstream(strip_params=[name]))
+
+
+ ("value", "reason"),
+ [
+ (float("inf"), "holds a number that is not finite"),
+ (float("nan"), "holds a number that is not finite"),
+ (datetime.date(2026, 10, 1), "holds a value that is not JSON"),
+ ({1: "one"}, "holds an object key that is not a string"),
+ (nested(8), "nests deeper than 8 levels"),
+ ],
+ ids=["infinity", "nan", "date", "integer-key", "too-deep"],
+)
+def test_set_params_hold_bounded_json_and_errors_never_repeat_a_value(
+ tmp_path: Path, value: Any, reason: str, caplog: pytest.LogCaptureFixture
+) -> None:
+ caplog.set_level(logging.DEBUG)
+
+ with pytest.raises(UpstreamConfigError, match=re.escape(f"set_params['provider'] {reason}")) as raised:
+ load_one(tmp_path, openai_upstream(set_params={"provider": [CANARY, value]}))
+
+ assert CANARY not in str(raised.value)
+ assert CANARY not in caplog.text
+
+
+def test_eight_levels_of_nesting_are_accepted() -> None:
+ upstream = Upstream.model_validate(openai_upstream(set_params={"provider": nested(8)}))
+
+ assert upstream.set_params["provider"] == nested(8)
+
+
+def test_set_params_and_strip_params_are_bounded() -> None:
+ too_many = {f"field_{index}": index for index in range(33)}
+
+ with pytest.raises(ValidationError, match="set_params sets at most 32 fields"):
+ Upstream.model_validate(openai_upstream(set_params=too_many))
+ with pytest.raises(ValidationError, match="strip_params strips at most 32 fields"):
+ Upstream.model_validate(openai_upstream(strip_params=list(too_many)))
+ with pytest.raises(ValidationError, match="set_params is larger than 16384 bytes as JSON"):
+ Upstream.model_validate(openai_upstream(set_params={"a": "x" * 8192, "b": "y" * 8192}))
+
+
+def test_a_value_that_repeats_one_subtree_is_measured_without_expanding_it() -> None:
+ level: list[Any] = ["x" * 16] * 10
+ for _ in range(7):
+ level = [level] * 10
+
+ with pytest.raises(ValidationError, match=re.escape("set_params['provider'] is larger than 16384 bytes as JSON")):
+ Upstream.model_validate(openai_upstream(set_params={"provider": level}))
+
+
+def test_a_field_cannot_be_both_set_and_stripped() -> None:
+ with pytest.raises(ValidationError, match="set_params and strip_params both name 'temperature'"):
+ Upstream.model_validate(openai_upstream(set_params={"temperature": 0}, strip_params=["temperature", "user"]))
+
+
+def test_apply_params_sets_then_strips_and_changes_neither_the_body_nor_the_upstream() -> None:
+ upstream = Upstream.model_validate(
+ openai_upstream(set_params={"provider": {"zdr": True}, "temperature": 0}, strip_params=["user"])
+ )
+ body = {"model": "org/model", "messages": [{"role": "user", "content": "hi"}], "temperature": 0.7, "user": "u-7"}
+ sent_before = copy.deepcopy(body)
+
+ sent = upstream.apply_params(body)
+
+ assert sent == {
+ "model": "org/model",
+ "messages": [{"role": "user", "content": "hi"}],
+ "temperature": 0,
+ "provider": {"zdr": True},
+ }
+ assert body == sent_before
+ sent["provider"]["zdr"] = False
+ assert upstream.apply_params(body)["provider"] == {"zdr": True}
+
+
+def test_set_params_stay_out_of_the_upstream_repr() -> None:
+ upstream = Upstream.model_validate(openai_upstream(set_params={"provider": {"order": [CANARY]}}))
+
+ assert CANARY not in repr(upstream)
+ assert CANARY not in str(upstream)
+
+
+def test_each_endpoint_produces_an_output_the_model_config_names() -> None:
+ every_task = {
+ "encode": {"dense": {"dim": 8}, "sparse": {"dim": 8}, "multivector": {"dim": 8}},
+ "score": {},
+ "extract": {},
+ **GENERATE,
+ }
+ config = ModelConfig.model_validate(remote_model(every_task))
+
+ assert set(ENDPOINT_OUTPUTS) == set(UpstreamEndpoint)
+ assert set(ENDPOINT_OUTPUTS.values()) <= set(config.outputs)
+
+
+ ("tasks", "endpoints"),
+ [
+ (DENSE, ["embeddings"]),
+ ({"encode": {"dense": {"dim": 8}, "sparse": {"dim": 8}}}, ["embeddings"]),
+ ({"score": {}}, ["rerank"]),
+ (GENERATE, ["chat"]),
+ (GENERATE, ["completions"]),
+ ({**DENSE, "score": {}}, ["rerank"]),
+ ],
+ ids=["dense", "dense-and-sparse", "score", "chat", "completions", "one-of-two-tasks"],
+)
+def test_a_remote_profile_is_accepted_when_an_endpoint_produces_one_of_the_model_outputs(
+ tasks: dict[str, Any], endpoints: list[str]
+) -> None:
+ install(*endpoints)
+
+ validate_profile_upstreams(ModelConfig.model_validate(remote_model(tasks)))
+
+
+ ("tasks", "endpoints", "reason"),
+ [
+ (DENSE, ["chat", "rerank"], "none of the model's outputs (dense); declare embeddings"),
+ ({"score": {}}, ["embeddings"], "none of the model's outputs (score); declare rerank"),
+ (GENERATE, ["embeddings", "rerank"], "none of the model's outputs (tokens); declare chat or completions"),
+ (
+ {"encode": {"sparse": {"dim": 8}}, "extract": {}},
+ ["completions", "chat", "embeddings", "rerank"],
+ "none of the model's outputs (sparse, json); an upstream of kind openai has no endpoint for them",
+ ),
+ ],
+ ids=["dense", "score", "generation", "sparse-and-extract"],
+)
+def test_a_remote_profile_is_refused_when_no_endpoint_produces_a_model_output(
+ tasks: dict[str, Any], endpoints: list[str], reason: str
+) -> None:
+ install(*endpoints)
+ config = ModelConfig.model_validate(remote_model(tasks))
+
+ expected = f"Profile 'default' of 'acme/remote' names upstream 'open-host', whose endpoints produce {reason}"
+ with pytest.raises(ValueError, match=re.escape(expected)):
+ validate_profile_upstreams(config)
+
+
+def test_an_sie_upstream_is_not_limited_by_endpoints() -> None:
+ sie = Upstream.model_validate({"kind": "sie", "base_url": "https://sie.example.internal", "rate_cap": RATE_CAP})
+ install_upstreams({"open-host": sie})
+
+ assert sie.outputs is None
+ validate_profile_upstreams(ModelConfig.model_validate(remote_model({"extract": {}}, adapter=SIE_ADAPTER)))
+
+
+def test_with_remote_serving_off_the_endpoints_are_not_checked() -> None:
+ install_upstreams({"open-host": Upstream.model_validate(openai_upstream(endpoints=["chat"]))}, remote_serving=False)
+
+ validate_profile_upstreams(ModelConfig.model_validate(remote_model({"score": {}})))
+
+
+def test_a_model_added_at_runtime_is_refused_when_its_upstream_cannot_serve_it() -> None:
+ install("embeddings")
+ registry = ModelRegistry(models_dir=None)
+
+ with pytest.raises(ValueError, match="declare rerank"):
+ registry.add_config(ModelConfig.model_validate(remote_model({"score": {}})))
+
+ assert not registry.has_model("acme/remote")
+
+
+async def test_a_config_snapshot_rejects_only_the_model_its_upstream_cannot_serve() -> None:
+ install("embeddings")
+ registry = ModelRegistry(models_dir=None)
+ executor = QueueExecutor(registry)
+
+ response = await executor.replace_model_configs(
+ ReplaceModelConfigsRequest(
+ bundle_id="default",
+ epoch=1,
+ bundle_config_hash="",
+ models=[
+ ReplaceModelConfigEntry(
+ model_id="acme/embed", model_config=yaml.safe_dump(remote_model(DENSE, "acme/embed"))
+ ),
+ ReplaceModelConfigEntry(
+ model_id="acme/rank", model_config=yaml.safe_dump(remote_model({"score": {}}, "acme/rank"))
+ ),
+ ],
+ )
+ )
+
+ assert registry.has_model("acme/embed")
+ assert not registry.has_model("acme/rank")
+ assert response.applied_models == ["acme/embed"]
diff --git a/packages/sie_server/tests/config/test_upstreams.py b/packages/sie_server/tests/config/test_upstreams.py
index f5b8f2197..18a5d078a 100644
--- a/packages/sie_server/tests/config/test_upstreams.py
+++ b/packages/sie_server/tests/config/test_upstreams.py
@@ -36,7 +36,8 @@ def test_a_valid_file_defines_both_kinds(tmp_path: Path) -> None:
" api_key_secret: TEAM_SIE_KEY\n"
" proxy_url: http://proxy.example.internal:3128\n" + RATE_CAP + " local-openai:\n"
" kind: openai\n"
- " base_url: http://127.0.0.1:8000/v1\n" + RATE_CAP,
+ " base_url: http://127.0.0.1:8000/v1\n"
+ " endpoints: [embeddings]\n" + RATE_CAP,
)
upstreams = load_upstreams(path)