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: route remote profiles to a dedicated remote worker bundle (#492)
Krisztian Gajdarab5d4a9919b1
diff --git a/packages/sie_config/tests/test_remote_bundle_routing.py b/packages/sie_config/tests/test_remote_bundle_routing.pynew file mode 100644index 000000000..a1e953c5c--- /dev/null+++ b/packages/sie_config/tests/test_remote_bundle_routing.py@@ -0,0 +1,100 @@+"""sie-config routes remote profiles to the remote bundle, and a remote-lane worker agrees on its hash."""++from __future__ import annotations++import copy+from collections.abc import Iterator+from pathlib import Path+from typing import Any++import pytest+import yaml+from sie_config.model_registry import ModelRegistry+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_PROFILE: dict[str, Any] = {+ "adapter_path": "sie_server.adapters.remote.sie:SieUpstreamAdapter",+ "max_batch_tokens": 8192,+ "adapter_options": {"loadtime": {"upstream": "team-sie", "upstream_model": "org/name"}},+}+REMOTE_BACKED: dict[str, Any] = {+ "sie_id": "acme/remote",+ "remote_backed": True,+ "tasks": {"encode": {"dense": {"dim": 384}}},+ "profiles": {"default": REMOTE_PROFILE},+}+HYBRID: dict[str, Any] = {+ "sie_id": "acme/hybrid",+ "hf_id": "acme/hybrid",+ "tasks": {"encode": {"dense": {"dim": 384}}},+ "profiles": {+ "default": {"adapter_path": "sie_server.adapters.bert_flash:BertFlashAdapter", "max_batch_tokens": 4096},+ "remote": REMOTE_PROFILE,+ },+}+++def registry(tmp_path: Path) -> ModelRegistry:+ models_dir = tmp_path / "models"+ models_dir.mkdir()+ return ModelRegistry(BUNDLES_DIR, models_dir)+++def team_sie_upstream() -> 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_remote_backed_model_routes_to_the_remote_bundle(registry: ModelRegistry) -> None:+ _, _, affected_bundles = registry.validate_model_config(copy.deepcopy(REMOTE_BACKED))+ registry.add_model_config(copy.deepcopy(REMOTE_BACKED))++ assert affected_bundles == ["remote", "default"]+ assert registry.resolve_bundle("acme/remote") == "remote"+++def test_only_the_remote_profile_of_a_local_model_routes_to_the_remote_bundle(registry: ModelRegistry) -> None:+ registry.add_model_config(copy.deepcopy(HYBRID))++ assert registry.get_model_profile_bundles("acme/hybrid") == {+ "default": ["default"],+ "remote": ["remote", "default"],+ }+ assert registry.resolve_bundle("acme/hybrid") == "default"+ assert registry.resolve_bundle("acme/hybrid:remote") == "remote"++[email protected]("team_sie_upstream")+async def test_a_remote_lane_worker_reports_the_control_plane_hash(registry: ModelRegistry) -> None:+ registry.add_model_config(copy.deepcopy(REMOTE_BACKED))+ 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="acme/remote", model_config=yaml.safe_dump(REMOTE_BACKED))],+ )+ )++ assert response.unsupported_models == []+ assert response.bundle_config_hash+ assert response.bundle_config_hash == registry.compute_bundle_config_hash("remote")diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 0eec63c30..881c11c1b 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -32,7 +32,7 @@ The gateway's contract with admin tooling for post-write readiness is `GET /v1/cKey terms used throughout this document:-- **Bundle**: a model-compatibility grouping. Answers "which workers can serve this model?". Defined by a `name`, a `priority`, an optional `engine`, and an `adapters[]` list of adapter module identifiers. The source of truth is `sie-config`'s filesystem (image-baked at `SIE_BUNDLES_DIR`, default `/app/bundles`); `sie-config` loads them at startup to drive write validation and exposes them via `GET /v1/configs/bundles` + `GET /v1/configs/bundles/{id}`. The gateway no longer bakes its own copy: `state::config_bootstrap::BootstrapClient::fetch_bundles` pulls them at startup and installs them into `ModelRegistry` via `install_bundles` before any model fetch. Neither service *persists* bundles, and there is no `POST /v1/configs/bundles` on either side — bundle changes are a `sie-config` redeploy and the gateway picks them up on its next bootstrap (or on the next poller-driven catch-up; see §4.2).+- **Bundle**: a model-compatibility grouping. Answers "which workers can serve this model?". Defined by a `name`, a `priority`, an optional `engine`, and an `adapters[]` list of adapter module identifiers. The source of truth is `sie-config`'s filesystem (image-baked at `SIE_BUNDLES_DIR`, default `/app/bundles`); `sie-config` loads them at startup to drive write validation and exposes them via `GET /v1/configs/bundles` + `GET /v1/configs/bundles/{id}`. The gateway no longer bakes its own copy: `state::config_bootstrap::BootstrapClient::fetch_bundles` pulls them at startup and installs them into `ModelRegistry` via `install_bundles` before any model fetch. Neither service *persists* bundles, and there is no `POST /v1/configs/bundles` on either side — bundle changes are a `sie-config` redeploy and the gateway picks them up on its next bootstrap (or on the next poller-driven catch-up; see §4.2). A profile resolves to its compatible bundle with the lowest `priority` number. Remote adapters (`sie_server.adapters.remote.*`) are listed both in `default`, so a single server serves them, and in `remote` at priority 1, so in a cluster every remote profile, including a `model:remote` variant of a model served locally, resolves to the `remote` lane.- **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.diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 1169d8b47..3ae2251da 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -2435,7 +2435,7 @@},{"$ref": "#/components/schemas/ModelRoutingWire",- "description": "How the bare model name is served: the routing policy and the kind of\nupstream a remote profile calls. A single SIE server emits it on every\nentry."+ "description": "How the bare model name is served: the routing policy and the kind of\nupstream a remote profile calls. Emitted on every entry."}]},diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 27ce16028..81425dba6 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -1242,4 +1242,103 @@ mod route_tests {.unwrap().contains("anything"));}++ fn seed_remote_backed_model(state: &AppState, bundles_dir: &std::path::Path, model_id: &str) {+ std::fs::write(+ bundles_dir.join("remote.yaml"),+ "name: remote\npriority: 1\nadapters:\n - sie_server.adapters.remote.sie\n",+ )+ .unwrap();+ state.model_registry.reload();+ 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("sie_server.adapters.remote.sie:SieUpstreamAdapter".to_string()),+ max_batch_tokens: Some(8192),+ compute_precision: None,+ adapter_options: Some(serde_json::json!({+ "loadtime": {"upstream": "team-sie", "upstream_model": "org/name"}+ })),+ extends: None,+ },+ );+ state+ .model_registry+ .add_model_config(ModelConfig {+ name: model_id.to_string(),+ hf_revision: None,+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles,+ inputs: None,+ tasks: None,+ max_sequence_length: None,+ })+ .unwrap();+ }++ #[tokio::test]+ async fn test_models_report_routing_on_every_entry() {+ let (app, state, bundles_dir, _models_dir) = build_router_with_state().await;+ seed_remote_backed_model(&state, bundles_dir.path(), "acme/remote");+ seed_model(&state, "BAAI/bge-m3");++ let listing = body_json(+ app.clone()+ .oneshot(+ Request::builder()+ .uri("/v1/models")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap(),+ )+ .await;+ let routing: HashMap<String, serde_json::Value> = listing["models"]+ .as_array()+ .unwrap()+ .iter()+ .map(|model| {+ (+ model["name"].as_str().unwrap().to_string(),+ model["routing"].clone(),+ )+ })+ .collect();+ assert_eq!(+ routing,+ HashMap::from([+ (+ "acme/remote".to_string(),+ serde_json::json!({"policy": "remote_only", "upstream_kind": "sie"})+ ),+ (+ "BAAI/bge-m3".to_string(),+ serde_json::json!({"policy": null, "upstream_kind": null})+ ),+ ])+ );++ let detail = app+ .oneshot(+ Request::builder()+ .uri("/v1/models/acme/remote")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(detail.status(), StatusCode::OK);+ assert_eq!(+ body_json(detail).await["routing"],+ serde_json::json!({"policy": "remote_only", "upstream_kind": "sie"})+ );+ }}diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex eabdf7964..214fbe894 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -2649,12 +2649,7 @@ pub struct ModelInfoWire {#[serde(default)]pub pending_generation: crate::queue::publisher::PendingGenerationSnapshot,/// How the bare model name is served: the routing policy and the kind of- /// upstream a remote profile calls. A single SIE server emits it on every- /// entry.- //- // Maintainer note: the gateway does not emit it yet. It is declared here,- // the schema of record, so the SDKs can type it; emission arrives with- // cluster remote worker pools.+ /// upstream a remote profile calls. Emitted on every entry.#[serde(skip_serializing_if = "Option::is_none")]pub routing: Option<ModelRoutingWire>,/// Short task-tier names that resolve to this model, for examplediff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex 72bc0e548..88684a77f 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -6607,4 +6607,86 @@ profiles:);}}++ fn repository_bundles_dir() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../sie_server/bundles")+ }++ fn remote_profile() -> crate::types::model::ProfileConfig {+ crate::types::model::ProfileConfig {+ adapter_options: Some(serde_json::json!({+ "loadtime": {"upstream": "team-sie", "upstream_model": "org/name"}+ })),+ ..profile(+ Some("sie_server.adapters.remote.sie:SieUpstreamAdapter"),+ Some(8192),+ None,+ )+ }+ }++ fn model_with_profiles(+ name: &str,+ profiles: Vec<(&str, crate::types::model::ProfileConfig)>,+ ) -> ModelConfig {+ ModelConfig {+ name: name.to_string(),+ hf_revision: None,+ adapter_module: None,+ default_bundle: None,+ pool: None,+ profiles: profiles+ .into_iter()+ .map(|(profile_name, profile)| (profile_name.to_string(), profile))+ .collect(),+ inputs: None,+ max_sequence_length: None,+ tasks: None,+ }+ }++ #[test]+ fn test_remote_profiles_resolve_to_the_remote_bundle_of_the_repository() {+ let (_dir, _bundles_dir, models_dir) = create_test_dirs();+ let registry = ModelRegistry::new(repository_bundles_dir(), &models_dir, true);+ registry+ .add_model_config(model_with_profiles(+ "acme/remote",+ vec![("default", remote_profile())],+ ))+ .unwrap();+ registry+ .add_model_config(model_with_profiles(+ "acme/hybrid",+ vec![+ (+ "default",+ profile(+ Some("sie_server.adapters.bert_flash:BertFlashAdapter"),+ Some(4096),+ None,+ ),+ ),+ ("remote", remote_profile()),+ ],+ ))+ .unwrap();++ assert_eq!(+ registry.get_model_bundles("acme/remote"),+ vec!["remote".to_string(), "default".to_string()]+ );+ assert_eq!(+ registry.resolve_bundle("acme/remote", None).unwrap(),+ "remote"+ );+ assert_eq!(+ registry.resolve_bundle("acme/hybrid", None).unwrap(),+ "default"+ );+ assert_eq!(+ registry.resolve_bundle("acme/hybrid:remote", None).unwrap(),+ "remote"+ );+ }}diff --git a/packages/sie_gateway/src/types/model.rs b/packages/sie_gateway/src/types/model.rsindex 9670c1975..5062dba15 100644--- a/packages/sie_gateway/src/types/model.rs+++ b/packages/sie_gateway/src/types/model.rs@@ -436,6 +436,20 @@ pub struct ProfileConfig {pub extends: Option<String>,}+/// Module prefix of the adapters that forward a profile to an upstream.+const REMOTE_ADAPTER_MODULE_PREFIX: &str = "sie_server.adapters.remote.";++/// The upstream kind each remote adapter module calls. An adapter refuses an+/// upstream of any other kind when it loads, so the module determines the kind.+const REMOTE_ADAPTER_UPSTREAM_KINDS: &[(&str, &str)] = &[("sie_server.adapters.remote.sie", "sie")];++fn remote_adapter_upstream_kind(module: &str) -> Option<&'static str> {+ REMOTE_ADAPTER_UPSTREAM_KINDS+ .iter()+ .find(|(candidate, _)| *candidate == module)+ .map(|(_, kind)| *kind)+}+#[derive(Debug, Clone)]pub struct ModelEntry {pub name: String,@@ -502,9 +516,29 @@ impl ModelEntry {"sql": self.info_extras.sql,"guard": self.info_extras.guard,},+ "routing": self.routing_value(),})}+ /// ``routing`` on a ``/v1/models`` entry, by the single server's rule: a+ /// route whose default profile uses a remote adapter is ``remote_only``.+ /// The gateway holds no upstream configuration, so the upstream kind is the+ /// one the adapter module speaks.+ fn routing_value(&self) -> Value {+ let module = self+ .profile_configs+ .get("default")+ .and_then(|profile| profile.adapter_path.as_deref())+ .map(|path| path.split(':').next().unwrap_or(path));+ match module {+ Some(module) if module.starts_with(REMOTE_ADAPTER_MODULE_PREFIX) => json!({+ "policy": "remote_only",+ "upstream_kind": remote_adapter_upstream_kind(module),+ }),+ _ => json!({ "policy": Value::Null, "upstream_kind": Value::Null }),+ }+ }+/// Per-profile LoRA-adapter served-names for this entry, scoped to a/// specific profile (not the union across profiles).///@@ -1541,4 +1575,93 @@ profiles:.expect("a100 profile entry");assert_eq!(a100_adapters, vec!["b1".to_string()]);}++ fn entry_with_default_adapter(adapter_path: Option<&str>) -> ModelEntry {+ let mut profile_configs = HashMap::new();+ if let Some(adapter_path) = adapter_path {+ profile_configs.insert(+ "default".to_string(),+ CanonicalProfile {+ kv_budget_tokens: None,+ adapter_path: Some(adapter_path.to_string()),+ max_batch_tokens: Some(8192),+ compute_precision: None,+ max_output_tokens: None,+ adapter_options: None,+ grammar_profile: None,+ chat_template_kwargs: None,+ },+ );+ }+ ModelEntry {+ name: "acme/model".to_string(),+ canonical_base_model: "acme/model".to_string(),+ canonical_profile: "default".to_string(),+ pool: None,+ bundles: Vec::new(),+ adapter_modules: HashSet::new(),+ profile_names: profile_configs.keys().cloned().collect(),+ profile_configs,+ info_extras: ModelInfoExtras::default(),+ }+ }++ #[test]+ fn test_routing_reports_remote_only_for_a_remote_default_profile() {+ let entry =+ entry_with_default_adapter(Some("sie_server.adapters.remote.sie:SieUpstreamAdapter"));+ assert_eq!(+ entry.to_model_info_value(false)["routing"],+ json!({"policy": "remote_only", "upstream_kind": "sie"})+ );+ }++ #[test]+ fn test_routing_names_no_kind_for_a_remote_adapter_without_one() {+ let entry = entry_with_default_adapter(Some("sie_server.adapters.remote.other:Adapter"));+ assert_eq!(+ entry.to_model_info_value(false)["routing"],+ json!({"policy": "remote_only", "upstream_kind": null})+ );+ }++ #[test]+ fn test_routing_is_local_for_a_local_profile_or_none() {+ for adapter_path in [+ Some("sie_server.adapters.sentence_transformer:SentenceTransformerAdapter"),+ Some("sie_server.adapters.remote_lookalike:Adapter"),+ None,+ ] {+ let entry = entry_with_default_adapter(adapter_path);+ assert_eq!(+ entry.to_model_info_value(true)["routing"],+ json!({"policy": null, "upstream_kind": null}),+ "{adapter_path:?}"+ );+ }+ }++ #[test]+ fn test_every_remote_bundle_adapter_names_its_upstream_kind() {+ let bundle: serde_yaml::Value =+ serde_yaml::from_str(include_str!("../../../sie_server/bundles/remote.yaml"))+ .expect("valid remote bundle YAML");+ let adapters: Vec<&str> = bundle["adapters"]+ .as_sequence()+ .expect("remote bundle lists adapters")+ .iter()+ .map(|adapter| adapter.as_str().expect("adapter module name"))+ .collect();+ assert!(!adapters.is_empty());+ for adapter in adapters {+ assert!(+ adapter.starts_with(REMOTE_ADAPTER_MODULE_PREFIX),+ "{adapter} in the remote bundle is not a remote adapter"+ );+ assert!(+ remote_adapter_upstream_kind(adapter).is_some(),+ "{adapter} needs an entry in REMOTE_ADAPTER_UPSTREAM_KINDS"+ );+ }+ }}diff --git a/packages/sie_server/bundles/remote.yaml b/packages/sie_server/bundles/remote.yamlnew file mode 100644index 000000000..42bbde4c5--- /dev/null+++ b/packages/sie_server/bundles/remote.yaml@@ -0,0 +1,10 @@+name: remote+priority: 1+default: false+# Remote profiles forward to an operator-defined upstream. A cluster serves+# them on a CPU worker lane that alone holds the upstream credentials. The+# default bundle lists the same adapters so a single server can serve them;+# this bundle's lower priority makes the gateway pick it whenever both match.+adapters:+- sie_server.adapters.remote.sie+deps: {}diff --git a/packages/sie_server/tests/config/test_remote_bundle.py b/packages/sie_server/tests/config/test_remote_bundle.pynew file mode 100644index 000000000..fdccb6aa6--- /dev/null+++ b/packages/sie_server/tests/config/test_remote_bundle.py@@ -0,0 +1,65 @@+"""Remote profiles route to the remote bundle, and a single server still serves them.++The gateway picks the compatible bundle with the lowest priority number. A+cluster runs the remote bundle on the only worker lane that holds upstream+credentials, so every remote adapter must be in that bundle and the bundle+must outrank any other bundle that lists a remote adapter. A single server+serves the default bundle when no bundle is named, so the default bundle keeps+the remote adapters too.+"""++from __future__ import annotations++import importlib.util+from pathlib import Path+from typing import Any++import yaml++BUNDLES_DIR = Path(__file__).resolve().parents[2] / "bundles"+REMOTE_ADAPTER_PREFIX = "sie_server.adapters.remote."+++def load_bundles() -> dict[str, dict[str, Any]]:+ bundles: dict[str, dict[str, Any]] = {}+ for path in sorted(BUNDLES_DIR.glob("*.yaml")):+ data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}+ bundles[data.get("name", path.stem)] = data+ return bundles+++def remote_adapters(bundle: dict[str, Any]) -> set[str]:+ return {adapter for adapter in bundle.get("adapters") or [] if adapter.startswith(REMOTE_ADAPTER_PREFIX)}+++def test_the_remote_bundle_lists_only_existing_remote_adapters_and_no_dependencies() -> None:+ remote = load_bundles()["remote"]++ assert remote["adapters"]+ assert remote_adapters(remote) == set(remote["adapters"])+ assert all(importlib.util.find_spec(adapter) is not None for adapter in remote["adapters"])+ assert not remote.get("deps")+++def test_every_remote_adapter_in_any_bundle_is_in_the_remote_bundle() -> None:+ bundles = load_bundles()++ listed = set().union(*(remote_adapters(bundle) for bundle in bundles.values()))++ assert listed == set(bundles["remote"]["adapters"])+++def test_the_remote_bundle_outranks_every_other_bundle_with_a_remote_adapter() -> None:+ bundles = load_bundles()+ others = {+ name: bundle["priority"] for name, bundle in bundles.items() if name != "remote" and remote_adapters(bundle)+ }++ assert others+ assert all(bundles["remote"]["priority"] < priority for priority in others.values()), others+++def test_the_default_bundle_keeps_the_remote_adapters_for_a_single_server() -> None:+ bundles = load_bundles()++ assert set(bundles["remote"]["adapters"]) <= set(bundles["default"]["adapters"])diff --git a/packages/sie_server/tests/test_remote_queue_path.py b/packages/sie_server/tests/test_remote_queue_path.pynew file mode 100644index 000000000..9dcbd567b--- /dev/null+++ b/packages/sie_server/tests/test_remote_queue_path.py@@ -0,0 +1,165 @@+"""A remote-backed model served by a remote-lane worker through the queue path.++The upstream is a real SIE app serving the built-in fake model on loopback. The+worker receives the model the way a cluster's remote lane does, as an export+for the ``remote`` bundle, and serves an encode batch through the executor the+worker sidecar drives over IPC.+"""++from __future__ import annotations++import asyncio+import socket+import threading+import time+from collections.abc import Iterator+from contextlib import contextmanager+from pathlib import Path+from typing import Any++import numpy as np+import pytest+import uvicorn+from fastapi import Request+from sie_sdk import SIEClient+from sie_sdk._msgpack import unpackb+from sie_server.app.app_factory import AppFactory+from sie_server.app.app_state_config import AppStateConfig+from sie_server.config.upstreams import Upstream, install_upstreams+from sie_server.core.registry import ModelRegistry+from sie_server.ipc_types import (+ EncodeBatchItem,+ ItemOutcome,+ ProcessEncodeBatchRequest,+ ReplaceModelConfigEntry,+ ReplaceModelConfigsRequest,+)+from sie_server.queue_executor import QueueExecutor++MODELS_DIR = Path(__file__).resolve().parents[1] / "models"+KEY_ENV = "REMOTE_QUEUE_PATH_TEST_KEY"+CANARY = "sk-canary-5a0e3c9d71b2f486"+MODEL_ID = "acme/remote-fake"+REMOTE_MODEL = f"""\+sie_id: {MODEL_ID}+remote_backed: true+inputs:+ text: true+tasks:+ encode:+ dense:+ dim: 384+profiles:+ default:+ adapter_path: sie_server.adapters.remote.sie:SieUpstreamAdapter+ max_batch_tokens: 8192+ adapter_options:+ loadtime:+ upstream: fake-sie+ upstream_model: sie-fake+"""+++@contextmanager+def sie_upstream() -> Iterator[tuple[str, list[str | None]]]:+ app = AppFactory.create_app(AppStateConfig(models_dir=str(MODELS_DIR), model_filter=["sie-fake"], device="cpu"))+ seen_authorization: list[str | None] = []++ @app.middleware("http")+ async def record_authorization(request: Request, call_next: Any) -> Any:+ if request.url.path.startswith("/v1/encode/"):+ seen_authorization.append(request.headers.get("authorization"))+ return await call_next(request)++ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ port = sock.getsockname()[1]+ server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning"))+ thread = threading.Thread(target=server.run, daemon=True)+ thread.start()+ deadline = time.monotonic() + 30+ while not server.started:+ assert time.monotonic() < deadline, "the upstream SIE app did not start"+ time.sleep(0.05)+ try:+ yield f"http://127.0.0.1:{port}", seen_authorization+ finally:+ server.should_exit = True+ thread.join(timeout=10)+++async def wait_until_ready(executor: QueueExecutor, model_id: str) -> None:+ deadline = time.monotonic() + 30+ while (state := await executor.ensure_model_ready(model_id)) != "ready":+ assert state in {"loading_started", "loading_in_progress"}, state+ assert time.monotonic() < deadline, "the remote profile did not load"+ await asyncio.sleep(0.05)+++def dense_values(outcome: ItemOutcome) -> np.ndarray:+ if outcome.raw_output is not None and outcome.raw_output.dense is not None:+ return np.asarray(outcome.raw_output.dense.values, dtype=np.float32)+ assert outcome.result_msgpack is not None+ return np.asarray(unpackb(outcome.result_msgpack, numeric_arrays=True)["dense"]["values"], dtype=np.float32)++[email protected](autouse=True)+def _reset_upstreams(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:+ monkeypatch.setenv(KEY_ENV, CANARY)+ yield+ install_upstreams({})+++async def test_a_remote_lane_worker_serves_a_remote_backed_model_through_the_queue_path() -> None:+ with sie_upstream() as (upstream_url, seen_authorization):+ with SIEClient(upstream_url) as upstream:+ expected = upstream.encode("sie-fake", {"text": "remote lane"})["dense"]+ seen_authorization.clear()+ install_upstreams(+ {+ "fake-sie": Upstream.model_validate(+ {+ "kind": "sie",+ "base_url": upstream_url,+ "api_key_secret": KEY_ENV,+ "rate_cap": {"requests_per_minute": 600, "max_concurrency": 8},+ }+ )+ }+ )+ executor = QueueExecutor(ModelRegistry(models_dir=None))++ applied = await executor.replace_model_configs(+ ReplaceModelConfigsRequest(+ bundle_id="remote",+ epoch=1,+ bundle_config_hash="",+ models=[ReplaceModelConfigEntry(model_id=MODEL_ID, model_config=REMOTE_MODEL)],+ )+ )+ await wait_until_ready(executor, MODEL_ID)+ batch = await executor.process_encode_batch(+ ProcessEncodeBatchRequest(+ model_id=MODEL_ID,+ items=[+ EncodeBatchItem(+ work_item_id="req-1.0",+ request_id="req-1",+ item_index=0,+ total_items=1,+ timestamp=time.time(),+ item={"text": "remote lane"},+ output_types=["dense"],+ bundle_config_hash=applied.bundle_config_hash,+ )+ ],+ )+ )++ assert applied.applied_models == [MODEL_ID]+ assert applied.unsupported_models == []+ assert applied.bundle_config_hash+ (outcome,) = batch.outcomes+ assert outcome.disposition == "publish_and_ack", outcome.error+ np.testing.assert_allclose(dense_values(outcome), expected, rtol=1e-6)+ assert seen_authorization == [f"Bearer {CANARY}"]diff --git a/packages/wire-fixtures/model_info.json b/packages/wire-fixtures/model_info.jsonindex ccbc50003..182a8b422 100644--- a/packages/wire-fixtures/model_info.json+++ b/packages/wire-fixtures/model_info.json@@ -39,6 +39,6 @@"optionality": "Python marks every typed key optional (`total=False`). TypeScript requires `name`, `loaded`, `inputs` and `outputs` on both `ModelInfo` and `WireModelInfo`; its remaining keys are optional. `pending_generation` is gateway-only. `last_error`/`max_sequence_length`/`revision`/`capabilities` are the four the emitters can send as an explicit null, so the SDK types admit null on each. The fixture pins which keys are declarable, not which are always present.","ts_renames": "The TS SDK camelCases three top-level keys \u2014 max_sequence_length -> maxSequenceLength, last_error -> lastError, pending_generation -> pendingGeneration \u2014 and leaves nested objects wire-shaped. Its consumer test checks the wire-side names listed here.","aliases": "Short task-tier names resolving to this model. Always emitted, empty when the model has none, so callers can distinguish 'no aliases' from an older gateway. Only catalog- or operator-declared names appear; the gateway's compiled-in routing defaults are not public API and are never listed.",- "routing": "How the bare model name is served: `policy` (`remote_only`, `fallback`, `threshold`, or null for local only) and `upstream_kind` (`sie`, `openai`, or null). The single server emits it on every entry. The gateway declares it and will emit it once cluster remote worker pools exist."+ "routing": "How the bare model name is served: `policy` (`remote_only`, `fallback`, `threshold`, or null for local only) and `upstream_kind` (`sie`, `openai`, or null). The single server and the gateway emit it on every entry."}}