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
feat(config): refuse a remote profile that names an undefined upstream (#500)
Krisztian Gajdar497709744ce5
diff --git a/packages/sie_config/src/sie_config/config_api.py b/packages/sie_config/src/sie_config/config_api.pyindex b3703d33d..6bc112be7 100644--- a/packages/sie_config/src/sie_config/config_api.py+++ b/packages/sie_config/src/sie_config/config_api.py@@ -23,6 +23,7 @@ from sie_config.model_registry import (ModelRegistry,ProfileConflictError,parse_model_spec,+ undeclared_upstreams,)from sie_config.model_schema import model_config_schema_errorsfrom sie_config.nats_publisher import NatsPublisher, PartialPublishError@@ -372,6 +373,40 @@ def _reject_worker_schema_errors(config: dict[str, Any]) -> None:)+_UPSTREAM_NAMES_ENV = "SIE_UPSTREAM_NAMES"+++def _declared_upstream_names() -> frozenset[str] | None:+ """The upstreams the remote workers define, from a comma-separated list. Unset means unknown."""+ raw = os.environ.get(_UPSTREAM_NAMES_ENV)+ if raw is None:+ return None+ return frozenset(name for name in (part.strip() for part in raw.split(",")) if name)+++def _reject_undeclared_upstreams(model_id: str, profiles: dict[str, Any], written: dict[str, Any]) -> None:+ """Reject with 422 a written remote profile that names an upstream outside ``SIE_UPSTREAM_NAMES``.++ ``profiles`` is the model's profile set after the write, which ``extends`` resolves+ against. Only the ``written`` profiles are checked.+ """+ declared = _declared_upstream_names()+ if declared is None:+ return+ undeclared = undeclared_upstreams(profiles, written, declared)+ if undeclared:+ raise HTTPException(+ status_code=422,+ detail={+ "error": "validation_error",+ "details": [+ {"message": f"Profile '{name}' of '{model_id}' names an undefined upstream {upstream!r}"}+ for name, upstream in undeclared.items()+ ],+ },+ )++def _load_filesystem_yaml(models_dir: Any, model_name: str) -> str | None:"""Load raw YAML for a filesystem-backed model (blocking; call via to_thread).@@ -694,6 +729,12 @@ async def add_model(request: Request) -> Response:) from eexisting_config = model_registry.get_full_config(model_id)+ written_profiles = config.get("profiles") or {}+ _reject_undeclared_upstreams(+ model_id,+ {**((existing_config or {}).get("profiles") or {}), **written_profiles},+ written_profiles,+ )if existing_config:conflicting_fields = []for key, new_value in config.items():@@ -1117,6 +1158,8 @@ async def replace_model(request: Request, model_id: str) -> Response:status_code=422,detail={"error": "validation_error", "details": [{"message": str(e)}]},) from e+ written_profiles = config.get("profiles") or {}+ _reject_undeclared_upstreams(config["sie_id"], written_profiles, written_profiles)# Unchanged-content no-op: compare the incoming config against the# registry's current merged config. Equal => no epoch bump, nodiff --git a/packages/sie_config/src/sie_config/model_registry.py b/packages/sie_config/src/sie_config/model_registry.pyindex c0521fe5b..5f0dd6c76 100644--- a/packages/sie_config/src/sie_config/model_registry.py+++ b/packages/sie_config/src/sie_config/model_registry.py@@ -6,8 +6,10 @@ import jsonimport loggingimport reimport threading+from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom pathlib import Path+from typing import Any, castimport orjsonimport yaml@@ -120,6 +122,32 @@ def _resolved_profile_hash_config(return resolved+REMOTE_ADAPTER_MODULE_PREFIX = "sie_server.adapters.remote."+++def undeclared_upstreams(profiles: dict, profile_names: Iterable[str], declared: frozenset[str]) -> dict[str, object]:+ """Map each named remote profile whose upstream is not in ``declared`` to the upstream it names.++ A profile is remote when its adapter, after ``extends``, is a remote adapter. Its+ upstream is ``adapter_options.loadtime.upstream`` after ``extends``, resolved as+ the worker resolves it.+ """+ undeclared: dict[str, object] = {}+ for name in profile_names:+ resolved = _resolved_profile_hash_config(profiles, name)+ if resolved is None:+ continue+ adapter_path = resolved["adapter_path"]+ if not (isinstance(adapter_path, str) and adapter_path.startswith(REMOTE_ADAPTER_MODULE_PREFIX)):+ continue+ options = resolved["adapter_options"]+ loadtime = cast("dict[str, Any]", options).get("loadtime") if isinstance(options, dict) else None+ upstream = loadtime.get("upstream") if isinstance(loadtime, dict) else None+ if not isinstance(upstream, str) or upstream not in declared:+ undeclared[name] = upstream+ return undeclared++_PROFILE_NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")diff --git a/packages/sie_config/tests/test_upstream_names.py b/packages/sie_config/tests/test_upstream_names.pynew file mode 100644index 000000000..3955e5b7e--- /dev/null+++ b/packages/sie_config/tests/test_upstream_names.py@@ -0,0 +1,216 @@+"""sie-config refuses a write whose remote profile names an upstream the remote workers do not define."""++from __future__ import annotations++import asyncio+from collections.abc import Iterator+from pathlib import Path+from typing import Any++import httpx+import pytest+import yaml+from fastapi import FastAPI+from fastapi.testclient import TestClient+from sie_config.config_api import router as config_router+from sie_config.model_registry import REMOTE_ADAPTER_MODULE_PREFIX, ModelRegistry+from sie_server.config.model import REMOTE_ADAPTER_MODULE_PREFIX as WORKER_REMOTE_ADAPTER_MODULE_PREFIX+from sie_server.config.upstreams import Upstream, install_upstreams+from sie_server.core.registry import ModelRegistry as WorkerModelRegistry+from sie_server.ipc_types import ReplaceModelConfigEntry, ReplaceModelConfigsRequest+from sie_server.queue_executor import QueueExecutor++BUNDLES_DIR = Path(__file__).resolve().parents[2] / "sie_server" / "bundles"+REMOTE_ADAPTER = "sie_server.adapters.remote.sie:SieUpstreamAdapter"+LOCAL_ADAPTER = "sie_server.adapters.bert_flash:BertFlashAdapter"+TASKS = {"encode": {"dense": {"dim": 384}}}+++def remote_profile(upstream: object) -> dict[str, Any]:+ return {+ "adapter_path": REMOTE_ADAPTER,+ "max_batch_tokens": 8192,+ "adapter_options": {"loadtime": {"upstream": upstream, "upstream_model": "org/name"}},+ }+++def remote_backed(upstream: object) -> dict[str, Any]:+ return {+ "sie_id": "acme/remote",+ "remote_backed": True,+ "tasks": TASKS,+ "profiles": {"default": remote_profile(upstream)},+ }+++def hybrid(upstream: object, **profiles: dict[str, Any]) -> dict[str, Any]:+ return {+ "sie_id": "acme/hybrid",+ "hf_id": "acme/hybrid",+ "tasks": TASKS,+ "profiles": {+ "default": {"adapter_path": LOCAL_ADAPTER, "max_batch_tokens": 4096},+ "remote": remote_profile(upstream),+ **profiles,+ },+ }+++def override_upstream(upstream: str) -> dict[str, Any]:+ return {"extends": "remote", "adapter_options": {"loadtime": {"upstream": upstream, "upstream_model": "org/name"}}}+++def client(tmp_path: Path) -> TestClient:+ models_dir = tmp_path / "models"+ models_dir.mkdir()+ app = FastAPI()+ app.include_router(config_router)+ app.state.model_registry = ModelRegistry(BUNDLES_DIR, models_dir)+ app.state.nats_publisher = None+ app.state.config_store = None+ return TestClient(app)+++def declare(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_UPSTREAM_NAMES", "team-sie")+++def post(client: TestClient, config: dict[str, Any]) -> httpx.Response:+ return client.post("/v1/configs/models", content=yaml.safe_dump(config))+++def refusal(profile: str, model: str, upstream: object) -> dict[str, Any]:+ return {+ "error": "validation_error",+ "details": [{"message": f"Profile '{profile}' of '{model}' names an undefined upstream {upstream!r}"}],+ }++[email protected]("declare")+def test_a_remote_profile_naming_an_undefined_upstream_is_refused_and_not_stored(client: TestClient) -> None:+ response = post(client, remote_backed("nobody"))++ assert response.status_code == 422+ assert response.json()["detail"] == refusal("default", "acme/remote", "nobody")+ assert client.get("/v1/configs/models/acme/remote").status_code == 404+ assert post(client, remote_backed("team-sie")).status_code == 201++[email protected]("names", ["team-sie", " other , team-sie ,"])+def test_the_list_is_comma_separated(client: TestClient, monkeypatch: pytest.MonkeyPatch, names: str) -> None:+ monkeypatch.setenv("SIE_UPSTREAM_NAMES", names)++ assert post(client, remote_backed("team-sie")).status_code == 201+++def test_without_the_list_upstream_names_are_left_to_the_worker(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.delenv("SIE_UPSTREAM_NAMES", raising=False)++ assert post(client, remote_backed("nobody")).status_code == 201+++def test_an_empty_list_refuses_every_remote_profile_and_no_local_one(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setenv("SIE_UPSTREAM_NAMES", "")+ local = {"sie_id": "acme/local", "hf_id": "acme/local", "tasks": TASKS, "profiles": hybrid("x")["profiles"]}+ del local["profiles"]["remote"]++ assert post(client, remote_backed("team-sie")).status_code == 422+ assert post(client, local).status_code == 201++[email protected]("declare")[email protected]("upstream", [["team-sie"], 7, None])+def test_an_upstream_that_is_not_a_name_is_refused(client: TestClient, upstream: object) -> None:+ assert post(client, remote_backed(upstream)).status_code == 422++[email protected]("declare")+def test_an_appended_profile_is_checked_after_extends(client: TestClient) -> None:+ assert post(client, hybrid("team-sie")).status_code == 201++ inherits = post(client, {"sie_id": "acme/hybrid", "profiles": {"alias": {"extends": "remote"}}})+ overrides = post(client, {"sie_id": "acme/hybrid", "profiles": {"elsewhere": override_upstream("nobody")}})++ assert inherits.status_code == 201+ assert overrides.status_code == 422+ assert overrides.json()["detail"] == refusal("elsewhere", "acme/hybrid", "nobody")+++def test_only_the_written_profiles_are_checked(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:+ assert post(client, hybrid("retired")).status_code == 201+ monkeypatch.setenv("SIE_UPSTREAM_NAMES", "team-sie")++ appended = {"sie_id": "acme/hybrid", "profiles": {"small": {"extends": "default", "max_batch_tokens": 1024}}}++ assert post(client, appended).status_code == 201++[email protected]("declare")+def test_a_replacement_is_checked_and_keeps_the_stored_config(client: TestClient) -> None:+ assert post(client, remote_backed("team-sie")).status_code == 201++ response = client.put("/v1/configs/models/acme/remote", content=yaml.safe_dump(remote_backed("nobody")))++ assert response.status_code == 422+ assert response.json()["detail"] == refusal("default", "acme/remote", "nobody")+ stored = client.app.state.model_registry.get_full_config("acme/remote")+ assert stored["profiles"]["default"]["adapter_options"]["loadtime"]["upstream"] == "team-sie"+++def remote_worker_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({})+++async def accepted_by_a_remote_worker(config: dict[str, Any]) -> bool:+ executor = QueueExecutor(WorkerModelRegistry(models_dir=None))+ response = await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="remote",+ epoch=1,+ bundle_config_hash="",+ models=[ReplaceModelConfigEntry(model_id=config["sie_id"], model_config=yaml.safe_dump(config))],+ )+ )+ return config["sie_id"] in response.applied_models++[email protected]("declare", "remote_worker_upstreams")+ ("config", "accepted"),+ [+ pytest.param(remote_backed("team-sie"), True, id="remote-backed-defined"),+ pytest.param(remote_backed("nobody"), False, id="remote-backed-undefined"),+ pytest.param(hybrid("nobody"), False, id="hybrid-undefined"),+ pytest.param(hybrid("team-sie", alias={"extends": "remote"}), True, id="alias-inherits-defined"),+ pytest.param(hybrid("team-sie", alias=override_upstream("nobody")), False, id="alias-overrides-undefined"),+ pytest.param(hybrid("team-sie", small={"extends": "default", "max_batch_tokens": 1024}), True, id="local"),+ ],+)+def test_sie_config_refuses_exactly_what_a_remote_worker_refuses(+ client: TestClient, config: dict[str, Any], accepted: bool+) -> None:+ assert (post(client, config).status_code == 201) is accepted+ assert asyncio.run(accepted_by_a_remote_worker(config)) is accepted+++def test_the_remote_adapter_prefix_is_the_workers() -> None:+ assert REMOTE_ADAPTER_MODULE_PREFIX == WORKER_REMOTE_ADAPTER_MODULE_PREFIXdiff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 881c11c1b..4682487ca 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -82,7 +82,7 @@ All config mutations go to `sie-config`. The gateway has no write handler.1. Admin or deploy tooling sends `POST /v1/configs/models` with a model config YAML body to `sie-config`. Auth: `_check_write_auth` (`packages/sie_config/src/sie_config/config_api.py`) requires a bearer matching `SIE_ADMIN_TOKEN` when that variable is set; if `SIE_ADMIN_TOKEN` is unset and a read-scoped token (`SIE_CONFIG_READ_TOKEN` or `SIE_AUTH_TOKEN`) is set, writes are rejected with `403` (a read token never grants write access); if no token is set (dev/local only) writes are accepted unauthenticated. Production deployments always set `SIE_ADMIN_TOKEN`.2. **Pre-lock validation** (outside the per-app write lock, on the FastAPI event loop): parse the YAML body and — when a top-level `sie_id` is present — run `_validate_model_id` (regex + `..`/`\\` rejection + `status`-suffix rejection). Reject invalid input with `400` before any state is touched. The body is also checked against `packages/sie_config/src/sie_config/model_config.schema.json`, the JSON Schema of the worker's `ModelConfig` (a test keeps the two equal): an unknown key or a wrong value type at any level returns `422 validation_error` with one `{loc, message}` entry per field, instead of accepting a config that every worker rejects. JSON types are applied strictly, so values that pydantic's lax mode would coerce, such as a quoted number, are rejected too. Required fields are not enforced here, since append bodies are partial. `PUT` runs the same check.3. **Critical section** under `_get_write_lock` (a lazy, per-app `asyncio.Lock` stored on `app.state`):- 1. `ModelRegistry.validate_model_config` — pure check against the in-memory registry (no mutation), run under the registry's internal `threading.RLock`. Validation rejects any write whose post-state resolves to zero routable bundles (`422`), so an `extends`-only profile cannot land a brand-new model that no worker bundle can serve. Appending a new `extends`-only profile to an already-routable model is allowed.+ 1. `ModelRegistry.validate_model_config` — pure check against the in-memory registry (no mutation), run under the registry's internal `threading.RLock`. Validation rejects any write whose post-state resolves to zero routable bundles (`422`), so an `extends`-only profile cannot land a brand-new model that no worker bundle can serve. Appending a new `extends`-only profile to an already-routable model is allowed. When `SIE_UPSTREAM_NAMES` is set, each profile in the body whose adapter, after `extends`, is a remote adapter (`sie_server.adapters.remote.*`) must name one of those upstreams in `adapter_options.loadtime.upstream`, or the write is rejected with `422 validation_error`. `PUT` runs the same check. Profiles already stored are not re-checked. A remote worker applies the same rule to every profile, against its own upstreams file, when it applies the config.2. **Compute `created_profiles` vs `existing_profiles_skipped`.** The write is treated as append-only: profiles already present in the registry with a compatible body are reported as skipped, not rewritten. If there are no new profiles *and* at least one skip, an on-disk conflict check compares the incoming YAML against `ConfigStore`'s existing file for this model (guards against disk drift from the in-memory registry).3. **Persist to disk** via `ConfigStore.write_model` — **only if there are new profiles (`created_profiles` non-empty) and a `ConfigStore` is configured**. The persisted YAML is the result of a merge with the existing stored document (when one exists): new top-level fields are added, missing top-level fields are preserved, and same-key mutations to existing non-`profiles` metadata are rejected with `409 content_conflict` (the API is append-only for metadata too). Incoming `profiles` are merged profile-by-profile. No-op replays skip this step entirely. On the `LocalBackend`, `write_model` is atomic (`tempfile.mkstemp` → write → `fsync` → `Path.replace`, in `packages/sie_sdk/src/sie_sdk/storage.py`); on `S3Backend` / `GCSBackend` the write is a single object-store PUT (last-writer-wins, atomic at the object level).4. **Mutate the in-memory registry** via `ModelRegistry.add_model_config`. Runs under the registry's `RLock`; uses atomic dict-swap semantics so lock-free readers (e.g. `GET /models`, `GET /bundles`) never observe a torn state. The registry re-runs `_validate_config_locked` internally, so validation effectively runs twice (once from step 3.1, once from inside `add_model_config`) — the doubled cost is negligible and the redundancy is intentional.@@ -530,6 +530,7 @@ Config service (`sie-config`):- `SIE_NATS_USER` / `SIE_NATS_PASSWORD` — NATS credentials (Helm sets user `sie-config`, the only user allowed to publish on `sie.config.models.>`). Both or neither; one alone fails startup.- `SIE_CONFIG_STORE_DIR` — base directory for the on-disk config store. When the Helm `config.configStore.enabled` flag is true, this is set to the mounted PVC path and `SIE_CONFIG_RESTORE=true` enables startup replay from the store into the in-memory registry.- `SIE_BUNDLES_DIR`, `SIE_MODELS_DIR` — bundle and model source directories. **`sie-config` is the source of truth**: it reads these at startup, validates writes against them, and re-serves the bundle list at `GET /v1/configs/bundles` for the gateway's bootstrap. Defaults via `sharedPaths.{bundlesDir,modelsDir}` (`/app/bundles`, `/app/models`) and image-baked.+- `SIE_UPSTREAM_NAMES` — comma-separated names of the upstreams the remote workers define. When it is set, even to an empty value, a write whose remote profile names any other upstream is rejected with `422` (§3). When it is unset, `sie-config` does not check upstream names and a remote worker rejects an undefined one when it applies the config.- `SIE_LOG_LEVEL`, `SIE_LOG_JSON` — log verbosity and structured-JSON toggle (both also exposed as CLI flags).Tracing (all runtimes):