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): derive a failed bridge's fallback error as the single server does (#580)

Krisztian Gajdar70b318162b45
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 99a5df58b..46bf20923 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -44,6 +44,7 @@ use crate::middleware::auth::{extract_bearer_token, mask_token};
use super::serving_disclosure::{
remote_forbidden, DeferredFallbackFinish, FallbackAttempt, ServingDisclosure,
+ UnansweredBeforeDeadline,
};
const GATEWAY_VERSION: &str = env!("CARGO_PKG_VERSION");
@@ -3982,7 +3983,11 @@ async fn queue_mode_proxy(
physical_lane,
"upstream_result_timeout",
);
- return build_queue_result_timeout_response(model, timeout_secs);
+ let mut response = build_queue_result_timeout_response(model, timeout_secs);
+ if buffered_results.is_none() {
+ response.extensions_mut().insert(UnansweredBeforeDeadline);
+ }
+ return response;
}
}
};
@@ -4616,8 +4621,9 @@ pub(crate) enum StreamingDriverErr {
/// reset, gateway shutting down, …). Maps to 504 Gateway Timeout.
ResultChannelClosed,
/// One of the three streaming generation timeouts fired. ``kind`` is
- /// ``"first_chunk"`` | ``"inter_chunk"`` | ``"overall"``.
- Timeout { kind: &'static str },
+ /// ``"first_chunk"`` | ``"inter_chunk"`` | ``"overall"``; ``answered``
+ /// says whether any output arrived before it.
+ Timeout { kind: &'static str, answered: bool },
/// Worker emitted a terminal chunk with ``error`` populated. The
/// caller chooses the wire status/code mapping; message, parameter,
/// and retry metadata are bounded at the worker trust boundary.
@@ -5118,6 +5124,10 @@ pub(crate) async fn run_streaming_generate(
// One of the three generation timeouts fired. This is not a
// client-disconnect cancellation, so defuse the Drop guard and
// send the worker cancel explicitly.
+ let answered = buffered_outcome.is_some()
+ || work_publisher
+ .stream_chunk_timing(&request_id)
+ .is_some_and(|(first_chunk_at, _)| first_chunk_at.is_some());
cancel_guard.defuse();
telemetry::record_queue_result_wait(
"generate",
@@ -5126,7 +5136,7 @@ pub(crate) async fn run_streaming_generate(
);
work_publisher.publish_cancel(&request_id).await;
work_publisher.drop_pending_stream(&request_id);
- return Err(StreamingDriverErr::Timeout { kind });
+ return Err(StreamingDriverErr::Timeout { kind, answered });
}
};
let wait_elapsed = wait_start.elapsed();
@@ -5309,7 +5319,7 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {
)),
)
.into_response(),
- StreamingDriverErr::Timeout { kind } => {
+ StreamingDriverErr::Timeout { kind, answered } => {
// Inter-chunk timeout returns 502 (partial response is
// corrupt; SDK cannot retry); first-chunk and overall
// return 504 (gateway/upstream timing).
@@ -5323,7 +5333,7 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {
"inter_chunk" => oai_code::INTER_CHUNK_TIMEOUT,
_ => oai_code::OVERALL_TIMEOUT,
};
- (
+ let mut resp = (
status,
Json(json_openai_error(
format!("Generation aborted: {kind} timeout"),
@@ -5332,7 +5342,11 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {
code,
)),
)
- .into_response()
+ .into_response();
+ if !answered {
+ resp.extensions_mut().insert(UnansweredBeforeDeadline);
+ }
+ resp
}
StreamingDriverErr::WorkerError {
code,
diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rs
index afdb2d017..f75b7c05e 100644
--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs
+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs
@@ -11,6 +11,7 @@ use std::sync::{Arc, Mutex, PoisonError};
use axum::extract::Request;
use axum::http::{Extensions, HeaderMap, HeaderName, HeaderValue, StatusCode};
use axum::response::Response;
+use futures_util::FutureExt;
use crate::observability::metrics as telemetry;
use crate::server::AppState;
@@ -119,6 +120,74 @@ struct LocalRefusal {
trigger: FallbackTrigger,
}
+/// Marks a failed response whose gateway deadline passed before the
+/// dispatched work answered.
+#[derive(Clone)]
+pub(crate) struct UnansweredBeforeDeadline;
+
+/// The single server's error codes (`ErrorCode` in `sie_server.types.responses`).
+const SIE_ERROR_CODES: [&str; 11] = [
+ "INVALID_INPUT",
+ "MODEL_NOT_FOUND",
+ "MODEL_NOT_LOADED",
+ "LORA_LOADING",
+ "MODEL_LOADING",
+ "MODEL_LOAD_FAILED",
+ "INFERENCE_ERROR",
+ "QUEUE_FULL",
+ "INTERNAL_ERROR",
+ "RESOURCE_EXHAUSTED",
+ "INPUT_TOO_LONG",
+];
+
+/// `X-SIE-Fallback-Error` for a failed remote attempt that answered with
+/// `status` and error `code`, as the single server's `_fallback_error`
+/// (`sie_server.api.routing`) derives it.
+fn fallback_error(status: StatusCode, code: Option<&str>) -> &'static str {
+ if let Some(code) = code {
+ let upper = code.to_uppercase();
+ if let Some(known) = SIE_ERROR_CODES.iter().find(|known| **known == upper) {
+ return known;
+ }
+ match code {
+ "server_overloaded" => return "QUEUE_FULL",
+ "invalid_request" => return "INVALID_INPUT",
+ _ => {}
+ }
+ }
+ if status.as_u16() >= 500 {
+ "INFERENCE_ERROR"
+ } else {
+ "INVALID_INPUT"
+ }
+}
+
+const ATTEMPT_ERROR_BODY_LIMIT: usize = 64 * 1024;
+
+/// A failed attempt's error code: its `X-SIE-Error-Code`, or else the `code`
+/// of its JSON `error` or `detail` object. Only a body that is complete
+/// without waiting is read.
+fn attempt_error_code(response: &mut Response) -> Option<String> {
+ if let Some(code) = response
+ .headers()
+ .get("x-sie-error-code")
+ .and_then(|value| value.to_str().ok())
+ {
+ return Some(code.to_string());
+ }
+ let body = std::mem::take(response.body_mut());
+ let bytes = axum::body::to_bytes(body, ATTEMPT_ERROR_BODY_LIMIT)
+ .now_or_never()?
+ .ok()?;
+ let body: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
+ body.get("error")
+ .filter(|error| error.is_object())
+ .or_else(|| body.get("detail"))?
+ .get("code")?
+ .as_str()
+ .map(str::to_string)
+}
+
impl FallbackAttempt {
pub(crate) fn install(req: &mut Request) -> Self {
if let Some(existing) = req.extensions().get::<Self>() {
@@ -236,10 +305,15 @@ impl FallbackAttempt {
.insert("x-sie-fallback-reason", reason);
return response;
}
- let failure = if response.status().is_client_error() {
- "INVALID_INPUT"
+ let failure = if response
+ .extensions()
+ .get::<UnansweredBeforeDeadline>()
+ .is_some()
+ {
+ "QUEUE_FULL"
} else {
- "INFERENCE_ERROR"
+ let status = response.status();
+ fallback_error(status, attempt_error_code(&mut response).as_deref())
};
let headers = original.response.headers_mut();
headers.insert(SERVED_BY_HEADER, HeaderValue::from_static("local"));
@@ -1252,6 +1326,152 @@ mod tests {
assert!(!response.headers().contains_key("x-sie-fallback-error"));
}
+ #[test]
+ fn the_fallback_error_is_the_code_the_single_server_derives_from_the_failed_attempt() {
+ for code in SIE_ERROR_CODES {
+ for spelling in [code.to_string(), code.to_lowercase()] {
+ for status in [StatusCode::BAD_REQUEST, StatusCode::SERVICE_UNAVAILABLE] {
+ assert_eq!(fallback_error(status, Some(&spelling)), code, "{spelling}");
+ }
+ }
+ }
+ for (status, code, expected) in [
+ (503, Some("server_overloaded"), "QUEUE_FULL"),
+ (400, Some("invalid_request"), "INVALID_INPUT"),
+ (503, Some("SERVER_OVERLOADED"), "INFERENCE_ERROR"),
+ (503, Some("PROVISIONING"), "INFERENCE_ERROR"),
+ (504, Some("GATEWAY_TIMEOUT"), "INFERENCE_ERROR"),
+ (504, Some("first_chunk_timeout"), "INFERENCE_ERROR"),
+ (503, Some("transport_failure"), "INFERENCE_ERROR"),
+ (413, Some("PAYLOAD_TOO_LARGE"), "INVALID_INPUT"),
+ (429, Some("rate_limit_exceeded"), "INVALID_INPUT"),
+ (400, Some("context_exceeded"), "INVALID_INPUT"),
+ (502, None, "INFERENCE_ERROR"),
+ (500, None, "INFERENCE_ERROR"),
+ (499, None, "INVALID_INPUT"),
+ (404, None, "INVALID_INPUT"),
+ ] {
+ assert_eq!(
+ fallback_error(StatusCode::from_u16(status).unwrap(), code),
+ expected,
+ "{status} {code:?}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn a_failed_attempt_names_its_code_in_its_header_or_body_and_a_deadline_wins() {
+ let json = |status: StatusCode, body: serde_json::Value| {
+ (status, axum::Json(body)).into_response()
+ };
+ let with_header = |mut response: Response, code: &'static str| {
+ response
+ .headers_mut()
+ .insert("x-sie-error-code", HeaderValue::from_static(code));
+ response
+ };
+ let unanswered = |mut response: Response| {
+ response.extensions_mut().insert(UnansweredBeforeDeadline);
+ response
+ };
+ let pending = Body::from_stream(futures_util::stream::pending::<
+ Result<bytes::Bytes, std::io::Error>,
+ >());
+ let cases = [
+ (
+ with_header(
+ json(
+ StatusCode::SERVICE_UNAVAILABLE,
+ json!({"error": {"code": "RESOURCE_EXHAUSTED"}}),
+ ),
+ "RESOURCE_EXHAUSTED",
+ ),
+ "RESOURCE_EXHAUSTED",
+ ),
+ (
+ with_header(
+ json(
+ StatusCode::PAYLOAD_TOO_LARGE,
+ json!({"error": {"code": "invalid_request"}}),
+ ),
+ "PAYLOAD_TOO_LARGE",
+ ),
+ "INVALID_INPUT",
+ ),
+ (
+ json(
+ StatusCode::BAD_REQUEST,
+ json!({"error": {"code": "INPUT_TOO_LONG", "type": "context_length_exceeded"}}),
+ ),
+ "INPUT_TOO_LONG",
+ ),
+ (
+ json(
+ StatusCode::SERVICE_UNAVAILABLE,
+ json!({"detail": {"code": "MODEL_LOADING", "message": "loading"}}),
+ ),
+ "MODEL_LOADING",
+ ),
+ (
+ json(
+ StatusCode::INTERNAL_SERVER_ERROR,
+ json!({"error": "all_items_failed", "details": [{"code": "INTERNAL_ERROR"}]}),
+ ),
+ "INFERENCE_ERROR",
+ ),
+ (
+ (StatusCode::BAD_REQUEST, "not json").into_response(),
+ "INVALID_INPUT",
+ ),
+ (
+ (StatusCode::SERVICE_UNAVAILABLE, pending).into_response(),
+ "INFERENCE_ERROR",
+ ),
+ (
+ unanswered(with_header(
+ json(
+ StatusCode::GATEWAY_TIMEOUT,
+ json!({"detail": {"code": "GATEWAY_TIMEOUT"}}),
+ ),
+ "GATEWAY_TIMEOUT",
+ )),
+ "QUEUE_FULL",
+ ),
+ (
+ unanswered(json(
+ StatusCode::SERVICE_UNAVAILABLE,
+ json!({"error": {"code": "RESOURCE_EXHAUSTED"}}),
+ )),
+ "QUEUE_FULL",
+ ),
+ ];
+ for (index, (failed, expected)) in cases.into_iter().enumerate() {
+ let attempt = FallbackAttempt::default();
+ let mut original =
+ (StatusCode::SERVICE_UNAVAILABLE, "original local refusal").into_response();
+ original
+ .headers_mut()
+ .insert("retry-after", HeaderValue::from_static("60"));
+ assert!(attempt.begin(original, FallbackTrigger::ModelLoading));
+ let restored = attempt.finish(failed);
+ assert_eq!(restored.status(), StatusCode::SERVICE_UNAVAILABLE);
+ assert_eq!(restored.headers()["retry-after"], "60");
+ assert_eq!(restored.headers()[SERVED_BY_HEADER], "local");
+ assert_eq!(restored.headers()["x-sie-fallback-reason"], "model_loading");
+ assert_eq!(
+ restored.headers()["x-sie-fallback-error"],
+ expected,
+ "case {index}"
+ );
+ assert_eq!(
+ axum::body::to_bytes(restored.into_body(), 1024)
+ .await
+ .unwrap(),
+ "original local refusal"
+ );
+ }
+ }
+
#[test]
fn remote_control_rejects_ambiguous_and_unrecognized_header_bytes() {
let mut headers = HeaderMap::new();
@@ -1416,6 +1636,174 @@ mod tests {
}
}
+ async fn streaming_surface(
+ gateway: &TestGateway,
+ surface: &str,
+ options: serde_json::Value,
+ ) -> Response {
+ let state = State(Arc::clone(&gateway.state));
+ match surface {
+ "native" => proxy_request(state, json_request("/v1/generate/acme/chat", json!({"prompt":"hello","max_new_tokens":4,"stream":true,"options":options})), "generate").await,
+ "chat" => proxy_chat(state, json_request("/v1/chat/completions", json!({"model":"acme/chat","messages":[{"role":"user","content":"hello"}],"stream":true}))).await,
+ "completions" => proxy_completions(state, json_request("/v1/completions", json!({"model":"acme/chat","prompt":"hello","max_tokens":4,"stream":true}))).await,
+ _ => unreachable!(),
+ }
+ }
+
+ fn assert_restored_cold_refusal(response: &Response, fallback_error: &str, case: &str) {
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE, "{case}");
+ assert_eq!(response.headers()["retry-after"], "60", "{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"],
+ fallback_error,
+ "{case}"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_failed_bridge_reports_the_code_its_remote_attempt_answered_with() {
+ let generation = format!(
+ "{HYBRID_GENERATE_MODEL}\nrouting:\n policy: fallback\n fallback_profile: remote\n"
+ );
+ for (code, retry_after_s, expected) in [
+ ("RESOURCE_EXHAUSTED", Some(7), "RESOURCE_EXHAUSTED"),
+ ("MODEL_LOADING", Some(7), "MODEL_LOADING"),
+ ("INPUT_TOO_LONG", None, "INPUT_TOO_LONG"),
+ ("inference_error", None, "INFERENCE_ERROR"),
+ ] {
+ for (surface, stream) in [
+ ("native", false),
+ ("chat", false),
+ ("completions", false),
+ ("responses", false),
+ ("native", true),
+ ("chat", true),
+ ("completions", true),
+ ] {
+ let gateway = TestGateway::new(&[&generation]).await;
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ gateway.dispatcher.refuse_remote_work(code, retry_after_s);
+ let response = if stream {
+ streaming_surface(&gateway, surface, json!({})).await
+ } else {
+ buffered_surface(&gateway, surface, json!({})).await
+ };
+ assert_restored_cold_refusal(
+ &response,
+ expected,
+ &format!("{code} {surface} stream={stream}"),
+ );
+ assert_eq!(
+ gateway.dispatcher.dispatched(),
+ vec![dispatched("generate", REMOTE_LANE, "acme/chat:remote")]
+ );
+ }
+ }
+ let extraction = format!(
+ "{HYBRID_EXTRACT_MODEL}\nrouting:\n policy: fallback\n fallback_profile: remote\n"
+ );
+ for (code, retry_after_s, expected) in [
+ ("QUEUE_FULL", Some(9), "QUEUE_FULL"),
+ ("MODEL_LOADING", Some(9), "MODEL_LOADING"),
+ ("RESOURCE_EXHAUSTED", Some(9), "RESOURCE_EXHAUSTED"),
+ ("INPUT_TOO_LONG", None, "INPUT_TOO_LONG"),
+ ("INVALID_INPUT", None, "INVALID_INPUT"),
+ ("INFERENCE_ERROR", None, "INFERENCE_ERROR"),
+ ] {
+ for msgpack in [false, true] {
+ let gateway = TestGateway::new(&[&extraction]).await;
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ gateway.dispatcher.refuse_remote_work(code, retry_after_s);
+ let response = proxy_request(
+ State(Arc::clone(&gateway.state)),
+ extraction_request(msgpack, json!({})),
+ "extract",
+ )
+ .await;
+ assert_restored_cold_refusal(
+ &response,
+ expected,
+ &format!("{code} extract msgpack={msgpack}"),
+ );
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn a_bridge_whose_remote_attempt_never_answers_reports_queue_full() {
+ let generation = format!(
+ "{HYBRID_GENERATE_MODEL}\nrouting:\n policy: fallback\n fallback_profile: remote\n"
+ );
+ let deadlines = json!({"first_chunk_timeout_s": 0.2, "overall_timeout_s": 0.4});
+ for (first_chunk_deadline, output_arrived, stream, expected) in [
+ (false, false, false, "QUEUE_FULL"),
+ (true, false, false, "QUEUE_FULL"),
+ (false, false, true, "QUEUE_FULL"),
+ (true, false, true, "QUEUE_FULL"),
+ (false, true, false, "INFERENCE_ERROR"),
+ ] {
+ let gateway = TestGateway::new(&[&generation]).await;
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ gateway.dispatcher.withhold_remote_answers(output_arrived);
+ if first_chunk_deadline {
+ gateway.dispatcher.enable_first_chunk_deadline();
+ }
+ let request = async {
+ if stream {
+ streaming_surface(&gateway, "native", deadlines.clone()).await
+ } else {
+ buffered_surface(&gateway, "native", deadlines.clone()).await
+ }
+ };
+ let response = tokio::time::timeout(Duration::from_secs(5), request)
+ .await
+ .expect("a generation deadline ends the remote attempt");
+ assert_restored_cold_refusal(
+ &response,
+ expected,
+ &format!(
+ "first_chunk_deadline={first_chunk_deadline} output_arrived={output_arrived} stream={stream}"
+ ),
+ );
+ }
+ let extraction = format!(
+ "{HYBRID_EXTRACT_MODEL}\nrouting:\n policy: fallback\n fallback_profile: remote\n"
+ );
+ for msgpack in [false, true] {
+ let mut gateway = TestGateway::new(&[&extraction]).await;
+ gateway.set_request_timeout(0.2);
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ gateway.dispatcher.withhold_remote_answers(false);
+ let request = proxy_request(
+ State(Arc::clone(&gateway.state)),
+ extraction_request(msgpack, json!({})),
+ "extract",
+ );
+ let response = tokio::time::timeout(Duration::from_secs(5), request)
+ .await
+ .expect("the queued-result deadline ends the remote attempt");
+ assert_restored_cold_refusal(
+ &response,
+ "QUEUE_FULL",
+ &format!("extract msgpack={msgpack}"),
+ );
+ }
+ }
+
#[tokio::test]
async fn extraction_cluster_fallback_rejects_invalid_requests_and_honors_selectors() {
let config = format!(
@@ -1755,7 +2143,7 @@ mod tests {
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(response.headers()["retry-after"], retry_after);
assert_eq!(response.headers()["x-sie-fallback-reason"], trigger);
- assert!(response.headers().contains_key("x-sie-fallback-error"));
+ assert_eq!(response.headers()["x-sie-fallback-error"], remote_code);
assert_eq!(stamped(&response), (Some("local"), None));
let body: serde_json::Value = serde_json::from_slice(
&axum::body::to_bytes(response.into_body(), 8192)
diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rs
index 7444d3415..a7164c9c9 100644
--- a/packages/sie_gateway/src/handlers/sse.rs
+++ b/packages/sie_gateway/src/handlers/sse.rs
@@ -62,6 +62,7 @@ use tokio::sync::broadcast;
use tokio_stream::wrappers::ReceiverStream;
use tracing::{debug, info, warn};
+use crate::handlers::serving_disclosure::UnansweredBeforeDeadline;
use crate::observability::metrics as telemetry;
use crate::queue::dispatch::{PendingDispatchKind, WorkDispatcher};
use crate::queue::publisher;
@@ -367,19 +368,24 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
match first_output_rx.await {
Ok(Ok(())) => {}
outcome => {
- let status = match outcome {
- Ok(Err(status)) => status,
- _ => StatusCode::SERVICE_UNAVAILABLE,
+ let failure = match outcome {
+ Ok(Err(failure)) => failure,
+ _ => PreOutputFailure::new(StatusCode::SERVICE_UNAVAILABLE, None),
};
// Only a request-owned bridge enables this gate. Its outer
// handler restores the original local refusal and retry hint.
- return (
- status,
+ let mut response = (
+ failure.status,
axum::Json(json!({"error": {
- "code": "transport_failure", "message": "Bridge failed before output"
+ "code": failure.code.as_deref().unwrap_or("transport_failure"),
+ "message": "Bridge failed before output"
}})),
)
.into_response();
+ if failure.unanswered {
+ response.extensions_mut().insert(UnansweredBeforeDeadline);
+ }
+ return response;
}
}
}
@@ -418,7 +424,26 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
response
}
-type FirstOutputGate = Option<tokio::sync::oneshot::Sender<Result<(), StatusCode>>>;
+/// What ended a stream before its first output event: the status and error
+/// code it would have answered with, and whether a deadline passed before
+/// any output arrived.
+struct PreOutputFailure {
+ status: StatusCode,
+ code: Option<String>,
+ unanswered: bool,
+}
+
+impl PreOutputFailure {
+ fn new(status: StatusCode, code: Option<&str>) -> Self {
+ Self {
+ status,
+ code: code.map(str::to_string),
+ unanswered: false,
+ }
+ }
+}
+
+type FirstOutputGate = Option<tokio::sync::oneshot::Sender<Result<(), PreOutputFailure>>>;
struct SseDriverArgs {
first_output: FirstOutputGate,
@@ -694,6 +719,7 @@ async fn run_sse_driver_with_lifecycle(
if now >= overall_deadline {
send_error_chunk_before_output(
&mut first_output,
+ !first_seen,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -779,6 +805,7 @@ async fn run_sse_driver_with_lifecycle(
}
send_error_chunk_before_output(
&mut first_output,
+ !first_seen,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -800,6 +827,7 @@ async fn run_sse_driver_with_lifecycle(
if la.elapsed() >= inter_chunk_timeout {
send_error_chunk_before_output(
&mut first_output,
+ false,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -837,6 +865,7 @@ async fn run_sse_driver_with_lifecycle(
Ok(Err(error)) => {
send_error_chunk_before_output(
&mut first_output,
+ false,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -855,6 +884,7 @@ async fn run_sse_driver_with_lifecycle(
Err(_) => {
send_error_chunk_before_output(
&mut first_output,
+ false,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -993,6 +1023,7 @@ async fn run_sse_driver_with_lifecycle(
);
send_error_chunk_before_output(
&mut first_output,
+ false,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -1027,6 +1058,7 @@ async fn run_sse_driver_with_lifecycle(
if !first_seen {
send_error_chunk_before_output(
&mut first_output,
+ false,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -1085,6 +1117,7 @@ async fn run_sse_driver_with_lifecycle(
TerminalDurabilityWait::Failed(error) => {
send_error_chunk_before_output(
&mut first_output,
+ false,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -1111,6 +1144,7 @@ async fn run_sse_driver_with_lifecycle(
TerminalDurabilityWait::MonitorStopped => {
send_error_chunk_before_output(
&mut first_output,
+ false,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -1149,6 +1183,7 @@ async fn run_sse_driver_with_lifecycle(
TerminalDurabilityWait::OverallTimeout => {
send_error_chunk_before_output(
&mut first_output,
+ false,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -1226,8 +1261,9 @@ async fn run_sse_driver_with_lifecycle(
if !skip_forward {
if let Some(gate) = first_output.take() {
let ready = match chunk.error.as_ref() {
- Some(error) => Err(crate::handlers::proxy::worker_error_http_status(
- error.client_safe_code(),
+ Some(error) => Err(PreOutputFailure::new(
+ crate::handlers::proxy::worker_error_http_status(error.client_safe_code()),
+ Some(error.client_safe_code()),
)),
None if chunk.done
&& matches!(
@@ -1235,7 +1271,7 @@ async fn run_sse_driver_with_lifecycle(
Some("cancelled" | "error")
) =>
{
- Err(StatusCode::SERVICE_UNAVAILABLE)
+ Err(PreOutputFailure::new(StatusCode::SERVICE_UNAVAILABLE, None))
}
None => Ok(()),
};
@@ -1605,9 +1641,11 @@ fn worker_error_value(error: &ChunkError, include_openai_type: bool) -> Value {
}
/// Preserve the bridge's pre-output HTTP refusal before enqueuing an error event.
+/// `unanswered` says that a deadline passed before any output arrived.
#[allow(clippy::too_many_arguments)]
async fn send_error_chunk_before_output(
first_output: &mut FirstOutputGate,
+ unanswered: bool,
tx: &tokio::sync::mpsc::Sender<Result<Event, Infallible>>,
endpoint: &SseEndpoint,
chat_id: &str,
@@ -1618,7 +1656,10 @@ async fn send_error_chunk_before_output(
message: &str,
) {
if let Some(gate) = first_output.take() {
- let _ = gate.send(Err(StatusCode::SERVICE_UNAVAILABLE));
+ let _ = gate.send(Err(PreOutputFailure {
+ unanswered,
+ ..PreOutputFailure::new(StatusCode::SERVICE_UNAVAILABLE, Some(code))
+ }));
}
send_error_chunk(
tx, endpoint, chat_id, created, model, request_id, code, message,
@@ -1638,8 +1679,9 @@ async fn send_synthetic_error_chunk_before_output(
error: &ChunkError,
) {
if let Some(gate) = first_output.take() {
- let _ = gate.send(Err(crate::handlers::proxy::worker_error_http_status(
- error.client_safe_code(),
+ let _ = gate.send(Err(PreOutputFailure::new(
+ crate::handlers::proxy::worker_error_http_status(error.client_safe_code()),
+ Some(error.client_safe_code()),
)));
}
send_synthetic_error_chunk(tx, endpoint, chat_id, created, model, request_id, error).await;
diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rs
index ddb78a565..c8a06f450 100644
--- a/packages/sie_gateway/src/handlers/test_support.rs
+++ b/packages/sie_gateway/src/handlers/test_support.rs
@@ -1,6 +1,7 @@
//! Handler test fixtures: a gateway with a local lane and a remote lane, and a
//! dispatcher that records what it publishes and answers every request.
+use std::any::Any;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
@@ -150,7 +151,8 @@ impl Dispatched {
}
}
-/// A dispatcher that records every publish and answers it at once.
+/// A dispatcher that records every publish and answers it at once, unless a
+/// test withholds remote answers.
#[derive(Default)]
pub(crate) struct RecordingDispatcher {
without_execution_authority: AtomicBool,
@@ -163,6 +165,9 @@ pub(crate) struct RecordingDispatcher {
stream_mid_error: AtomicBool,
stream_terminal_failure: Mutex<Option<&'static str>>,
remote_refusal: Mutex<Option<(&'static str, Option<u32>)>>,
+ remote_silence: Mutex<Option<bool>>,
+ unanswered: Mutex<Vec<Box<dyn Any + Send>>>,
+ first_chunk_republish: AtomicBool,
bridged_refusal: Mutex<Option<(&'static str, u32)>>,
redelivered: Mutex<Vec<oneshot::Sender<Vec<WorkResult>>>>,
dispatched: Mutex<Vec<Dispatched>>,
@@ -177,6 +182,36 @@ impl RecordingDispatcher {
*self.remote_refusal.lock().unwrap() = Some((code, retry_after_s));
}
+ /// Leave remote-lane work unanswered. With `after_output`, a generation
+ /// reports that its first chunk has arrived.
+ pub(crate) fn withhold_remote_answers(&self, after_output: bool) {
+ *self.remote_silence.lock().unwrap() = Some(after_output);
+ }
+
+ /// Behave as a transport that supports republishing generation work at
+ /// its first-chunk deadline, so a generation that is not republished ends
+ /// at that deadline.
+ pub(crate) fn enable_first_chunk_deadline(&self) {
+ self.first_chunk_republish.store(true, Ordering::SeqCst);
+ }
+
+ fn remote_answer(&self, target: &PublishTarget) -> RemoteAnswer {
+ if target.bundle() != REMOTE_LANE.2 {
+ return RemoteAnswer::Served;
+ }
+ if let Some(refusal) = *self.remote_refusal.lock().unwrap() {
+ return RemoteAnswer::Refused(refusal);
+ }
+ if self.remote_silence.lock().unwrap().is_some() {
+ return RemoteAnswer::Withheld;
+ }
+ RemoteAnswer::Served
+ }
+
+ fn keep_unanswered(&self, pending: impl Any + Send) {
+ self.unanswered.lock().unwrap().push(Box::new(pending));
+ }
+
pub(crate) fn dispatched(&self) -> Vec<Dispatched> {
self.dispatched.lock().unwrap().clone()
}
@@ -249,6 +284,20 @@ impl RecordingDispatcher {
}
}
+enum RemoteAnswer {
+ Served,
+ Refused((&'static str, Option<u32>)),
+ Withheld,
+}
+
+fn refusal_error((code, retry_after_s): (&str, Option<u32>)) -> serde_json::Value {
+ json!({
+ "code": code,
+ "message": "The upstream serving the model is busy, please retry",
+ "retry_after_s": retry_after_s,
+ })
+}
+
fn successful_result(request_id: &str, item_index: u32, payload: serde_json::Value) -> WorkResult {
let mut result: WorkResult = serde_json::from_value(json!({
"work_item_id": format!("{request_id}.{item_index}"),
@@ -285,19 +334,20 @@ fn terminal_chunk_collector(
oneshot::Receiver<StreamOutcome>,
broadcast::Receiver<ChunkEnvelope>,
) {
- stream_chunk_collector(display_model, bundle_config_hash, false, false, None)
+ stream_chunk_collector(display_model, bundle_config_hash, None, false, None)
}
fn stream_chunk_collector(
display_model: &str,
bundle_config_hash: &str,
- fail: bool,
+ error: Option<serde_json::Value>,
after_output: bool,
terminal_failure: Option<&str>,
) -> (
oneshot::Receiver<StreamOutcome>,
broadcast::Receiver<ChunkEnvelope>,
) {
+ let fail = error.is_some();
let (tx, rx) = oneshot::channel();
let mut collector = StreamCollector::new(tx, display_model.to_string(), "default".to_string());
let tap = collector.install_chunk_tap();
@@ -313,7 +363,7 @@ fn stream_chunk_collector(
"kind": "chunk", "request_id": "request-1", "attempt_id": "attempt-1",
"seq": u64::from(fail && after_output), "text_delta": if fail || terminal_failure.is_some() {""} else {"ok"}, "done": true, "is_first": !(fail && after_output),
"finish_reason": terminal_failure.unwrap_or(if fail {"error"} else {"stop"}),
- "error": if fail {json!({"code":"inference_error","message":"private upstream failure"})} else {json!(null)},
+ "error": error.unwrap_or(serde_json::Value::Null),
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
"executed_bundle_config_hash": bundle_config_hash,
}))
@@ -397,10 +447,13 @@ impl WorkDispatcher for RecordingDispatcher {
}
return Ok((request_id, rx, DispatchDurability::accepted()));
}
- let remote_refusal = *self.remote_refusal.lock().unwrap();
- let results = if let Some(refusal) =
- remote_refusal.filter(|_| target.bundle() == REMOTE_LANE.2)
- {
+ let answer = self.remote_answer(&target);
+ if matches!(answer, RemoteAnswer::Withheld) {
+ let (tx, rx) = oneshot::channel::<Vec<WorkResult>>();
+ self.keep_unanswered(tx);
+ return Ok((request_id, rx, DispatchDurability::accepted()));
+ }
+ let results = if let RemoteAnswer::Refused(refusal) = answer {
(0..items.len().max(1) as u32)
.map(|index| refused_result(&request_id, index, refusal))
.collect()
@@ -462,7 +515,21 @@ impl WorkDispatcher for RecordingDispatcher {
.lock()
.unwrap()
.push(params.fallback_reason);
- let (rx, _tap) = terminal_chunk_collector(display_model, bundle_config_hash);
+ let (rx, _tap) = match self.remote_answer(&target) {
+ RemoteAnswer::Served => terminal_chunk_collector(display_model, bundle_config_hash),
+ RemoteAnswer::Refused(refusal) => stream_chunk_collector(
+ display_model,
+ bundle_config_hash,
+ Some(refusal_error(refusal)),
+ false,
+ None,
+ ),
+ RemoteAnswer::Withheld => {
+ let (tx, rx) = oneshot::channel();
+ self.keep_unanswered(tx);
+ (rx, broadcast::channel(1).1)
+ }
+ };
Ok((
"request-1".to_string(),
rx,
@@ -497,10 +564,30 @@ impl WorkDispatcher for RecordingDispatcher {
if self.generate_refused.load(Ordering::SeqCst) {
return Err("private upstream failure".into());
}
+ let error = match self.remote_answer(&target) {
+ RemoteAnswer::Refused(refusal) => Some(refusal_error(refusal)),
+ RemoteAnswer::Withheld => {
+ let (tx, rx) = oneshot::channel();
+ let mut collector =
+ StreamCollector::new(tx, display_model.to_string(), "default".to_string());
+ let tap = collector.install_chunk_tap();
+ self.keep_unanswered(collector);
+ return Ok((
+ "request-1".to_string(),
+ rx,
+ tap,
+ DispatchDurability::accepted(),
+ ));
+ }
+ RemoteAnswer::Served => self
+ .stream_error
+ .load(Ordering::SeqCst)
+ .then(|| json!({"code":"inference_error","message":"private upstream failure"})),
+ };
let (rx, tap) = stream_chunk_collector(
display_model,
bundle_config_hash,
- self.stream_error.load(Ordering::SeqCst),
+ error,
self.stream_mid_error.load(Ordering::SeqCst),
*self.stream_terminal_failure.lock().unwrap(),
);
@@ -550,8 +637,13 @@ impl WorkDispatcher for RecordingDispatcher {
false
}
+ fn supports_first_chunk_pool_republish(&self) -> bool {
+ self.first_chunk_republish.load(Ordering::SeqCst)
+ }
+
fn stream_chunk_timing(&self, _request_id: &str) -> Option<(Option<Instant>, Option<Instant>)> {
- None
+ let now = Instant::now();
+ (*self.remote_silence.lock().unwrap() == Some(true)).then_some((Some(now), Some(now)))
}
}
@@ -641,6 +733,14 @@ impl TestGateway {
}
}
+ /// 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");
+ Arc::get_mut(&mut state.config)
+ .expect("the gateway config is not shared yet")
+ .request_timeout = seconds;
+ }
+
/// Register a healthy worker on `lane` that reports `loaded` as loaded.
pub(crate) async fn add_worker(&self, name: &str, lane: (&str, &str, &str), loaded: &[&str]) {
self.add_worker_with_authority(name, lane, loaded, false, false)
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index 88dda4a88..c80ced9f0 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -188,6 +188,13 @@ returns the original local refusal and `X-SIE-Fallback-Error`. The SDK exposes
these fields in response request metadata. `/v1/models` reports routing and
upstream kind.
+`X-SIE-Fallback-Error` is the SIE error code the remote attempt answered with,
+for example `RESOURCE_EXHAUSTED` from a capped or breaker-open generation
+upstream, or `QUEUE_FULL` and `MODEL_LOADING` from an encode or extraction
+upstream that cannot serve now. The OpenAI codes `server_overloaded` and
+`invalid_request` become `QUEUE_FULL` and `INVALID_INPUT`. Any other failure is
+`INFERENCE_ERROR` for a server error and `INVALID_INPUT` for a client error.
+
Each upstream has a required rate cap and a circuit breaker. The limits are
shared by that worker process's adapters, not across replicas: adding remote
worker replicas increases the aggregate permitted traffic. Under
@@ -495,16 +502,26 @@ The remote attempt pins a fresh worker with the exact current configuration
hash and positive versioned execution capability. It cannot retry on the ordinary
pool subject. Its work item names the trigger in `fallback_reason`, so the remote
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 a bounded
+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.
+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
+a gateway deadline passes before the remote attempt answers anything (the
+queued-result deadline, or a generation's first-chunk or overall deadline before
+its first output), the gateway reports `QUEUE_FULL`: the remote lane never
+answered. On a single node the same generation deadlines end the remote attempt
+itself, with `first_chunk_timeout` or `overall_timeout`, and are reported as
+`INFERENCE_ERROR`.
+
A streaming bridge waits for its first valid event before returning HTTP success.
A worker error, cancelled/failed terminal, transport failure or durability failure
-before output restores the local refusal. Once an event is ready, subsequent
-errors remain in the stream, with cleanup and no replay of inference. Explicit
-profiles keep ordinary streaming behavior.
+before output restores the local refusal, and `X-SIE-Fallback-Error` carries the
+worker's error code. Once an event is ready, subsequent errors remain in the
+stream, with cleanup and no replay of inference. Explicit profiles keep ordinary
+streaming behavior.
Extraction-only models can use the same cold/loading bridge on native extraction
and OpenAI audio transcription. JSON and MessagePack extraction are validated