Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
fix(gateway): name the model in cold-start refusals and let the transport set Retry-After (#688)
Krisztian Gajdarce295a970c13
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 21d7649b3..1bbe1974c 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -59,8 +59,8 @@ 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: 60`, `X-SIE-Error-Code: PROVISIONING`, and gateway version headers. 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 (`Retry-After: 60`, `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 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 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.- When **every** failed item carries **`MODEL_LOAD_FAILED`**, the gateway returns **`502 Bad Gateway`** with the SDK-style **`error`** object (`code`, `message`, `error_class`, `attempts`, `permanent`) — matching the terminal model-load contract consumed by SDK retry logic (no `Retry-After`; the SDK must not burn the `MODEL_LOADING` retry budget). The gateway synthesises conservative `attempts` / `permanent` fields on this queue path when the worker payload does not carry registry-shaped failure metadata.@@ -1089,3 +1089,33 @@ lane. It is `false` by default and is a non-publishing hint.- **No bridge.** A request that is not bridged dispatches as before.- **A remote attempt refused as `PROVISIONING`** received no answer. Itrestores the local refusal with `X-SIE-Fallback-Error: QUEUE_FULL`.+- **How long a cold lane takes.** `WorkDispatcher::provisioning_retry_after`+ is a second non-publishing hint: an estimate of how long the lane needs+ before it can accept work. It is `None` by default. The gateway reads it,+ with the lane's pool target, only when it answers `503 PROVISIONING` for+ 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 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.+ - On the OpenAI-compatible routes (`/v1/chat/completions`,+ `/v1/completions`, `/v1/responses`, `/v1/embeddings`,+ `/v1/audio/transcriptions`) and the rerank routes (`/v1/rerank`,+ `/v2/rerank`) the ceiling is 60 seconds. The OpenAI Python client+ honors `Retry-After` only when it is greater than 0 and at most 60+ seconds. Above that it ignores the header and retries on its own+ short backoff, so a client with many retries would spend them within+ 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.+ - 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.diff --git a/packages/sie_gateway/src/handlers/audio.rs b/packages/sie_gateway/src/handlers/audio.rsindex fe66dbc32..5020a364c 100644--- a/packages/sie_gateway/src/handlers/audio.rs+++ b/packages/sie_gateway/src/handlers/audio.rs@@ -24,7 +24,7 @@ use super::serving_disclosure::{DeferredFallbackFinish, FallbackAttempt};use super::proxy::{invalid_remote_header_response, is_openai_compat_forwarded_header,is_openai_compat_inner_request_header, is_valid_compat_model_id, proxy_request,- translate_inner_compat_error,+ translate_inner_compat_error, CompatibilityRoute,};const MAX_AUDIO_FILE_BYTES: usize = 24 * 1024 * 1024;@@ -675,6 +675,7 @@ pub async fn proxy_openai_transcription(inner_request.extensions_mut().insert(DeferredFallbackFinish);+ inner_request.extensions_mut().insert(CompatibilityRoute);let native_response = proxy_request(State(state), inner_request, "extract").await;let native_headers = native_response.headers().clone();let mut response = async {@@ -990,6 +991,36 @@ mod tests {assert_eq!(error.code, oai_code::PAYLOAD_TOO_LARGE);}+ #[tokio::test]+ async fn audio_transcriptions_cap_the_provisioning_estimate() {+ for (local, retry_after) in [+ (std::time::Duration::from_secs(680), "60"),+ (std::time::Duration::from_secs(45), "45"),+ ] {+ let gateway = TestGateway::new(&[HYBRID_EXTRACT_MODEL]).await;+ gateway.dispatcher.estimate_provisioning(LOCAL_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_cluster_fallback_preserves_bridge_and_restored_refusal_headers() {let config = format!(diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 158219da8..81d9c5d7b 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -377,6 +377,17 @@ 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;+/// 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.+const PROVISIONING_RETRY_AFTER_MIN_S: u64 = 5;+const NATIVE_PROVISIONING_RETRY_AFTER_MAX_S: u64 = 900;+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;const MODEL_LOADING_RETRY_AFTER: &str = RetryAfter::DEFAULT.model_loading;@@ -538,11 +549,39 @@ enum PoolResolution {}#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum ProvisioningSurface {+pub(crate) enum ProvisioningSurface {Native,OpenAiCompat,}+/// The kind of route a request arrived on, which sets the ceiling on a+/// transport's provisioning `Retry-After` estimate. Distinct from+/// [`ProvisioningSurface`], the error envelope: native `/v1/generate`+/// answers in the OpenAI envelope but is a native route.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum RouteKind {+ /// `/v1/encode`, `/v1/score`, `/v1/extract` and `/v1/generate`.+ Native,+ /// The OpenAI-compatible routes and the other compatibility routes+ /// (`/v1/rerank`, `/v2/rerank`), including those that wrap a native route.+ Compatibility,+}++/// Marks the inner native request of a compatibility route. The gateway+/// creates it; a caller cannot supply it.+#[derive(Clone, Copy)]+pub(crate) struct CompatibilityRoute;++/// A request's route kind: a compatibility route when its wrapper marked it+/// with [`CompatibilityRoute`], a native route otherwise.+fn route_kind(extensions: &Extensions) -> RouteKind {+ if extensions.get::<CompatibilityRoute>().is_some() {+ RouteKind::Compatibility+ } else {+ RouteKind::Native+ }+}+/// Result of `resolve_effective_pool` — bundles the routing decision/// with a flag telling the caller whether the registry had an exact/// `(bundle, machine_profile)` worker match.@@ -825,25 +864,60 @@ async fn demand_profiles_for_pool(}}-fn provisioning_message(gpu: &str, bundle: &str) -> String {- if gpu.is_empty() {- format!(- "No worker available for bundle '{}'. Provisioning in progress.",- bundle- )+/// 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!(- "No worker available for GPU type '{}'. Provisioning in progress.",- gpu+ "Capacity for model '{model}' is starting. Retry after the number of seconds in Retry-After.")}}-fn add_provisioning_headers(resp: &mut Response, retry_after: &'static str) {- resp.headers_mut().insert(- HeaderName::from_static("retry-after"),- HeaderValue::from_static(retry_after),- );+/// A transport's provisioning estimate in whole seconds, rounded up and+/// clamped to the provisioning `Retry-After` bounds of `route`.+fn bounded_provisioning_retry_after_s(estimate: Duration, route: RouteKind) -> u64 {+ let ceiling = match route {+ RouteKind::Native => NATIVE_PROVISIONING_RETRY_AFTER_MAX_S,+ RouteKind::Compatibility => COMPATIBILITY_PROVISIONING_RETRY_AFTER_MAX_S,+ };+ estimate+ .as_secs()+ .saturating_add(u64::from(estimate.subsec_nanos() > 0))+ .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],+ 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,+ )+}++fn add_provisioning_headers(resp: &mut Response, retry_after: HeaderValue) {+ resp.headers_mut()+ .insert(HeaderName::from_static("retry-after"), retry_after);resp.headers_mut().insert(HeaderName::from_static("x-sie-version"),HeaderValue::from_static(GATEWAY_VERSION),@@ -1022,56 +1096,67 @@ pub(crate) fn monitor_dispatch_durability(completion_rx}+/// [`provisioning_response`], counted as a provisioning response for+/// `surface`.fn build_provisioning_response_for_surface(- gpu: &str,- bundle: &str,+ model: &str,+ retry_after: HeaderValue,surface: ProvisioningSurface,) -> Response {- let message = provisioning_message(gpu, bundle);- match surface {- ProvisioningSurface::Native => {- record_provisioning_response(surface, StatusCode::SERVICE_UNAVAILABLE);- let mut resp = (- StatusCode::SERVICE_UNAVAILABLE,- Json(json!({- "error": {- "code": err_code::PROVISIONING,- "message": message,- }- })),- )- .into_response();- add_provisioning_headers(&mut resp, PROVISIONING_RETRY_AFTER);- resp.headers_mut().insert(- HeaderName::from_static("x-sie-error-code"),- HeaderValue::from_static(err_code::PROVISIONING),- );- resp- }- ProvisioningSurface::OpenAiCompat => {- record_provisioning_response(surface, StatusCode::SERVICE_UNAVAILABLE);- let mut resp = (- StatusCode::SERVICE_UNAVAILABLE,- Json(json_openai_error(- message,- oai_type::SERVER_ERROR,- None,- oai_code::PROVISIONING,- )),- )- .into_response();- add_provisioning_headers(&mut resp, PROVISIONING_RETRY_AFTER);- resp.headers_mut().insert(- HeaderName::from_static("x-sie-error-code"),- HeaderValue::from_static(err_code::PROVISIONING),- );- resp- }- }+ record_provisioning_response(surface, StatusCode::SERVICE_UNAVAILABLE);+ provisioning_response(model, retry_after, 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.+pub(crate) fn provisioning_response(+ model: &str,+ retry_after: HeaderValue,+ surface: ProvisioningSurface,+) -> Response {+ let message = provisioning_message(model);+ let mut resp = match surface {+ ProvisioningSurface::Native => (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(json!({+ "error": {+ "code": err_code::PROVISIONING,+ "message": message,+ }+ })),+ )+ .into_response(),+ ProvisioningSurface::OpenAiCompat => (+ StatusCode::SERVICE_UNAVAILABLE,+ Json(json_openai_error(+ message,+ oai_type::SERVER_ERROR,+ None,+ oai_code::PROVISIONING,+ )),+ )+ .into_response(),+ };+ add_provisioning_headers(&mut resp, retry_after);+ resp.headers_mut().insert(+ HeaderName::from_static("x-sie-error-code"),+ HeaderValue::from_static(err_code::PROVISIONING),+ );+ resp}-fn build_openai_provisioning_response(gpu: &str, bundle: &str) -> Response {- build_provisioning_response_for_surface(gpu, bundle, ProvisioningSurface::OpenAiCompat)+/// The pool targets of the lanes a cold lookup records demand for.+fn cold_lane_targets(+ pool: &str,+ profiles: &[String],+ bundle: &str,+ model: &str,+) -> Vec<publisher::PublishTarget> {+ profiles+ .iter()+ .map(|profile| lane_wake_target(pool, profile, bundle, model))+ .collect()}fn pool_not_found_message(pool: &str) -> String {@@ -1107,13 +1192,19 @@ fn provisioning_surface_for_endpoint(endpoint: &str) -> ProvisioningSurface {}}+/// `model` is the model the caller asked for. `dispatch_model` is the route+/// the lane serves.+#[allow(clippy::too_many_arguments)]async fn capped_lane_admission_response(state: &AppState,admission_pool: &str,demand_pool: &str,machine_profile: &str,bundle: &str,+ model: &str,+ dispatch_model: &str,provisioning_surface: ProvisioningSurface,+ route: RouteKind,) -> Option<Response> {let admission = state.pool_manager@@ -1173,9 +1264,19 @@ async fn capped_lane_admission_response({state.demand_tracker.record(&lane);}+ let retry_after = provisioning_retry_after(+ state,+ &[lane_wake_target(+ demand_pool,+ machine_profile,+ bundle,+ dispatch_model,+ )],+ route,+ );return Some(build_provisioning_response_for_surface(- machine_profile,- bundle,+ model,+ retry_after,provisioning_surface,));}@@ -2521,9 +2622,9 @@ fn transport_lane_provisioning(})}-/// The lane a transport wakes for a `provisioning` bridge. No worker is-/// pinned, because the transport reports that none is ready.-fn lane_wake_target(+/// The lane a transport wakes for a `provisioning` bridge, and estimates a+/// provisioning `Retry-After` for. No worker is pinned, because none is ready.+pub(crate) fn lane_wake_target(pool: &str,machine_profile: &str,bundle: &str,@@ -3372,8 +3473,21 @@ async fn proxy_request_inner(&admission_pool,).await;- let refusal =- build_provisioning_response_for_surface(&gpu, &bundle, provisioning_surface);+ let retry_after = provisioning_retry_after(+ &state,+ &cold_lane_targets(+ &demand_pool,+ &pending_demand_profiles,+ &bundle,+ &dispatch_model,+ ),+ route_kind(req.extensions()),+ );+ let refusal = build_provisioning_response_for_surface(+ &model_name,+ retry_after,+ provisioning_surface,+ );match begin_native_fallback(&state,&mut req,@@ -3431,7 +3545,10 @@ async fn proxy_request_inner(&demand_pool,effective_machine_profile,&bundle,+ &model_name,+ &dispatch_model,provisioning_surface,+ route_kind(req.extensions()),).await{@@ -3458,13 +3575,21 @@ async fn proxy_request_inner(None};if provisioning_bridge.is_some() {- let refusal = build_provisioning_response_for_surface(&gpu, &bundle, provisioning_surface);let target = lane_wake_target(effective_pool,effective_machine_profile,&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(&state,work_publisher.as_ref(),@@ -3721,9 +3846,19 @@ async fn proxy_request_inner(Ok(target) => Some(target),Err(()) => {state.demand_tracker.record(&physical_lane);+ let retry_after = provisioning_retry_after(+ &state,+ &[lane_wake_target(+ effective_pool,+ effective_machine_profile,+ &bundle,+ &dispatch_model,+ )],+ route_kind(req.extensions()),+ );return build_provisioning_response_for_surface(- effective_machine_profile,- &bundle,+ &model_name,+ retry_after,provisioning_surface,);}@@ -4442,9 +4577,14 @@ async fn queue_mode_proxy(physical_lane,"no_consumers",);+ let retry_after = provisioning_retry_after(+ state,+ &[lane_wake_target(pool, gpu, bundle, model)],+ route_kind(request_extensions),+ );return build_provisioning_response_for_surface(- gpu,- bundle,+ display_model,+ retry_after,provisioning_surface_for_endpoint(endpoint),);}@@ -5245,11 +5385,17 @@ pub(crate) enum StreamingDriverErr {/// JetStream publish failed before any work item left the gateway./// ``error`` is the lowercased publisher message; ``retry_after`` is/// the recommended ``Retry-After`` header value when applicable- /// (``no_consumers`` and ``backpressure`` cases).+ /// (``backpressure`` case).PublishFailed {message: String,retry_after: Option<&'static str>,},+ /// The publish found no capacity ready on the lane (``no consumers``):+ /// a ``503 PROVISIONING`` answer for the requested ``model``.+ Provisioning {+ model: String,+ retry_after: HeaderValue,+ },/// Initial publish submission returned, but the transport later rejected/// or abandoned its durable-acceptance acknowledgement.DurabilityFailed { message: String },@@ -5322,6 +5468,7 @@ pub(crate) async fn run_streaming_generate(admission_pool: &str,bundle_config_hash: &str,params: &publisher::WorkParams,+ route: RouteKind,) -> Result<StreamingDriverOk, StreamingDriverErr> {let publish_start = Instant::now();// Resolve the routing key, build the pressure-aware routing snapshot,@@ -5444,20 +5591,25 @@ pub(crate) async fn run_streaming_generate(Err(e) => {error!(error = %e, "failed to publish generate work");let lower = e.to_lowercase();- let retry_after = if lower.contains("no consumers") {+ if lower.contains("no consumers") {telemetry::record_rejected_request(state.demand_tracker.as_ref(),physical_lane,"no_consumers",);- Some(PROVISIONING_RETRY_AFTER)- } else {- // backpressure (records demand for KEDA) / generic failure. #1568- record_publish_failure(state, physical_lane, &lower)- };+ return Err(StreamingDriverErr::Provisioning {+ model: model.to_string(),+ retry_after: provisioning_retry_after(+ state,+ &[lane_wake_target(pool, gpu, bundle, dispatch_model)],+ route,+ ),+ });+ }+ // backpressure (records demand for KEDA) / generic failure. #1568return Err(StreamingDriverErr::PublishFailed {message: e,- retry_after,+ retry_after: record_publish_failure(state, physical_lane, &lower),});}};@@ -5897,45 +6049,12 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {StreamingDriverErr::PublishFailed {message,retry_after,- } => {- let is_no_consumers = message.to_lowercase().contains("no consumers");- let openai_code = if is_no_consumers {- oai_code::PROVISIONING- } else {- oai_code::TRANSPORT_FAILURE- };- let mut resp = (- StatusCode::SERVICE_UNAVAILABLE,- Json(json_openai_error(- format!("Queue publish failed: {message}"),- oai_type::SERVER_ERROR,- None,- openai_code,- )),- )- .into_response();- if let Some(ra) = retry_after {- resp.headers_mut().insert(- HeaderName::from_static("retry-after"),- HeaderValue::from_static(ra),- );- }- if is_no_consumers {- resp.headers_mut().insert(- HeaderName::from_static("x-sie-error-code"),- HeaderValue::from_static(err_code::PROVISIONING),- );- }- resp.headers_mut().insert(- HeaderName::from_static("x-sie-version"),- HeaderValue::from_static(GATEWAY_VERSION),- );- resp.headers_mut().insert(- HeaderName::from_static("x-sie-server-version"),- HeaderValue::from_static(GATEWAY_VERSION),- );- resp- }+ } => build_streaming_publish_failed_for_sse(message, *retry_after),+ StreamingDriverErr::Provisioning { model, retry_after } => provisioning_response(+ model,+ retry_after.clone(),+ ProvisioningSurface::OpenAiCompat,+ ),StreamingDriverErr::DurabilityFailed { message } => (StatusCode::SERVICE_UNAVAILABLE,Json(json_openai_error(@@ -6072,28 +6191,23 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {}/// SSE-side helper: build a JSON error response for a publish-/// failure that happened *before* any SSE bytes went out. Mirrors-/// the `PublishFailed` arm of :func:`build_streaming_error_response`-/// but is reachable from outside the SSE driver task (so SSE handlers+/// failure that happened *before* any SSE bytes went out. It is the+/// `PublishFailed` arm of :func:`build_streaming_error_response`, and is+/// reachable from outside the SSE driver task (so SSE handlers/// can return a regular HTTP error response instead of a malformed-/// half-open SSE stream when the queue publish itself fails).+/// half-open SSE stream when the queue publish itself fails). A publish+/// that found no ready capacity is answered by [`provisioning_response`].pub(crate) fn build_streaming_publish_failed_for_sse(message: &str,retry_after: Option<&'static str>,) -> Response {- let is_no_consumers = message.to_lowercase().contains("no consumers");- let openai_code = if is_no_consumers {- oai_code::PROVISIONING- } else {- oai_code::TRANSPORT_FAILURE- };let mut resp = (StatusCode::SERVICE_UNAVAILABLE,Json(json_openai_error(format!("Queue publish failed: {message}"),oai_type::SERVER_ERROR,None,- openai_code,+ oai_code::TRANSPORT_FAILURE,)),).into_response();@@ -6103,12 +6217,6 @@ pub(crate) fn build_streaming_publish_failed_for_sse(HeaderValue::from_static(ra),);}- if is_no_consumers {- resp.headers_mut().insert(- HeaderName::from_static("x-sie-error-code"),- HeaderValue::from_static(err_code::PROVISIONING),- );- }resp.headers_mut().insert(HeaderName::from_static("x-sie-version"),HeaderValue::from_static(GATEWAY_VERSION),@@ -6156,6 +6264,7 @@ async fn queue_mode_streaming_generate(admission_pool,bundle_config_hash,params,+ RouteKind::Native,).await;@@ -8693,7 +8802,21 @@ async fn resolve_generation_route(&admission_pool,).await;- let refusal = build_openai_provisioning_response(&gpu, &bundle);+ let retry_after = provisioning_retry_after(+ state,+ &cold_lane_targets(+ &demand_pool,+ &pending_demand_profiles,+ &bundle,+ dispatch_model,+ ),+ RouteKind::Compatibility,+ );+ let refusal = build_provisioning_response_for_surface(+ customer_model,+ retry_after,+ ProvisioningSurface::OpenAiCompat,+ );let attempt = ext.get::<FallbackAttempt>();let plan = fallback_plan_for_request(state,@@ -8770,7 +8893,10 @@ async fn resolve_generation_route(&demand_pool,&effective_machine_profile,&bundle,+ customer_model,+ dispatch_model,ProvisioningSurface::OpenAiCompat,+ RouteKind::Compatibility,).await{@@ -8794,13 +8920,21 @@ async fn resolve_generation_route(FallbackTrigger::Provisioning,request_intent,) {- let refusal = build_openai_provisioning_response(&gpu, &bundle);let target = lane_wake_target(&effective_pool,&effective_machine_profile,&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(state,work_publisher_arc.as_ref(),@@ -9529,6 +9663,7 @@ async fn proxy_chat_inner(&admission_pool,&bundle_config_hash,&work_params,+ RouteKind::Compatibility,).await;@@ -10202,6 +10337,7 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response&admission_pool,&bundle_config_hash,&work_params,+ RouteKind::Compatibility,).await;@@ -10835,6 +10971,7 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {&admission_pool,&bundle_config_hash,&work_params,+ RouteKind::Compatibility,).await;let StreamingDriverOk {@@ -15260,6 +15397,7 @@ pub async fn proxy_openai_embeddings(State(state): State<Arc<AppState>>, req: Re}};*inner_req.extensions_mut() = extensions;+ inner_req.extensions_mut().insert(CompatibilityRoute);let resp = proxy_request(State(state.clone()), inner_req, "encode").await;let inner_status = resp.status();if inner_status != StatusCode::OK {@@ -15840,6 +15978,7 @@ async fn proxy_rerank_inner(}};*inner.extensions_mut() = parts.extensions;+ inner.extensions_mut().insert(CompatibilityRoute);let response = proxy_request(State(state), inner, "score").await;if response.status() != StatusCode::OK {return translate_inner_rerank_error(response).await;@@ -19385,7 +19524,10 @@ mod tests {DEFAULT_POOL_NAME,"l4","default",+ "BAAI/bge-m3",+ "BAAI/bge-m3",ProvisioningSurface::Native,+ RouteKind::Native,).await.expect("zero-cap lane should fail fast");@@ -19413,7 +19555,10 @@ mod tests {DEFAULT_POOL_NAME,"l4","default",+ "BAAI/bge-m3",+ "BAAI/bge-m3",ProvisioningSurface::OpenAiCompat,+ RouteKind::Compatibility,).await.expect("zero-cap lane should fail fast");@@ -19450,7 +19595,10 @@ mod tests {demand_pool,"l4",bundle,+ "BAAI/bge-m3",+ "BAAI/bge-m3",ProvisioningSurface::Native,+ RouteKind::Native,).await.expect("capped lane with no admitted workers should provision");@@ -19466,6 +19614,10 @@ mod tests {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"]["code"], err_code::PROVISIONING);+ assert_eq!(+ value["error"]["message"],+ "Capacity for model 'BAAI/bge-m3' is starting. Retry after the number of seconds in Retry-After."+ );assert!(value.get("status").is_none());let lane = state@@ -19497,7 +19649,10 @@ mod tests {demand_pool,"l4",bundle,+ "BAAI/bge-m3",+ "BAAI/bge-m3",ProvisioningSurface::OpenAiCompat,+ RouteKind::Compatibility,).await.expect("OpenAI-compatible capped lane should provision");@@ -19516,10 +19671,10 @@ mod tests {assert!(value.get("detail").is_none());assert_eq!(value["error"]["type"], oai_type::SERVER_ERROR);assert_eq!(value["error"]["code"], oai_code::PROVISIONING);- assert!(value["error"]["message"]- .as_str()- .unwrap_or("")- .contains("Provisioning in progress"));+ assert_eq!(+ value["error"]["message"],+ "Capacity for model 'BAAI/bge-m3' is starting. Retry after the number of seconds in Retry-After."+ );let lane = state.demand_tracker.resolve_lane(demand_pool, "l4", bundle)@@ -19781,8 +19936,12 @@ mod tests {}#[tokio::test]- async fn test_openai_provisioning_response_empty_gpu_is_retryable_503() {- let resp = build_openai_provisioning_response("", "default");+ async fn test_openai_provisioning_response_without_model_is_retryable_503() {+ let resp = build_provisioning_response_for_surface(+ "",+ HeaderValue::from_static(PROVISIONING_RETRY_AFTER),+ ProvisioningSurface::OpenAiCompat,+ );assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);assert_eq!(resp.headers().get("retry-after").unwrap(),@@ -19801,9 +19960,133 @@ mod tests {assert!(value.get("status").is_none());assert_eq!(value["error"]["type"], oai_type::SERVER_ERROR);assert_eq!(value["error"]["code"], oai_code::PROVISIONING);- let message = value["error"]["message"].as_str().unwrap_or("");- assert!(message.contains("bundle 'default'"));- assert!(message.contains("Provisioning in progress"));+ assert_eq!(+ value["error"]["message"],+ "Capacity is starting. Retry after the number of seconds in Retry-After."+ );+ }++ #[test]+ fn test_provisioning_retry_after_estimate_rounds_up_and_is_clamped_per_route() {+ for (estimate, native, compatibility) in [+ (Duration::ZERO, 5, 5),+ (Duration::from_millis(1), 5, 5),+ (Duration::from_secs(5), 5, 5),+ (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),+ ] {+ assert_eq!(+ bounded_provisioning_retry_after_s(estimate, RouteKind::Native),+ native,+ "{estimate:?}"+ );+ assert_eq!(+ bounded_provisioning_retry_after_s(estimate, RouteKind::Compatibility),+ compatibility,+ "{estimate:?}"+ );+ }+ }++ #[tokio::test]+ async fn test_provisioning_retry_after_takes_the_soonest_transport_estimate() {+ 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 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+ );+ }++ 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);+ }++ dispatcher.estimate_provisioning(("default", "l4", "default"), Duration::from_secs(680));+ dispatcher.estimate_provisioning(+ ("default", "h100", "default"),+ Duration::from_millis(240_500),+ );+ let lanes = [lane("l4"), lane("h100"), lane("a10g")];+ assert_eq!(+ provisioning_retry_after(&state, &[lane("l4")], RouteKind::Native),+ "680"+ );+ assert_eq!(+ provisioning_retry_after(&state, &lanes, RouteKind::Native),+ "241"+ );+ assert_eq!(+ provisioning_retry_after(&state, &[lane("l4")], RouteKind::Compatibility),+ "60"+ );+ assert_eq!(+ provisioning_retry_after(&state, &lanes, RouteKind::Compatibility),+ "60"+ );+ for route in routes {+ assert_eq!(+ provisioning_retry_after(&state, &[lane("a10g")], route),+ default+ );+ }++ dispatcher.estimate_provisioning(+ ("default", "a10g", "default"),+ Duration::from_millis(30_200),+ );+ for route in routes {+ assert_eq!(provisioning_retry_after(&state, &lanes, 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"+ );+ }++ #[tokio::test]+ async fn test_provisioning_response_names_only_the_model() {+ for surface in [+ ProvisioningSurface::Native,+ ProvisioningSurface::OpenAiCompat,+ ] {+ let resp = provisioning_response("acme/m", HeaderValue::from_static("680"), surface);+ assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(resp.headers()["retry-after"], "680");+ 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();+ assert_eq!(+ value["error"]["message"],+ "Capacity for model 'acme/m' is starting. Retry after the number of seconds in Retry-After.",+ "{surface:?}"+ );+ }}// ── is_valid_pool_name (pool subject-injection guard) ──────────@@ -21367,27 +21650,15 @@ mod tests {#[tokio::test]async fn test_translate_inner_compat_provisioning_error_to_openai_503() {- let mut resp = (- StatusCode::SERVICE_UNAVAILABLE,- Json(json!({- "error": {- "code": err_code::PROVISIONING,- "message": "No worker available for GPU type 'l4'. Provisioning in progress.",- },- })),- )- .into_response();- resp.headers_mut().insert(- "retry-after",- HeaderValue::from_static(PROVISIONING_RETRY_AFTER),+ let resp = provisioning_response(+ "acme/m",+ HeaderValue::from_static("680"),+ 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(),- PROVISIONING_RETRY_AFTER- );+ assert_eq!(out.headers().get("retry-after").unwrap(), "680");assert_eq!(out.headers().get("x-sie-error-code").unwrap(),err_code::PROVISIONING@@ -21400,10 +21671,10 @@ mod tests {assert!(body.get("detail").is_none(), "no leaked detail shape");assert_eq!(body["error"]["type"], oai_type::SERVER_ERROR);assert_eq!(body["error"]["code"], oai_code::PROVISIONING);- assert!(body["error"]["message"]- .as_str()- .unwrap_or("")- .contains("l4"));+ assert_eq!(+ body["error"]["message"],+ "Capacity for model 'acme/m' is starting. Retry after the number of seconds in Retry-After."+ );}#[tokio::test]@@ -27643,17 +27914,14 @@ mod tests {// ── Fix 5: 429 rate_limit_error for KV-saturated + pool-full path#[tokio::test]- async fn test_build_streaming_error_response_no_consumers_is_provisioning() {- let err = StreamingDriverErr::PublishFailed {- message: "nats: no consumers available".to_string(),- retry_after: Some(PROVISIONING_RETRY_AFTER),+ 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"),};let resp = build_streaming_error_response(&err);assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);- assert_eq!(- resp.headers().get("retry-after").unwrap(),- PROVISIONING_RETRY_AFTER- );+ assert_eq!(resp.headers().get("retry-after").unwrap(), "680");assert_eq!(resp.headers().get("x-sie-error-code").unwrap(),err_code::PROVISIONING@@ -27665,30 +27933,31 @@ mod tests {let v: serde_json::Value = serde_json::from_slice(&body).unwrap();assert_eq!(v["error"]["type"], oai_type::SERVER_ERROR);assert_eq!(v["error"]["code"], oai_code::PROVISIONING);+ assert_eq!(+ v["error"]["message"],+ "Capacity for model 'acme/m' is starting. Retry after the number of seconds in Retry-After."+ );}#[tokio::test]- async fn test_build_streaming_publish_failed_for_sse_no_consumers_is_provisioning() {+ async fn test_build_streaming_publish_failed_for_sse_is_transport_failure() {let resp = build_streaming_publish_failed_for_sse(- "no consumers available for work stream",- Some(PROVISIONING_RETRY_AFTER),+ "backpressure: lane is full",+ Some(BACKPRESSURE_RETRY_AFTER),);assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE);assert_eq!(resp.headers().get("retry-after").unwrap(),- PROVISIONING_RETRY_AFTER- );- assert_eq!(- resp.headers().get("x-sie-error-code").unwrap(),- err_code::PROVISIONING+ BACKPRESSURE_RETRY_AFTER);+ assert!(resp.headers().get("x-sie-error-code").is_none());let body = axum::body::to_bytes(resp.into_body(), 16 * 1024).await.unwrap();let v: serde_json::Value = serde_json::from_slice(&body).unwrap();assert_eq!(v["error"]["type"], oai_type::SERVER_ERROR);- assert_eq!(v["error"]["code"], oai_code::PROVISIONING);+ assert_eq!(v["error"]["code"], oai_code::TRANSPORT_FAILURE);}/// ``rate_limit_exceeded`` worker code maps to 429 with the OpenAIdiff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rsindex 018009397..a72198547 100644--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs@@ -1574,7 +1574,8 @@ mod tests {}use crate::handlers::proxy::{- proxy_chat, proxy_completions, proxy_openai_embeddings, proxy_request, proxy_responses,+ proxy_chat, proxy_completions, proxy_openai_embeddings, proxy_request, proxy_rerank,+ proxy_rerank_v2, proxy_responses,};use crate::handlers::test_support::{Dispatched, TestGateway, HYBRID_ENCODE_MODEL, HYBRID_EXTRACT_MODEL, HYBRID_GENERATE_MODEL,@@ -4733,6 +4734,327 @@ mod tests {assert_eq!(response.headers()["x-sie-fallback-error"], "QUEUE_FULL");}+ fn starting_message(model: &str) -> String {+ format!(+ "Capacity for model '{model}' is starting. Retry after the number of seconds in Retry-After."+ )+ }++ async fn error_message(response: Response) -> serde_json::Value {+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ serde_json::from_slice::<serde_json::Value>(&body).unwrap()["error"]["message"].clone()+ }++ /// Each case runs with an estimate above the 60-second ceiling of the+ /// compatibility routes, which caps it there, and with one below it, which+ /// those routes then send unchanged.+ #[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(44_200), "45", "45"),+ ] {+ let gateway = transport_cold_gateway(None).await;+ gateway.dispatcher.refuse_model_loads();+ gateway+ .dispatcher+ .estimate_provisioning(LOCAL_LANE, estimate);++ let extraction = extract(&gateway, extraction_request(false, json!({}))).await;+ let chat = buffered_surface(&gateway, "chat", json!({})).await;+ for (model, response, retry_after) in [+ ("acme/extract", extraction, native),+ ("acme/chat", chat, compatibility),+ ] {+ let case = format!("{model} {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");+ assert!(!response.headers().contains_key("x-sie-fallback-reason"));+ assert_eq!(error_message(response).await, starting_message(model));+ }+ }+ }++ #[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(45), "45", "45"),+ ] {+ let gateway = transport_cold_gateway(None).await;+ gateway.dispatcher.report_remote_lane_starting();+ gateway.dispatcher.estimate_provisioning(LOCAL_LANE, local);+ gateway+ .dispatcher+ .estimate_provisioning(REMOTE_LANE, Duration::from_secs(30));++ let extraction = extract(&gateway, extraction_request(false, json!({}))).await;+ let chat = buffered_surface(&gateway, "chat", json!({})).await;+ for (model, response, retry_after) in [+ ("acme/extract", extraction, native),+ ("acme/chat", chat, compatibility),+ ] {+ let case = format!("{model} {local:?}");+ 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");+ assert_eq!(response.headers()["x-sie-fallback-error"], "QUEUE_FULL");+ assert_eq!(stamped(&response), (Some("local"), None), "{case}");+ assert_eq!(error_message(response).await, starting_message(model));+ }+ }+ }++ #[tokio::test]+ async fn a_restored_cold_refusal_keeps_the_estimate_it_was_built_with() {+ 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"),+ ] {+ for (surface, stream) in [+ ("native", false),+ ("chat", false),+ ("completions", false),+ ("responses", false),+ ("native", true),+ ("chat", true),+ ("completions", true),+ ] {+ let case = format!("{surface} stream={stream} {local:?}");+ let gateway = TestGateway::new(&[&generation]).await;+ gateway+ .add_verified_worker("remote-1", REMOTE_LANE, &[])+ .await;+ 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));++ let response = if stream {+ streaming_surface(&gateway, surface, json!({})).await+ } else {+ buffered_surface(&gateway, surface, json!({})).await+ };++ let retry_after = if surface == "native" {+ native+ } else {+ compatibility+ };+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{case}");+ assert_eq!(response.headers()["retry-after"], retry_after, "{case}");+ assert_eq!(stamped(&response), (Some("local"), None), "{case}");+ assert_eq!(+ response.headers()["x-sie-fallback-reason"],+ "provisioning",+ "{case}"+ );+ assert_eq!(+ response.headers()["x-sie-fallback-error"],+ "RESOURCE_EXHAUSTED",+ "{case}"+ );+ assert_eq!(+ error_message(response).await,+ starting_message("acme/chat"),+ "{case}"+ );+ }+ }+ }++ #[tokio::test]+ async fn a_publish_refused_while_its_lane_starts_answers_with_that_lane_estimate() {+ for (remote, native, compatibility) in [+ (Duration::from_secs(95), "95", "60"),+ (Duration::from_secs(40), "40", "40"),+ ] {+ let gateway = gateway().await;+ gateway.dispatcher.report_remote_lane_starting();+ gateway+ .dispatcher+ .estimate_provisioning(REMOTE_LANE, remote);+ gateway+ .dispatcher+ .estimate_provisioning(LOCAL_LANE, Duration::from_secs(680));+ let state = || State(Arc::clone(&gateway.state));+ let messages = json!([{"role": "user", "content": "hello"}]);++ let responses = [+ (+ "encode",+ "acme/remote",+ native,+ proxy_request(+ state(),+ json_request(+ "/v1/encode/acme/remote",+ json!({"items": [{"text": "hello"}]}),+ ),+ "encode",+ )+ .await,+ ),+ (+ "native generate",+ "acme/chat:remote",+ native,+ proxy_request(+ state(),+ json_request(+ "/v1/generate/acme__chat:remote",+ json!({"prompt": "hello", "max_new_tokens": 4}),+ ),+ "generate",+ )+ .await,+ ),+ (+ "native generate stream",+ "acme/chat:remote",+ native,+ proxy_request(+ state(),+ json_request(+ "/v1/generate/acme__chat:remote",+ json!({"prompt": "hello", "max_new_tokens": 4, "stream": true}),+ ),+ "generate",+ )+ .await,+ ),+ (+ "embeddings",+ "acme/remote",+ compatibility,+ proxy_openai_embeddings(+ state(),+ json_request(+ "/v1/embeddings",+ json!({"model": "acme/remote", "input": "hello"}),+ ),+ )+ .await,+ ),+ (+ "chat",+ "acme/chat:remote",+ compatibility,+ proxy_chat(+ state(),+ json_request(+ "/v1/chat/completions",+ json!({"model": "acme/chat:remote", "messages": messages}),+ ),+ )+ .await,+ ),+ (+ "chat stream",+ "acme/chat:remote",+ compatibility,+ proxy_chat(+ state(),+ json_request(+ "/v1/chat/completions",+ json!({"model": "acme/chat:remote", "messages": messages, "stream": true}),+ ),+ )+ .await,+ ),+ ];+ for (case, model, retry_after, response) in responses {+ let case = format!("{case} {remote:?}");+ 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_eq!(+ error_message(response).await,+ starting_message(model),+ "{case}"+ );+ }+ }+ }++ /// A score model with no local weights, served on the remote lane.+ const REMOTE_SCORE_MODEL: &str = "\+sie_id: acme/remote-score+remote_backed: true+tasks:+ score: {}+profiles:+ default:+ adapter_path: sie_server.adapters.remote.sie:SieUpstreamAdapter+ max_batch_tokens: 8192+ adapter_options:+ loadtime:+ upstream: team-sie+ upstream_model: acme/remote-score+";++ #[tokio::test]+ async fn the_rerank_routes_cap_the_estimate_that_native_score_keeps() {+ for (remote, native, compatibility) in [+ (Duration::from_secs(95), "95", "60"),+ (Duration::from_secs(40), "40", "40"),+ ] {+ let gateway = TestGateway::new(&[REMOTE_SCORE_MODEL]).await;+ gateway.add_worker("remote-1", REMOTE_LANE, &[]).await;+ gateway.dispatcher.report_remote_lane_starting();+ gateway+ .dispatcher+ .estimate_provisioning(REMOTE_LANE, remote);+ let state = || State(Arc::clone(&gateway.state));+ let rerank =+ json!({"model": "acme/remote-score", "query": "hello", "documents": ["world"]});++ let responses = [+ (+ "score",+ native,+ proxy_request(+ state(),+ json_request(+ "/v1/score/acme/remote-score",+ json!({"query": {"text": "hello"}, "items": [{"text": "world"}]}),+ ),+ "score",+ )+ .await,+ ),+ (+ "rerank",+ compatibility,+ proxy_rerank(state(), json_request("/v1/rerank", rerank.clone())).await,+ ),+ (+ "rerank v2",+ compatibility,+ proxy_rerank_v2(state(), json_request("/v2/rerank", rerank.clone())).await,+ ),+ ];+ for (case, retry_after, response) in responses {+ let case = format!("{case} {remote:?}");+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{case}");+ assert_eq!(response.headers()["retry-after"], retry_after, "{case}");+ }+ }+ }+#[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.rsindex 34ae121fc..9782d3c39 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -250,22 +250,42 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {Err(e) => {// Pre-stream publish failure — surface as a regular JSON// error response (mirrors `build_streaming_error_response`- // for the `PublishFailed` arm).+ // for the `Provisioning` and `PublishFailed` arms).let lower = e.to_lowercase();- let retry_after = if lower.contains("no consumers") {+ if lower.contains("no consumers") {telemetry::record_rejected_request(state.demand_tracker.as_ref(),&physical_lane,"no_consumers",);- Some(crate::handlers::proxy::PROVISIONING_RETRY_AFTER)- } else {- // Shared with the buffered and streaming paths rather than- // re-derived here: this arm used to match only "backpressure"- // and so missed the broker's own stream-full rejection, which- // means the same thing.- crate::handlers::proxy::record_publish_failure(state, &physical_lane, &lower)- };+ 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(+ state,+ &[crate::handlers::proxy::lane_wake_target(+ &pool,+ &gpu,+ &bundle,+ &dispatch_model,+ )],+ route,+ );+ return crate::handlers::proxy::provisioning_response(+ &model,+ retry_after,+ crate::handlers::proxy::ProvisioningSurface::OpenAiCompat,+ );+ }+ // Shared with the buffered and streaming paths rather than+ // re-derived here: this arm used to match only "backpressure"+ // and so missed the broker's own stream-full rejection, which+ // means the same thing.+ let retry_after =+ crate::handlers::proxy::record_publish_failure(state, &physical_lane, &lower);return crate::handlers::proxy::build_streaming_publish_failed_for_sse(&e, retry_after);}};diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rsindex 246d08984..0103c5c0d 100644--- a/packages/sie_gateway/src/handlers/test_support.rs+++ b/packages/sie_gateway/src/handlers/test_support.rs@@ -177,9 +177,19 @@ 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>>>,+ provisioning_estimates: Mutex<HashMap<LaneKey, Duration>>,}impl RecordingDispatcher {+ /// Estimate that the `(pool, machine_profile, bundle)` lane needs+ /// `estimate` before it can accept work.+ pub(crate) fn estimate_provisioning(&self, lane: (&str, &str, &str), estimate: Duration) {+ self.provisioning_estimates+ .lock()+ .unwrap()+ .insert(LaneKey::new(lane.0, lane.1, lane.2), estimate);+ }+/// 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);@@ -411,6 +421,15 @@ impl WorkDispatcher for RecordingDispatcher {&& lane == &LaneKey::new(LOCAL_LANE.0, LOCAL_LANE.1, LOCAL_LANE.2)}+ fn provisioning_retry_after(&self, target: &PublishTarget) -> Option<Duration> {+ assert!(matches!(target, PublishTarget::Pool { .. }));+ self.provisioning_estimates+ .lock()+ .unwrap()+ .get(&target.lane())+ .copied()+ }+fn pre_dispatch_backpressure(&self, lane: &LaneKey) -> Result<(), DispatchBackpressure> {if lane.bundle == LOCAL_LANE.2 && self.local_backpressure.load(Ordering::SeqCst) {Err("backpressure: local lane is full".into())diff --git a/packages/sie_gateway/src/queue/dispatch.rs b/packages/sie_gateway/src/queue/dispatch.rsindex 87d9e471b..b6f0dbd77 100644--- a/packages/sie_gateway/src/queue/dispatch.rs+++ b/packages/sie_gateway/src/queue/dispatch.rs@@ -198,6 +198,18 @@ pub trait WorkDispatcher: Send + Sync {false}+ /// Non-publishing estimate of how long the lane `target` names needs+ /// before it can accept work. The gateway reads it only to answer+ /// `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+ /// to 60 seconds on the OpenAI-compatible and other compatibility routes.+ /// `None` keeps the gateway's 60-second default on both.+ fn provisioning_retry_after(&self, _target: &PublishTarget) -> Option<Duration> {+ None+ }+/// Request readiness without inference. Only transports whose worker/// settlement supports no-result load items may implement this operation.#[allow(dead_code)] // Called by the subsequent cluster fallback routing delivery.diff --git a/packages/sie_ts_sdk/tests/internal.test.ts b/packages/sie_ts_sdk/tests/internal.test.tsindex 08d3316f9..b3248eb3d 100644--- a/packages/sie_ts_sdk/tests/internal.test.ts+++ b/packages/sie_ts_sdk/tests/internal.test.ts@@ -312,7 +312,8 @@ describe("handleError (gateway / FastAPI bodies)", () => {JSON.stringify({error: {code: "PROVISIONING",- message: "No worker available for GPU type 'l4'. Provisioning in progress.",+ message:+ "Capacity for model 'BAAI/bge-m3' is starting. Retry after the number of seconds in Retry-After.",},}),{@@ -322,7 +323,8 @@ describe("handleError (gateway / FastAPI bodies)", () => {);await expect(handleError(res, "l4")).rejects.toMatchObject({name: "ProvisioningError",- message: "No worker available for GPU type 'l4'. Provisioning in progress.",+ message:+ "Capacity for model 'BAAI/bge-m3' is starting. Retry after the number of seconds in Retry-After.",gpu: "l4",retryAfter: 5000,});