Skip to content

armgit / sie

Public Imported from GitHub
0

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

test(remote): pin remote routing in vectors shared by the server and gateway (#584)

Krisztian Gajdara11ceaaf7b75
diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rs
index f75b7c05e..318380bf7 100644
--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs
+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs
@@ -2654,6 +2654,372 @@ mod tests {
.eq_ignore_ascii_case(UPSTREAM_HEADER.as_str()));
assert_eq!(served_by["values"], json!(["local", "remote"]));
}
+
+ fn remote_routing_vectors() -> serde_json::Value {
+ serde_json::from_str(include_str!("../../../wire-fixtures/remote_routing.json")).unwrap()
+ }
+
+ /// The vectors of one section of `wire-fixtures/remote_routing.json` that
+ /// apply to a gateway.
+ fn gateway_vectors(section: &str) -> Vec<serde_json::Value> {
+ remote_routing_vectors()[section]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|vector| {
+ vector.get("topologies").is_none_or(|topologies| {
+ topologies.as_array().unwrap().contains(&json!("gateway"))
+ })
+ })
+ .cloned()
+ .collect()
+ }
+
+ fn vector_status(value: &serde_json::Value) -> StatusCode {
+ StatusCode::from_u16(u16::try_from(value.as_u64().unwrap()).unwrap()).unwrap()
+ }
+
+ fn header_values(values: &serde_json::Value) -> Vec<&str> {
+ values
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|value| value.as_str().unwrap())
+ .collect()
+ }
+
+ /// A gateway whose `acme/chat` and `acme/hybrid-encode` local profiles are
+ /// in the abstract local `state` of the shared vectors, with a verified
+ /// remote worker and `triggers` declared on both models.
+ async fn gateway_in_local_state(state: &str, triggers: &serde_json::Value) -> TestGateway {
+ let mut routing =
+ "\nrouting:\n policy: fallback\n fallback_profile: remote\n".to_string();
+ if !triggers.is_null() {
+ routing.push_str(&format!(
+ " triggers: [{}]\n",
+ header_values(triggers).join(", ")
+ ));
+ }
+ let generate = format!("{HYBRID_GENERATE_MODEL}{routing}");
+ let encode = format!("{HYBRID_ENCODE_MODEL}{routing}");
+ let gateway = TestGateway::new(&[&generate, &encode, REMOTE_ENCODE_MODEL]).await;
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ let loaded = ["acme/chat", "acme/hybrid-encode"];
+ match state {
+ "ready" | "unhealthy" => {
+ gateway
+ .add_verified_worker("local-1", LOCAL_LANE, &loaded)
+ .await;
+ }
+ "loading" => {
+ gateway
+ .add_verified_worker("local-1", LOCAL_LANE, &[])
+ .await;
+ }
+ "saturated" => {
+ gateway
+ .add_saturated_worker("local-1", LOCAL_LANE, &loaded)
+ .await;
+ }
+ "no_worker" => {}
+ _ => unreachable!("{state}"),
+ }
+ if state == "unhealthy" {
+ gateway
+ .state
+ .registry
+ .mark_unhealthy("http://local-1:8080")
+ .await;
+ }
+ gateway
+ }
+
+ fn assert_kept_off_remote(gateway: &TestGateway, response: &Response, case: &str) {
+ assert!(
+ !response.headers().contains_key("x-sie-fallback-reason"),
+ "{case}"
+ );
+ assert!(
+ !response.headers().contains_key("x-sie-fallback-error"),
+ "{case}"
+ );
+ assert_ne!(stamped(response).0, Some("remote"), "{case}");
+ assert!(
+ !gateway
+ .dispatcher
+ .dispatched()
+ .iter()
+ .any(|work| work.bundle == REMOTE_LANE.2),
+ "{case}"
+ );
+ }
+
+ async fn detail_code(response: Response) -> serde_json::Value {
+ let body: serde_json::Value = serde_json::from_slice(
+ &axum::body::to_bytes(response.into_body(), 16384)
+ .await
+ .unwrap(),
+ )
+ .unwrap();
+ body["detail"]["code"].clone()
+ }
+
+ fn encode_request(model: &str, remote: &[&str]) -> Request {
+ let mut request = json_request(
+ &format!("/v1/encode/{model}"),
+ json!({"items": [{"text": "hello"}]}),
+ );
+ for value in remote {
+ request
+ .headers_mut()
+ .append(REMOTE_HEADER, HeaderValue::from_str(value).unwrap());
+ }
+ request
+ }
+
+ #[tokio::test]
+ async fn the_local_state_decides_the_bridge_as_the_shared_vectors_say() {
+ for vector in gateway_vectors("bridge") {
+ let case = vector.to_string();
+ let gateway =
+ gateway_in_local_state(vector["local"].as_str().unwrap(), &vector["triggers"])
+ .await;
+ let response = buffered_surface(&gateway, "native", json!({})).await;
+ if vector["remote"].as_bool().unwrap() {
+ assert_eq!(response.status(), StatusCode::OK, "{case}");
+ assert_eq!(
+ stamped(&response),
+ (Some("remote"), Some("team-sie")),
+ "{case}"
+ );
+ assert_eq!(
+ response.headers()["x-sie-fallback-reason"],
+ vector["fallback_reason"].as_str().unwrap(),
+ "{case}"
+ );
+ assert!(
+ gateway.dispatcher.dispatched().contains(&dispatched(
+ "generate",
+ REMOTE_LANE,
+ "acme/chat:remote"
+ )),
+ "{case}"
+ );
+ } else {
+ assert_kept_off_remote(&gateway, &response, &case);
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn a_remote_header_other_than_one_exact_forbid_is_refused_as_the_shared_vectors_say() {
+ let header = remote_routing_vectors()["remote_header"].clone();
+ let gateway = gateway_in_local_state("ready", &serde_json::Value::Null).await;
+ for remote in header["refused"].as_array().unwrap() {
+ let remote = header_values(remote);
+ let response = proxy_request(
+ State(Arc::clone(&gateway.state)),
+ encode_request("acme/hybrid-encode", &remote),
+ "encode",
+ )
+ .await;
+ assert_eq!(
+ response.status(),
+ vector_status(&header["refusal"]["status"]),
+ "{remote:?}"
+ );
+ assert_eq!(
+ detail_code(response).await,
+ header["refusal"]["code"],
+ "{remote:?}"
+ );
+ }
+ assert!(gateway.dispatcher.dispatched().is_empty());
+ for remote in header["accepted"].as_array().unwrap() {
+ let remote = header_values(remote);
+ let response = proxy_request(
+ State(Arc::clone(&gateway.state)),
+ encode_request("acme/hybrid-encode", &remote),
+ "encode",
+ )
+ .await;
+ assert_eq!(response.status(), StatusCode::OK, "{remote:?}");
+ assert_eq!(stamped(&response), (Some("local"), None), "{remote:?}");
+ }
+ }
+
+ #[tokio::test]
+ async fn forbid_follows_the_shared_vectors() {
+ for vector in gateway_vectors("forbid") {
+ let case = vector.to_string();
+ let state = vector["local"].as_str().unwrap_or("ready");
+ let gateway = gateway_in_local_state(state, &serde_json::Value::Null).await;
+ let model = match vector["model"].as_str().unwrap() {
+ "bare" => "acme/hybrid-encode",
+ "remote_profile" => "acme/hybrid-encode:remote",
+ "remote_only" => "acme/remote",
+ other => unreachable!("{other}"),
+ };
+ let response = proxy_request(
+ State(Arc::clone(&gateway.state)),
+ encode_request(model, &["forbid"]),
+ "encode",
+ )
+ .await;
+ assert_kept_off_remote(&gateway, &response, &case);
+ if let Some(refusal) = vector.get("refusal") {
+ assert_eq!(
+ response.status(),
+ vector_status(&refusal["status"]),
+ "{case}"
+ );
+ assert_eq!(detail_code(response).await, refusal["code"], "{case}");
+ assert!(gateway.dispatcher.dispatched().is_empty(), "{case}");
+ } else {
+ assert!(!vector["remote"].as_bool().unwrap(), "{case}");
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn a_named_profile_is_served_as_written_as_the_shared_vectors_say() {
+ for vector in gateway_vectors("named_profile") {
+ let case = vector.to_string();
+ let gateway =
+ gateway_in_local_state(vector["local"].as_str().unwrap(), &serde_json::Value::Null)
+ .await;
+ let response = match vector["model"].as_str().unwrap() {
+ "local_profile" => {
+ buffered_surface(&gateway, "native", json!({"profile": "default"})).await
+ }
+ "remote_profile" => {
+ proxy_chat(
+ State(Arc::clone(&gateway.state)),
+ json_request(
+ "/v1/chat/completions",
+ json!({"model": "acme/chat:remote", "messages": [{"role": "user", "content": "hello"}]}),
+ ),
+ )
+ .await
+ }
+ other => unreachable!("{other}"),
+ };
+ if vector["remote"].as_bool().unwrap() {
+ assert_eq!(response.status(), StatusCode::OK, "{case}");
+ assert_eq!(
+ stamped(&response),
+ (Some("remote"), Some("team-sie")),
+ "{case}"
+ );
+ assert!(
+ !response.headers().contains_key("x-sie-fallback-reason"),
+ "{case}"
+ );
+ } else {
+ assert_kept_off_remote(&gateway, &response, &case);
+ }
+ }
+ }
+
+ #[test]
+ fn the_fallback_error_is_derived_as_the_shared_vectors_say() {
+ for vector in gateway_vectors("fallback_error") {
+ let status = vector_status(&vector["status"]);
+ let code = vector["code"].as_str();
+ let expected = vector["fallback_error"].as_str().unwrap();
+ assert_eq!(fallback_error(status, code), expected, "{vector}");
+ for in_header in [false, true] {
+ let attempt = FallbackAttempt::default();
+ assert!(attempt.begin(
+ StatusCode::SERVICE_UNAVAILABLE.into_response(),
+ FallbackTrigger::ModelLoading
+ ));
+ let failed = match code {
+ Some(code) if in_header => {
+ let mut failed = status.into_response();
+ failed
+ .headers_mut()
+ .insert("x-sie-error-code", HeaderValue::from_str(code).unwrap());
+ failed
+ }
+ _ => (status, axum::Json(json!({"error": {"code": code}}))).into_response(),
+ };
+ let restored = attempt.finish(failed);
+ assert_eq!(
+ restored.headers()["x-sie-fallback-error"],
+ expected,
+ "{vector} in_header={in_header}"
+ );
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn the_restored_refusal_keeps_the_local_answer_as_the_shared_vectors_say() {
+ for vector in gateway_vectors("restored_refusal") {
+ let local = &vector["local"];
+ let mut original = (
+ vector_status(&local["status"]),
+ axum::Json(json!({"detail": {"code": local["code"], "message": "local refusal"}})),
+ )
+ .into_response();
+ if let Some(retry_after) = local["retry_after"].as_str() {
+ original
+ .headers_mut()
+ .insert("retry-after", HeaderValue::from_str(retry_after).unwrap());
+ }
+ let trigger: FallbackTrigger =
+ serde_json::from_value(vector["fallback_reason"].clone()).unwrap();
+ let attempt = FallbackAttempt::default();
+ assert!(attempt.begin(original, trigger));
+ let failed = match &vector["attempt"] {
+ serde_json::Value::String(kind) => {
+ assert_eq!(kind, "unanswered_before_deadline");
+ let mut failed = StatusCode::GATEWAY_TIMEOUT.into_response();
+ failed.extensions_mut().insert(UnansweredBeforeDeadline);
+ failed
+ }
+ attempt => {
+ let mut failed = vector_status(&attempt["status"]).into_response();
+ if let Some(code) = attempt["code"].as_str() {
+ failed
+ .headers_mut()
+ .insert("x-sie-error-code", HeaderValue::from_str(code).unwrap());
+ }
+ failed
+ }
+ };
+ let restored = attempt.finish(failed);
+ assert_eq!(
+ restored.status(),
+ vector_status(&local["status"]),
+ "{vector}"
+ );
+ assert_eq!(
+ restored
+ .headers()
+ .get("retry-after")
+ .map(|value| value.to_str().unwrap()),
+ local["retry_after"].as_str(),
+ "{vector}"
+ );
+ assert_eq!(stamped(&restored), (Some("local"), None), "{vector}");
+ assert_eq!(
+ restored.headers()["x-sie-fallback-reason"],
+ vector["fallback_reason"].as_str().unwrap(),
+ "{vector}"
+ );
+ assert_eq!(
+ restored.headers()["x-sie-fallback-error"],
+ vector["fallback_error"].as_str().unwrap(),
+ "{vector}"
+ );
+ assert_eq!(detail_code(restored).await, local["code"], "{vector}");
+ }
+ }
+
#[tokio::test]
async fn threshold_shared_decision_routes_remote_without_local_demand_then_wakes_and_bridges() {
use crate::handlers::test_support::ThresholdBroker;
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index 96652be45..8b080c9b2 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -163,9 +163,9 @@ is on unless disabled. Start with `--no-remote-serving` or set
values also disable it.
A caller can narrow that permission with `X-SIE-Remote: forbid`, or
-`SIEClient(..., remote="forbid")`. Other header values are rejected. A
-remote-backed model has no local alternative, so forbidding remote serving
-returns a client error.
+`SIEClient(..., remote="forbid")`. Other header values, and more than one
+`X-SIE-Remote` field, are rejected. A remote-backed model has no local
+alternative, so forbidding remote serving returns a client error.
On the gateway, `forbid` for a model with a `fallback` or `threshold` policy
selects only a fresh worker that advertises the versioned execution fence for
diff --git a/packages/sie_server/src/sie_server/api/routing.py b/packages/sie_server/src/sie_server/api/routing.py
index dba37947a..794c8d5ee 100644
--- a/packages/sie_server/src/sie_server/api/routing.py
+++ b/packages/sie_server/src/sie_server/api/routing.py
@@ -206,10 +206,10 @@ async def route_request(
def _remote_forbidden(request: Request) -> bool:
- value = request.headers.get(REMOTE_HEADER)
- if value is None:
+ values = request.headers.getlist(REMOTE_HEADER)
+ if not values:
return False
- if value == _FORBID:
+ if values == [_FORBID]:
return True
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
diff --git a/packages/sie_server/tests/api/test_remote_routing.py b/packages/sie_server/tests/api/test_remote_routing.py
index 2cd1b4878..2ab3da2d1 100644
--- a/packages/sie_server/tests/api/test_remote_routing.py
+++ b/packages/sie_server/tests/api/test_remote_routing.py
@@ -4,13 +4,19 @@ These tests call :func:`route_request` against a real registry. The local
profile is the fake adapter, held unloading, failed or with a full queue by
the fake's faults and the worker's own queue. The remote profile is never
called here: the decision and the local warm-up are what is under test.
+
+The vectors in ``wire-fixtures/remote_routing.json``, which the gateway checks
+too, drive the decision, ``X-SIE-Remote`` and the refusal that answers a failed
+remote attempt.
"""
from __future__ import annotations
import asyncio
+import json
import time
-from collections.abc import Callable, Iterator
+from collections.abc import AsyncIterator, Callable, Iterator
+from contextlib import asynccontextmanager
from pathlib import Path
from types import SimpleNamespace
from typing import Any
@@ -30,6 +36,14 @@ from sie_server.types.inputs import Item
SPAN = trace.INVALID_SPAN
TIMEOUT_S = 10.0
+VECTORS = json.loads(
+ (Path(__file__).resolve().parents[3] / "wire-fixtures" / "remote_routing.json").read_text(encoding="utf-8")
+)
+
+
+def single_node(vectors: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """The vectors that apply to a single server."""
+ return [vector for vector in vectors if "single_node" in vector.get("topologies", ["single_node"])]
def model_config(sie_id: str, *, faults: dict[str, Any] | None = None, triggers: list[str] | None = None) -> dict:
@@ -68,18 +82,81 @@ def registry_for(tmp_path: Path, *configs: dict, engine_config: EngineConfig | N
return ModelRegistry(models_dir=models, device="cpu", enable_hot_reload=False, engine_config=engine_config)
-def request_for(registry: ModelRegistry) -> Request:
+def request_for(registry: ModelRegistry, remote: list[str] | None = None) -> Request:
+ """A request whose ``X-SIE-Remote`` fields carry ``remote``, one field per value."""
return Request(
{
"type": "http",
"method": "POST",
"path": "/",
- "headers": [],
+ "headers": [(b"x-sie-remote", value.encode()) for value in remote or []],
"app": SimpleNamespace(state=SimpleNamespace(registry=registry)),
}
)
+REMOTE_ONLY = {
+ "sie_id": "acme/remote-only",
+ "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": "team-sie", "upstream_model": "sie-fake"}},
+ }
+ },
+}
+MODEL_NAMES = {
+ "bare": "acme/hybrid",
+ "local_profile": "acme/hybrid",
+ "remote_profile": "acme/hybrid:remote",
+ "remote_only": "acme/remote-only",
+}
+
+
+@asynccontextmanager
+async def in_local_state(tmp_path: Path, state: str, triggers: list[str] | None = None) -> AsyncIterator[ModelRegistry]:
+ """A registry whose ``acme/hybrid`` local profile is in the abstract local ``state`` of the vectors.
+
+ ``saturated`` holds the one slot of the local worker, so a request that
+ adds one item finds the queue full.
+ """
+ latch = tmp_path / "release-local-load"
+ faults = {"fail_load": True} if state == "unhealthy" else {"load_latch_file": str(latch)}
+ registry = registry_for(
+ tmp_path,
+ model_config("acme/hybrid", faults=faults, triggers=triggers),
+ REMOTE_ONLY,
+ engine_config=EngineConfig(max_concurrent_requests=1) if state == "saturated" else None,
+ )
+ held = []
+ try:
+ if state in {"ready", "saturated"}:
+ latch.touch()
+ await registry.load_async("acme/hybrid", device="cpu")
+ if state == "saturated":
+ worker = await registry.start_worker("acme/hybrid")
+ held.append(await worker.submit([make_text_item([1, 2], 0)], [Item(text="held")], ["dense"]))
+ if state == "loading":
+ await registry.start_load_async("acme/hybrid", device="cpu")
+ await wait_until(lambda: registry.is_loading("acme/hybrid"))
+ if state == "unhealthy":
+ await registry.start_load_async("acme/hybrid", device="cpu")
+ await wait_until(lambda: registry.is_failed("acme/hybrid"))
+ yield registry
+ finally:
+ latch.touch()
+ await asyncio.wait_for(asyncio.gather(*held), TIMEOUT_S)
+ await wait_until(lambda: not registry.is_loading("acme/hybrid"))
+ await registry.unload_all_async()
+
+
+def fallback_headers(error: HTTPException) -> dict[str, str]:
+ return {name: value for name, value in (error.headers or {}).items() if name.startswith("X-SIE-Fallback")}
+
+
async def wait_until(predicate: Callable[[], bool], timeout_s: float = TIMEOUT_S) -> None:
deadline = time.monotonic() + timeout_s
while not predicate():
@@ -218,27 +295,13 @@ LOCAL_REFUSAL = HTTPException(
)
- ("status_code", "code", "fallback_error"),
- [
- (503, "QUEUE_FULL", "QUEUE_FULL"),
- (503, "MODEL_LOADING", "MODEL_LOADING"),
- (503, "server_overloaded", "QUEUE_FULL"),
- (500, "inference_error", "INFERENCE_ERROR"),
- (400, "INPUT_TOO_LONG", "INPUT_TOO_LONG"),
- (400, "invalid_request", "INVALID_INPUT"),
- (502, "transport_failure", "INFERENCE_ERROR"),
- (422, None, "INVALID_INPUT"),
- ],
-)
-def test_a_failed_bridged_attempt_is_answered_with_the_local_refusal(
- status_code: int, code: str | None, fallback_error: str
-) -> None:
[email protected]("vector", single_node(VECTORS["fallback_error"]), ids=lambda vector: str(vector["code"]))
+def test_a_failed_bridged_attempt_is_answered_with_the_local_refusal(vector: dict[str, Any]) -> None:
route = ServingRoute(
key="acme/hybrid:remote", upstream="team-sie", fallback_reason="model_loading", local_refusal=LOCAL_REFUSAL
)
- refusal = route.refusal_after(status_code, code)
+ refusal = route.refusal_after(vector["status"], vector["code"])
assert refusal is not None
assert refusal.status_code == 503
@@ -247,10 +310,124 @@ def test_a_failed_bridged_attempt_is_answered_with_the_local_refusal(
"Retry-After": "5",
"X-SIE-Served-By": "local",
"X-SIE-Fallback-Reason": "model_loading",
- "X-SIE-Fallback-Error": fallback_error,
+ "X-SIE-Fallback-Error": vector["fallback_error"],
}
+ "vector", single_node(VECTORS["restored_refusal"]), ids=lambda vector: vector["fallback_reason"]
+)
+def test_the_restored_refusal_keeps_the_local_answer_and_names_both_outcomes(vector: dict[str, Any]) -> None:
+ local = vector["local"]
+ retry = {"Retry-After": local["retry_after"]} if local["retry_after"] is not None else {}
+ route = ServingRoute(
+ key="acme/hybrid:remote",
+ upstream="team-sie",
+ fallback_reason=vector["fallback_reason"],
+ local_refusal=HTTPException(
+ status_code=local["status"],
+ detail={"code": local["code"], "message": "local refusal"},
+ headers=retry or None,
+ ),
+ )
+
+ refusal = route.refusal_after(vector["attempt"]["status"], vector["attempt"]["code"])
+
+ assert refusal is not None
+ assert refusal.status_code == local["status"]
+ assert refusal.detail == {"code": local["code"], "message": "local refusal"}
+ assert refusal.headers == {
+ **retry,
+ "X-SIE-Served-By": "local",
+ "X-SIE-Fallback-Reason": vector["fallback_reason"],
+ "X-SIE-Fallback-Error": vector["fallback_error"],
+ }
+
+
+ "vector",
+ single_node(VECTORS["bridge"]),
+ ids=lambda vector: f"{vector['local']}-{'+'.join(vector['triggers'] or ['default'])}",
+)
+async def test_the_local_state_decides_the_bridge_as_the_shared_vectors_say(
+ tmp_path: Path, vector: dict[str, Any]
+) -> None:
+ refusal = None
+ async with in_local_state(tmp_path, vector["local"], vector["triggers"]) as registry:
+ try:
+ route = await route_request(request_for(registry), "acme/hybrid", SPAN, queued_items=1)
+ except HTTPException as error:
+ route, refusal = None, error
+
+ if refusal is not None:
+ assert fallback_headers(refusal) == {}
+ if vector["remote"]:
+ assert route is not None
+ assert route.key == "acme/hybrid:remote"
+ assert route.upstream == "team-sie"
+ assert route.fallback_reason == vector["fallback_reason"]
+ else:
+ assert route in (None, ServingRoute(key="acme/hybrid"))
+
+
[email protected]("remote", VECTORS["remote_header"]["refused"], ids=repr)
+async def test_a_remote_header_other_than_one_exact_forbid_is_refused(tmp_path: Path, remote: list[str]) -> None:
+ async with in_local_state(tmp_path, "ready") as registry:
+ with pytest.raises(HTTPException) as refused:
+ await route_request(request_for(registry, remote), "acme/hybrid", SPAN)
+
+ assert refused.value.status_code == VECTORS["remote_header"]["refusal"]["status"]
+ assert refused.value.detail["code"] == VECTORS["remote_header"]["refusal"]["code"]
+
+
[email protected]("remote", VECTORS["remote_header"]["accepted"], ids=repr)
+async def test_one_exact_forbid_keeps_a_ready_model_local(tmp_path: Path, remote: list[str]) -> None:
+ async with in_local_state(tmp_path, "ready") as registry:
+ route = await route_request(request_for(registry, remote), "acme/hybrid", SPAN)
+
+ assert route == ServingRoute(key="acme/hybrid")
+
+
[email protected]("vector", single_node(VECTORS["forbid"]), ids=lambda vector: vector["model"])
+async def test_forbid_follows_the_shared_vectors(tmp_path: Path, vector: dict[str, Any]) -> None:
+ refusal = None
+ async with in_local_state(tmp_path, vector.get("local", "ready")) as registry:
+ try:
+ route = await route_request(request_for(registry, ["forbid"]), MODEL_NAMES[vector["model"]], SPAN)
+ except HTTPException as error:
+ route, refusal = None, error
+ remote_loaded = registry.is_loaded("acme/hybrid:remote") or registry.is_loaded("acme/remote-only")
+
+ assert not remote_loaded
+ if refusal is not None:
+ assert fallback_headers(refusal) == {}
+ if "refusal" in vector:
+ assert refusal is not None
+ assert refusal.status_code == vector["refusal"]["status"]
+ assert refusal.detail["code"] == vector["refusal"]["code"]
+ else:
+ assert not vector["remote"]
+ assert route in (None, ServingRoute(key="acme/hybrid"))
+
+
[email protected]("vector", single_node(VECTORS["named_profile"]), ids=lambda vector: vector["model"])
+async def test_a_named_profile_is_served_as_written(tmp_path: Path, vector: dict[str, Any]) -> None:
+ profile = "default" if vector["model"] == "local_profile" else None
+ refusal = None
+ async with in_local_state(tmp_path, vector["local"]) as registry:
+ try:
+ route = await route_request(request_for(registry), MODEL_NAMES[vector["model"]], SPAN, profile=profile)
+ except HTTPException as error:
+ route, refusal = None, error
+
+ if refusal is not None:
+ assert fallback_headers(refusal) == {}
+ if vector["remote"]:
+ assert route == ServingRoute(key="acme/hybrid:remote", upstream="team-sie")
+ else:
+ assert route is None
+
+
def test_a_route_that_was_not_bridged_replaces_no_error() -> None:
assert ServingRoute(key="acme/hybrid").refusal_after(500, "INFERENCE_ERROR") is None
assert ServingRoute(key="acme/remote-only", upstream="team-sie").refusal_after(503, "QUEUE_FULL") is None
diff --git a/packages/wire-fixtures/README.md b/packages/wire-fixtures/README.md
index 6948c3649..0002c5fcc 100644
--- a/packages/wire-fixtures/README.md
+++ b/packages/wire-fixtures/README.md
@@ -24,6 +24,12 @@ executable.
The gateway writes `prefix/plain_key`, the queue retains `plain_key`, and the
sidecar accepts that key or the exact `full_reference`; Python and both Rust
binaries load the same fixture to prevent prefix drift.
+- `remote_routing.json` — remote routing of a model with a local and a remote
+ profile, checked by the single server and the gateway: which abstract local
+ states send a request for the bare model name to the remote profile, what
+ `X-SIE-Remote` accepts and refuses, how a named profile is served, the
+ `X-SIE-Fallback-Error` each failed attempt's status and error code yields,
+ and the local refusal that answers a failed remote attempt.
- `retry_classification.json` — how the SDKs classify a non-2xx response to a
buffered call: `retry` or `terminal` for the idempotent operations (encode,
score, extract) and for generation, keyed by status, error code, and whether
@@ -80,11 +86,16 @@ fixture set. Current consumers:
client).
- Gateway — `packages/sie_gateway/src/handlers/serving_disclosure.rs`
(asserts that the `X-SIE-Served-By` and `X-SIE-Upstream` names and the
- served-by values it emits are the ones `serving_disclosure.json` declares).
+ served-by values it emits are the ones `serving_disclosure.json` declares,
+ and checks every gateway vector of `remote_routing.json` through its
+ handlers and its fallback refusal).
- Server — `packages/sie_server/tests/adapters/test_remote_fallback.py` (each
disclosure header the single server sends on a response served locally,
remotely or through a bridge, and on the local refusal that answers a failed
- remote attempt, has a value or pattern `serving_disclosure.json` declares).
+ remote attempt, has a value or pattern `serving_disclosure.json` declares),
+ and `packages/sie_server/tests/api/test_remote_routing.py` (checks every
+ single-server vector of `remote_routing.json` through the routing decision
+ and the refusal that answers a failed remote attempt).
- Worker sidecar — `packages/sie_server_sidecar/src/health_publisher.rs`
(the published key set equals `fields`, minus `omitted_when_empty` when those
are empty) and gateway — `packages/sie_gateway/src/types/worker.rs` (the
diff --git a/packages/wire-fixtures/remote_routing.json b/packages/wire-fixtures/remote_routing.json
new file mode 100644
index 000000000..6130ce810
--- /dev/null
+++ b/packages/wire-fixtures/remote_routing.json
@@ -0,0 +1,113 @@
+{
+ "description": "Remote routing of a model that has a local profile and a remote profile: which local states send a request for the model's bare name to the remote profile, what X-SIE-Remote changes, and how the local refusal answers a failed remote attempt. A single server ('single_node') and a gateway ('gateway') each check every vector, mapping the abstract local states and models below to their own topology. A vector that lists 'topologies' applies only to those.",
+ "local_states": {
+ "ready": "The local profile can serve the request now.",
+ "loading": "The local profile is not loaded. A single server is loading it; a gateway has a local worker that has not loaded it.",
+ "no_worker": "No local worker exists. Only a gateway has this state.",
+ "saturated": "The local queue cannot take the request.",
+ "unhealthy": "The local profile cannot serve. On a single server its load failed; on a gateway its worker is unhealthy."
+ },
+ "models": {
+ "bare": "The bare name of a model whose routing policy is fallback, with fallback_profile remote.",
+ "local_profile": "The same model with its local profile named explicitly.",
+ "remote_profile": "The same model with its remote profile named explicitly.",
+ "remote_only": "A model served only by an upstream."
+ },
+ "bridge": [
+ {"local": "ready", "triggers": null, "remote": false},
+ {"local": "loading", "triggers": null, "remote": true, "fallback_reason": "model_loading"},
+ {"local": "loading", "triggers": ["saturated"], "remote": false},
+ {"local": "no_worker", "triggers": null, "remote": true, "fallback_reason": "provisioning", "topologies": ["gateway"]},
+ {"local": "no_worker", "triggers": ["model_loading"], "remote": false, "topologies": ["gateway"]},
+ {"local": "saturated", "triggers": null, "remote": false},
+ {"local": "saturated", "triggers": ["saturated"], "remote": true, "fallback_reason": "saturated"},
+ {"local": "unhealthy", "triggers": null, "remote": false},
+ {"local": "unhealthy", "triggers": ["unhealthy"], "remote": true, "fallback_reason": "unhealthy"}
+ ],
+ "remote_header": {
+ "accepted": [["forbid"]],
+ "refused": [["Forbid"], ["FORBID"], ["allow"], [""], ["forbid,forbid"], ["forbid, forbid"], ["forbid", "forbid"]],
+ "refusal": {"status": 400, "code": "INVALID_INPUT"}
+ },
+ "forbid": [
+ {"model": "bare", "local": "loading", "remote": false},
+ {"model": "remote_profile", "refusal": {"status": 400, "code": "INVALID_INPUT"}},
+ {"model": "remote_only", "refusal": {"status": 400, "code": "INVALID_INPUT"}}
+ ],
+ "named_profile": [
+ {"model": "local_profile", "local": "loading", "remote": false},
+ {"model": "remote_profile", "local": "loading", "remote": true, "fallback_reason": null}
+ ],
+ "fallback_error": [
+ {"status": 400, "code": "INVALID_INPUT", "fallback_error": "INVALID_INPUT"},
+ {"status": 404, "code": "MODEL_NOT_FOUND", "fallback_error": "MODEL_NOT_FOUND"},
+ {"status": 503, "code": "MODEL_NOT_LOADED", "fallback_error": "MODEL_NOT_LOADED"},
+ {"status": 503, "code": "LORA_LOADING", "fallback_error": "LORA_LOADING"},
+ {"status": 503, "code": "MODEL_LOADING", "fallback_error": "MODEL_LOADING"},
+ {"status": 502, "code": "MODEL_LOAD_FAILED", "fallback_error": "MODEL_LOAD_FAILED"},
+ {"status": 500, "code": "INFERENCE_ERROR", "fallback_error": "INFERENCE_ERROR"},
+ {"status": 503, "code": "QUEUE_FULL", "fallback_error": "QUEUE_FULL"},
+ {"status": 500, "code": "INTERNAL_ERROR", "fallback_error": "INTERNAL_ERROR"},
+ {"status": 503, "code": "RESOURCE_EXHAUSTED", "fallback_error": "RESOURCE_EXHAUSTED"},
+ {"status": 400, "code": "INPUT_TOO_LONG", "fallback_error": "INPUT_TOO_LONG"},
+ {"status": 503, "code": "queue_full", "fallback_error": "QUEUE_FULL"},
+ {"status": 500, "code": "inference_error", "fallback_error": "INFERENCE_ERROR"},
+ {"status": 400, "code": "Input_Too_Long", "fallback_error": "INPUT_TOO_LONG"},
+ {"status": 503, "code": "server_overloaded", "fallback_error": "QUEUE_FULL"},
+ {"status": 400, "code": "invalid_request", "fallback_error": "INVALID_INPUT"},
+ {"status": 503, "code": "SERVER_OVERLOADED", "fallback_error": "INFERENCE_ERROR"},
+ {"status": 503, "code": "INVALID_REQUEST", "fallback_error": "INFERENCE_ERROR"},
+ {"status": 504, "code": "first_chunk_timeout", "fallback_error": "INFERENCE_ERROR"},
+ {"status": 504, "code": "overall_timeout", "fallback_error": "INFERENCE_ERROR"},
+ {"status": 504, "code": "GATEWAY_TIMEOUT", "fallback_error": "INFERENCE_ERROR"},
+ {"status": 503, "code": "PROVISIONING", "fallback_error": "INFERENCE_ERROR"},
+ {"status": 503, "code": "transport_failure", "fallback_error": "INFERENCE_ERROR"},
+ {"status": 413, "code": "PAYLOAD_TOO_LARGE", "fallback_error": "INVALID_INPUT"},
+ {"status": 429, "code": "rate_limit_exceeded", "fallback_error": "INVALID_INPUT"},
+ {"status": 502, "code": null, "fallback_error": "INFERENCE_ERROR"},
+ {"status": 500, "code": null, "fallback_error": "INFERENCE_ERROR"},
+ {"status": 422, "code": null, "fallback_error": "INVALID_INPUT"}
+ ],
+ "restored_refusal": [
+ {
+ "local": {"status": 503, "code": "MODEL_LOADING", "retry_after": "5"},
+ "fallback_reason": "model_loading",
+ "attempt": {"status": 503, "code": "RESOURCE_EXHAUSTED"},
+ "fallback_error": "RESOURCE_EXHAUSTED"
+ },
+ {
+ "local": {"status": 503, "code": "QUEUE_FULL", "retry_after": "1"},
+ "fallback_reason": "saturated",
+ "attempt": {"status": 400, "code": "INPUT_TOO_LONG"},
+ "fallback_error": "INPUT_TOO_LONG"
+ },
+ {
+ "local": {"status": 502, "code": "MODEL_LOAD_FAILED", "retry_after": null},
+ "fallback_reason": "unhealthy",
+ "attempt": {"status": 502, "code": null},
+ "fallback_error": "INFERENCE_ERROR"
+ },
+ {
+ "local": {"status": 503, "code": "PROVISIONING", "retry_after": "60"},
+ "fallback_reason": "provisioning",
+ "attempt": {"status": 503, "code": "QUEUE_FULL"},
+ "fallback_error": "QUEUE_FULL",
+ "topologies": ["gateway"]
+ },
+ {
+ "local": {"status": 503, "code": "MODEL_LOADING", "retry_after": "5"},
+ "fallback_reason": "model_loading",
+ "attempt": "unanswered_before_deadline",
+ "fallback_error": "QUEUE_FULL",
+ "topologies": ["gateway"]
+ }
+ ],
+ "notes": {
+ "bridge": "remote true: the request is served by the remote profile and the response names fallback_reason in X-SIE-Fallback-Reason. remote false: the request is served or refused locally and carries no X-SIE-Fallback-* header. triggers null means the policy declares none, which enables provisioning and model_loading.",
+ "remote_header": "Each entry lists the X-SIE-Remote field values of one request. Only exactly one 'forbid' is accepted.",
+ "forbid": "With X-SIE-Remote: forbid. remote false: served or refused locally, never by an upstream, with no X-SIE-Fallback-* header.",
+ "named_profile": "A request that names a profile is served as written: the local profile never goes remote, and the remote profile is served remotely without a fallback reason.",
+ "fallback_error": "X-SIE-Fallback-Error for a failed remote attempt that answered with status and SIE error code (null: no code). An SIE error code passes through in any letter case, server_overloaded and invalid_request (exactly) become QUEUE_FULL and INVALID_INPUT, and otherwise a status from 500 is INFERENCE_ERROR and a lower one INVALID_INPUT.",
+ "restored_refusal": "A failed remote attempt is answered with the local refusal it replaced: the same status, code and Retry-After (null: none), X-SIE-Served-By: local, no X-SIE-Upstream, and X-SIE-Fallback-Reason and X-SIE-Fallback-Error set. unanswered_before_deadline: a gateway deadline passed before the remote attempt answered anything."
+ }
+}