Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(gateway): bound and re-estimate provisioning Retry-After, name the caller's model (#698)

Krisztian Gajdarec068c4ac356
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index 1bbe1974c..3f50b6589 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -59,7 +59,7 @@ Rules enforced on the inference path:
- If the queue transport is unavailable (no usable NATS client at init), the gateway returns `503`. It does not fall back to direct mode.
- Unknown model ids fast-fail with `404` whenever the in-memory `ModelRegistry` has been populated (either by the filesystem seed or by a successful bootstrap / delta from `sie-config`). In the pre-bootstrap edge case where the registry is still empty — no seed, no export applied yet — the proxy falls back to the caller-supplied bundle (or `"default"`) so an unseeded gateway can still publish work to a cold pool that a caller pinned via `X-SIE-Pool`. Once any model is registered, this fallback is disabled and the 404 contract applies.
- Automatic pool selection only considers healthy workers whose reported `bundle_config_hash` matches the gateway's expected hash. For the requested model, a lane (`pool`, `machine_profile`, `bundle`) is eligible only when no such worker in it lists the model in `unsupported_models`: every worker of a lane consumes the lane subject, so a worker that cannot serve the model would otherwise receive its items and NAK them, spending JetStream delivery attempts. Worker-direct rings (generation and capped logical pools) exclude workers that list the model. When every lane is excluded the gateway returns the `503 PROVISIONING` contract below and counts the exclusion in `sie.gateway.routing.unsupported_model_exclusions`. Explicit `X-SIE-Pool` selects a logical pool; the gateway publishes to that pool's backing queue pool (`PoolSpec.queue_pool`, default `default`) and stamps the logical pool into the work item as `admission_pool`. Deliveries whose hash is not the worker-sidecar's current hash, whose model the worker lists in `unsupported_models`, or whose logical pool does not assign that worker, are NAKed before backend IPC. Successful non-streaming results echo the execution hash; the gateway emits `X-SIE-Model-Revision` only when every successful result matches the hash and immutable revision captured atomically at routing time. The header value is the lowercase 64-hex executed bundle/config SHA-256, not the catalog weights revision (for example, a 40-hex Hugging Face commit). Buffered generation also follows this rule even though it internally collects worker chunks. True SSE responses (`stream: true`) always omit the header because headers precede the terminal result. Successful terminal SSE events may instead carry the worker-origin `execution_identity_sha256` / `execution_binding_sha256` pair, both lowercase 64-hex digests; absence remains valid for older or self-hosted deployments and does not attest execution. These digests are distinct from both the weights revision and the bundle/config hash.
-- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway records pending demand for KEDA and returns a retryable `503` provisioning response with `Retry-After`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. `Retry-After` is 60 seconds unless the dispatch transport estimates when the lane can accept work (see [Lanes a transport reports cold](#lanes-a-transport-reports-cold)). The message names the requested model and not its machine profile or bundle, for example `Capacity for model 'BAAI/bge-m3' is starting. Retry after the number of seconds in Retry-After.` SIE-native surfaces use the SDK retry envelope (`{"error":{"code","message"}}`); OpenAI-compatible surfaces (`/v1/generate`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`) use the OpenAI error envelope, because standard OpenAI clients parse 2xx as successful model output. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.
+- On scale-from-zero — i.e. no healthy worker registered for the `(bundle, machine_profile)` tuple and the caller did not pin an explicit pool — the gateway records pending demand for KEDA and returns a retryable `503` provisioning response with `Retry-After`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. `Retry-After` is 60 seconds unless the dispatch transport estimates when the lane can accept work (see [Lanes a transport reports cold](#lanes-a-transport-reports-cold)). The message names the model as the caller sent it, before alias, case or `__` resolution, and not its machine profile or bundle, for example `Capacity for model 'BAAI/bge-m3' is starting. Retry after the number of seconds in Retry-After.` SIE-native surfaces use the SDK retry envelope (`{"error":{"code","message"}}`); OpenAI-compatible surfaces (`/v1/generate`, `/v1/embeddings`, `/v1/chat/completions`, `/v1/completions`, `/v1/responses`) use the OpenAI error envelope, because standard OpenAI clients parse 2xx as successful model output. This applies whether or not the caller set `X-SIE-MACHINE-PROFILE`; default-routing clients get the same contract as profile-pinned clients.
- On no-consumer conditions for the JetStream publish, the gateway treats the miss as the same pre-execution provisioning state and returns the same retryable `503 PROVISIONING` contract (the same `Retry-After` and message, `X-SIE-Error-Code: PROVISIONING`, and surface-specific error envelope). On backpressure conditions the gateway returns `503` with `Retry-After: 5`. Backpressure is evaluated twice: pool-wide against the `WORK_POOL_{pool}` stream's pending count (`SIE_GATEWAY_MAX_STREAM_PENDING`), and per lane (`pool`/`machine_profile`/`bundle`) against a gateway-local in-flight work-item count (`SIE_GATEWAY_MAX_LANE_IN_FLIGHT_ITEMS`). The per-lane decision is always computed and recorded on `sie.gateway.queue.lane_admission.decisions`, but it only sheds when `SIE_GATEWAY_LANE_BACKPRESSURE_ENFORCE` is set; with the flag off (the default) the pool-wide check is the sole gate. Both sheds produce the same `503` contract and both record pending demand for the exact physical lane so KEDA scales it.
- On queue result timeouts the gateway returns `504` with `X-SIE-Error-Code: GATEWAY_TIMEOUT` and `Retry-After: 5`. This means the gateway accepted and published the work item, but no worker result reached the gateway before `SIE_GATEWAY_REQUEST_TIMEOUT`; it must not be collapsed into worker-emitted `MODEL_LOADING`, which remains a separate retryable `503 MODEL_LOADING` signal.
- When workers report failure on every item of a batch with the **same retryable error code** in `WorkResult.error_code`, the gateway translates that into a `503` with the SDK-expected envelope (`error.code`, `Retry-After`, `X-SIE-Error-Code`) so the SDK auto-retries. Currently recognised codes: `RESOURCE_EXHAUSTED`, `MODEL_LOADING`, `LORA_LOADING`, and `QUEUE_FULL` (a worker that cannot serve the item now, such as a remote profile whose upstream is busy, unreachable, rate capped or behind an open circuit breaker; a remote profile whose upstream model is not ready answers `MODEL_LOADING`). A remote worker answers these upstream refusals at once with the upstream's wait rather than redelivering the item. Generation workers attach the operator's validated `oom_recovery.retry_after_s` value to a `RESOURCE_EXHAUSTED` terminal chunk, and a worker may set `WorkResult.retry_after_s` on a failed item; for `RESOURCE_EXHAUSTED`, `QUEUE_FULL` and `MODEL_LOADING` failures, the gateway uses the longest worker hint that qualifies as an integer in `1..=60` seconds, ignoring other hints. If no hint qualifies, or the code is `LORA_LOADING` even when a worker provides a hint, it uses the current five-second default compiled into the gateway. **Mixed batches** (different codes per item) keep going through the compatibility `500 all_items_failed` path with per-item `code` fields exposed in `details[]`, so callers can see exactly which items hit which failure mode. Workers reporting `RESOURCE_EXHAUSTED` are **not** marked unhealthy — losing an allocation race is not a worker-health signal.
@@ -1096,14 +1096,17 @@ lane. It is `false` by default and is a non-publishing hint.
that lane, whether the transport reported the lane cold, a publish found no
consumers, a capped lane has no admitted worker, or the registry has no
worker for it. A transport that never reports cold lanes can still give
- the estimate.
+ the estimate. For a lane the transport reports cold, the gateway reads it
+ after it publishes the wake, because a transport may only have an estimate
+ once a wake is pending.
- The estimate becomes `Retry-After`, rounded up to whole seconds and
clamped by the kind of route the request arrived on. The floor is
always 5 seconds, the gateway's short transient-retry hint.
- On the native routes (`/v1/encode`, `/v1/score`, `/v1/extract`,
- `/v1/generate`) the ceiling is 900 seconds: the 15-minute default
- provisioning budget of the Python and TypeScript SDKs, which wait for
- `Retry-After` within that budget.
+ `/v1/generate`) the ceiling is 300 seconds, well inside the 15-minute
+ default provisioning budget of the Python and TypeScript SDKs, which
+ wait for `Retry-After` within that budget. One hint cannot use up the
+ budget, so the SDKs still retry after it.
- On the OpenAI-compatible routes (`/v1/chat/completions`,
`/v1/completions`, `/v1/responses`, `/v1/embeddings`,
`/v1/audio/transcriptions`) and the rerank routes (`/v1/rerank`,
@@ -1114,8 +1117,10 @@ lane. It is `false` by default and is a non-publishing hint.
seconds. A compatibility route that wraps a native one keeps this
ceiling.
- A request that may be served by several cold lanes, such as one without
- a machine profile, gets the soonest estimate among them.
+ a machine profile, gets the soonest value among them. A lane without an
+ estimate counts as 60 seconds.
- Without an estimate, `Retry-After` stays 60 seconds.
- - A refusal held through a bridge keeps the `Retry-After` it was built
- with, so a restored refusal reports the local lane's estimate, not the
- remote attempt's.
+ - A refusal held through a bridge is estimated again when it is restored,
+ from the same lanes and route, by the same rules. The restored refusal
+ reports the local lanes' estimate at that moment, not the remote
+ attempt's and not the one it was built with.
diff --git a/packages/sie_gateway/src/error.rs b/packages/sie_gateway/src/error.rs
index 2709724b8..f3a6815c3 100644
--- a/packages/sie_gateway/src/error.rs
+++ b/packages/sie_gateway/src/error.rs
@@ -1,4 +1,4 @@
-use axum::http::{HeaderName, HeaderValue, StatusCode};
+use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use crate::http_error::{code as err_code, json_detail};
@@ -9,9 +9,6 @@ pub enum AppError {
#[error("no healthy workers available")]
NoWorkerAvailable,
- #[error("GPU provisioning in progress: {0}")]
- GpuProvisioning(String),
-
#[error("worker connection error: {0}")]
UpstreamConnection(String),
@@ -21,18 +18,12 @@ pub enum AppError {
impl IntoResponse for AppError {
fn into_response(self) -> Response {
- let is_gpu_provisioning = matches!(self, AppError::GpuProvisioning(_));
let (status, code, message) = match &self {
AppError::NoWorkerAvailable => (
StatusCode::SERVICE_UNAVAILABLE,
err_code::QUEUE_UNAVAILABLE,
self.to_string(),
),
- AppError::GpuProvisioning(_) => (
- StatusCode::SERVICE_UNAVAILABLE,
- err_code::PROVISIONING,
- self.to_string(),
- ),
AppError::UpstreamConnection(_) => (
StatusCode::BAD_GATEWAY,
err_code::INTERNAL_ERROR,
@@ -46,26 +37,7 @@ impl IntoResponse for AppError {
};
let body = json_detail(code, message);
- let mut response = (status, axum::Json(body)).into_response();
- if is_gpu_provisioning {
- response.headers_mut().insert(
- HeaderName::from_static("retry-after"),
- HeaderValue::from_static("60"),
- );
- response.headers_mut().insert(
- HeaderName::from_static("x-sie-error-code"),
- HeaderValue::from_static(err_code::PROVISIONING),
- );
- response.headers_mut().insert(
- HeaderName::from_static("x-sie-version"),
- HeaderValue::from_static(env!("CARGO_PKG_VERSION")),
- );
- response.headers_mut().insert(
- HeaderName::from_static("x-sie-server-version"),
- HeaderValue::from_static(env!("CARGO_PKG_VERSION")),
- );
- }
- response
+ (status, axum::Json(body)).into_response()
}
}
@@ -85,26 +57,6 @@ mod tests {
);
}
- #[test]
- fn test_gpu_provisioning_is_503() {
- assert_eq!(
- response_status(AppError::GpuProvisioning("l4".into())),
- StatusCode::SERVICE_UNAVAILABLE
- );
- }
-
- #[test]
- fn test_gpu_provisioning_has_retry_headers() {
- let response = AppError::GpuProvisioning("l4".into()).into_response();
- assert_eq!(response.headers().get("retry-after").unwrap(), "60");
- assert_eq!(
- response.headers().get("x-sie-error-code").unwrap(),
- err_code::PROVISIONING
- );
- assert!(response.headers().get("x-sie-version").is_some());
- assert!(response.headers().get("x-sie-server-version").is_some());
- }
-
#[test]
fn test_upstream_connection_is_502() {
assert_eq!(
@@ -127,9 +79,5 @@ mod tests {
AppError::NoWorkerAvailable.to_string(),
"no healthy workers available"
);
- assert_eq!(
- AppError::GpuProvisioning("l4".into()).to_string(),
- "GPU provisioning in progress: l4"
- );
}
}
diff --git a/packages/sie_gateway/src/handlers/audio.rs b/packages/sie_gateway/src/handlers/audio.rs
index 5020a364c..3627008cf 100644
--- a/packages/sie_gateway/src/handlers/audio.rs
+++ b/packages/sie_gateway/src/handlers/audio.rs
@@ -998,7 +998,55 @@ mod tests {
(std::time::Duration::from_secs(45), "45"),
] {
let gateway = TestGateway::new(&[HYBRID_EXTRACT_MODEL]).await;
+ // A cold lookup without a machine profile is about every machine
+ // profile of the pool.
+ for lane in [LOCAL_LANE, (LOCAL_LANE.0, REMOTE_LANE.1, LOCAL_LANE.2)] {
+ gateway.dispatcher.estimate_provisioning(lane, local);
+ }
+ let (content_type, body) =
+ multipart_body(&[("model", "acme/extract")], "clip.wav", b"RIFFtest");
+ let request = Request::builder()
+ .method(Method::POST)
+ .uri("/v1/audio/transcriptions")
+ .header(header::CONTENT_TYPE, content_type)
+ .body(Body::from(body))
+ .unwrap();
+
+ let response =
+ proxy_openai_transcription(State(Arc::clone(&gateway.state)), request).await;
+
+ assert_eq!(
+ response.status(),
+ StatusCode::SERVICE_UNAVAILABLE,
+ "{local:?}"
+ );
+ assert_eq!(response.headers()["retry-after"], retry_after, "{local:?}");
+ assert_eq!(response.headers()["x-sie-error-code"], "PROVISIONING");
+ }
+ }
+
+ #[tokio::test]
+ async fn audio_transcriptions_cap_a_transport_cold_lane_estimate() {
+ let config = format!(
+ "{HYBRID_EXTRACT_MODEL}\nrouting:\n policy: fallback\n fallback_profile: remote\n"
+ );
+ for (local, retry_after) in [
+ (std::time::Duration::from_secs(95), "60"),
+ (std::time::Duration::from_secs(40), "40"),
+ ] {
+ let gateway = TestGateway::new(&[&config]).await;
+ gateway
+ .add_verified_worker("local-1", LOCAL_LANE, &["acme/extract"])
+ .await;
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ gateway.dispatcher.report_cold_local_lane();
+ gateway.dispatcher.refuse_model_loads();
gateway.dispatcher.estimate_provisioning(LOCAL_LANE, local);
+ gateway
+ .dispatcher
+ .estimate_provisioning(REMOTE_LANE, std::time::Duration::from_secs(280));
let (content_type, body) =
multipart_body(&[("model", "acme/extract")], "clip.wav", b"RIFFtest");
let request = Request::builder()
@@ -1018,6 +1066,10 @@ mod tests {
);
assert_eq!(response.headers()["retry-after"], retry_after, "{local:?}");
assert_eq!(response.headers()["x-sie-error-code"], "PROVISIONING");
+ let woken = gateway.dispatcher.dispatched();
+ assert_eq!(woken.len(), 1, "{woken:?}");
+ assert_eq!(woken[0].endpoint, "load");
+ assert_eq!(woken[0].bundle, LOCAL_LANE.2);
}
}
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 7f129580d..4e79b1eef 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -377,16 +377,19 @@ impl RetryAfter {
/// asynchronous job. Keep the Retry-After hint within the range common OpenAI
/// SDKs honor directly.
pub(crate) const PROVISIONING_RETRY_AFTER: &str = RetryAfter::DEFAULT.provisioning;
+/// [`PROVISIONING_RETRY_AFTER`] in whole seconds: what a lane counts as when
+/// the transport gives no estimate for it.
+const PROVISIONING_RETRY_AFTER_DEFAULT_S: u64 = 60;
/// Bounds, in whole seconds, on a transport's `Retry-After` estimate for a
/// provisioning answer ([`WorkDispatcher::provisioning_retry_after`]). The
/// floor is the gateway's short transient-retry hint. The ceiling depends on
-/// the [`RouteKind`]: on a native route it is the 15-minute default
-/// provisioning budget of the Python and TypeScript SDKs, and on a
-/// compatibility route it is the 60 seconds up to which the OpenAI clients
-/// honor `Retry-After`. Above that they ignore it and retry on their own
-/// short backoff.
+/// the [`RouteKind`]. On a native route it is 300 seconds, well inside the
+/// 15-minute default provisioning budget of the Python and TypeScript SDKs,
+/// so that one hint cannot use up that budget. On a compatibility route it is
+/// the 60 seconds up to which the OpenAI clients honor `Retry-After`. Above
+/// that they ignore it and retry on their own short backoff.
const PROVISIONING_RETRY_AFTER_MIN_S: u64 = 5;
-const NATIVE_PROVISIONING_RETRY_AFTER_MAX_S: u64 = 900;
+const NATIVE_PROVISIONING_RETRY_AFTER_MAX_S: u64 = 300;
const COMPATIBILITY_PROVISIONING_RETRY_AFTER_MAX_S: u64 = 60;
const BACKPRESSURE_RETRY_AFTER: &str = RetryAfter::DEFAULT.backpressure;
const GATEWAY_TIMEOUT_RETRY_AFTER: &str = RetryAfter::DEFAULT.gateway_timeout;
@@ -864,16 +867,13 @@ async fn demand_profiles_for_pool(
}
}
-/// The message of a `503 PROVISIONING` answer. It names the requested model
-/// only: machine profiles and bundles are deployment detail.
-fn provisioning_message(model: &str) -> String {
- if model.is_empty() {
- "Capacity is starting. Retry after the number of seconds in Retry-After.".to_string()
- } else {
- format!(
- "Capacity for model '{model}' is starting. Retry after the number of seconds in Retry-After."
- )
- }
+/// The message of a `503 PROVISIONING` answer. It names the model as the
+/// caller sent it, never what routing resolved it to: machine profiles,
+/// bundles and alias targets are deployment detail.
+fn provisioning_message(requested_model: &str) -> String {
+ format!(
+ "Capacity for model '{requested_model}' is starting. Retry after the number of seconds in Retry-After."
+ )
}
/// A transport's provisioning estimate in whole seconds, rounded up and
@@ -889,30 +889,54 @@ fn bounded_provisioning_retry_after_s(estimate: Duration, route: RouteKind) -> u
.clamp(PROVISIONING_RETRY_AFTER_MIN_S, ceiling)
}
-/// The `Retry-After` of a `503 PROVISIONING` answer on a `route` about the
-/// lanes `targets` name, each a lane's pool target as [`lane_wake_target`]
-/// builds it. It is the soonest estimate the transport gives for any of them,
-/// bounded by [`bounded_provisioning_retry_after_s`], or the 60-second default
-/// when it gives none.
-pub(crate) fn provisioning_retry_after(
- state: &AppState,
- targets: &[publisher::PublishTarget],
+/// What the `Retry-After` of a `503 PROVISIONING` answer is estimated from:
+/// the lanes the answer is about, each a lane's pool target as
+/// [`lane_wake_target`] builds it, and the kind of route it answers. The
+/// answer carries it in its extensions, so an answer held through a remote
+/// attempt is estimated again when it is restored.
+#[derive(Clone)]
+pub(crate) struct ProvisioningEstimate {
+ dispatcher: Option<Arc<dyn WorkDispatcher>>,
+ targets: Vec<publisher::PublishTarget>,
route: RouteKind,
-) -> HeaderValue {
- state
- .work_publisher
- .as_deref()
- .and_then(|dispatcher| {
- targets
- .iter()
- .filter_map(|target| dispatcher.provisioning_retry_after(target))
- .map(|estimate| bounded_provisioning_retry_after_s(estimate, route))
- .min()
- })
- .map_or_else(
- || HeaderValue::from_static(PROVISIONING_RETRY_AFTER),
- HeaderValue::from,
- )
+}
+
+impl ProvisioningEstimate {
+ pub(crate) fn new(
+ state: &AppState,
+ targets: Vec<publisher::PublishTarget>,
+ route: RouteKind,
+ ) -> Self {
+ Self {
+ dispatcher: state.work_publisher.clone(),
+ targets,
+ route,
+ }
+ }
+
+ /// The soonest estimate the transport now gives for any of the lanes,
+ /// bounded by [`bounded_provisioning_retry_after_s`]. A lane without an
+ /// estimate counts as the 60-second default, and so does an answer about
+ /// no lane.
+ pub(crate) fn retry_after(&self) -> HeaderValue {
+ let seconds = self
+ .dispatcher
+ .as_deref()
+ .and_then(|dispatcher| {
+ self.targets
+ .iter()
+ .map(|target| {
+ dispatcher
+ .provisioning_retry_after(target)
+ .map_or(PROVISIONING_RETRY_AFTER_DEFAULT_S, |estimate| {
+ bounded_provisioning_retry_after_s(estimate, self.route)
+ })
+ })
+ .min()
+ })
+ .unwrap_or(PROVISIONING_RETRY_AFTER_DEFAULT_S);
+ HeaderValue::from(seconds)
+ }
}
fn add_provisioning_headers(resp: &mut Response, retry_after: HeaderValue) {
@@ -1099,23 +1123,24 @@ pub(crate) fn monitor_dispatch_durability(
/// [`provisioning_response`], counted as a provisioning response for
/// `surface`.
fn build_provisioning_response_for_surface(
- model: &str,
- retry_after: HeaderValue,
+ requested_model: &str,
+ estimate: ProvisioningEstimate,
surface: ProvisioningSurface,
) -> Response {
record_provisioning_response(surface, StatusCode::SERVICE_UNAVAILABLE);
- provisioning_response(model, retry_after, surface)
+ provisioning_response(requested_model, estimate, surface)
}
-/// The `503 PROVISIONING` answer for `model`, with the `Retry-After` from
-/// [`provisioning_retry_after`]. Unlike
-/// [`build_provisioning_response_for_surface`], it does not count the answer.
+/// The `503 PROVISIONING` answer for the model the caller sent as
+/// `requested_model`, with the `Retry-After` of `estimate`, which it carries.
+/// Unlike [`build_provisioning_response_for_surface`], it does not count the
+/// answer.
pub(crate) fn provisioning_response(
- model: &str,
- retry_after: HeaderValue,
+ requested_model: &str,
+ estimate: ProvisioningEstimate,
surface: ProvisioningSurface,
) -> Response {
- let message = provisioning_message(model);
+ let message = provisioning_message(requested_model);
let mut resp = match surface {
ProvisioningSurface::Native => (
StatusCode::SERVICE_UNAVAILABLE,
@@ -1138,11 +1163,12 @@ pub(crate) fn provisioning_response(
)
.into_response(),
};
- add_provisioning_headers(&mut resp, retry_after);
+ add_provisioning_headers(&mut resp, estimate.retry_after());
resp.headers_mut().insert(
HeaderName::from_static("x-sie-error-code"),
HeaderValue::from_static(err_code::PROVISIONING),
);
+ resp.extensions_mut().insert(estimate);
resp
}
@@ -1192,8 +1218,8 @@ fn provisioning_surface_for_endpoint(endpoint: &str) -> ProvisioningSurface {
}
}
-/// `model` is the model the caller asked for. `dispatch_model` is the route
-/// the lane serves.
+/// `requested_model` is the model as the caller sent it. `dispatch_model` is
+/// the route the lane serves.
#[allow(clippy::too_many_arguments)]
async fn capped_lane_admission_response(
state: &AppState,
@@ -1201,7 +1227,7 @@ async fn capped_lane_admission_response(
demand_pool: &str,
machine_profile: &str,
bundle: &str,
- model: &str,
+ requested_model: &str,
dispatch_model: &str,
provisioning_surface: ProvisioningSurface,
route: RouteKind,
@@ -1264,9 +1290,9 @@ async fn capped_lane_admission_response(
{
state.demand_tracker.record(&lane);
}
- let retry_after = provisioning_retry_after(
+ let estimate = ProvisioningEstimate::new(
state,
- &[lane_wake_target(
+ vec![lane_wake_target(
demand_pool,
machine_profile,
bundle,
@@ -1275,8 +1301,8 @@ async fn capped_lane_admission_response(
route,
);
return Some(build_provisioning_response_for_surface(
- model,
- retry_after,
+ requested_model,
+ estimate,
provisioning_surface,
));
}
@@ -2082,6 +2108,8 @@ fn bridged_fallback_reason(ext: &axum::http::Extensions) -> Option<FallbackTrigg
/// and engine. Produced by [`resolve_routing`].
struct RoutingResult {
caller_selected_route: bool,
+ /// The model as the caller sent it, before alias, case or `__` resolution.
+ requested_model: String,
model_name: String,
dispatch_model: String,
bundle: String,
@@ -2197,6 +2225,7 @@ async fn resolve_routing(
debug_assert_eq!(route.engine, "sealed");
return Ok(RoutingResult {
caller_selected_route,
+ requested_model: model,
dispatch_model: model_name.clone(),
model_name,
bundle: route.bundle,
@@ -2215,6 +2244,7 @@ async fn resolve_routing(
};
return Ok(RoutingResult {
caller_selected_route,
+ requested_model: model,
model_name,
dispatch_model: plan.model.clone(),
bundle: plan.bundle.clone(),
@@ -2428,6 +2458,7 @@ async fn resolve_routing(
Ok(RoutingResult {
caller_selected_route,
+ requested_model: model,
model_name,
dispatch_model,
bundle,
@@ -3200,6 +3231,7 @@ async fn proxy_request_inner(
let RoutingResult {
caller_selected_route,
+ requested_model,
model_name,
dispatch_model,
bundle,
@@ -3473,9 +3505,9 @@ async fn proxy_request_inner(
&admission_pool,
)
.await;
- let retry_after = provisioning_retry_after(
+ let estimate = ProvisioningEstimate::new(
&state,
- &cold_lane_targets(
+ cold_lane_targets(
&demand_pool,
&pending_demand_profiles,
&bundle,
@@ -3484,8 +3516,8 @@ async fn proxy_request_inner(
route_kind(req.extensions()),
);
let refusal = build_provisioning_response_for_surface(
- &model_name,
- retry_after,
+ &requested_model,
+ estimate,
provisioning_surface,
);
match begin_native_fallback(
@@ -3545,7 +3577,7 @@ async fn proxy_request_inner(
&demand_pool,
effective_machine_profile,
&bundle,
- &model_name,
+ &requested_model,
&dispatch_model,
provisioning_surface,
route_kind(req.extensions()),
@@ -3581,16 +3613,9 @@ async fn proxy_request_inner(
&bundle,
&dispatch_model,
);
- let refusal = build_provisioning_response_for_surface(
- &model_name,
- provisioning_retry_after(
- &state,
- std::slice::from_ref(&target),
- route_kind(req.extensions()),
- ),
- provisioning_surface,
- );
- if !warm_local_model(
+ let estimate =
+ ProvisioningEstimate::new(&state, vec![target.clone()], route_kind(req.extensions()));
+ let woken = warm_local_model(
&state,
work_publisher.as_ref(),
&physical_lane,
@@ -3598,8 +3623,13 @@ async fn proxy_request_inner(
&engine,
&bundle_config_hash,
)
- .await
- {
+ .await;
+ let refusal = build_provisioning_response_for_surface(
+ &requested_model,
+ estimate,
+ provisioning_surface,
+ );
+ if !woken {
return refusal;
}
let Some(plan) = native_bridge_plan(
@@ -3846,9 +3876,9 @@ async fn proxy_request_inner(
Ok(target) => Some(target),
Err(()) => {
state.demand_tracker.record(&physical_lane);
- let retry_after = provisioning_retry_after(
+ let estimate = ProvisioningEstimate::new(
&state,
- &[lane_wake_target(
+ vec![lane_wake_target(
effective_pool,
effective_machine_profile,
&bundle,
@@ -3857,8 +3887,8 @@ async fn proxy_request_inner(
route_kind(req.extensions()),
);
return build_provisioning_response_for_surface(
- &model_name,
- retry_after,
+ &requested_model,
+ estimate,
provisioning_surface,
);
}
@@ -3920,6 +3950,7 @@ async fn proxy_request_inner(
&state,
Arc::clone(work_publisher),
endpoint,
+ &requested_model,
&model_name,
&dispatch_model,
&bundle,
@@ -4404,6 +4435,7 @@ async fn queue_mode_proxy(
state: &AppState,
work_publisher: Arc<dyn WorkDispatcher>,
endpoint: &str,
+ requested_model: &str,
display_model: &str,
model: &str,
bundle: &str,
@@ -4490,6 +4522,7 @@ async fn queue_mode_proxy(
state,
work_publisher: work_publisher_arc,
physical_lane: physical_lane.clone(),
+ requested_model: requested_model.to_string(),
model: display_model.to_string(),
dispatch_model: model.to_string(),
bundle: bundle.to_string(),
@@ -4500,6 +4533,7 @@ async fn queue_mode_proxy(
bundle_config_hash: bundle_config_hash.to_string(),
work_params: params,
endpoint: super::sse::SseEndpoint::Generate,
+ route: route_kind(request_extensions),
})
.await;
}
@@ -4507,6 +4541,7 @@ async fn queue_mode_proxy(
state,
work_publisher_arc,
physical_lane,
+ requested_model,
display_model,
model,
bundle,
@@ -4521,6 +4556,7 @@ async fn queue_mode_proxy(
token_id,
content_length,
start,
+ route_kind(request_extensions),
)
.await;
}
@@ -4577,14 +4613,14 @@ async fn queue_mode_proxy(
physical_lane,
"no_consumers",
);
- let retry_after = provisioning_retry_after(
+ let estimate = ProvisioningEstimate::new(
state,
- &[lane_wake_target(pool, gpu, bundle, model)],
+ vec![lane_wake_target(pool, gpu, bundle, model)],
route_kind(request_extensions),
);
return build_provisioning_response_for_surface(
- display_model,
- retry_after,
+ requested_model,
+ estimate,
provisioning_surface_for_endpoint(endpoint),
);
}
@@ -5391,10 +5427,10 @@ pub(crate) enum StreamingDriverErr {
retry_after: Option<&'static str>,
},
/// The publish found no capacity ready on the lane (``no consumers``):
- /// a ``503 PROVISIONING`` answer for the requested ``model``.
+ /// a ``503 PROVISIONING`` answer for the model the caller sent.
Provisioning {
- model: String,
- retry_after: HeaderValue,
+ requested_model: String,
+ estimate: ProvisioningEstimate,
},
/// Initial publish submission returned, but the transport later rejected
/// or abandoned its durable-acceptance acknowledgement.
@@ -5455,7 +5491,9 @@ pub(crate) async fn run_streaming_generate(
state: &AppState,
work_publisher: Arc<dyn WorkDispatcher>,
physical_lane: &PhysicalLane,
- // DISPLAY id (the requested model) — drives metric labels + the cancel
+ // The model as the caller sent it, which a provisioning answer names.
+ requested_model: &str,
+ // DISPLAY id (the resolved model) — drives metric labels + the cancel
// guard. ``dispatch_model`` below is the id actually published to NATS /
// the work item (the grammar ``:no-spec`` variant when routing fired);
// they are equal for non-routed requests. See ``route_grammar_to_profile``.
@@ -5598,15 +5636,15 @@ pub(crate) async fn run_streaming_generate(
"no_consumers",
);
return Err(StreamingDriverErr::Provisioning {
- model: model.to_string(),
- retry_after: provisioning_retry_after(
+ requested_model: requested_model.to_string(),
+ estimate: ProvisioningEstimate::new(
state,
- &[lane_wake_target(pool, gpu, bundle, dispatch_model)],
+ vec![lane_wake_target(pool, gpu, bundle, dispatch_model)],
route,
),
});
}
- // backpressure (records demand for KEDA) / generic failure. #1568
+ // backpressure (records demand for KEDA) / generic failure.
return Err(StreamingDriverErr::PublishFailed {
message: e,
retry_after: record_publish_failure(state, physical_lane, &lower),
@@ -6050,9 +6088,12 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {
message,
retry_after,
} => build_streaming_publish_failed_for_sse(message, *retry_after),
- StreamingDriverErr::Provisioning { model, retry_after } => provisioning_response(
- model,
- retry_after.clone(),
+ StreamingDriverErr::Provisioning {
+ requested_model,
+ estimate,
+ } => provisioning_response(
+ requested_model,
+ estimate.clone(),
ProvisioningSurface::OpenAiCompat,
),
StreamingDriverErr::DurabilityFailed { message } => (
@@ -6233,7 +6274,9 @@ async fn queue_mode_streaming_generate(
state: &AppState,
work_publisher: Arc<dyn WorkDispatcher>,
physical_lane: &PhysicalLane,
- // DISPLAY id (requested model) — response body, success metrics, audit log.
+ // The model as the caller sent it, which a provisioning answer names.
+ requested_model: &str,
+ // DISPLAY id (resolved model) — response body, success metrics, audit log.
model: &str,
// DISPATCH id (grammar ``:no-spec`` variant when routed) — NATS subject +
// work item. Equal to ``model`` for non-routed requests.
@@ -6250,11 +6293,13 @@ async fn queue_mode_streaming_generate(
token_id: &str,
content_length: i64,
start: Instant,
+ route: RouteKind,
) -> Response {
let driver = run_streaming_generate(
state,
work_publisher,
physical_lane,
+ requested_model,
model,
dispatch_model,
bundle,
@@ -6264,7 +6309,7 @@ async fn queue_mode_streaming_generate(
admission_pool,
bundle_config_hash,
params,
- RouteKind::Native,
+ route,
)
.await;
@@ -8531,12 +8576,14 @@ struct ResolvedRoute {
/// Resolve GPU/pool routing from headers, validate them, pick the effective
/// pool (or surface an OpenAI-shaped 503 provisioning response), and bind the
/// work publisher. Shared by the chat + completions handlers; the OpenAI-shaped
-/// errors are identical across both.
+/// errors are identical across both. `requested_model` is the model as the
+/// caller sent it, which a provisioning response names.
#[allow(clippy::result_large_err, clippy::too_many_arguments)]
async fn resolve_generation_route(
state: &AppState,
hdr: &HeaderMap,
bundle: &str,
+ requested_model: &str,
customer_model: &str,
dispatch_model: &str,
request_intent: GenerationRequestIntent,
@@ -8772,6 +8819,7 @@ async fn resolve_generation_route(
state,
hdr,
&bundle,
+ requested_model,
customer_model,
dispatch_model,
request_intent,
@@ -8824,9 +8872,9 @@ async fn resolve_generation_route(
&admission_pool,
)
.await;
- let retry_after = provisioning_retry_after(
+ let estimate = ProvisioningEstimate::new(
state,
- &cold_lane_targets(
+ cold_lane_targets(
&demand_pool,
&pending_demand_profiles,
&bundle,
@@ -8835,8 +8883,8 @@ async fn resolve_generation_route(
RouteKind::Compatibility,
);
let refusal = build_provisioning_response_for_surface(
- customer_model,
- retry_after,
+ requested_model,
+ estimate,
ProvisioningSurface::OpenAiCompat,
);
let attempt = ext.get::<FallbackAttempt>();
@@ -8861,6 +8909,7 @@ async fn resolve_generation_route(
state,
hdr,
&plan.bundle,
+ requested_model,
customer_model,
&plan.model,
request_intent,
@@ -8915,7 +8964,7 @@ async fn resolve_generation_route(
&demand_pool,
&effective_machine_profile,
&bundle,
- customer_model,
+ requested_model,
dispatch_model,
ProvisioningSurface::OpenAiCompat,
RouteKind::Compatibility,
@@ -8948,16 +8997,9 @@ async fn resolve_generation_route(
&bundle,
dispatch_model,
);
- let refusal = build_provisioning_response_for_surface(
- customer_model,
- provisioning_retry_after(
- state,
- std::slice::from_ref(&target),
- RouteKind::Compatibility,
- ),
- ProvisioningSurface::OpenAiCompat,
- );
- if !warm_local_model(
+ let estimate =
+ ProvisioningEstimate::new(state, vec![target.clone()], RouteKind::Compatibility);
+ let woken = warm_local_model(
state,
work_publisher_arc.as_ref(),
&physical_lane,
@@ -8965,8 +9007,13 @@ async fn resolve_generation_route(
&engine,
&bundle_config_hash,
)
- .await
- {
+ .await;
+ let refusal = build_provisioning_response_for_surface(
+ requested_model,
+ estimate,
+ ProvisioningSurface::OpenAiCompat,
+ );
+ if !woken {
return Err(refusal);
}
let attempt = ext
@@ -8979,6 +9026,7 @@ async fn resolve_generation_route(
state,
hdr,
&plan.bundle,
+ requested_model,
customer_model,
&plan.model,
request_intent,
@@ -9047,6 +9095,7 @@ async fn resolve_generation_route(
state,
hdr,
&plan.bundle,
+ requested_model,
customer_model,
&plan.model,
request_intent,
@@ -9123,6 +9172,7 @@ async fn resolve_generation_route(
state,
hdr,
&plan.bundle,
+ requested_model,
customer_model,
&plan.model,
request_intent,
@@ -9611,6 +9661,7 @@ async fn proxy_chat_inner(
&state,
&hdr,
&bundle,
+ &params.model,
&model_name,
&dispatch_model,
if params.grammar.is_some() {
@@ -9632,6 +9683,7 @@ async fn proxy_chat_inner(
let start = Instant::now();
// Copied out BEFORE the params are consumed into `WorkParams` below.
+ let requested_model = params.model.clone();
let stream = params.stream;
let stream_include_usage = params.stream_include_usage;
let mut work_params = params.into_work_params();
@@ -9656,6 +9708,7 @@ async fn proxy_chat_inner(
state: state.as_ref(),
work_publisher: work_publisher_arc,
physical_lane: physical_lane.clone(),
+ requested_model,
model: model_name.clone(),
dispatch_model: dispatch_model.clone(),
bundle: bundle.clone(),
@@ -9668,6 +9721,7 @@ async fn proxy_chat_inner(
endpoint: super::sse::SseEndpoint::Chat {
include_usage: stream_include_usage,
},
+ route: RouteKind::Compatibility,
})
.await;
}
@@ -9676,6 +9730,7 @@ async fn proxy_chat_inner(
&state,
work_publisher_arc,
&physical_lane,
+ &requested_model,
&model_name,
&dispatch_model,
&bundle,
@@ -10293,6 +10348,7 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response
&state,
&hdr,
&bundle,
+ &params.model,
&model_name,
&model_name,
GenerationRequestIntent::Default,
@@ -10310,6 +10366,7 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response
let start = Instant::now();
// Copied out BEFORE the params are consumed into `WorkParams` below.
+ let requested_model = params.model.clone();
let stream = params.stream;
let stream_include_usage = params.stream_include_usage;
let mut work_params = params.into_work_params();
@@ -10328,6 +10385,7 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response
state: state.as_ref(),
work_publisher: work_publisher_arc,
physical_lane: physical_lane.clone(),
+ requested_model,
model: model_name.clone(),
// /v1/completions does not accept grammar, so it never routes:
// dispatch == display.
@@ -10342,6 +10400,7 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response
endpoint: super::sse::SseEndpoint::Completion {
include_usage: stream_include_usage,
},
+ route: RouteKind::Compatibility,
})
.await;
}
@@ -10350,6 +10409,7 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response
&state,
work_publisher_arc,
&physical_lane,
+ &requested_model,
&model_name,
&dispatch_model,
&bundle,
@@ -10960,6 +11020,7 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {
&state,
&hdr,
&bundle,
+ &params.model,
&model_name,
&model_name,
GenerationRequestIntent::Default,
@@ -10976,6 +11037,7 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {
};
let start = Instant::now();
+ let requested_model = params.model.clone();
let mut work_params = params.into_work_params();
work_params.require_execution_authority_v1 = require_execution_authority_v1;
work_params.fallback_reason = fallback_reason;
@@ -10984,6 +11046,7 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {
&state,
work_publisher_arc,
&physical_lane,
+ &requested_model,
&model_name,
&dispatch_model,
&bundle,
@@ -17160,6 +17223,7 @@ mod tests {
// literal (not against `RetryAfter::DEFAULT.*`, which would be a
// tautological `x == x`), so a broken alias is actually caught.
assert_eq!(PROVISIONING_RETRY_AFTER, "60");
+ assert_eq!(PROVISIONING_RETRY_AFTER_DEFAULT_S, 60);
assert_eq!(BACKPRESSURE_RETRY_AFTER, "5");
assert_eq!(GATEWAY_TIMEOUT_RETRY_AFTER, "5");
assert_eq!(MODEL_LOADING_RETRY_AFTER, "5");
@@ -19710,6 +19774,297 @@ mod tests {
state.demand_tracker.clear(&lane);
}
+ #[tokio::test]
+ async fn test_capped_lane_admission_estimates_its_demand_lane_for_the_route() {
+ use crate::handlers::test_support::RecordingDispatcher;
+
+ let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ pm.create_pool_with_caps(
+ "tenant",
+ std::collections::HashMap::from([("l4".to_string(), 0)]),
+ std::collections::HashMap::from([("l4".to_string(), 1)]),
+ None,
+ None,
+ 0,
+ vec![],
+ )
+ .await
+ .unwrap();
+ let mut state = admission_test_state(Arc::clone(&pm));
+ let dispatcher = Arc::new(RecordingDispatcher::default());
+ state.work_publisher = Some(dispatcher.clone());
+ let demand_pool = "test-zero-assigned-native";
+ let bundle = "test-zero-assigned-native-bundle";
+ dispatcher.estimate_provisioning(("tenant", "l4", bundle), Duration::from_secs(280));
+
+ for (estimate, native, compatibility) in [
+ (Duration::from_secs(95), "95", "60"),
+ (Duration::from_secs(40), "40", "40"),
+ ] {
+ dispatcher.estimate_provisioning((demand_pool, "l4", bundle), estimate);
+ for (route, surface, retry_after) in [
+ (RouteKind::Native, ProvisioningSurface::Native, native),
+ (
+ RouteKind::Compatibility,
+ ProvisioningSurface::OpenAiCompat,
+ compatibility,
+ ),
+ ] {
+ let case = format!("{route:?} {estimate:?}");
+ let resp = capped_lane_admission_response(
+ &state,
+ "tenant",
+ demand_pool,
+ "l4",
+ bundle,
+ "speech",
+ "acme/extract:remote",
+ surface,
+ route,
+ )
+ .await
+ .expect("a capped lane without an admitted worker provisions");
+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE, "{case}");
+ assert_eq!(resp.headers()["retry-after"], retry_after, "{case}");
+ let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap();
+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ value["error"]["message"],
+ "Capacity for model 'speech' is starting. Retry after the number of seconds in Retry-After.",
+ "{case}"
+ );
+ }
+ }
+ let lane = state
+ .demand_tracker
+ .resolve_lane(demand_pool, "l4", bundle)
+ .unwrap();
+ state.demand_tracker.clear(&lane);
+ }
+
+ /// A gateway whose logical pool `tenant` caps the local lane's machine
+ /// profile at one worker and admits the `assigned` workers, while a healthy
+ /// worker of the default pool serves the local lane. The transport
+ /// estimates the local lane `local`, and the same lane of `tenant` 280
+ /// seconds. `vectors` and `assistant` are aliases of its two models.
+ async fn capped_tenant_gateway(assigned: &[&str], local: Duration) -> TestGateway {
+ let mut gateway = TestGateway::new(&[
+ crate::handlers::test_support::LOCAL_ENCODE_MODEL,
+ HYBRID_GENERATE_MODEL,
+ ])
+ .await;
+ gateway.add_model_alias("vectors", "acme/local");
+ gateway.add_model_alias("assistant", "acme/chat");
+ gateway
+ .add_worker("local-1", LOCAL_LANE, &["acme/local", "acme/chat"])
+ .await;
+ let pools = &gateway.state.pool_manager;
+ pools
+ .create_pool_with_caps(
+ "tenant",
+ std::collections::HashMap::from([(LOCAL_LANE.1.to_string(), 0)]),
+ std::collections::HashMap::from([(LOCAL_LANE.1.to_string(), 1)]),
+ None,
+ None,
+ 0,
+ vec![],
+ )
+ .await
+ .unwrap();
+ let workers: Vec<_> = assigned
+ .iter()
+ .map(|name| {
+ (
+ name.to_string(),
+ format!("http://{name}:8080"),
+ LOCAL_LANE.1.to_string(),
+ LOCAL_LANE.2.to_string(),
+ LOCAL_LANE.0.to_string(),
+ )
+ })
+ .collect();
+ pools.assign_workers("tenant", &workers).await;
+ assert_eq!(
+ pools
+ .capped_lane_status("tenant", LOCAL_LANE.1, LOCAL_LANE.2)
+ .await
+ .unwrap()
+ .assigned_count,
+ assigned.len()
+ );
+ gateway.dispatcher.estimate_provisioning(LOCAL_LANE, local);
+ gateway.dispatcher.estimate_provisioning(
+ ("tenant", LOCAL_LANE.1, LOCAL_LANE.2),
+ Duration::from_secs(280),
+ );
+ gateway
+ }
+
+ fn tenant_request(uri: &str, body: serde_json::Value) -> Request {
+ let mut request = json_request(uri, body);
+ request
+ .headers_mut()
+ .insert("x-sie-pool", HeaderValue::from_static("tenant"));
+ request
+ }
+
+ /// A capped lane that admits no worker answers provisioning with the
+ /// estimate of the queue pool's lane, bounded by each request's route.
+ #[tokio::test]
+ async fn a_capped_lane_without_an_admitted_worker_answers_with_its_lane_estimate() {
+ for (local, native, compatibility) in [
+ (Duration::from_secs(95), "95", "60"),
+ (Duration::from_secs(40), "40", "40"),
+ ] {
+ let gateway = capped_tenant_gateway(&[], local).await;
+ let state = || State(Arc::clone(&gateway.state));
+ let responses = [
+ (
+ "encode",
+ "vectors",
+ native,
+ proxy_request(
+ state(),
+ tenant_request(
+ "/v1/encode/vectors",
+ serde_json::json!({"items": [{"text": "hello"}]}),
+ ),
+ "encode",
+ )
+ .await,
+ ),
+ (
+ "generate",
+ "assistant",
+ native,
+ proxy_request(
+ state(),
+ tenant_request(
+ "/v1/generate/assistant",
+ serde_json::json!({"prompt": "hello", "max_new_tokens": 4}),
+ ),
+ "generate",
+ )
+ .await,
+ ),
+ (
+ "embeddings",
+ "vectors",
+ compatibility,
+ proxy_openai_embeddings(
+ state(),
+ tenant_request(
+ "/v1/embeddings",
+ serde_json::json!({"model": "vectors", "input": "hello"}),
+ ),
+ )
+ .await,
+ ),
+ (
+ "chat",
+ "assistant",
+ compatibility,
+ proxy_chat(
+ state(),
+ tenant_request(
+ "/v1/chat/completions",
+ serde_json::json!({
+ "model": "assistant",
+ "messages": [{"role": "user", "content": "hello"}],
+ }),
+ ),
+ )
+ .await,
+ ),
+ ];
+ for (case, model, retry_after, response) in responses {
+ assert_capped_provisioning(
+ response,
+ &format!("{case} {local:?}"),
+ model,
+ retry_after,
+ )
+ .await;
+ }
+ assert!(gateway.dispatcher.dispatched().is_empty());
+ }
+ }
+
+ async fn assert_capped_provisioning(
+ response: Response,
+ case: &str,
+ model: &str,
+ retry_after: &str,
+ ) {
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{case}");
+ assert_eq!(response.headers()["retry-after"], retry_after, "{case}");
+ assert_eq!(
+ response.headers()["x-sie-error-code"],
+ err_code::PROVISIONING,
+ "{case}"
+ );
+ let body = to_bytes(response.into_body(), 64 * 1024).await.unwrap();
+ let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ assert_eq!(
+ value["error"]["message"],
+ format!(
+ "Capacity for model '{model}' is starting. Retry after the number of seconds in Retry-After."
+ ),
+ "{case}"
+ );
+ }
+
+ /// A capped lane whose admitted workers are not registered has no worker
+ /// to publish to, and answers provisioning with the estimate of the queue
+ /// pool's lane, bounded by each request's route.
+ #[tokio::test]
+ async fn a_capped_lane_without_a_registered_admitted_worker_answers_with_its_lane_estimate() {
+ for (local, native, compatibility) in [
+ (Duration::from_secs(95), "95", "60"),
+ (Duration::from_secs(40), "40", "40"),
+ ] {
+ let gateway = capped_tenant_gateway(&["assigned-elsewhere"], local).await;
+ let state = || State(Arc::clone(&gateway.state));
+ let responses = [
+ (
+ "encode",
+ native,
+ proxy_request(
+ state(),
+ tenant_request(
+ "/v1/encode/vectors",
+ serde_json::json!({"items": [{"text": "hello"}]}),
+ ),
+ "encode",
+ )
+ .await,
+ ),
+ (
+ "embeddings",
+ compatibility,
+ proxy_openai_embeddings(
+ state(),
+ tenant_request(
+ "/v1/embeddings",
+ serde_json::json!({"model": "vectors", "input": "hello"}),
+ ),
+ )
+ .await,
+ ),
+ ];
+ for (case, retry_after, response) in responses {
+ assert_capped_provisioning(
+ response,
+ &format!("{case} {local:?}"),
+ "vectors",
+ retry_after,
+ )
+ .await;
+ }
+ assert!(gateway.dispatcher.dispatched().is_empty());
+ }
+ }
+
#[tokio::test]
async fn test_record_publish_failure_backpressure_records_demand() {
// Backpressure (a present-but-saturated worker) must record pending
@@ -19963,11 +20318,24 @@ mod tests {
}
}
+ /// A provisioning estimate of `seconds` for one lane on a native route.
+ fn provisioning_estimate_of(seconds: u64) -> ProvisioningEstimate {
+ let dispatcher = Arc::new(crate::handlers::test_support::RecordingDispatcher::default());
+ dispatcher
+ .estimate_provisioning(("default", "l4", "default"), Duration::from_secs(seconds));
+ ProvisioningEstimate {
+ dispatcher: Some(dispatcher),
+ targets: vec![lane_wake_target("default", "l4", "default", "acme/m")],
+ route: RouteKind::Native,
+ }
+ }
+
#[tokio::test]
- async fn test_openai_provisioning_response_without_model_is_retryable_503() {
+ async fn test_openai_provisioning_response_is_retryable_503() {
+ let state = admission_test_state(Arc::new(PoolManager::new(vec!["l4".to_string()])));
let resp = build_provisioning_response_for_surface(
- "",
- HeaderValue::from_static(PROVISIONING_RETRY_AFTER),
+ "acme/m",
+ ProvisioningEstimate::new(&state, Vec::new(), RouteKind::Compatibility),
ProvisioningSurface::OpenAiCompat,
);
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
@@ -19990,7 +20358,7 @@ mod tests {
assert_eq!(value["error"]["code"], oai_code::PROVISIONING);
assert_eq!(
value["error"]["message"],
- "Capacity is starting. Retry after the number of seconds in Retry-After."
+ "Capacity for model 'acme/m' is starting. Retry after the number of seconds in Retry-After."
);
}
@@ -20003,11 +20371,12 @@ mod tests {
(Duration::from_millis(5_001), 6, 6),
(Duration::from_millis(59_001), 60, 60),
(Duration::from_secs(61), 61, 60),
- (Duration::from_secs(660), 660, 60),
- (Duration::from_millis(899_001), 900, 60),
- (Duration::from_secs(900), 900, 60),
- (Duration::from_secs(901), 900, 60),
- (Duration::MAX, 900, 60),
+ (Duration::from_secs(240), 240, 60),
+ (Duration::from_millis(299_001), 300, 60),
+ (Duration::from_secs(300), 300, 60),
+ (Duration::from_secs(301), 300, 60),
+ (Duration::from_secs(900), 300, 60),
+ (Duration::MAX, 300, 60),
] {
assert_eq!(
bounded_provisioning_retry_after_s(estimate, RouteKind::Native),
@@ -20023,59 +20392,54 @@ mod tests {
}
#[tokio::test]
- async fn test_provisioning_retry_after_takes_the_soonest_transport_estimate() {
+ async fn test_provisioning_retry_after_takes_the_soonest_lane_value() {
use crate::handlers::test_support::RecordingDispatcher;
let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));
let mut state = admission_test_state(pm);
- let lane = |profile: &str| lane_wake_target("default", profile, "default", "acme/m");
+ let retry_after = |state: &AppState, profiles: &[&str], route| {
+ let lanes = profiles
+ .iter()
+ .map(|profile| lane_wake_target("default", profile, "default", "acme/m"))
+ .collect();
+ ProvisioningEstimate::new(state, lanes, route).retry_after()
+ };
let default = HeaderValue::from_static(PROVISIONING_RETRY_AFTER);
let routes = [RouteKind::Native, RouteKind::Compatibility];
for route in routes {
- assert_eq!(
- provisioning_retry_after(&state, &[lane("l4")], route),
- default
- );
+ assert_eq!(retry_after(&state, &["l4"], route), default);
}
let dispatcher = Arc::new(RecordingDispatcher::default());
state.work_publisher = Some(dispatcher.clone());
for route in routes {
- assert_eq!(
- provisioning_retry_after(&state, &[lane("l4")], route),
- default
- );
- assert_eq!(provisioning_retry_after(&state, &[], route), default);
+ assert_eq!(retry_after(&state, &["l4"], route), default);
+ assert_eq!(retry_after(&state, &[], route), default);
}
- dispatcher.estimate_provisioning(("default", "l4", "default"), Duration::from_secs(680));
+ dispatcher.estimate_provisioning(("default", "l4", "default"), Duration::from_secs(280));
dispatcher.estimate_provisioning(
("default", "h100", "default"),
Duration::from_millis(240_500),
);
- let lanes = [lane("l4"), lane("h100"), lane("a10g")];
+ assert_eq!(retry_after(&state, &["l4"], RouteKind::Native), "280");
assert_eq!(
- provisioning_retry_after(&state, &[lane("l4")], RouteKind::Native),
- "680"
- );
- assert_eq!(
- provisioning_retry_after(&state, &lanes, RouteKind::Native),
+ retry_after(&state, &["l4", "h100"], RouteKind::Native),
"241"
);
+ assert_eq!(retry_after(&state, &["l4"], RouteKind::Compatibility), "60");
assert_eq!(
- provisioning_retry_after(&state, &[lane("l4")], RouteKind::Compatibility),
- "60"
- );
- assert_eq!(
- provisioning_retry_after(&state, &lanes, RouteKind::Compatibility),
+ retry_after(&state, &["l4", "h100"], RouteKind::Compatibility),
"60"
);
for route in routes {
assert_eq!(
- provisioning_retry_after(&state, &[lane("a10g")], route),
- default
+ retry_after(&state, &["l4", "h100", "a10g"], route),
+ default,
+ "a lane without an estimate counts as the default"
);
+ assert_eq!(retry_after(&state, &["a10g"], route), default);
}
dispatcher.estimate_provisioning(
@@ -20083,18 +20447,12 @@ mod tests {
Duration::from_millis(30_200),
);
for route in routes {
- assert_eq!(provisioning_retry_after(&state, &lanes, route), "31");
+ assert_eq!(retry_after(&state, &["l4", "h100", "a10g"], route), "31");
}
dispatcher.estimate_provisioning(("default", "l4", "default"), Duration::from_secs(7_200));
- assert_eq!(
- provisioning_retry_after(&state, &[lane("l4")], RouteKind::Native),
- "900"
- );
- assert_eq!(
- provisioning_retry_after(&state, &[lane("l4")], RouteKind::Compatibility),
- "60"
- );
+ assert_eq!(retry_after(&state, &["l4"], RouteKind::Native), "300");
+ assert_eq!(retry_after(&state, &["l4"], RouteKind::Compatibility), "60");
}
#[tokio::test]
@@ -20103,9 +20461,9 @@ mod tests {
ProvisioningSurface::Native,
ProvisioningSurface::OpenAiCompat,
] {
- let resp = provisioning_response("acme/m", HeaderValue::from_static("680"), surface);
+ let resp = provisioning_response("acme/m", provisioning_estimate_of(280), surface);
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
- assert_eq!(resp.headers()["retry-after"], "680");
+ assert_eq!(resp.headers()["retry-after"], "280");
assert_eq!(resp.headers()["x-sie-error-code"], err_code::PROVISIONING);
let body = to_bytes(resp.into_body(), 64 * 1024).await.unwrap();
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
@@ -21680,13 +22038,13 @@ mod tests {
async fn test_translate_inner_compat_provisioning_error_to_openai_503() {
let resp = provisioning_response(
"acme/m",
- HeaderValue::from_static("680"),
+ provisioning_estimate_of(280),
ProvisioningSurface::Native,
);
let out = translate_inner_compat_error(resp).await;
assert_eq!(out.status(), StatusCode::SERVICE_UNAVAILABLE);
- assert_eq!(out.headers().get("retry-after").unwrap(), "680");
+ assert_eq!(out.headers().get("retry-after").unwrap(), "280");
assert_eq!(
out.headers().get("x-sie-error-code").unwrap(),
err_code::PROVISIONING
@@ -28005,12 +28363,12 @@ mod tests {
#[tokio::test]
async fn test_build_streaming_error_response_provisioning_is_provisioning() {
let err = StreamingDriverErr::Provisioning {
- model: "acme/m".to_string(),
- retry_after: HeaderValue::from_static("680"),
+ requested_model: "acme/m".to_string(),
+ estimate: provisioning_estimate_of(280),
};
let resp = build_streaming_error_response(&err);
assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);
- assert_eq!(resp.headers().get("retry-after").unwrap(), "680");
+ assert_eq!(resp.headers().get("retry-after").unwrap(), "280");
assert_eq!(
resp.headers().get("x-sie-error-code").unwrap(),
err_code::PROVISIONING
diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rs
index a72198547..8fe9d8e52 100644
--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs
+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs
@@ -9,10 +9,12 @@
use std::sync::{Arc, Mutex, PoisonError};
use axum::extract::Request;
+use axum::http::header::RETRY_AFTER;
use axum::http::{Extensions, HeaderMap, HeaderName, HeaderValue, StatusCode};
use axum::response::Response;
use futures_util::FutureExt;
+use crate::handlers::proxy::ProvisioningEstimate;
use crate::observability::metrics as telemetry;
use crate::server::{
AppState, GenerationRequestIntent, GovernedGenerationRoute, RemoteRouteReason,
@@ -350,7 +352,9 @@ impl FallbackAttempt {
}
/// Called after normal disclosure stamping and before HTTP success/output.
- /// A failed bridge preserves the original body and Retry-After verbatim.
+ /// A failed bridge preserves the original body and Retry-After verbatim,
+ /// except that a provisioning answer's Retry-After is estimated again from
+ /// the lanes and route kind it carries, as a new answer would be now.
pub(crate) fn finish(&self, mut response: Response) -> Response {
let (original, observation) = {
let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
@@ -394,7 +398,15 @@ impl FallbackAttempt {
let status = response.status();
fallback_error(status, attempt_error_code(&mut response).as_deref())
};
+ let retry_after = original
+ .response
+ .extensions()
+ .get::<ProvisioningEstimate>()
+ .map(ProvisioningEstimate::retry_after);
let headers = original.response.headers_mut();
+ if let Some(retry_after) = retry_after {
+ headers.insert(RETRY_AFTER, retry_after);
+ }
headers.insert(SERVED_BY_HEADER, HeaderValue::from_static("local"));
headers.remove(UPSTREAM_HEADER);
headers.insert("x-sie-fallback-reason", reason);
@@ -4753,7 +4765,7 @@ mod tests {
#[tokio::test]
async fn a_cold_lane_answers_provisioning_with_its_transport_estimate() {
for (estimate, native, compatibility) in [
- (Duration::from_millis(659_200), "660", "60"),
+ (Duration::from_millis(259_200), "260", "60"),
(Duration::from_millis(44_200), "45", "45"),
] {
let gateway = transport_cold_gateway(None).await;
@@ -4763,10 +4775,17 @@ mod tests {
.estimate_provisioning(LOCAL_LANE, estimate);
let extraction = extract(&gateway, extraction_request(false, json!({}))).await;
- let chat = buffered_surface(&gateway, "chat", json!({})).await;
+ let chat = proxy_chat(
+ State(Arc::clone(&gateway.state)),
+ json_request(
+ "/v1/chat/completions",
+ json!({"model": "acme__chat", "messages": [{"role": "user", "content": "hello"}]}),
+ ),
+ )
+ .await;
for (model, response, retry_after) in [
("acme/extract", extraction, native),
- ("acme/chat", chat, compatibility),
+ ("acme__chat", chat, compatibility),
] {
let case = format!("{model} {estimate:?}");
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{case}");
@@ -4778,10 +4797,80 @@ mod tests {
}
}
+ /// A transport may estimate a lane only once its wake is published, so a
+ /// refusal answered after the wake carries that estimate.
+ #[tokio::test]
+ async fn a_lane_estimated_once_its_wake_is_published_answers_with_that_estimate() {
+ for (estimate, native, compatibility) in [
+ (Duration::from_secs(280), "280", "60"),
+ (Duration::from_secs(45), "45", "45"),
+ ] {
+ for (surface, retry_after) in [("encode", native), ("embeddings", compatibility)] {
+ let case = format!("{surface} {estimate:?}");
+ let gateway = numerical_gateway_with_local(
+ NUMERICAL_FALLBACK,
+ &["acme/hybrid-encode"],
+ ADMITTED_IDENTITY,
+ )
+ .await;
+ gateway.dispatcher.report_cold_local_lane();
+ let registry = Arc::clone(&gateway.state.registry);
+ let dispatcher = Arc::clone(&gateway.dispatcher);
+ gateway.dispatcher.on_model_load(Box::new(move || {
+ registry.health_subscription_started();
+ dispatcher.estimate_provisioning(LOCAL_LANE, estimate);
+ }));
+
+ let response = if surface == "encode" {
+ proxy_request(
+ State(Arc::clone(&gateway.state)),
+ json_request(
+ "/v1/encode/acme__hybrid-encode",
+ json!({"items":[{"text":"hello"}]}),
+ ),
+ "encode",
+ )
+ .await
+ } else {
+ proxy_openai_embeddings(
+ State(Arc::clone(&gateway.state)),
+ json_request(
+ "/v1/embeddings",
+ json!({"model": "acme__hybrid-encode", "input": "hello"}),
+ ),
+ )
+ .await
+ };
+
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{case}");
+ assert_eq!(response.headers()["retry-after"], retry_after, "{case}");
+ assert_eq!(
+ response.headers()["x-sie-error-code"],
+ "PROVISIONING",
+ "{case}"
+ );
+ assert!(
+ !response.headers().contains_key("x-sie-fallback-reason"),
+ "{case}"
+ );
+ assert_eq!(
+ gateway.dispatcher.dispatched(),
+ vec![dispatched("load", LOCAL_LANE, "acme/hybrid-encode")],
+ "{case}"
+ );
+ assert_eq!(
+ error_message(response).await,
+ starting_message("acme__hybrid-encode"),
+ "{case}"
+ );
+ }
+ }
+ }
+
#[tokio::test]
async fn a_remote_lane_still_starting_restores_the_local_lane_estimate() {
for (local, native, compatibility) in [
- (Duration::from_secs(680), "680", "60"),
+ (Duration::from_secs(280), "280", "60"),
(Duration::from_secs(45), "45", "45"),
] {
let gateway = transport_cold_gateway(None).await;
@@ -4808,14 +4897,23 @@ mod tests {
}
}
+ /// A refusal held through a remote attempt is estimated again when it is
+ /// restored. An estimate the transport gives meanwhile replaces the one it
+ /// was built with, and a lane whose estimate is gone counts as the
+ /// default again. The remote lane's estimate never applies.
#[tokio::test]
- async fn a_restored_cold_refusal_keeps_the_estimate_it_was_built_with() {
+ async fn a_restored_cold_refusal_is_estimated_when_it_is_restored() {
let generation = format!(
"{HYBRID_GENERATE_MODEL}\nrouting:\n policy: fallback\n fallback_profile: remote\n"
);
- for (local, native, compatibility) in [
- (Duration::from_secs(680), "680", "60"),
- (Duration::from_secs(45), "45", "45"),
+ // Without a machine profile, a cold lookup is about every machine
+ // profile of the pool.
+ let cold_lanes = [LOCAL_LANE, (LOCAL_LANE.0, REMOTE_LANE.1, LOCAL_LANE.2)];
+ for (built, restored, native, compatibility) in [
+ (None, Some(Duration::from_secs(280)), "280", "60"),
+ (None, Some(Duration::from_secs(45)), "45", "45"),
+ (Some(Duration::from_secs(280)), None, "60", "60"),
+ (Some(Duration::from_secs(45)), None, "60", "60"),
] {
for (surface, stream) in [
("native", false),
@@ -4826,7 +4924,7 @@ mod tests {
("chat", true),
("completions", true),
] {
- let case = format!("{surface} stream={stream} {local:?}");
+ let case = format!("{surface} stream={stream} {built:?} then {restored:?}");
let gateway = TestGateway::new(&[&generation]).await;
gateway
.add_verified_worker("remote-1", REMOTE_LANE, &[])
@@ -4834,10 +4932,24 @@ mod tests {
gateway
.dispatcher
.refuse_remote_work("RESOURCE_EXHAUSTED", Some(7));
- gateway.dispatcher.estimate_provisioning(LOCAL_LANE, local);
gateway
.dispatcher
.estimate_provisioning(REMOTE_LANE, Duration::from_secs(30));
+ if let Some(estimate) = built {
+ for lane in cold_lanes {
+ gateway.dispatcher.estimate_provisioning(lane, estimate);
+ }
+ }
+ gateway
+ .dispatcher
+ .on_remote_work(Box::new(move |dispatcher| {
+ for lane in cold_lanes {
+ match restored {
+ Some(estimate) => dispatcher.estimate_provisioning(lane, estimate),
+ None => dispatcher.forget_provisioning_estimate(lane),
+ }
+ }
+ }));
let response = if stream {
streaming_surface(&gateway, surface, json!({})).await
@@ -4906,7 +5018,7 @@ mod tests {
),
(
"native generate",
- "acme/chat:remote",
+ "acme__chat:remote",
native,
proxy_request(
state(),
@@ -4920,7 +5032,7 @@ mod tests {
),
(
"native generate stream",
- "acme/chat:remote",
+ "acme__chat:remote",
native,
proxy_request(
state(),
@@ -4971,6 +5083,45 @@ mod tests {
)
.await,
),
+ (
+ "completions",
+ "acme/chat:remote",
+ compatibility,
+ proxy_completions(
+ state(),
+ json_request(
+ "/v1/completions",
+ json!({"model": "acme/chat:remote", "prompt": "hello", "max_tokens": 4}),
+ ),
+ )
+ .await,
+ ),
+ (
+ "completions stream",
+ "acme/chat:remote",
+ compatibility,
+ proxy_completions(
+ state(),
+ json_request(
+ "/v1/completions",
+ json!({"model": "acme/chat:remote", "prompt": "hello", "max_tokens": 4, "stream": true}),
+ ),
+ )
+ .await,
+ ),
+ (
+ "responses",
+ "acme/chat:remote",
+ compatibility,
+ proxy_responses(
+ state(),
+ json_request(
+ "/v1/responses",
+ json!({"model": "acme/chat:remote", "input": "hello"}),
+ ),
+ )
+ .await,
+ ),
];
for (case, model, retry_after, response) in responses {
let case = format!("{case} {remote:?}");
@@ -5055,6 +5206,427 @@ profiles:
}
}
+ /// A cold lookup on a route that wraps a native route caps the estimate
+ /// that the native route keeps.
+ #[tokio::test]
+ async fn a_cold_lookup_caps_the_estimate_on_the_routes_that_wrap_a_native_route() {
+ // Without a machine profile, a cold lookup is about every machine
+ // profile of the pool.
+ let cold_lanes = [LOCAL_LANE, (LOCAL_LANE.0, REMOTE_LANE.1, LOCAL_LANE.2)];
+ for (estimate, native, compatibility) in [
+ (Duration::from_secs(95), "95", "60"),
+ (Duration::from_secs(40), "40", "40"),
+ ] {
+ let gateway = TestGateway::new(&[LOCAL_ENCODE_MODEL]).await;
+ for lane in cold_lanes {
+ gateway.dispatcher.estimate_provisioning(lane, estimate);
+ }
+ let state = || State(Arc::clone(&gateway.state));
+ let responses = [
+ (
+ "encode",
+ native,
+ proxy_request(
+ state(),
+ json_request(
+ "/v1/encode/acme/local",
+ json!({"items": [{"text": "hello"}]}),
+ ),
+ "encode",
+ )
+ .await,
+ ),
+ (
+ "embeddings",
+ compatibility,
+ proxy_openai_embeddings(
+ state(),
+ json_request(
+ "/v1/embeddings",
+ json!({"model": "acme/local", "input": "hello"}),
+ ),
+ )
+ .await,
+ ),
+ ];
+ for (case, retry_after, response) in responses {
+ let case = format!("{case} {estimate:?}");
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{case}");
+ assert_eq!(response.headers()["retry-after"], retry_after, "{case}");
+ assert_eq!(
+ response.headers()["x-sie-error-code"],
+ "PROVISIONING",
+ "{case}"
+ );
+ }
+ }
+ }
+
+ /// A score model served locally, with a numerical bridge to its remote
+ /// profile on `team-sie`.
+ const HYBRID_SCORE_MODEL: &str = "\
+sie_id: acme/hybrid-score
+hf_id: acme/hybrid-score
+tasks:
+ score: {}
+profiles:
+ default:
+ adapter_path: sie_server.adapters.bert_flash:BertFlashAdapter
+ max_batch_tokens: 4096
+ remote:
+ adapter_path: sie_server.adapters.remote.sie:SieUpstreamAdapter
+ max_batch_tokens: 8192
+ adapter_options:
+ loadtime:
+ upstream: team-sie
+ upstream_model: acme/hybrid-score
+";
+
+ /// A gateway whose remote worker admits the local identity of the score
+ /// model that its local worker has loaded.
+ async fn numerical_score_gateway() -> TestGateway {
+ let gateway =
+ TestGateway::new(&[&format!("{HYBRID_SCORE_MODEL}{NUMERICAL_FALLBACK}")]).await;
+ gateway
+ .add_numerical_worker(
+ "remote-1",
+ REMOTE_LANE,
+ &[],
+ true,
+ inventory(json!({
+ "model_id": "acme/hybrid-score",
+ "model_contract_sha256": MODEL_CONTRACT,
+ "local_identity": null,
+ "admission": {
+ "sha256": "a".repeat(64),
+ "kind": "sie",
+ "local_identities": [ADMITTED_IDENTITY],
+ "model_contract_sha256": MODEL_CONTRACT,
+ "outputs": ["score"],
+ "expires_at_unix_ms": unix_ms_from_now(60_000),
+ },
+ })),
+ )
+ .await;
+ gateway
+ .add_numerical_worker(
+ "local-1",
+ LOCAL_LANE,
+ &["acme/hybrid-score"],
+ true,
+ inventory(json!({
+ "model_id": "acme/hybrid-score",
+ "model_contract_sha256": MODEL_CONTRACT,
+ "local_identity": ADMITTED_IDENTITY,
+ })),
+ )
+ .await;
+ gateway
+ }
+
+ /// The compatibility routes that wrap a native route cap the estimate of
+ /// a lane its transport reports cold, which the native route keeps.
+ #[tokio::test]
+ async fn the_compatibility_routes_cap_a_transport_cold_lane_estimate() {
+ for (local, native, compatibility) in [
+ (Duration::from_secs(95), "95", "60"),
+ (Duration::from_secs(40), "40", "40"),
+ ] {
+ let encoding = numerical_gateway_with_local(
+ NUMERICAL_FALLBACK,
+ &["acme/hybrid-encode"],
+ ADMITTED_IDENTITY,
+ )
+ .await;
+ let scoring = numerical_score_gateway().await;
+ for gateway in [&encoding, &scoring] {
+ gateway.dispatcher.report_cold_local_lane();
+ gateway.dispatcher.refuse_model_loads();
+ gateway.dispatcher.estimate_provisioning(LOCAL_LANE, local);
+ gateway
+ .dispatcher
+ .estimate_provisioning(REMOTE_LANE, Duration::from_secs(280));
+ }
+ let rerank =
+ json!({"model": "acme/hybrid-score", "query": "hello", "documents": ["world"]});
+
+ let responses = [
+ (
+ "encode",
+ native,
+ &encoding,
+ encode(&encoding, json!({"items": [{"text": "hello"}]})).await,
+ ),
+ (
+ "embeddings",
+ compatibility,
+ &encoding,
+ proxy_openai_embeddings(
+ State(Arc::clone(&encoding.state)),
+ json_request(
+ "/v1/embeddings",
+ json!({"model": "acme/hybrid-encode", "input": "hello"}),
+ ),
+ )
+ .await,
+ ),
+ (
+ "score",
+ native,
+ &scoring,
+ proxy_request(
+ State(Arc::clone(&scoring.state)),
+ json_request(
+ "/v1/score/acme/hybrid-score",
+ json!({"query": {"text": "hello"}, "items": [{"text": "world"}]}),
+ ),
+ "score",
+ )
+ .await,
+ ),
+ (
+ "rerank",
+ compatibility,
+ &scoring,
+ proxy_rerank(
+ State(Arc::clone(&scoring.state)),
+ json_request("/v1/rerank", rerank.clone()),
+ )
+ .await,
+ ),
+ (
+ "rerank v2",
+ compatibility,
+ &scoring,
+ proxy_rerank_v2(
+ State(Arc::clone(&scoring.state)),
+ json_request("/v2/rerank", rerank.clone()),
+ )
+ .await,
+ ),
+ ];
+ for (case, retry_after, gateway, response) in responses {
+ let case = format!("{case} {local:?}");
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{case}");
+ assert_eq!(response.headers()["retry-after"], retry_after, "{case}");
+ assert!(
+ !response.headers().contains_key("x-sie-fallback-reason"),
+ "{case}"
+ );
+ let woken = gateway.dispatcher.dispatched();
+ assert!(
+ woken.iter().all(|work| work.endpoint == "load"
+ && (
+ work.pool.as_str(),
+ work.machine_profile.as_str(),
+ work.bundle.as_str()
+ ) == LOCAL_LANE),
+ "{case}: {woken:?}"
+ );
+ assert!(!woken.is_empty(), "{case}");
+ }
+ }
+ }
+
+ /// A provisioning answer names the model as the caller sent it, not the
+ /// id that an alias, `__` or a profile suffix resolved it to.
+ #[tokio::test]
+ async fn a_provisioning_answer_names_the_model_the_caller_sent() {
+ let mut gateway = TestGateway::new(&[
+ LOCAL_ENCODE_MODEL,
+ REMOTE_ENCODE_MODEL,
+ HYBRID_GENERATE_MODEL,
+ ])
+ .await;
+ gateway.add_model_alias("vectors", "acme/remote");
+ gateway.add_model_alias("speech", "acme/chat:remote");
+ gateway.add_worker("remote-1", REMOTE_LANE, &[]).await;
+ gateway.dispatcher.report_remote_lane_starting();
+ let state = || State(Arc::clone(&gateway.state));
+ let messages = json!([{"role": "user", "content": "hello"}]);
+
+ let responses = [
+ (
+ "vectors",
+ proxy_request(
+ state(),
+ json_request("/v1/encode/vectors", json!({"items": [{"text": "hello"}]})),
+ "encode",
+ )
+ .await,
+ ),
+ (
+ "vectors",
+ proxy_openai_embeddings(
+ state(),
+ json_request(
+ "/v1/embeddings",
+ json!({"model": "vectors", "input": "hello"}),
+ ),
+ )
+ .await,
+ ),
+ (
+ "speech",
+ proxy_request(
+ state(),
+ json_request(
+ "/v1/generate/speech",
+ json!({"prompt": "hello", "max_new_tokens": 4}),
+ ),
+ "generate",
+ )
+ .await,
+ ),
+ (
+ "speech",
+ proxy_request(
+ state(),
+ json_request(
+ "/v1/generate/speech",
+ json!({"prompt": "hello", "max_new_tokens": 4, "stream": true}),
+ ),
+ "generate",
+ )
+ .await,
+ ),
+ (
+ "speech",
+ proxy_chat(
+ state(),
+ json_request(
+ "/v1/chat/completions",
+ json!({"model": "speech", "messages": messages}),
+ ),
+ )
+ .await,
+ ),
+ (
+ "speech",
+ proxy_chat(
+ state(),
+ json_request(
+ "/v1/chat/completions",
+ json!({"model": "speech", "messages": messages, "stream": true}),
+ ),
+ )
+ .await,
+ ),
+ (
+ "speech",
+ proxy_completions(
+ state(),
+ json_request(
+ "/v1/completions",
+ json!({"model": "speech", "prompt": "hello", "max_tokens": 4}),
+ ),
+ )
+ .await,
+ ),
+ (
+ "speech",
+ proxy_responses(
+ state(),
+ json_request(
+ "/v1/responses",
+ json!({"model": "speech", "input": "hello"}),
+ ),
+ )
+ .await,
+ ),
+ (
+ "acme__chat:remote",
+ proxy_chat(
+ state(),
+ json_request(
+ "/v1/chat/completions",
+ json!({"model": "acme__chat:remote", "messages": messages}),
+ ),
+ )
+ .await,
+ ),
+ ];
+ for (model, response) in responses {
+ assert_eq!(
+ response.status(),
+ StatusCode::SERVICE_UNAVAILABLE,
+ "{model}"
+ );
+ assert_eq!(
+ response.headers()["x-sie-error-code"],
+ "PROVISIONING",
+ "{model}"
+ );
+ assert_eq!(
+ error_message(response).await,
+ starting_message(model),
+ "{model}"
+ );
+ }
+ }
+
+ /// A generation model whose grammar requests run on its `no-spec` profile.
+ const GRAMMAR_ROUTED_MODEL: &str = "\
+sie_id: acme/grammar
+hf_id: acme/grammar
+tasks:
+ generate:
+ grammar_profile: no-spec
+ capabilities:
+ grammar: [json_schema]
+profiles:
+ default:
+ adapter_path: sie_server.adapters.sglang:SGLangAdapter
+ max_batch_tokens: 8192
+ no-spec:
+ adapter_path: sie_server.adapters.sglang:SGLangAdapter
+ max_batch_tokens: 8192
+";
+
+ /// A grammar request runs on the model's grammar profile, and its
+ /// provisioning answer names the model the caller sent.
+ #[tokio::test]
+ async fn a_grammar_request_provisioning_answer_names_the_model_the_caller_sent() {
+ let gateway = TestGateway::new(&[GRAMMAR_ROUTED_MODEL]).await;
+ let state = || State(Arc::clone(&gateway.state));
+ let schema = json!({"type": "object"});
+
+ let responses = [
+ proxy_request(
+ state(),
+ json_request(
+ "/v1/generate/acme__grammar",
+ json!({"prompt": "hello", "max_new_tokens": 4, "grammar": {"json_schema": schema}}),
+ ),
+ "generate",
+ )
+ .await,
+ proxy_chat(
+ state(),
+ json_request(
+ "/v1/chat/completions",
+ json!({
+ "model": "acme__grammar",
+ "messages": [{"role": "user", "content": "hello"}],
+ "response_format": {
+ "type": "json_schema",
+ "json_schema": {"name": "answer", "schema": schema},
+ },
+ }),
+ ),
+ )
+ .await,
+ ];
+ for response in responses {
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
+ assert_eq!(response.headers()["x-sie-error-code"], "PROVISIONING");
+ assert_eq!(
+ error_message(response).await,
+ starting_message("acme__grammar")
+ );
+ }
+ }
+
#[tokio::test]
async fn a_cold_lane_bridge_that_admission_refuses_dispatches_locally_without_a_wake() {
let config = format!("{HYBRID_ENCODE_MODEL}{NUMERICAL_FALLBACK}");
diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rs
index 9782d3c39..59a15cd13 100644
--- a/packages/sie_gateway/src/handlers/sse.rs
+++ b/packages/sie_gateway/src/handlers/sse.rs
@@ -100,7 +100,9 @@ pub struct SseParams<'a> {
pub state: &'a AppState,
pub work_publisher: Arc<dyn WorkDispatcher>,
pub physical_lane: PhysicalLane,
- /// DISPLAY id (the requested model) — surfaced in the streamed chunk
+ /// The model as the caller sent it, which a provisioning answer names.
+ pub requested_model: String,
+ /// DISPLAY id (the resolved model) — surfaced in the streamed chunk
/// ``model`` field and the routing/timeout metric labels.
pub model: String,
/// DISPATCH id — the grammar ``:no-spec`` variant when routing fired,
@@ -116,6 +118,8 @@ pub struct SseParams<'a> {
pub bundle_config_hash: String,
pub work_params: publisher::WorkParams,
pub endpoint: SseEndpoint,
+ /// The kind of route the request arrived on.
+ pub(crate) route: crate::handlers::proxy::RouteKind,
}
/// Build the SSE response. Publishes the work item, subscribes to
@@ -135,6 +139,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
state,
work_publisher,
physical_lane,
+ requested_model,
model,
dispatch_model,
bundle,
@@ -145,6 +150,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
bundle_config_hash,
work_params,
endpoint,
+ route,
} = params;
// Resolve the routing key & target the same way
@@ -258,15 +264,9 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
&physical_lane,
"no_consumers",
);
- let route = match endpoint {
- SseEndpoint::Generate => crate::handlers::proxy::RouteKind::Native,
- SseEndpoint::Chat { .. } | SseEndpoint::Completion { .. } => {
- crate::handlers::proxy::RouteKind::Compatibility
- }
- };
- let retry_after = crate::handlers::proxy::provisioning_retry_after(
+ let estimate = crate::handlers::proxy::ProvisioningEstimate::new(
state,
- &[crate::handlers::proxy::lane_wake_target(
+ vec![crate::handlers::proxy::lane_wake_target(
&pool,
&gpu,
&bundle,
@@ -275,8 +275,8 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
route,
);
return crate::handlers::proxy::provisioning_response(
- &model,
- retry_after,
+ &requested_model,
+ estimate,
crate::handlers::proxy::ProvisioningSurface::OpenAiCompat,
);
}
diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rs
index 0103c5c0d..c807ac33d 100644
--- a/packages/sie_gateway/src/handlers/test_support.rs
+++ b/packages/sie_gateway/src/handlers/test_support.rs
@@ -177,9 +177,12 @@ pub(crate) struct RecordingDispatcher {
fallback_reasons: Mutex<Vec<Option<FallbackTrigger>>>,
numerical_admissions: Mutex<Vec<Option<String>>>,
on_model_load: Mutex<Option<Box<dyn FnOnce() + Send>>>,
+ on_remote_work: Mutex<Option<RemoteWorkAction>>,
provisioning_estimates: Mutex<HashMap<LaneKey, Duration>>,
}
+type RemoteWorkAction = Box<dyn FnOnce(&RecordingDispatcher) + Send>;
+
impl RecordingDispatcher {
/// Estimate that the `(pool, machine_profile, bundle)` lane needs
/// `estimate` before it can accept work.
@@ -190,11 +193,24 @@ impl RecordingDispatcher {
.insert(LaneKey::new(lane.0, lane.1, lane.2), estimate);
}
+ /// Stop estimating the `(pool, machine_profile, bundle)` lane.
+ pub(crate) fn forget_provisioning_estimate(&self, lane: (&str, &str, &str)) {
+ self.provisioning_estimates
+ .lock()
+ .unwrap()
+ .remove(&LaneKey::new(lane.0, lane.1, lane.2));
+ }
+
/// Run `action` once, when the next load-only item is published.
pub(crate) fn on_model_load(&self, action: Box<dyn FnOnce() + Send>) {
*self.on_model_load.lock().unwrap() = Some(action);
}
+ /// Run `action` once, when the next remote-lane work is published.
+ pub(crate) fn on_remote_work(&self, action: RemoteWorkAction) {
+ *self.on_remote_work.lock().unwrap() = Some(action);
+ }
+
/// Answer remote-lane work as a remote worker does when its upstream cannot
/// serve now: a published `code` error with the upstream's wait, if any.
pub(crate) fn refuse_remote_work(&self, code: &'static str, retry_after_s: Option<u32>) {
@@ -304,7 +320,14 @@ impl RecordingDispatcher {
}
fn record(&self, dispatched: Dispatched) {
+ let remote_work = dispatched.bundle == REMOTE_LANE.2 && dispatched.endpoint != "load";
self.dispatched.lock().unwrap().push(dispatched);
+ if remote_work {
+ let action = self.on_remote_work.lock().unwrap().take();
+ if let Some(action) = action {
+ action(self);
+ }
+ }
}
fn record_authority(&self, target: &PublishTarget, params: &WorkParams) {
@@ -812,6 +835,15 @@ impl TestGateway {
.model_access_policy = Some(policy);
}
+ /// Resolve `alias` to `target`, as an operator's model alias does.
+ pub(crate) fn add_model_alias(&mut self, alias: &str, target: &str) {
+ let state = Arc::get_mut(&mut self.state).expect("the gateway state is not shared yet");
+ Arc::get_mut(&mut state.config)
+ .expect("the gateway config is not shared yet")
+ .model_aliases
+ .insert(alias.to_string(), target.to_string());
+ }
+
/// Wait at most `seconds` for queued results.
pub(crate) fn set_request_timeout(&mut self, seconds: f64) {
let state = Arc::get_mut(&mut self.state).expect("the gateway state is not shared yet");
diff --git a/packages/sie_gateway/src/queue/dispatch.rs b/packages/sie_gateway/src/queue/dispatch.rs
index b6f0dbd77..996e6ced3 100644
--- a/packages/sie_gateway/src/queue/dispatch.rs
+++ b/packages/sie_gateway/src/queue/dispatch.rs
@@ -203,9 +203,12 @@ pub trait WorkDispatcher: Send + Sync {
/// `503 PROVISIONING` for that lane, on the request path, so it must not
/// block. `target` is the lane's pool target, with no worker pinned. The
/// gateway sends the estimate as `Retry-After`, rounded up to whole
- /// seconds and clamped to 5 to 900 seconds on the native routes and to 5
+ /// seconds and clamped to 5 to 300 seconds on the native routes and to 5
/// to 60 seconds on the OpenAI-compatible and other compatibility routes.
- /// `None` keeps the gateway's 60-second default on both.
+ /// `None` counts as the gateway's 60-second default on both, and an
+ /// answer about several lanes sends the soonest of their values. The
+ /// gateway reads the estimate again when it restores a provisioning
+ /// answer it held through a remote attempt.
fn provisioning_retry_after(&self, _target: &PublishTarget) -> Option<Duration> {
None
}
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index 916aec307..e8d4ca8de 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -662,8 +662,10 @@ pool subject. Its work item names the trigger in `fallback_reason`, so the remot
worker answers it at once whenever it cannot serve it now, rather than
redelivering it until the gateway's request timeout. Remote failure restores the
original local refusal body and `Retry-After`, with `X-SIE-Fallback-Reason` and
-`X-SIE-Fallback-Error`; success discloses the remote profile's upstream. The
-customer model name remains the requested model.
+`X-SIE-Fallback-Error`; a restored `PROVISIONING` refusal takes its
+`Retry-After` from the transport's estimate at that moment. Success discloses
+the remote profile's upstream. The customer model name remains the requested
+model.
The gateway derives `X-SIE-Fallback-Error` from the remote worker's error code
as a single node derives it from its remote attempt, with one difference. When