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(sdk): forbid remote serving and report which side served (#495)

Krisztian Gajdar17ce8b48bab9
diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.py
index 709960952..d72537461 100644
--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py
+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py
@@ -622,6 +622,15 @@ EXECUTION_IDENTITY_SHA256_HEADER = "X-SIE-Execution-Identity-SHA256"
EXECUTION_BINDING_SHA256_HEADER = "X-SIE-Execution-Binding-SHA256"
REQUEST_ID_HEADER = "X-SIE-Request-ID"
CREDITS_DEBITED_HEADER = "X-SIE-Credits-Debited"
+REMOTE_HEADER = "X-SIE-Remote"
+SERVED_BY_HEADER = "X-SIE-Served-By"
+UPSTREAM_HEADER = "X-SIE-Upstream"
+FALLBACK_REASON_HEADER = "X-SIE-Fallback-Reason"
+FALLBACK_ERROR_HEADER = "X-SIE-Fallback-Error"
+SERVED_BY_VALUES = frozenset({"local", "remote"})
+FALLBACK_REASONS = frozenset({"provisioning", "model_loading", "saturated", "unhealthy"})
+UPSTREAM_NAME_PATTERN = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")
+FALLBACK_ERROR_PATTERN = re.compile(r"^[A-Za-z][A-Za-z0-9_]{0,63}$")
REQUEST_USAGE_HEADERS = {
"input_tokens": "X-SIE-Units-Input-Tokens",
"pairs": "X-SIE-Units-Pairs",
@@ -1063,6 +1072,19 @@ def parse_request_metadata(headers: Any, body: Any = None) -> RequestMetadata |
):
metadata["execution_binding_sha256"] = execution_binding_sha256
+ served_by = _header_value(headers, SERVED_BY_HEADER)
+ if isinstance(served_by, str) and served_by in SERVED_BY_VALUES:
+ metadata["served_by"] = served_by
+ upstream = _header_value(headers, UPSTREAM_HEADER)
+ if isinstance(upstream, str) and UPSTREAM_NAME_PATTERN.fullmatch(upstream):
+ metadata["upstream"] = upstream
+ fallback_reason = _header_value(headers, FALLBACK_REASON_HEADER)
+ if isinstance(fallback_reason, str) and fallback_reason in FALLBACK_REASONS:
+ metadata["fallback_reason"] = fallback_reason
+ fallback_error = _header_value(headers, FALLBACK_ERROR_HEADER)
+ if isinstance(fallback_error, str) and FALLBACK_ERROR_PATTERN.fullmatch(fallback_error):
+ metadata["fallback_error"] = fallback_error
+
return metadata or None
diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.py
index b10049966..a4a20d53f 100644
--- a/packages/sie_sdk/src/sie_sdk/client/async_.py
+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py
@@ -115,6 +115,7 @@ from ._shared import (
MSGPACK_CONTENT_TYPE,
PROVISIONING_ERROR_CODE,
RECOMMEND_PATH,
+ REMOTE_HEADER,
REQUEST_ID_HEADER,
RESOURCE_EXHAUSTED_ERROR_CODE,
RESOURCE_EXHAUSTED_MAX_RETRIES,
@@ -449,6 +450,12 @@ class SIEAsyncClient:
sent (default: 150, longer than the gateway's default 120 s
request deadline). A read timeout is never retried, because the
server may still be processing the request.
+ remote: ``"forbid"`` sends ``X-SIE-Remote: forbid`` with every request, so
+ no request is served through a remote upstream. A model served
+ locally answers from local capacity, including ``503 MODEL_LOADING``
+ while it loads, and a model served only remotely answers ``400``.
+ ``None`` (default) leaves the choice to the model's routing policy.
+ The setting applies to every call made with this client.
Example:
>>> async with SIEAsyncClient("http://localhost:8080") as client:
@@ -490,6 +497,7 @@ class SIEAsyncClient:
base_url_headers: Mapping[str, str] | None = None,
connect_timeout_s: float | None = None,
read_timeout_s: float | None = None,
+ remote: Literal["forbid"] | None = None,
) -> None:
base_url = resolve_base_url(base_url)
api_key = resolve_api_key(api_key, base_url, control_plane_url)
@@ -532,6 +540,11 @@ class SIEAsyncClient:
}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
+ if remote is not None:
+ if remote != "forbid":
+ msg = "remote must be 'forbid' or None"
+ raise ValueError(msg)
+ headers[REMOTE_HEADER] = remote
self._headers = headers.copy()
diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.py
index dcdd15e46..0f884581a 100644
--- a/packages/sie_sdk/src/sie_sdk/client/sync.py
+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py
@@ -124,6 +124,7 @@ from ._shared import (
MSGPACK_CONTENT_TYPE,
PROVISIONING_ERROR_CODE,
RECOMMEND_PATH,
+ REMOTE_HEADER,
REQUEST_ID_HEADER,
RESOURCE_EXHAUSTED_ERROR_CODE,
RESOURCE_EXHAUSTED_MAX_RETRIES,
@@ -421,6 +422,12 @@ class SIEClient:
sent (default: 150, longer than the gateway's default 120 s
request deadline). A read timeout is never retried, because the
server may still be processing the request.
+ remote: ``"forbid"`` sends ``X-SIE-Remote: forbid`` with every request, so
+ no request is served through a remote upstream. A model served
+ locally answers from local capacity, including ``503 MODEL_LOADING``
+ while it loads, and a model served only remotely answers ``400``.
+ ``None`` (default) leaves the choice to the model's routing policy.
+ The setting applies to every call made with this client.
Example:
>>> client = SIEClient("http://localhost:8080")
@@ -461,6 +468,7 @@ class SIEClient:
base_url_headers: Mapping[str, str] | None = None,
connect_timeout_s: float | None = None,
read_timeout_s: float | None = None,
+ remote: Literal["forbid"] | None = None,
) -> None:
base_url = resolve_base_url(base_url)
api_key = resolve_api_key(api_key, base_url, control_plane_url)
@@ -508,6 +516,11 @@ class SIEClient:
}
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
+ if remote is not None:
+ if remote != "forbid":
+ msg = "remote must be 'forbid' or None"
+ raise ValueError(msg)
+ headers[REMOTE_HEADER] = remote
self._headers = headers.copy()
diff --git a/packages/sie_sdk/src/sie_sdk/types.py b/packages/sie_sdk/src/sie_sdk/types.py
index b4c38c72e..14669b494 100644
--- a/packages/sie_sdk/src/sie_sdk/types.py
+++ b/packages/sie_sdk/src/sie_sdk/types.py
@@ -225,6 +225,17 @@ class RequestMetadata(TypedDict, total=False):
rate_book_version: str
execution_identity_sha256: str
execution_binding_sha256: str
+ #: Which side served the request: ``"local"`` capacity, or a ``"remote"``
+ #: upstream, named in ``upstream``.
+ served_by: Literal["local", "remote"]
+ #: The upstream that served the request, when ``served_by`` is ``"remote"``.
+ upstream: str
+ #: Why a request for the bare model name was served remotely instead of by
+ #: local capacity.
+ fallback_reason: Literal["provisioning", "model_loading", "saturated", "unhealthy"]
+ #: Error code of a remote attempt that failed. The response is then the
+ #: local refusal that the remote attempt was meant to replace.
+ fallback_error: str
class EncodeResult(TypedDict, total=False):
diff --git a/packages/sie_sdk/tests/client/test_remote_serving.py b/packages/sie_sdk/tests/client/test_remote_serving.py
new file mode 100644
index 000000000..dcc658076
--- /dev/null
+++ b/packages/sie_sdk/tests/client/test_remote_serving.py
@@ -0,0 +1,196 @@
+"""Forbidding remote serving, and reading which side served, through the real clients.
+
+Both clients talk to a local HTTP server that records each request's headers and
+answers with the serving disclosure headers, so the option and the parsing run
+through the production transport. The header contract is shared with the
+TypeScript SDK through ``packages/wire-fixtures/serving_disclosure.json``.
+"""
+
+from __future__ import annotations
+
+import json
+import threading
+from collections.abc import Iterator
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from typing import Any
+
+import httpx
+import msgpack
+import numpy as np
+import pytest
+from sie_sdk import SIEAsyncClient, SIEClient, SIEError
+from sie_sdk.client._shared import handle_error, parse_request_metadata
+
+_OPERATIONS = ("encode", "generate", "chat_completions")
+_SERVED_REMOTELY = {
+ "X-SIE-Served-By": "remote",
+ "X-SIE-Upstream": "team-sie",
+ "X-SIE-Fallback-Reason": "model_loading",
+}
+
+
+class _RecordingServer:
+ """Answers every POST with one success body plus ``reply_headers``, recording request headers."""
+
+ def __init__(self) -> None:
+ self.reply_headers: dict[str, str] = {}
+ self.request_headers: list[dict[str, str]] = []
+ server = self
+
+ class _Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+
+ def do_POST(self) -> None:
+ self.rfile.read(int(self.headers.get("Content-Length") or 0))
+ server.request_headers.append({name.lower(): value for name, value in self.headers.items()})
+ content_type, body = _success_body(self.path)
+ self.send_response(200)
+ self.send_header("Content-Type", content_type)
+ for name, value in server.reply_headers.items():
+ self.send_header(name, value)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, format: str, *args: Any) -> None:
+ return None
+
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ self._server.daemon_threads = True
+ self._thread = threading.Thread(target=self._server.serve_forever, args=(0.01,), daemon=True)
+ self._thread.start()
+
+ @property
+ def url(self) -> str:
+ host, port = self._server.server_address[:2]
+ return f"http://{host!s}:{port}"
+
+ def close(self) -> None:
+ self._server.shutdown()
+ self._server.server_close()
+
+
+def _success_body(path: str) -> tuple[str, bytes]:
+ if path.startswith("/v1/encode/"):
+ items = [{"id": "a", "dense": {"dims": 4, "values": np.zeros(4, dtype=np.float32)}}]
+ return "application/msgpack", msgpack.packb({"model": "m", "items": items}, use_bin_type=True)
+ if path.startswith("/v1/generate/"):
+ return "application/json", json.dumps({"model": "m", "text": "ok"}).encode()
+ return "application/json", json.dumps(
+ {"id": "c", "object": "chat.completion", "model": "m", "choices": []}
+ ).encode()
+
+
+def server() -> Iterator[_RecordingServer]:
+ recording = _RecordingServer()
+ try:
+ yield recording
+ finally:
+ recording.close()
+
+
+def _request_metadata(result: Any) -> dict[str, Any]:
+ first = result[0] if isinstance(result, list) else result
+ return first["request"]
+
+
+def _call_sync(client: SIEClient, operation: str) -> Any:
+ if operation == "encode":
+ return client.encode("m", {"id": "a", "text": "hi"})
+ if operation == "generate":
+ return client.generate("m", "hi", max_new_tokens=4)
+ return client.chat_completions("m", [{"role": "user", "content": "hi"}])
+
+
+async def _call_async(client: SIEAsyncClient, operation: str) -> Any:
+ if operation == "encode":
+ return await client.encode("m", {"id": "a", "text": "hi"})
+ if operation == "generate":
+ return await client.generate("m", "hi", max_new_tokens=4)
+ return await client.chat_completions("m", [{"role": "user", "content": "hi"}])
+
+
[email protected]("operation", _OPERATIONS)
+def test_a_forbidding_sync_client_sends_the_header_and_reads_the_serving_side(
+ server: _RecordingServer, operation: str
+) -> None:
+ server.reply_headers = {"X-SIE-Served-By": "local"}
+ with SIEClient(server.url, remote="forbid") as client:
+ result = _call_sync(client, operation)
+
+ assert server.request_headers[0]["x-sie-remote"] == "forbid"
+ assert _request_metadata(result)["served_by"] == "local"
+
+
[email protected]("operation", _OPERATIONS)
+async def test_a_forbidding_async_client_sends_the_header_and_reads_the_serving_side(
+ server: _RecordingServer, operation: str
+) -> None:
+ server.reply_headers = {"X-SIE-Served-By": "local"}
+ async with SIEAsyncClient(server.url, remote="forbid") as client:
+ result = await _call_async(client, operation)
+
+ assert server.request_headers[0]["x-sie-remote"] == "forbid"
+ assert _request_metadata(result)["served_by"] == "local"
+
+
+async def test_a_default_client_leaves_the_choice_to_the_server(server: _RecordingServer) -> None:
+ with SIEClient(server.url) as client:
+ client.encode("m", {"id": "a", "text": "hi"})
+ async with SIEAsyncClient(server.url) as async_client:
+ await async_client.encode("m", {"id": "a", "text": "hi"})
+
+ assert [headers.get("x-sie-remote") for headers in server.request_headers] == [None, None]
+
+
[email protected]("operation", _OPERATIONS)
+def test_a_remotely_served_result_names_the_upstream_and_the_reason(server: _RecordingServer, operation: str) -> None:
+ server.reply_headers = dict(_SERVED_REMOTELY)
+ with SIEClient(server.url) as client:
+ result = _call_sync(client, operation)
+
+ request = _request_metadata(result)
+ assert request["served_by"] == "remote"
+ assert request["upstream"] == "team-sie"
+ assert request["fallback_reason"] == "model_loading"
+
+
[email protected]("client_class", [SIEClient, SIEAsyncClient])
+def test_only_forbid_is_accepted(client_class: type[SIEClient | SIEAsyncClient]) -> None:
+ with pytest.raises(ValueError, match="remote must be 'forbid' or None"):
+ client_class("http://127.0.0.1:9", remote="allow") # type: ignore[arg-type]
+
+
+def test_a_local_refusal_after_a_failed_remote_attempt_carries_both_outcomes() -> None:
+ response = httpx.Response(
+ 503,
+ headers={
+ "Retry-After": "5",
+ "X-SIE-Fallback-Reason": "model_loading",
+ "X-SIE-Fallback-Error": "INFERENCE_ERROR",
+ },
+ json={"detail": {"code": "MODEL_LOADING", "message": "Model 'm' is loading, please retry"}},
+ )
+
+ with pytest.raises(SIEError) as raised:
+ handle_error(response)
+
+ assert raised.value.request == {"fallback_reason": "model_loading", "fallback_error": "INFERENCE_ERROR"}
+
+
+ ("header", "value"),
+ [
+ ("X-SIE-Served-By", "elsewhere"),
+ ("X-SIE-Served-By", "Remote"),
+ ("X-SIE-Upstream", "Team_SIE"),
+ ("X-SIE-Upstream", "-team"),
+ ("X-SIE-Upstream", "a" * 64),
+ ("X-SIE-Fallback-Reason", "sometimes"),
+ ("X-SIE-Fallback-Error", "not a code"),
+ ("X-SIE-Fallback-Error", "1CODE"),
+ ],
+)
+def test_a_disclosure_value_outside_its_contract_is_dropped(header: str, value: str) -> None:
+ assert parse_request_metadata({header: value}) is None
diff --git a/packages/sie_sdk/tests/test_wire_contract.py b/packages/sie_sdk/tests/test_wire_contract.py
index c40c150d5..054952301 100644
--- a/packages/sie_sdk/tests/test_wire_contract.py
+++ b/packages/sie_sdk/tests/test_wire_contract.py
@@ -9,15 +9,28 @@ from __future__ import annotations
import json
from pathlib import Path
-from typing import get_args
-
-from sie_sdk.client._shared import REQUEST_USAGE_HEADERS, parse_extract_results
+from typing import get_args, get_type_hints
+
+from sie_sdk.client._shared import (
+ FALLBACK_ERROR_HEADER,
+ FALLBACK_ERROR_PATTERN,
+ FALLBACK_REASON_HEADER,
+ FALLBACK_REASONS,
+ REMOTE_HEADER,
+ REQUEST_USAGE_HEADERS,
+ SERVED_BY_HEADER,
+ SERVED_BY_VALUES,
+ UPSTREAM_HEADER,
+ UPSTREAM_NAME_PATTERN,
+ parse_extract_results,
+)
from sie_sdk.types import (
DECLARED_USAGE_FIELDS,
SETTLED_CHARGE_FIELDS,
TERMINAL_UNIT_FIELDS,
ModelInfo,
ModelState,
+ RequestMetadata,
RequestUsage,
)
@@ -123,3 +136,23 @@ def test_extract_parser_preserves_malformed_item_failures() -> None:
{"code": "INTERNAL_ERROR", "message": "Malformed extraction item error"},
{"code": "INTERNAL_ERROR", "message": "Malformed extraction item error"},
]
+
+
+def test_serving_disclosure_matches_golden_fixture() -> None:
+ """The remote-serving headers are one contract shared by the server and both SDKs."""
+ fixture = _load("serving_disclosure.json")
+ headers = fixture["response_headers"]
+ metadata = get_type_hints(RequestMetadata)
+
+ assert fixture["request_header"] == {"name": REMOTE_HEADER, "values": ["forbid"]}
+ assert {key: header["name"] for key, header in headers.items()} == {
+ "served_by": SERVED_BY_HEADER,
+ "upstream": UPSTREAM_HEADER,
+ "fallback_reason": FALLBACK_REASON_HEADER,
+ "fallback_error": FALLBACK_ERROR_HEADER,
+ }
+ assert set(headers) <= set(metadata)
+ assert set(headers["served_by"]["values"]) == SERVED_BY_VALUES == set(get_args(metadata["served_by"]))
+ assert set(headers["fallback_reason"]["values"]) == FALLBACK_REASONS == set(get_args(metadata["fallback_reason"]))
+ assert headers["upstream"]["pattern"] == UPSTREAM_NAME_PATTERN.pattern
+ assert headers["fallback_error"]["pattern"] == FALLBACK_ERROR_PATTERN.pattern
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index 6dfde2903..fd14f9afe 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -146,6 +146,14 @@ import type {
StreamGenerateOptions,
WireModelInfo,
} from "./types.js";
+import {
+ FALLBACK_ERROR_PATTERN,
+ FALLBACK_REASONS,
+ type FallbackReason,
+ SERVED_BY_VALUES,
+ type ServedBy,
+ UPSTREAM_NAME_PATTERN,
+} from "./types.js";
import { SDK_VERSION } from "./version.js";
const JOB_RESULT_NOT_FOUND_ERROR_CODE = "RESULT_NOT_FOUND";
@@ -436,6 +444,8 @@ function parseNonnegativeMeterHeader(headers: Headers, name: string): number | u
return Number.isSafeInteger(parsed) ? parsed : undefined;
}
+const REMOTE_HEADER = "X-SIE-Remote";
+
/**
* Parse optional request-scoped metadata from one successful terminal response.
*
@@ -465,6 +475,22 @@ function parseRequestMetadata(headers: Headers, body?: unknown): RequestMetadata
if (executionBindingSha256 !== null && /^[0-9a-f]{64}$/.test(executionBindingSha256)) {
metadata.executionBindingSha256 = executionBindingSha256;
}
+ const servedBy = headers.get("x-sie-served-by");
+ if (servedBy !== null && (SERVED_BY_VALUES as readonly string[]).includes(servedBy)) {
+ metadata.servedBy = servedBy as ServedBy;
+ }
+ const upstream = headers.get("x-sie-upstream");
+ if (upstream !== null && UPSTREAM_NAME_PATTERN.test(upstream)) {
+ metadata.upstream = upstream;
+ }
+ const fallbackReason = headers.get("x-sie-fallback-reason");
+ if (fallbackReason !== null && (FALLBACK_REASONS as readonly string[]).includes(fallbackReason)) {
+ metadata.fallbackReason = fallbackReason as FallbackReason;
+ }
+ const fallbackError = headers.get("x-sie-fallback-error");
+ if (fallbackError !== null && FALLBACK_ERROR_PATTERN.test(fallbackError)) {
+ metadata.fallbackError = fallbackError;
+ }
const usageHeaders = {
inputTokens: "x-sie-units-input-tokens",
@@ -952,6 +978,7 @@ export class SIEClient {
private readonly provisionTimeout: number;
private readonly controlPlaneUrl?: string;
private readonly org?: string;
+ private readonly remote?: "forbid";
/** Batch class — `POST/GET /v1/jobs` on the keyed gateway. */
readonly jobs: JobsNamespace;
@@ -1029,6 +1056,12 @@ export class SIEClient {
this.provisionTimeout = options.provisionTimeout ?? DEFAULT_PROVISION_TIMEOUT;
this.controlPlaneUrl = options.controlPlaneUrl?.replace(/\/$/, "");
this.org = options.org;
+ if (options.remote !== undefined && options.remote !== "forbid") {
+ throw new TypeError(
+ `remote must be "forbid" or omitted, got ${JSON.stringify(options.remote)}`,
+ );
+ }
+ this.remote = options.remote;
// First-class batch + connector surface.
this.jobs = {
@@ -1420,6 +1453,7 @@ export class SIEClient {
if (pool) headers["X-SIE-Pool"] = pool;
if (gpu) headers["X-SIE-MACHINE-PROFILE"] = gpu;
if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
+ if (this.remote) headers[REMOTE_HEADER] = this.remote;
const safeModel = model.replaceAll("/", "__");
const url = `${this.baseUrl}/v1/generate/${encodeURIComponent(safeModel)}`;
@@ -1986,6 +2020,7 @@ export class SIEClient {
[SDK_VERSION_HEADER]: SDK_VERSION,
};
if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
+ if (this.remote) headers[REMOTE_HEADER] = this.remote;
return headers;
}
@@ -2847,6 +2882,10 @@ export class SIEClient {
headers.Authorization = `Bearer ${this.apiKey}`;
}
+ if (this.remote) {
+ headers[REMOTE_HEADER] = this.remote;
+ }
+
const fetchWithinBudget = async (
requestUrl: string,
init: Omit<RequestInit, "signal">,
diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.ts
index 22e2da8b7..b02f8e45c 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -138,6 +138,25 @@ export interface RequestUsage {
}
/** Optional gateway metadata from the successful terminal response. */
+/** Which side served a request: SIE's own capacity or a remote upstream. */
+export const SERVED_BY_VALUES = ["local", "remote"] as const;
+export type ServedBy = (typeof SERVED_BY_VALUES)[number];
+
+/** Why a request for the bare model name was served through its remote profile. */
+export const FALLBACK_REASONS = [
+ "provisioning",
+ "model_loading",
+ "saturated",
+ "unhealthy",
+] as const;
+export type FallbackReason = (typeof FALLBACK_REASONS)[number];
+
+/** An upstream name, as `X-SIE-Upstream` carries it. */
+export const UPSTREAM_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
+
+/** An SIE error code, as `X-SIE-Fallback-Error` carries it. */
+export const FALLBACK_ERROR_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
+
export interface RequestMetadata {
id?: string;
/** Worker-origin immutable release/runtime identity digest. */
@@ -158,6 +177,17 @@ export interface RequestMetadata {
creditsDebited?: number;
/** Immutable rate-book version that rated `creditsDebited`, when reported. */
rateBookVersion?: string;
+ /** Which side served the request: `local` capacity, or a `remote` upstream named in `upstream`. */
+ servedBy?: ServedBy;
+ /** The upstream that served the request, when `servedBy` is `remote`. */
+ upstream?: string;
+ /** Why a request for the bare model name was served remotely instead of by local capacity. */
+ fallbackReason?: FallbackReason;
+ /**
+ * Error code of a remote attempt that failed. The response is then the
+ * local refusal that the remote attempt was meant to replace.
+ */
+ fallbackError?: string;
}
/**
@@ -843,6 +873,15 @@ export interface SIEClientOptions {
controlPlaneUrl?: string;
/** Org the `connections` namespace operates on (org-scoped by path in the POC). */
org?: string;
+ /**
+ * `"forbid"` sends `X-SIE-Remote: forbid` with every model request, so no
+ * request is served through a remote upstream. A model served locally
+ * answers from local capacity, including `503 MODEL_LOADING` while it loads,
+ * and a model served only remotely answers `400`. Omitted, the model's
+ * routing policy decides. The setting applies to every call made with this
+ * client.
+ */
+ remote?: "forbid";
}
/** Optional immutable namespace policy for a PostgreSQL connection. */
diff --git a/packages/sie_ts_sdk/tests/remoteServing.test.ts b/packages/sie_ts_sdk/tests/remoteServing.test.ts
new file mode 100644
index 000000000..a914ab202
--- /dev/null
+++ b/packages/sie_ts_sdk/tests/remoteServing.test.ts
@@ -0,0 +1,150 @@
+/**
+ * Forbidding remote serving, and reading which side served.
+ *
+ * The header contract is shared with the server and the Python SDK through
+ * packages/wire-fixtures/serving_disclosure.json. Requests go through the real
+ * client with a stubbed `fetch`, so the option and the parsing run on the
+ * production request and response paths.
+ */
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { SIEClient } from "../src/client.js";
+import { packMessage } from "../src/msgpack.js";
+import {
+ FALLBACK_ERROR_PATTERN,
+ FALLBACK_REASONS,
+ type RequestMetadata,
+ SERVED_BY_VALUES,
+ type SIEClientOptions,
+ UPSTREAM_NAME_PATTERN,
+} from "../src/types.js";
+
+const mockFetch = vi.fn();
+vi.stubGlobal("fetch", mockFetch);
+
+interface DisclosureHeader {
+ name: string;
+ values?: string[];
+ pattern?: string;
+}
+
+const fixture = JSON.parse(
+ readFileSync(
+ fileURLToPath(new URL("../../wire-fixtures/serving_disclosure.json", import.meta.url)),
+ "utf8",
+ ),
+) as {
+ request_header: { name: string; values: string[] };
+ response_headers: Record<
+ "served_by" | "upstream" | "fallback_reason" | "fallback_error",
+ DisclosureHeader
+ >;
+};
+const header = fixture.response_headers;
+
+const SERVED_REMOTELY: Record<string, string> = {
+ [header.served_by.name]: "remote",
+ [header.upstream.name]: "team-sie",
+ [header.fallback_reason.name]: "model_loading",
+};
+
+type Operation = "encode" | "generate" | "chatCompletions";
+const OPERATIONS: Operation[] = ["encode", "generate", "chatCompletions"];
+
+function reply(operation: Operation, headers: Record<string, string>): Response {
+ if (operation === "encode") {
+ return new Response(
+ packMessage({ model: "m", items: [{ dense: { values: new Float32Array([0.5]) } }] }),
+ { status: 200, headers: { "Content-Type": "application/msgpack", ...headers } },
+ );
+ }
+ const body =
+ operation === "generate"
+ ? { model: "m", text: "ok", finish_reason: "stop" }
+ : { id: "c", object: "chat.completion", created: 1, model: "m", choices: [] };
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json", ...headers },
+ });
+}
+
+async function call(client: SIEClient, operation: Operation): Promise<RequestMetadata | undefined> {
+ if (operation === "encode") return (await client.encode("m", { text: "hi" })).request;
+ if (operation === "generate")
+ return (await client.generate("m", "hi", { maxNewTokens: 4 })).request;
+ return (await client.chatCompletions({ model: "m", messages: [{ role: "user", content: "hi" }] }))
+ .request;
+}
+
+function sentHeaders(): Record<string, string> {
+ return mockFetch.mock.calls[0]?.[1]?.headers as Record<string, string>;
+}
+
+describe("remote serving", () => {
+ beforeEach(() => mockFetch.mockReset());
+ afterEach(() => vi.clearAllMocks());
+
+ it("declares the same headers and values as the shared fixture", () => {
+ expect(fixture.request_header).toEqual({ name: "X-SIE-Remote", values: ["forbid"] });
+ expect([...SERVED_BY_VALUES]).toEqual(header.served_by.values);
+ expect([...FALLBACK_REASONS]).toEqual(header.fallback_reason.values);
+ expect(UPSTREAM_NAME_PATTERN.source).toBe(header.upstream.pattern);
+ expect(FALLBACK_ERROR_PATTERN.source).toBe(header.fallback_error.pattern);
+ });
+
+ it.each(OPERATIONS)("a forbidding client sends X-SIE-Remote on %s", async (operation) => {
+ mockFetch.mockResolvedValueOnce(reply(operation, { [header.served_by.name]: "local" }));
+ const client = new SIEClient("http://localhost:8080", { remote: "forbid" });
+
+ const request = await call(client, operation);
+
+ expect(sentHeaders()[fixture.request_header.name]).toBe("forbid");
+ expect(request?.servedBy).toBe("local");
+ });
+
+ it("a default client leaves the choice to the server", async () => {
+ mockFetch.mockResolvedValueOnce(reply("encode", {}));
+ const client = new SIEClient("http://localhost:8080");
+
+ await call(client, "encode");
+
+ expect(sentHeaders()[fixture.request_header.name]).toBeUndefined();
+ });
+
+ it.each(OPERATIONS)(
+ "a remotely served %s result names the upstream and the reason",
+ async (operation) => {
+ mockFetch.mockResolvedValueOnce(reply(operation, SERVED_REMOTELY));
+ const client = new SIEClient("http://localhost:8080");
+
+ const request = await call(client, operation);
+
+ expect(request).toMatchObject({
+ servedBy: "remote",
+ upstream: "team-sie",
+ fallbackReason: "model_loading",
+ });
+ },
+ );
+
+ it("refuses any other remote option", () => {
+ const options = { remote: "allow" } as unknown as SIEClientOptions;
+
+ expect(() => new SIEClient("http://localhost:8080", options)).toThrow(TypeError);
+ });
+
+ it.each([
+ [header.served_by.name, "elsewhere"],
+ [header.served_by.name, "Remote"],
+ [header.upstream.name, "Team_SIE"],
+ [header.upstream.name, "a".repeat(64)],
+ [header.fallback_reason.name, "sometimes"],
+ [header.fallback_error.name, "not a code"],
+ ])("drops %s: %s, which is outside its contract", async (name, value) => {
+ mockFetch.mockResolvedValueOnce(reply("generate", { [name]: value }));
+ const client = new SIEClient("http://localhost:8080");
+
+ expect(await call(client, "generate")).toBeUndefined();
+ });
+});
diff --git a/packages/wire-fixtures/README.md b/packages/wire-fixtures/README.md
index 0038d89bc..6edb365ea 100644
--- a/packages/wire-fixtures/README.md
+++ b/packages/wire-fixtures/README.md
@@ -29,6 +29,11 @@ executable.
score, extract) and for generation, keyed by status, error code, and whether
a usable `Retry-After` is present. It also pins how a `Retry-After` value is
parsed (delay seconds or an HTTP date; a past date means retry now).
+- `serving_disclosure.json` — remote serving: the `X-SIE-Remote: forbid`
+ request header a caller sends to keep a request off remote upstreams, and the
+ response headers that say which side served (`X-SIE-Served-By`,
+ `X-SIE-Upstream`, `X-SIE-Fallback-Reason`, `X-SIE-Fallback-Error`), each with
+ its allowed values or pattern. An SDK drops a value outside them.
- `worker_status.json` — the worker heartbeat the sidecar publishes on
`sie.health.<worker_id>`: the exact `fields` it sends, the
`omitted_when_empty` fields it leaves out when empty, and a fully populated
@@ -60,13 +65,19 @@ fixture set. Current consumers:
`request_usage.json`), and
`packages/sie_sdk/tests/client/test_retry_classification.py` (replays every
`retry_classification.json` case through both clients against a local HTTP
- server).
+ server). `test_wire_contract.py` also asserts the header names, values and
+ patterns of `serving_disclosure.json` against the client constants and
+ `RequestMetadata`.
- TypeScript SDK — `packages/sie_ts_sdk/tests/wireContract.test.ts` (asserts the
runtime `MODEL_STATES` and `MODEL_INFO_WIRE_FIELDS` arrays — the single
sources the `ModelState` type and `WireModelInfo` interface are checked
against — match the fixtures), and
`packages/sie_ts_sdk/tests/retryClassification.test.ts` (replays every
- `retry_classification.json` case through the client with a stubbed `fetch`).
+ `retry_classification.json` case through the client with a stubbed `fetch`),
+ and `packages/sie_ts_sdk/tests/remoteServing.test.ts` (checks the runtime
+ `SERVED_BY_VALUES`, `FALLBACK_REASONS` and header patterns against
+ `serving_disclosure.json`, then sends and parses the headers through the
+ client).
- 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/serving_disclosure.json b/packages/wire-fixtures/serving_disclosure.json
new file mode 100644
index 000000000..583872e99
--- /dev/null
+++ b/packages/wire-fixtures/serving_disclosure.json
@@ -0,0 +1,23 @@
+{
+ "description": "Remote serving: the request header a caller sends to forbid remote serving, and the response headers that say which side served. A server emits the response headers; an SDK reads each into request metadata and drops a value outside its declared values or pattern.",
+ "request_header": {
+ "name": "X-SIE-Remote",
+ "values": ["forbid"]
+ },
+ "response_headers": {
+ "served_by": {"name": "X-SIE-Served-By", "values": ["local", "remote"]},
+ "upstream": {"name": "X-SIE-Upstream", "pattern": "^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$"},
+ "fallback_reason": {
+ "name": "X-SIE-Fallback-Reason",
+ "values": ["provisioning", "model_loading", "saturated", "unhealthy"]
+ },
+ "fallback_error": {"name": "X-SIE-Fallback-Error", "pattern": "^[A-Za-z][A-Za-z0-9_]{0,63}$"}
+ },
+ "notes": {
+ "served_by": "local or remote. Present on a served response.",
+ "upstream": "The upstream's name, present only when served remotely.",
+ "fallback_reason": "The trigger that sent a request for the bare model name to its remote profile.",
+ "fallback_error": "An SIE error code. Present when the remote attempt failed and the response is the local refusal it was meant to replace.",
+ "metadata_fields": "The Python SDK keeps the keys above as request metadata field names; the TypeScript SDK camelCases them (servedBy, upstream, fallbackReason, fallbackError)."
+ }
+}