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(api): tell the caller why a remote upstream refused, without naming it (#744)
Krisztian Gajdarf52781a5bdd3
diff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex 46701fdf8..0b4ae3246 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -1685,6 +1685,16 @@"null"]},+ "reason": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/UpstreamFailureReason"+ }+ ]+ },"retry_after_s": {"description": "Authoritative retry hint in seconds for RESOURCE_EXHAUSTED only; null\nfor other terminal errors.","format": "int32",@@ -2952,6 +2962,16 @@"null"]},+ "reason": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/UpstreamFailureReason"+ }+ ]+ },"type": {"description": "One of the stable types in ``http_error::openai_type``.","type": "string"@@ -4114,6 +4134,21 @@],"type": "object"},+ "UpstreamFailureReason": {+ "description": "Class of a remote upstream's failure, when one ended the generation.",+ "enum": [+ "upstream_credential_unavailable",+ "upstream_credential_rejected",+ "upstream_payment_required",+ "upstream_model_not_found",+ "upstream_refused",+ "upstream_unavailable",+ "upstream_busy",+ "upstream_not_ready",+ "upstream_invalid_response"+ ],+ "type": "string"+ },"Usage": {"description": "Authoritative worker-emitted usage. Post-tokenization counts, never a\ncharacter estimate. A reported `0` is a measurement (a request that read no\ntext); an absent block means the serving path could not count. Structurally\nidentical to `ScoreUsage`, which shipped this shape first.","properties": {diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 663817258..9900b69bc 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -26,8 +26,8 @@ use crate::queue::lane_admission::LaneKey;use crate::queue::publisher;use crate::queue::streaming::{client_safe_worker_error_code, client_safe_worker_error_message,- client_safe_worker_error_param, is_lower_sha256, MODEL_LOAD_FAILED_ERROR_CODE,- MODEL_LOAD_FAILED_PUBLIC_MESSAGE,+ client_safe_worker_error_param, is_lower_sha256, UpstreamFailureReason,+ MODEL_LOAD_FAILED_ERROR_CODE, MODEL_LOAD_FAILED_PUBLIC_MESSAGE,};use crate::server::{@@ -5450,6 +5450,7 @@ pub(crate) enum StreamingDriverErr {message: String,param: Option<String>,retry_after_s: Option<u16>,+ reason: Option<UpstreamFailureReason>,request_id: String,attempt_id: String,},@@ -5985,6 +5986,7 @@ pub(crate) async fn run_streaming_generate(message: err.client_safe_message().to_string(),param: err.client_safe_param().map(str::to_string),retry_after_s: err.validated_retry_after_s(),+ reason: err.client_safe_reason(),request_id: request_id.clone(),attempt_id: outcome.attempt_id.clone(),});@@ -6150,6 +6152,7 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {message,param,retry_after_s,+ reason,request_id,attempt_id,} => {@@ -6174,7 +6177,7 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {let status = worker_error_http_status(stable_code);let err_type = worker_error_openai_type(stable_code);let mut body = json_openai_error(- client_safe_worker_error_message(code, message),+ client_safe_worker_error_message(code, message, *reason),err_type,client_safe_worker_error_param(code, param.as_deref()),openai_code,@@ -6187,6 +6190,9 @@ fn build_streaming_error_response(err: &StreamingDriverErr) -> Response {"attempt_id".to_string(),serde_json::Value::String(attempt_id.clone()),);+ if let Some(reason) = reason {+ err_obj.insert("reason".to_string(), json!(reason.as_str()));+ }}}let mut resp = (status, Json(body)).into_response();@@ -28906,6 +28912,7 @@ mod tests {retry_after_s: None,request_id: "req-rl-1".to_string(),attempt_id: "att-rl-1".to_string(),+ reason: None,};let resp = build_streaming_error_response(&err);assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);@@ -28939,6 +28946,7 @@ mod tests {retry_after_s: None,request_id: "req-large-1".to_string(),attempt_id: "att-large-1".to_string(),+ reason: None,};let response = build_streaming_error_response(&err);@@ -28965,6 +28973,7 @@ mod tests {retry_after_s: None,request_id: "req-too-long-1".to_string(),attempt_id: "att-too-long-1".to_string(),+ reason: None,};let response = build_streaming_error_response(&err);@@ -28992,6 +29001,7 @@ mod tests {retry_after_s: None,request_id: "req-unsupported-1".to_string(),attempt_id: "att-unsupported-1".to_string(),+ reason: None,};let response = build_streaming_error_response(&err);@@ -29020,6 +29030,7 @@ mod tests {retry_after_s: None,request_id: "req-cold-1".to_string(),attempt_id: "att-cold-1".to_string(),+ reason: None,};let resp = build_streaming_error_response(&err);@@ -29047,6 +29058,7 @@ mod tests {retry_after_s: None,request_id: "req-empty-1".to_string(),attempt_id: "att-empty-1".to_string(),+ reason: None,};let resp = build_streaming_error_response(&err);@@ -29080,6 +29092,7 @@ mod tests {retry_after_s: None,request_id: "req-load-failed-1".to_string(),attempt_id: "att-load-failed-1".to_string(),+ reason: None,};let resp = build_streaming_error_response(&err);@@ -29115,6 +29128,7 @@ mod tests {retry_after_s: None,request_id: "req-unknown-1".to_string(),attempt_id: "att-unknown-1".to_string(),+ reason: None,};let resp = build_streaming_error_response(&err);@@ -29144,6 +29158,7 @@ mod tests {retry_after_s: None,request_id: "req-sensitive-1".to_string(),attempt_id: "att-sensitive-1".to_string(),+ reason: None,};let response = build_streaming_error_response(&err);@@ -29171,6 +29186,7 @@ mod tests {retry_after_s: None,request_id: "req-future-1".to_string(),attempt_id: "att-future-1".to_string(),+ reason: None,};let response = build_streaming_error_response(&err);@@ -29200,6 +29216,7 @@ mod tests {retry_after_s: None,request_id: "req-retry-1".to_string(),attempt_id: "att-retry-1".to_string(),+ reason: None,};let resp = build_streaming_error_response(&err);@@ -29244,6 +29261,7 @@ mod tests {retry_after_s: Some(12),request_id: "req-retry-configured".to_string(),attempt_id: "att-retry-configured".to_string(),+ reason: None,};let response = build_streaming_error_response(&err);@@ -29271,6 +29289,7 @@ mod tests {retry_after_s,request_id: "req-loading".to_string(),attempt_id: "att-loading".to_string(),+ reason: None,};let response = build_streaming_error_response(&err);diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rsindex 8fe9d8e52..ffc6e546d 100644--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs@@ -2690,6 +2690,127 @@ mod tests {);}+ #[tokio::test]+ async fn a_remote_generation_failure_tells_the_caller_its_reason_on_every_surface() {+ let messages = json!([{"role": "user", "content": "hello"}]);+ for (code, retry_after_s, reason, message) in [+ (+ "inference_error",+ None,+ "upstream_payment_required",+ "the upstream account cannot pay for the request",+ ),+ (+ "RESOURCE_EXHAUSTED",+ Some(7),+ "upstream_busy",+ "The upstream serving the model is busy, please retry",+ ),+ (+ "MODEL_LOADING",+ Some(7),+ "upstream_not_ready",+ "The upstream serving the model is busy, please retry",+ ),+ ] {+ for (surface, stream) in [+ ("native", false),+ ("chat", false),+ ("completions", false),+ ("responses", false),+ ("native", true),+ ("chat", true),+ ("completions", true),+ ] {+ let gateway = gateway().await;+ gateway+ .dispatcher+ .fail_remote_generation(code, retry_after_s, reason);+ let state = State(Arc::clone(&gateway.state));+ let response = match surface {+ "native" => {+ proxy_request(+ state,+ json_request(+ "/v1/generate/acme__chat:remote",+ json!({"prompt": "hello", "max_new_tokens": 4, "stream": stream}),+ ),+ "generate",+ )+ .await+ }+ "chat" => {+ proxy_chat(+ state,+ json_request(+ "/v1/chat/completions",+ json!({"model": "acme/chat:remote", "messages": messages, "stream": stream}),+ ),+ )+ .await+ }+ "completions" => {+ proxy_completions(+ state,+ json_request(+ "/v1/completions",+ json!({"model": "acme/chat:remote", "prompt": "hello", "stream": stream}),+ ),+ )+ .await+ }+ _ => {+ proxy_responses(+ state,+ json_request(+ "/v1/responses",+ json!({"model": "acme/chat:remote", "input": "hello"}),+ ),+ )+ .await+ }+ };+ let case = format!("{code} {surface} stream={stream}");+ let status = response.status();+ let retry_after = response+ .headers()+ .get("retry-after")+ .map(|value| value.to_str().unwrap().to_string());+ let body = String::from_utf8(+ axum::body::to_bytes(response.into_body(), 64 * 1024)+ .await+ .unwrap()+ .to_vec(),+ )+ .unwrap();+ let error: serde_json::Value = if stream {+ assert_eq!(status, StatusCode::OK, "{case}");+ body.lines()+ .filter_map(|line| line.strip_prefix("data: "))+ .filter_map(|data| serde_json::from_str::<serde_json::Value>(data).ok())+ .find_map(|event| event.get("error").cloned())+ .unwrap_or_else(|| panic!("{case}: no error event in {body}"))+ } else {+ let expected = if code == "inference_error" {+ StatusCode::INTERNAL_SERVER_ERROR+ } else {+ assert!(retry_after.is_some(), "{case}");+ StatusCode::SERVICE_UNAVAILABLE+ };+ assert_eq!(status, expected, "{case}: {body}");+ serde_json::from_str::<serde_json::Value>(&body).unwrap()["error"].clone()+ };+ assert_eq!(error["code"], code, "{case}");+ assert_eq!(error["reason"], reason, "{case}");+ assert_eq!(error["message"], message, "{case}");+ assert!(!body.contains("team-sie"), "{case}");+ if code == "inference_error" {+ assert!(!body.contains("busy, please retry"), "{case}");+ }+ }+ }+ }+#[test]fn only_a_served_response_or_a_server_side_refusal_is_stamped() {let disclosure = ServingDisclosure::default();diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rsindex a54d7d301..a5b71bc1f 100644--- a/packages/sie_gateway/src/handlers/sse.rs+++ b/packages/sie_gateway/src/handlers/sse.rs@@ -1667,6 +1667,9 @@ fn worker_error_value(error: &ChunkError, include_openai_type: bool) -> Value {if let Some(retry_after_s) = error.validated_retry_after_s() {object.insert("retry_after_s".to_string(), json!(retry_after_s));}+ if let Some(reason) = error.client_safe_reason() {+ object.insert("reason".to_string(), json!(reason.as_str()));+ }Value::Object(object)}@@ -2227,6 +2230,7 @@ mod tests {message: "sensitive diagnostic".into(),param: None,retry_after_s: None,+ reason: None,},).await;@@ -2427,6 +2431,7 @@ mod tests {message: "scheduler full".to_string(),param: Some("model".to_string()),retry_after_s: Some(12),+ reason: None,},).await;@@ -2516,6 +2521,7 @@ mod tests {message: "scheduler full".to_string(),param: None,retry_after_s: None,+ reason: None,},).await;@@ -2569,6 +2575,7 @@ mod tests {message: "pool republish failed".to_string(),param: None,retry_after_s: None,+ reason: None,}),origin: StreamOutcomeOrigin::GatewaySynthetic,tool_calls: None,@@ -2656,6 +2663,7 @@ mod tests {message: "top_k is unavailable".to_string(),param: Some("top_k".to_string()),retry_after_s: None,+ reason: None,},).await;@@ -2923,6 +2931,7 @@ mod tests {message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),param: None,retry_after_s: None,+ reason: None,});let value = build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk);@@ -2950,6 +2959,7 @@ mod tests {message: "top_k is unavailable".to_string(),param: Some("top_k".to_string()),retry_after_s: None,+ reason: None,});let value = build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk);@@ -3023,6 +3033,7 @@ mod tests {message: "upstream gone".to_string(),param: None,retry_after_s: None,+ reason: None,});for value in [@@ -3045,6 +3056,7 @@ mod tests {message: "top_k is unavailable".to_string(),param: Some("top_k".to_string()),retry_after_s: None,+ reason: None,});let v = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);assert_eq!(v["error"]["code"], "unsupported_field");@@ -3065,6 +3077,7 @@ mod tests {message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),param: None,retry_after_s: None,+ reason: None,});let value = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);@@ -3158,6 +3171,7 @@ mod tests {message: "upstream gone".to_string(),param: None,retry_after_s: None,+ reason: None,});let v = build_generate_chunk_event(&chunk, &[]);assert_eq!(v["error"]["code"], "transport_failure");@@ -3172,6 +3186,7 @@ mod tests {message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),param: None,retry_after_s: None,+ reason: None,});let value = build_generate_chunk_event(&chunk, &[]);@@ -3196,6 +3211,7 @@ mod tests {message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),param: None,retry_after_s: None,+ reason: None,});let values = [@@ -3215,6 +3231,48 @@ mod tests {}}+ #[test]+ fn test_sse_upstream_failure_reason_reaches_all_generation_shapes() {+ for (reason, expected) in [+ (+ "upstream_payment_required",+ Some("the upstream account cannot pay for the request"),+ ),+ ("SENSITIVE_REASON_SENTINEL", None),+ ] {+ let mut chunk = _terminal_chunk("error", None);+ chunk.error = Some(ChunkError {+ code: "inference_error".to_string(),+ message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),+ param: None,+ retry_after_s: None,+ reason: Some(reason.to_string()),+ });++ for value in [+ build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false),+ build_text_completion_chunk_event("cmpl-1", 0, "m", &chunk),+ build_generate_chunk_event(&chunk, &[]),+ ] {+ let error = &value["error"];+ assert_eq!(error["code"], "inference_error");+ match expected {+ Some(message) => {+ assert_eq!(error["reason"], reason);+ assert_eq!(error["message"], message);+ }+ None => {+ assert!(error.get("reason").is_none());+ assert_eq!(error["message"], "internal error during generation");+ }+ }+ let serialized = value.to_string();+ assert!(!serialized.contains("SENSITIVE_WORKER_FAILURE_SENTINEL"));+ assert!(!serialized.contains("SENSITIVE_REASON_SENTINEL"));+ }+ }+ }+#[test]fn test_sse_payload_too_large_preserves_worker_code_on_all_generation_shapes() {let mut chunk = _terminal_chunk("error", None);@@ -3223,6 +3281,7 @@ mod tests {message: "payload exceeds limit".to_string(),param: None,retry_after_s: None,+ reason: None,});for value in [@@ -3243,6 +3302,7 @@ mod tests {message: "resource pressure".to_string(),param: Some("model".to_string()),retry_after_s: Some(12),+ reason: None,});let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);@@ -3263,12 +3323,14 @@ mod tests {message: "resource pressure".to_string(),param: None,retry_after_s: Some(61),+ reason: None,},ChunkError {code: "MODEL_LOADING".to_string(),message: "draining".to_string(),param: None,retry_after_s: Some(12),+ reason: None,},] {let mut chunk = _terminal_chunk("error", None);@@ -3293,6 +3355,7 @@ mod tests {message: sentinel.to_string(),param: Some(sentinel.to_string()),retry_after_s: None,+ reason: None,});let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);@@ -3318,6 +3381,7 @@ mod tests {message: sentinel.to_string(),param: Some(sentinel.to_string()),retry_after_s: None,+ reason: None,});let value = build_generate_chunk_event(&chunk, &[]);@@ -3339,6 +3403,7 @@ mod tests {message: sentinel.to_string(),param: Some(sentinel.to_string()),retry_after_s: None,+ reason: None,});let chat = build_chat_chunk_event("chatcmpl-1", 0, "m", &chunk, false, false);@@ -3446,6 +3511,7 @@ mod tests {message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),param: None,retry_after_s: None,+ reason: None,};let (tx, mut rx) = tokio::sync::mpsc::channel(4);send_synthetic_error_chunk(&tx, &endpoint, "cmpl-1", 1, "m", "req-1", &error).await;@@ -3962,6 +4028,7 @@ mod tests {message: "saturated".to_string(),param: None,retry_after_s: None,+ reason: None,});collector.apply(err_chunk);let got = tap.recv().await.unwrap();@@ -3997,6 +4064,7 @@ mod tests {message: "top_k is unavailable".to_string(),param: Some("top_k".to_string()),retry_after_s: None,+ reason: None,});collector.apply(error);diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rsindex c807ac33d..757b17495 100644--- a/packages/sie_gateway/src/handlers/test_support.rs+++ b/packages/sie_gateway/src/handlers/test_support.rs@@ -167,6 +167,7 @@ pub(crate) struct RecordingDispatcher {stream_mid_error: AtomicBool,stream_terminal_failure: Mutex<Option<&'static str>>,remote_refusal: Mutex<Option<(&'static str, Option<u32>)>>,+ remote_failure_reason: Mutex<Option<&'static str>>,remote_silence: Mutex<Option<bool>>,unanswered: Mutex<Vec<Box<dyn Any + Send>>>,first_chunk_republish: AtomicBool,@@ -217,6 +218,25 @@ impl RecordingDispatcher {*self.remote_refusal.lock().unwrap() = Some((code, retry_after_s));}+ /// Answer remote-lane generation as a remote worker does when its+ /// upstream failed: a `code` terminal with the upstream's wait, if any,+ /// that names `reason`.+ pub(crate) fn fail_remote_generation(+ &self,+ code: &'static str,+ retry_after_s: Option<u32>,+ reason: &'static str,+ ) {+ *self.remote_refusal.lock().unwrap() = Some((code, retry_after_s));+ *self.remote_failure_reason.lock().unwrap() = Some(reason);+ }++ fn remote_generation_error(&self, refusal: (&str, Option<u32>)) -> serde_json::Value {+ let mut error = refusal_error(refusal);+ error["reason"] = json!(*self.remote_failure_reason.lock().unwrap());+ error+ }+/// 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) {@@ -612,7 +632,7 @@ impl WorkDispatcher for RecordingDispatcher {RemoteAnswer::Refused(refusal) => stream_chunk_collector(display_model,bundle_config_hash,- Some(refusal_error(refusal)),+ Some(self.remote_generation_error(refusal)),false,None,),@@ -660,7 +680,7 @@ impl WorkDispatcher for RecordingDispatcher {return Err("no consumers ready: the lane is starting".into());}let error = match self.remote_answer(&target) {- RemoteAnswer::Refused(refusal) => Some(refusal_error(refusal)),+ RemoteAnswer::Refused(refusal) => Some(self.remote_generation_error(refusal)),RemoteAnswer::Withheld => {let (tx, rx) = oneshot::channel();let mut collector =diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 8700fc382..bb021a03a 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -134,6 +134,7 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {GenerateResponse,GenerateChunk,GenerateChunkError,+ UpstreamFailureReason,GenerateUsage,PromptTokensDetails,ChatCompletionRequest,@@ -2127,6 +2128,31 @@ pub struct GenerateChunkError {#[schema(minimum = 1, maximum = 60)]#[serde(default, skip_serializing_if = "Option::is_none")]pub retry_after_s: Option<u16>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reason: Option<UpstreamFailureReason>,+}++/// Class of a remote upstream's failure, when one ended the generation.+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub enum UpstreamFailureReason {+ #[serde(rename = "upstream_credential_unavailable")]+ CredentialUnavailable,+ #[serde(rename = "upstream_credential_rejected")]+ CredentialRejected,+ #[serde(rename = "upstream_payment_required")]+ PaymentRequired,+ #[serde(rename = "upstream_model_not_found")]+ ModelNotFound,+ #[serde(rename = "upstream_refused")]+ Refused,+ #[serde(rename = "upstream_unavailable")]+ Unavailable,+ #[serde(rename = "upstream_busy")]+ Busy,+ #[serde(rename = "upstream_not_ready")]+ NotReady,+ #[serde(rename = "upstream_invalid_response")]+ InvalidResponse,}/// One JSON payload from a SIE-native generation SSE ``data:`` event.@@ -2582,6 +2608,8 @@ pub struct OpenAIErrorBody {pub param: Option<String>,/// SIE-native discriminator, see ``http_error::openai_code``.pub code: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reason: Option<UpstreamFailureReason>,}#[derive(Debug, Serialize, Deserialize, ToSchema)]@@ -3726,6 +3754,22 @@ mod tests {);assert_eq!(chunk_error["properties"]["retry_after_s"]["minimum"], 1);assert_eq!(chunk_error["properties"]["retry_after_s"]["maximum"], 60);+ let reasons: Vec<&str> = crate::queue::streaming::UpstreamFailureReason::ALL+ .iter()+ .map(|reason| reason.as_str())+ .collect();+ assert_eq!(+ spec["components"]["schemas"]["UpstreamFailureReason"]["enum"],+ json!(reasons)+ );+ for schema in ["GenerateChunkError", "OpenAIErrorBody"] {+ let properties = &spec["components"]["schemas"][schema]["properties"];+ assert_eq!(+ properties["reason"]["oneOf"][1]["$ref"],+ "#/components/schemas/UpstreamFailureReason",+ "{schema}"+ );+ }assert_eq!(chunk["properties"]["logprobs"]["type"],json!(["array", "null"])diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex c9359a066..0726042c6 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -4092,6 +4092,7 @@ impl WorkPublisher {message: message.to_string(),param: None,retry_after_s: None,+ reason: None,}),origin: StreamOutcomeOrigin::GatewaySynthetic,tool_calls: None,@@ -5395,6 +5396,7 @@ impl WorkPublisher {message: "gateway shutdown before stream completed".to_string(),param: None,retry_after_s: None,+ reason: None,}),origin: StreamOutcomeOrigin::GatewaySynthetic,tool_calls: None,diff --git a/packages/sie_gateway/src/queue/streaming.rs b/packages/sie_gateway/src/queue/streaming.rsindex 46d7cc110..f6b1bc085 100644--- a/packages/sie_gateway/src/queue/streaming.rs+++ b/packages/sie_gateway/src/queue/streaming.rs@@ -331,6 +331,10 @@ pub struct ChunkError {/// errors. The gateway validates code + bounds before trusting it.#[serde(default, skip_serializing_if = "Option::is_none")]pub retry_after_s: Option<u16>,+ /// Class of a remote upstream's failure. Additive for mixed-version+ /// rollouts; the gateway admits only [`UpstreamFailureReason`] names.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub reason: Option<String>,}impl ChunkError {@@ -352,7 +356,19 @@ impl ChunkError {/// errors remain exact; generic backend and grammar-internal failures use/// stable public text so mixed-version workers cannot disclose internals.pub(crate) fn client_safe_message(&self) -> &str {- client_safe_worker_error_message(&self.code, &self.message)+ client_safe_worker_error_message(&self.code, &self.message, self.client_safe_reason())+ }++ /// The worker's upstream failure class, when it is one the gateway knows+ /// on an error code a remote upstream's failure can produce.+ pub(crate) fn client_safe_reason(&self) -> Option<UpstreamFailureReason> {+ match self.code.as_str() {+ "inference_error" | "RESOURCE_EXHAUSTED" | "MODEL_LOADING" => self+ .reason+ .as_deref()+ .and_then(UpstreamFailureReason::parse),+ _ => None,+ }}/// Treat worker terminal parameters as untrusted. Only the typed@@ -403,10 +419,81 @@ pub(crate) fn client_safe_worker_error_code(code: &str) -> &'static str {}}-pub(crate) fn client_safe_worker_error_message<'a>(code: &str, message: &'a str) -> &'a str {+/// Class of a remote upstream's failure that ended a generation.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub(crate) enum UpstreamFailureReason {+ CredentialUnavailable,+ CredentialRejected,+ PaymentRequired,+ ModelNotFound,+ Refused,+ Unavailable,+ Busy,+ NotReady,+ InvalidResponse,+}++impl UpstreamFailureReason {+ pub(crate) const ALL: [Self; 9] = [+ Self::CredentialUnavailable,+ Self::CredentialRejected,+ Self::PaymentRequired,+ Self::ModelNotFound,+ Self::Refused,+ Self::Unavailable,+ Self::Busy,+ Self::NotReady,+ Self::InvalidResponse,+ ];++ pub(crate) fn parse(name: &str) -> Option<Self> {+ Self::ALL.into_iter().find(|reason| reason.as_str() == name)+ }++ pub(crate) fn as_str(self) -> &'static str {+ match self {+ Self::CredentialUnavailable => "upstream_credential_unavailable",+ Self::CredentialRejected => "upstream_credential_rejected",+ Self::PaymentRequired => "upstream_payment_required",+ Self::ModelNotFound => "upstream_model_not_found",+ Self::Refused => "upstream_refused",+ Self::Unavailable => "upstream_unavailable",+ Self::Busy => "upstream_busy",+ Self::NotReady => "upstream_not_ready",+ Self::InvalidResponse => "upstream_invalid_response",+ }+ }++ /// Caller-facing text for an ``inference_error`` of this class, in place+ /// of the worker's own message.+ pub(crate) fn message(self) -> &'static str {+ match self {+ Self::CredentialUnavailable => "the server has no usable credential for its upstream",+ Self::CredentialRejected => "the upstream rejected the server's credential",+ Self::PaymentRequired => "the upstream account cannot pay for the request",+ Self::ModelNotFound => "the upstream has no route for the configured model",+ Self::Refused => "the upstream refused the request",+ Self::Unavailable => "the upstream could not be reached, timed out or failed",+ Self::Busy => "the upstream is busy",+ Self::NotReady => "the model is not ready on the upstream",+ Self::InvalidResponse => {+ "the upstream answered with something the server cannot accept"+ }+ }+ }+}++pub(crate) fn client_safe_worker_error_message<'a>(+ code: &str,+ message: &'a str,+ reason: Option<UpstreamFailureReason>,+) -> &'a str {match client_safe_worker_error_code(code) {MODEL_LOAD_FAILED_ERROR_CODE => MODEL_LOAD_FAILED_PUBLIC_MESSAGE,- "inference_error" if code == "inference_error" => "internal error during generation",+ "inference_error" if code == "inference_error" => reason.map_or(+ "internal error during generation",+ UpstreamFailureReason::message,+ ),"inference_error" => UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE,"grammar_compile_failed" => "internal error compiling grammar",_ => message,@@ -1414,6 +1501,7 @@ mod tests {message: "Model 'Qwen/Qwen3-4B-Instruct-2507' is loading; retry later.".to_string(),param: None,retry_after_s: None,+ reason: None,});assert_eq!(c.apply(term), ChunkApplied::Terminal);@@ -1605,6 +1693,7 @@ mod tests {message: public_message.to_string(),param: Some(param.to_string()),retry_after_s: None,+ reason: None,};assert_eq!(error.client_safe_message(), expected_message, "{code}");assert_eq!(error.client_safe_param(), expected_param, "{code}");@@ -1709,19 +1798,99 @@ mod tests {assert_eq!(client_safe_worker_error_message(MODEL_LOAD_FAILED_ERROR_CODE,- "SENSITIVE_WORKER_FAILURE_SENTINEL"+ "SENSITIVE_WORKER_FAILURE_SENTINEL",+ None),MODEL_LOAD_FAILED_PUBLIC_MESSAGE);assert_eq!(client_safe_worker_error_message("SENSITIVE_WORKER_ERROR_CODE_SENTINEL",- "SENSITIVE_WORKER_FAILURE_SENTINEL"+ "SENSITIVE_WORKER_FAILURE_SENTINEL",+ Some(UpstreamFailureReason::PaymentRequired)),UNKNOWN_WORKER_ERROR_PUBLIC_MESSAGE);}+ #[test]+ fn test_worker_upstream_failure_reasons_are_the_wire_fixture() {+ let fixture: serde_json::Value = serde_json::from_str(include_str!(+ "../../../wire-fixtures/upstream_failure_reasons.json"+ ))+ .unwrap();+ let reasons: serde_json::Map<String, serde_json::Value> = UpstreamFailureReason::ALL+ .iter()+ .map(|reason| (reason.as_str().to_string(), reason.message().into()))+ .collect();+ assert_eq!(fixture["reasons"], serde_json::Value::Object(reasons));+ let worker = &fixture["worker_terminal_error"];+ let decoded: ChunkError =+ rmp_serde::from_slice(&rmp_serde::to_vec_named(worker).unwrap()).unwrap();+ assert_eq!(+ decoded+ .client_safe_reason()+ .map(UpstreamFailureReason::as_str),+ worker["reason"].as_str()+ );+ assert_eq!(decoded.client_safe_message(), worker["message"]);+ }++ #[test]+ fn test_worker_upstream_failure_reason_is_a_closed_set_with_fixed_text() {+ let error = |code: &str, reason: &str| ChunkError {+ code: code.to_string(),+ message: "SENSITIVE_WORKER_FAILURE_SENTINEL".to_string(),+ param: None,+ retry_after_s: None,+ reason: Some(reason.to_string()),+ };+ for reason in UpstreamFailureReason::ALL {+ let failed = error("inference_error", reason.as_str());+ assert_eq!(failed.client_safe_reason(), Some(reason));+ assert_eq!(failed.client_safe_message(), reason.message());+ }+ let busy = ChunkError {+ message: "the upstream is busy, please retry".to_string(),+ ..error("RESOURCE_EXHAUSTED", "upstream_busy")+ };+ assert_eq!(busy.client_safe_reason(), Some(UpstreamFailureReason::Busy));+ assert_eq!(+ busy.client_safe_message(),+ "the upstream is busy, please retry"+ );+ for code in ["invalid_request", "unsupported_field", "INPUT_TOO_LONG"] {+ assert_eq!(+ error(code, "upstream_payment_required").client_safe_reason(),+ None,+ "{code}"+ );+ }+ let unknown = error("inference_error", "SENSITIVE_REASON_SENTINEL");+ assert_eq!(unknown.client_safe_reason(), None);+ assert_eq!(+ unknown.client_safe_message(),+ "internal error during generation"+ );+ let decoded: ChunkError = rmp_serde::from_slice(+ &rmp_serde::to_vec_named(&serde_json::json!({+ "code": "inference_error",+ "message": "SENSITIVE_WORKER_FAILURE_SENTINEL",+ "reason": "upstream_payment_required",+ }))+ .unwrap(),+ )+ .unwrap();+ assert_eq!(+ decoded.client_safe_reason(),+ Some(UpstreamFailureReason::PaymentRequired)+ );+ assert_eq!(+ decoded.client_safe_message(),+ "the upstream account cannot pay for the request"+ );+ }+/// Multi-candidate (`n>1`): the terminal chunk carries a `candidates`/// array which the collector passes through verbatim onto the/// `StreamOutcome` for the body builder to expand into `choices[]`.diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.mdindex 8fb38c040..4aaf9f55f 100644--- a/packages/sie_server/REMOTE_BACKENDS.md+++ b/packages/sie_server/REMOTE_BACKENDS.md@@ -271,9 +271,69 @@ with `503` because the upstream is unavailable, busy or not ready, logs one`remote chat for <model> failed: upstream answered 401` or`remote chat for <model> failed: the upstream credential is unavailable`. Afailure after a stream has started logs `failed after output`. Native-generation and completions log an upstream they cannot reach as-`remote generation failed: upstream '<name>' is unavailable: <reason>`. No-line contains the credential, the prompt or anything the upstream sent.+generation, completions and chat that the server renders through the model's+template log a failed upstream call, an error the upstream sent in place of an+answer, and an SIE upstream's terminal error event as+`remote generation failed: <reason>`, for example+`remote generation failed: upstream answered 402`,+`remote generation failed: upstream ended generation with inference_error` or+`remote generation failed: upstream '<name>' is unavailable: <reason>`.+Rendered chat logs an answer it refuses as+`remote chat for <model> failed: <reason>`. No line contains the credential,+the prompt or anything the upstream sent.++The caller's error names the class of a remote generation failure in a+`reason` field, next to `code` and `message`: in the response's `error`+object, or in `detail` for native generation on a single node, and in the+error event of a stream that has already started. A cluster gateway forwards a+worker's `reason` only on an `inference_error`, `RESOURCE_EXHAUSTED` or+`MODEL_LOADING` error, and only when it is one of these values:++| `reason` | Cause |+| --- | --- |+| `upstream_credential_unavailable` | The server has no credential to send, for example because the environment variable that holds it is not set. |+| `upstream_credential_rejected` | The upstream answered `401`, or `403` without a known error code. |+| `upstream_payment_required` | The upstream answered `402`, for example because its account has no credits. |+| `upstream_model_not_found` | The upstream answered `404`, for example because it does not serve the configured model. |+| `upstream_refused` | The upstream answered another `4xx`, including a `403` whose error code names the state of its account or service, such as `ACCOUNT_SUSPENDED`. |+| `upstream_unavailable` | The upstream could not be reached, timed out, closed a started stream, answered `408` or `5xx`, or reported a failure of its own, or its circuit breaker is open. |+| `upstream_busy` | The upstream answered `429` or a busy code, or the server's rate or concurrency cap for it is reached. |+| `upstream_not_ready` | The upstream reports that the model is not ready. |+| `upstream_invalid_response` | The answer is not one the server accepts: malformed, cut short, too large, compressed, a redirect, or a chat answer that breaks the request's tools or token limits. |++The `reason` names the cause, and the status says whether a retry may help:+for example a `429` with the final code `COLD_START_RATE_LIMITED` is a final+failure whose reason is `upstream_busy`. An error object that the upstream+sends in place of an answer, as the body of a `200` or as an event of a stream,+is a final failure classed by the HTTP status its numeric `code` names, and+otherwise as `upstream_unavailable`. An SIE upstream names the class of its own+upstream's failure in a `reason` of its error, and the server keeps that class.+When it is not `upstream_unavailable`, `upstream_busy` or `upstream_not_ready`,+the failure is final here too. A terminal error event of an SIE upstream with+the code `inference_error` carries the class that event names, or+`upstream_unavailable` when it names none. One with `RESOURCE_EXHAUSTED` or+`MODEL_LOADING` carries `upstream_busy` or `upstream_not_ready`, and one with+any other code, which describes the request or the model's output, carries no+`reason`.++On a single node, the expiry of a remote profile's `first_chunk_timeout_s` or+`overall_timeout_s` keeps its `504` and code and carries+`upstream_unavailable`, and so does chat that times out after output. A cluster+gateway's own deadline carries no `reason`, because it also covers the queue+and the worker. A request that falls back to a remote profile answers a failed+remote attempt with the original local refusal, unchanged, and names that+attempt's failure only in `X-SIE-Fallback-Error`, so it carries no `reason`.++The status and `code` do not change. A failure that a retry would not fix is+`502` `upstream_error` from single-node chat and `500` `inference_error` from+native generation, completions, responses and a cluster, and its message is+fixed text for the reason, for example+`the upstream account cannot pay for the request`. A retryable failure stays+a `503` with `Retry-After` and its message. An upstream's refusal of the+caller's input stays `400` and carries no `reason`. The `reason` and message+never contain the upstream's name, URL, model id, answer or account; the+`WARNING` line above keeps that detail for the operator, and `X-SIE-Upstream`+still names the upstream as described above.Each upstream has a required rate cap and a circuit breaker. The limits areshared by that worker process's adapters, not across replicas: adding remote@@ -317,7 +377,8 @@ when it calls a function the request did not declare, calls any function undermakes several calls under `parallel_tool_calls: false`, or makes no call when`tool_choice` is `"required"` or names a function. Before output, a single nodeanswers that failure with `502` `upstream_error` and a cluster with `500`-`inference_error`, as each answers any other upstream failure. A stream that+`inference_error`, as each answers any other upstream failure, and the reason+is `upstream_invalid_response`. A stream thathas already started ends with an error event. A streamed function name ischecked as OpenAI clients assemble it, by concatenating the fragments of eachcall index. A fragment is delivered while the name so far begins a permitteddiff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex c053e6cba..e41301c8b 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -413,11 +413,35 @@}}},+ "500": {+ "description": "Generation failed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GenerateErrorResponse"+ }+ }+ }+ },"503": {- "description": "Model loading or unavailable"+ "description": "Model loading or unavailable",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GenerateErrorResponse"+ }+ }+ }},"504": {- "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s"+ "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GenerateErrorResponse"+ }+ }+ }},"422": {"description": "Validation Error",@@ -948,13 +972,34 @@"description": "Request body or prompt is too large"},"500": {- "description": "Generation failed"+ "description": "Generation failed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIGenerationErrorResponse"+ }+ }+ }},"503": {- "description": "Model loading or temporarily unavailable"+ "description": "Model loading or temporarily unavailable",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIGenerationErrorResponse"+ }+ }+ }},"504": {- "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s"+ "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIGenerationErrorResponse"+ }+ }+ }},"422": {"description": "Validation Error",@@ -1044,13 +1089,34 @@"description": "Request body or rendered input is too large"},"500": {- "description": "Generation failed"+ "description": "Generation failed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIGenerationErrorResponse"+ }+ }+ }},"503": {- "description": "Model loading or temporarily unavailable"+ "description": "Model loading or temporarily unavailable",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIGenerationErrorResponse"+ }+ }+ }},"504": {- "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s"+ "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/OpenAIGenerationErrorResponse"+ }+ }+ }},"422": {"description": "Validation Error",@@ -1412,6 +1478,75 @@"title": "ExtractResultModel","description": "Single item extraction result."},+ "GenerateErrorDetailModel": {+ "properties": {+ "code": {+ "type": "string",+ "title": "Code",+ "description": "Stable error code"+ },+ "message": {+ "type": "string",+ "title": "Message",+ "description": "Client-safe error message"+ },+ "param": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Param",+ "description": "Offending request field, when known"+ },+ "reason": {+ "anyOf": [+ {+ "type": "string",+ "enum": [+ "upstream_credential_unavailable",+ "upstream_credential_rejected",+ "upstream_payment_required",+ "upstream_model_not_found",+ "upstream_refused",+ "upstream_unavailable",+ "upstream_busy",+ "upstream_not_ready",+ "upstream_invalid_response"+ ]+ },+ {+ "type": "null"+ }+ ],+ "title": "Reason",+ "description": "Class of a remote upstream's failure, when one caused the error"+ }+ },+ "type": "object",+ "required": [+ "code",+ "message"+ ],+ "title": "GenerateErrorDetailModel",+ "description": "Detail returned for a native generation error."+ },+ "GenerateErrorResponse": {+ "properties": {+ "detail": {+ "$ref": "#/components/schemas/GenerateErrorDetailModel"+ }+ },+ "type": "object",+ "required": [+ "detail"+ ],+ "title": "GenerateErrorResponse",+ "description": "FastAPI error envelope for a native generation error."+ },"GenerateInputTooLongDetailModel": {"properties": {"code": {@@ -2238,6 +2373,81 @@"title": "OpenAIEmbeddingsModelLoadFailedErrorResponse","description": "Top-level OpenAI error envelope for a terminal ``/v1/embeddings`` model-load failure."},+ "OpenAIGenerationErrorModel": {+ "properties": {+ "message": {+ "type": "string",+ "title": "Message",+ "description": "Client-safe error message"+ },+ "type": {+ "type": "string",+ "title": "Type",+ "description": "OpenAI error type, e.g. 'server_error'"+ },+ "param": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Param",+ "description": "Offending request field, when known"+ },+ "code": {+ "type": "string",+ "title": "Code",+ "description": "Stable error code"+ },+ "reason": {+ "anyOf": [+ {+ "type": "string",+ "enum": [+ "upstream_credential_unavailable",+ "upstream_credential_rejected",+ "upstream_payment_required",+ "upstream_model_not_found",+ "upstream_refused",+ "upstream_unavailable",+ "upstream_busy",+ "upstream_not_ready",+ "upstream_invalid_response"+ ]+ },+ {+ "type": "null"+ }+ ],+ "title": "Reason",+ "description": "Class of a remote upstream's failure, when one caused the error"+ }+ },+ "type": "object",+ "required": [+ "message",+ "type",+ "code"+ ],+ "title": "OpenAIGenerationErrorModel",+ "description": "Inner object of the top-level OpenAI ``{\"error\": {...}}`` envelope of a generation error."+ },+ "OpenAIGenerationErrorResponse": {+ "properties": {+ "error": {+ "$ref": "#/components/schemas/OpenAIGenerationErrorModel"+ }+ },+ "type": "object",+ "required": [+ "error"+ ],+ "title": "OpenAIGenerationErrorResponse",+ "description": "Top-level OpenAI error envelope of a generation error."+ },"OpenAIResponseOutputMessageModel": {"properties": {"type": {@@ -3338,6 +3548,30 @@"default": null,"description": "Authoritative retry hint in seconds for RESOURCE_EXHAUSTED only; null for other terminal errors","title": "Retry After S"+ },+ "reason": {+ "anyOf": [+ {+ "enum": [+ "upstream_credential_unavailable",+ "upstream_credential_rejected",+ "upstream_payment_required",+ "upstream_model_not_found",+ "upstream_refused",+ "upstream_unavailable",+ "upstream_busy",+ "upstream_not_ready",+ "upstream_invalid_response"+ ],+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "description": "Class of a remote upstream's failure, when one ended the generation",+ "title": "Reason"}},"required": [diff --git a/packages/sie_server/src/sie_server/adapters/_generation_base.py b/packages/sie_server/src/sie_server/adapters/_generation_base.pyindex b84df742f..c8401bec0 100644--- a/packages/sie_server/src/sie_server/adapters/_generation_base.py+++ b/packages/sie_server/src/sie_server/adapters/_generation_base.py@@ -26,6 +26,7 @@ from typing import Any, ClassVar, Literal, castfrom sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters.base import ModelAdapter, ModelCapabilities, ModelDims+from sie_server.adapters.errors import UPSTREAM_FAILURE_MESSAGES, UpstreamFailureReasonfrom sie_server.types.grammar import GrammarSpecfrom sie_server.types.inputs import ImageInput, VideoInput@@ -63,10 +64,15 @@ FinishReason = Literal["stop", "length", "cancelled", "error", "tool_calls"]class GenerationError(RuntimeError):- """Base for adapter-declared generation failures with stable semantics."""+ """Base for adapter-declared generation failures with stable semantics.++ ``upstream_reason`` names the class of a remote upstream's failure, when+ one caused this error.+ """code: ClassVar[str] = "inference_error"param: str | None = None+ upstream_reason: UpstreamFailureReason | None = Noneclass GenerationUnsupportedFieldError(GenerationError):@@ -107,9 +113,16 @@ class GenerationCapacityError(GenerationError):code = "RESOURCE_EXHAUSTED"- def __init__(self, message: str = "", *, retry_after_s: int | None = None) -> None:+ def __init__(+ self,+ message: str = "",+ *,+ retry_after_s: int | None = None,+ upstream_reason: UpstreamFailureReason | None = None,+ ) -> None:super().__init__(message)self.retry_after_s = retry_after_s+ self.upstream_reason = upstream_reasonclass GenerationDrainingError(GenerationCapacityError):@@ -118,6 +131,20 @@ class GenerationDrainingError(GenerationCapacityError):code = "MODEL_LOADING"+class GenerationUpstreamError(GenerationError):+ """A remote upstream failed the generation, and the same request would fail again.++ The message is operator-side detail. A caller sees the fixed text of+ ``upstream_reason`` instead.+ """++ upstream_reason: UpstreamFailureReason++ def __init__(self, message: str, *, upstream_reason: UpstreamFailureReason) -> None:+ super().__init__(message)+ self.upstream_reason = upstream_reason++_CLIENT_SAFE_GENERATION_ERROR_MESSAGES = {"inference_error": "internal error during generation","grammar_compile_failed": "internal error compiling grammar",@@ -201,7 +228,9 @@ def client_safe_generation_error_code(error_code: str | None) -> str:return code if code in _CLIENT_SAFE_GENERATION_ERROR_CODES else "inference_error"-def client_safe_generation_error_message(error_code: str | None, error_message: str | None) -> str:+def client_safe_generation_error_message(+ error_code: str | None, error_message: str | None, upstream_reason: UpstreamFailureReason | None = None+) -> str:"""Return the public message for an adapter-yielded terminal error.Adapter terminal chunks are an untrusted backend boundary just like raised@@ -210,9 +239,12 @@ def client_safe_generation_error_message(error_code: str | None, error_message:their actionable message. Unknown future adapter codes fail closed ratherthan making their backend-controlled message public. A terminal errorwithout a code is the generic ``inference_error`` fallback used by every- public generation surface.+ public generation surface, unless a remote upstream's ``upstream_reason``+ selects that reason's fixed text."""code = error_code or "inference_error"+ if upstream_reason is not None and code == "inference_error":+ return UPSTREAM_FAILURE_MESSAGES[upstream_reason]if safe_message := _CLIENT_SAFE_GENERATION_ERROR_MESSAGES.get(code):return safe_messageif code in _CLIENT_PASSTHROUGH_GENERATION_ERROR_CODES and error_message:@@ -497,6 +529,9 @@ class GenerationChunk:# Private reasoning text an upstream returned beside the answer. It is# counted and then dropped, never published.reasoning_delta: str = ""+ # Terminal error chunk only: the class of the remote upstream's failure+ # that ended the generation.+ upstream_reason: UpstreamFailureReason | None = None# Backwards-compatibility alias: walking-skeleton callers (the local-dev@@ -524,6 +559,7 @@ class GenerationResult:error_code: str | None = Noneerror_message: str | None = Nonecached_tokens: int | None = None+ upstream_reason: UpstreamFailureReason | None = Noneclass ThinkingBlockStripper:@@ -934,6 +970,7 @@ async def collect_generation(cached_tokens: int | None = Noneerror_code: str | None = Noneerror_message: str | None = None+ upstream_reason: UpstreamFailureReason | None = Noneresult_selected = Falsetry:async for chunk in chunks:@@ -948,6 +985,7 @@ async def collect_generation(cached_tokens = chunk.cached_tokenserror_code = chunk.error_codeerror_message = chunk.error_message+ upstream_reason = chunk.upstream_reasonbreakresult = GenerationResult(text="".join(parts),@@ -957,6 +995,7 @@ async def collect_generation(error_code=error_code,error_message=error_message,cached_tokens=cached_tokens,+ upstream_reason=upstream_reason,)result_selected = Truereturn resultdiff --git a/packages/sie_server/src/sie_server/adapters/errors.py b/packages/sie_server/src/sie_server/adapters/errors.pyindex ff834464e..037a0f3ad 100644--- a/packages/sie_server/src/sie_server/adapters/errors.py+++ b/packages/sie_server/src/sie_server/adapters/errors.py@@ -1,16 +1,43 @@-from typing import Literal+from typing import Literal, castUpstreamFailureKind = Literal["not_ready", "busy", "unavailable"]UpstreamRefusal = Literal["rate_cap", "concurrency_cap", "breaker_open"]+UpstreamFailureReason = Literal[+ "upstream_credential_unavailable",+ "upstream_credential_rejected",+ "upstream_payment_required",+ "upstream_model_not_found",+ "upstream_refused",+ "upstream_unavailable",+ "upstream_busy",+ "upstream_not_ready",+ "upstream_invalid_response",+]RETRY_AFTER_MIN_S = 1RETRY_AFTER_MAX_S = 60+UPSTREAM_FAILURE_MESSAGES: dict[UpstreamFailureReason, str] = {+ "upstream_credential_unavailable": "the server has no usable credential for its upstream",+ "upstream_credential_rejected": "the upstream rejected the server's credential",+ "upstream_payment_required": "the upstream account cannot pay for the request",+ "upstream_model_not_found": "the upstream has no route for the configured model",+ "upstream_refused": "the upstream refused the request",+ "upstream_unavailable": "the upstream could not be reached, timed out or failed",+ "upstream_busy": "the upstream is busy",+ "upstream_not_ready": "the model is not ready on the upstream",+ "upstream_invalid_response": "the upstream answered with something the server cannot accept",+}_KIND_TEXT: dict[UpstreamFailureKind, str] = {"not_ready": "is not ready","busy": "is busy","unavailable": "is unavailable",}+_KIND_REASON: dict[UpstreamFailureKind, UpstreamFailureReason] = {+ "not_ready": "upstream_not_ready",+ "busy": "upstream_busy",+ "unavailable": "upstream_unavailable",+}_REFUSAL_TEXT: dict[UpstreamRefusal, tuple[UpstreamFailureKind, str]] = {"rate_cap": ("busy", "its request rate cap is reached"),"concurrency_cap": ("busy", "its concurrency cap is reached"),@@ -18,6 +45,13 @@ _REFUSAL_TEXT: dict[UpstreamRefusal, tuple[UpstreamFailureKind, str]] = {}+def known_upstream_failure_reason(value: object) -> UpstreamFailureReason | None:+ """``value`` when it names a :data:`UpstreamFailureReason`, else ``None``."""+ return (+ cast("UpstreamFailureReason", value) if isinstance(value, str) and value in UPSTREAM_FAILURE_MESSAGES else None+ )++class InputTooLongError(ValueError):pass@@ -26,15 +60,16 @@ class UpstreamUnavailableError(RuntimeError):"""An upstream did not serve the request, and the same request may succeed later.``kind`` says why: the model is ``not_ready`` on the upstream, the upstream- is ``busy``, or it is ``unavailable``. ``retry_after_s`` is the wait to- suggest to the caller. The message is fixed text and never carries anything- the upstream sent.+ is ``busy``, or it is ``unavailable``. ``upstream_reason`` is the caller's+ name for that kind. ``retry_after_s`` is the wait to suggest to the caller.+ The message is fixed text and never carries anything the upstream sent."""def __init__(self, upstream: str, kind: UpstreamFailureKind, *, retry_after_s: int, reason: str) -> None:super().__init__(f"upstream {upstream!r} {_KIND_TEXT[kind]}: {reason}")self.upstream = upstreamself.kind: UpstreamFailureKind = kind+ self.upstream_reason: UpstreamFailureReason = _KIND_REASON[kind]self.retry_after_s = retry_after_sdiff --git a/packages/sie_server/src/sie_server/adapters/remote/_chat_transport.py b/packages/sie_server/src/sie_server/adapters/remote/_chat_transport.pyindex 70432af5c..b132ae3d6 100644--- a/packages/sie_server/src/sie_server/adapters/remote/_chat_transport.py+++ b/packages/sie_server/src/sie_server/adapters/remote/_chat_transport.py@@ -70,7 +70,9 @@ async def chat_completion_stream(yielded = Trueyield eventparser.finish()- except UpstreamUnavailableError:+ except UpstreamUnavailableError as error:if yielded:- raise RemoteUpstreamError("the upstream failed during chat generation") from None+ raise RemoteUpstreamError(+ "the upstream failed during chat generation", upstream_reason=error.upstream_reason+ ) from Noneraisediff --git a/packages/sie_server/src/sie_server/adapters/remote/_http.py b/packages/sie_server/src/sie_server/adapters/remote/_http.pyindex 624cdc503..ded9155ec 100644--- a/packages/sie_server/src/sie_server/adapters/remote/_http.py+++ b/packages/sie_server/src/sie_server/adapters/remote/_http.py@@ -19,6 +19,15 @@ streamed or buffered, carries the caller's input and sampling, so there a 400or 422 without a known code is a refused input too, and is logged because aconfigured default the upstream refuses looks the same. Everything else is a:class:`RemoteUpstreamError`.++Every failure names its class for the caller as an ``upstream_reason`` from+:data:`~sie_server.adapters.errors.UpstreamFailureReason`, whether or not a+retry may succeed: a missing credential, a 401 or a bare 403, a 402, a 404, a+408 or 5xx, a 429, another 4xx (a 403 with a known code names the account's+or the upstream's state, not the credential), an answer this server cannot+accept, or the retryable kinds above. An upstream that is itself an SIE server+names the class of its own upstream's failure in a ``reason``, which is kept,+and a final class there makes the failure final here too."""from __future__ import annotations@@ -33,16 +42,24 @@ from collections.abc import AsyncIteratorfrom contextlib import asynccontextmanagerfrom datetime import UTC, datetimefrom email.utils import parsedate_to_datetime+from typing import Anyimport httpxfrom sie_sdk._msgpack import unpackb-from sie_server.adapters._generation_base import GenerationCapacityError, GenerationDrainingError, GenerationError+from sie_server.adapters._generation_base import (+ GenerationCapacityError,+ GenerationDrainingError,+ GenerationError,+ GenerationUpstreamError,+)from sie_server.adapters.errors import (RETRY_AFTER_MAX_S,RETRY_AFTER_MIN_S,InputTooLongError,+ UpstreamFailureReason,UpstreamUnavailableError,+ known_upstream_failure_reason,)from sie_server.adapters.remote._limits import upstream_limiterfrom sie_server.config.upstreams import UpstreamCredentialError, upstream_for_serving@@ -78,13 +95,33 @@ _KNOWN_ERROR_CODES = ("MODEL_NOT_FOUND","MODEL_NOT_LOADED","RATE_LIMIT",+ "THIRD_PARTY_REGION_UNAVAILABLE",+ "THIRD_PARTY_RUNTIME_UNLISTED",+ "THIRD_PARTY_SERVING_DISABLED",}))+_STATUS_REASONS: dict[int, UpstreamFailureReason] = {+ 401: "upstream_credential_rejected",+ 402: "upstream_payment_required",+ 403: "upstream_credential_rejected",+ 404: "upstream_model_not_found",+ 408: "upstream_unavailable",+ 429: "upstream_busy",+}+_RETRYABLE_REASONS = frozenset({"upstream_busy", "upstream_not_ready", "upstream_unavailable"})class RemoteUpstreamError(RuntimeError):- """The upstream call failed in a way a retry would not fix, or its answer broke the profile's contract."""+ """The upstream call failed in a way a retry would not fix, or its answer broke the profile's contract.++ The message is operator-side detail. ``upstream_reason`` is the class of+ failure a caller may see.+ """++ def __init__(self, message: str, *, upstream_reason: UpstreamFailureReason = "upstream_invalid_response") -> None:+ super().__init__(message)+ self.upstream_reason: UpstreamFailureReason = upstream_reasondef send_bounded(@@ -112,16 +149,20 @@ def _send(client: httpx.Client, request: httpx.Request, *, upstream: str, max_bytry:response = client.send(request, stream=True)except UpstreamCredentialError:- raise RemoteUpstreamError("the upstream credential is unavailable") from None+ raise RemoteUpstreamError(+ "the upstream credential is unavailable", upstream_reason="upstream_credential_unavailable"+ ) from Noneexcept httpx.HTTPError as exc:raise failure_for_transport_error(exc, upstream=upstream) from Nonetry:if response.status_code >= 400:+ error_body = _read_error_body(response, deadline)raise failure_for_status(response.status_code,- upstream_error_code(response.headers, _read_error_body(response, deadline)),+ upstream_error_code(response.headers, error_body),parse_retry_after(response.headers.get("retry-after")),upstream=upstream,+ reason=upstream_error_reason(response.headers, error_body),)if _is_compressed(response):raise RemoteUpstreamError("upstream sent a compressed body, which is refused")@@ -133,21 +174,31 @@ def _send(client: httpx.Client, request: httpx.Request, *, upstream: str, max_bydef failure_for_status(- status: int, code: str | None, retry_after_s: int | None, *, upstream: str, caller_request: bool = False+ status: int,+ code: str | None,+ retry_after_s: int | None,+ *,+ upstream: str,+ caller_request: bool = False,+ reason: UpstreamFailureReason | None = None,) -> Exception:- """The failure an upstream error status amounts to, given its known error code and wait.+ """The failure an upstream error status amounts to, given its known error code, wait and reason.``caller_request`` says the call forwarded the caller's own request, so a- 400 or 422 without a known code refused that request.+ 400 or 422 without a known code refused that request. ``reason`` is the+ class an SIE upstream named for its own upstream's failure."""- reply = f"{status} {code}" if code else str(status)+ reply = " ".join(str(part) for part in (status, code, reason) if part)answered = f"answered {reply}"wait = retry_after_s if retry_after_s is not None else DEFAULT_RETRY_AFTER_S+ final_reason = reason or _status_reason(status, code)if code in _TERMINAL_CODES or status in _TERMINAL_SERVER_STATUSES:- return RemoteUpstreamError(f"upstream {answered}")+ return RemoteUpstreamError(f"upstream {answered}", upstream_reason=final_reason)if status == 429:return UpstreamUnavailableError(upstream, "busy", retry_after_s=wait, reason=answered)if status >= 500:+ if reason is not None and reason not in _RETRYABLE_REASONS:+ return RemoteUpstreamError(f"upstream {answered}", upstream_reason=reason)if code in _NOT_READY_CODES:return UpstreamUnavailableError(upstream, "not_ready", retry_after_s=wait, reason=answered)if code in _BUSY_CODES or (code in _BUSY_WITH_RETRY_AFTER_CODES and retry_after_s is not None):@@ -157,7 +208,33 @@ def failure_for_status(return InputTooLongError(f"the upstream refused the input as too long ({status} INPUT_TOO_LONG)")if status in {400, 422} and (code == "INVALID_INPUT" or (caller_request and code is None)):return InvalidInputError(f"the upstream refused the input ({reply})")- return RemoteUpstreamError(f"upstream {answered}")+ return RemoteUpstreamError(f"upstream {answered}", upstream_reason=final_reason)+++def _status_reason(status: int, code: str | None) -> UpstreamFailureReason:+ if status == 403 and code is not None:+ return "upstream_refused"+ return _STATUS_REASONS.get(status, "upstream_unavailable" if status >= 500 else "upstream_refused")+++def in_band_failure(error: Any, *, instead_of: str) -> RemoteUpstreamError:+ """The failure an error object an upstream sent in place of ``instead_of`` amounts to.++ It is final. Its class is the ``reason`` an SIE upstream names, else the+ one of the HTTP status a numeric ``code`` names, else ``upstream_unavailable``.+ """+ reason = known_upstream_failure_reason(error.get("reason")) if isinstance(error, dict) else None+ status = _status_code(error.get("code")) if isinstance(error, dict) else None+ if reason is None:+ reason = "upstream_unavailable" if status is None else _status_reason(status, None)+ sent = "an error" if status is None else f"error {status}"+ return RemoteUpstreamError(f"upstream sent {sent} instead of {instead_of}", upstream_reason=reason)+++def _status_code(value: object) -> int | None:+ if isinstance(value, str) and value.isascii() and value.isdecimal():+ value = int(value)+ return value if isinstance(value, int) and not isinstance(value, bool) and 400 <= value <= 599 else Nonedef failure_for_transport_error(exc: httpx.HTTPError, *, upstream: str) -> Exception:@@ -174,7 +251,7 @@ def failure_for_transport_error(exc: httpx.HTTPError, *, upstream: str) -> Excepretry_after_s=DEFAULT_RETRY_AFTER_S,reason=failed,)- return RemoteUpstreamError(f"upstream {failed}")+ return RemoteUpstreamError(f"upstream {failed}", upstream_reason="upstream_unavailable")@asynccontextmanager@@ -208,19 +285,21 @@ async def open_stream(httpx.ReadTimeout("upstream response headers exceeded the deadline"), upstream=upstream) from Noneexcept UpstreamCredentialError:- raise RemoteUpstreamError("the upstream credential is unavailable") from None+ raise RemoteUpstreamError(+ "the upstream credential is unavailable", upstream_reason="upstream_credential_unavailable"+ ) from Noneexcept httpx.HTTPError as exc:raise failure_for_transport_error(exc, upstream=upstream) from Nonetry:if response.status_code >= 400:+ error_body = await _read_error_body_async(response, timeout_s=error_body_timeout_s)failure = failure_for_status(response.status_code,- upstream_error_code(- response.headers, await _read_error_body_async(response, timeout_s=error_body_timeout_s)- ),+ upstream_error_code(response.headers, error_body),parse_retry_after(response.headers.get("retry-after")),upstream=upstream,caller_request=True,+ reason=upstream_error_reason(response.headers, error_body),)if isinstance(failure, InputTooLongError | InvalidInputError):logger.warning("upstream %r refused a generation request: %s", upstream, failure)@@ -274,11 +353,23 @@ async def sse_data(response: httpx.Response, *, max_event_bytes: int, max_total_raise RemoteUpstreamError("upstream sent an event over the size limit")-def generation_error(error: UpstreamUnavailableError) -> GenerationError:- """Map an upstream failure before output to a retryable 503 with its wait."""+def generation_error(error: UpstreamUnavailableError | RemoteUpstreamError) -> GenerationError:+ """Map an upstream failure to the generation error that carries its reason.++ A failure the same request may survive becomes a retryable 503 with its+ wait. Any other becomes a :class:`GenerationUpstreamError`, whose message+ stays operator-side.+ """+ reason = error.upstream_reason+ if isinstance(error, RemoteUpstreamError):+ return GenerationUpstreamError(str(error), upstream_reason=reason)if error.kind == "not_ready":- return GenerationDrainingError("the upstream is not ready, please retry", retry_after_s=error.retry_after_s)- return GenerationCapacityError(f"the upstream is {error.kind}, please retry", retry_after_s=error.retry_after_s)+ return GenerationDrainingError(+ "the upstream is not ready, please retry", retry_after_s=error.retry_after_s, upstream_reason=reason+ )+ return GenerationCapacityError(+ f"the upstream is {error.kind}, please retry", retry_after_s=error.retry_after_s, upstream_reason=reason+ )def upstream_error_code(headers: httpx.Headers, body: bytes) -> str | None:@@ -290,22 +381,31 @@ def upstream_error_code(headers: httpx.Headers, body: bytes) -> str | None:from_header = _known_code(headers.get("x-sie-error-code"))if from_header is not None:return from_header+ return _known_code(_error_envelope(headers, body).get("code"))+++def upstream_error_reason(headers: httpx.Headers, body: bytes) -> UpstreamFailureReason | None:+ """The ``reason`` an SIE upstream names in its error, when it is a known class, else ``None``."""+ return known_upstream_failure_reason(_error_envelope(headers, body).get("reason"))+++def _error_envelope(headers: httpx.Headers, body: bytes) -> dict[str, object]:if not body:- return None+ return {}try:if "msgpack" in headers.get("content-type", "").lower():decoded = unpackb(body, numeric_arrays=False)else:decoded = json.loads(body)except Exception: # noqa: BLE001 - untrusted bytes; an unreadable body carries no code- return None+ return {}if not isinstance(decoded, dict):- return None+ return {}for key in ("error", "detail"):envelope = decoded.get(key)if isinstance(envelope, dict):- return _known_code(envelope.get("code"))- return None+ return envelope+ return {}def parse_retry_after(value: str | None) -> int | None:diff --git a/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py b/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.pyindex fa5622c88..22f200d84 100644--- a/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py+++ b/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py@@ -8,7 +8,7 @@ import timeimport uuidfrom typing import Any, cast-from sie_server.adapters.remote._http import RemoteUpstreamError+from sie_server.adapters.remote._http import RemoteUpstreamError, in_band_failure_MAX_CHOICES = 128_MAX_COUNT = 1 << 32@@ -31,7 +31,7 @@ def _json(data: bytes, *, max_bytes: int) -> dict[str, Any]:if not isinstance(payload, dict):raise _invalid()if "error" in payload:- raise RemoteUpstreamError("upstream sent an error instead of a chat answer")+ raise in_band_failure(payload["error"], instead_of="a chat answer")return payloaddiff --git a/packages/sie_server/src/sie_server/adapters/remote/_openai_completions.py b/packages/sie_server/src/sie_server/adapters/remote/_openai_completions.pyindex 12f8b783e..bba528b61 100644--- a/packages/sie_server/src/sie_server/adapters/remote/_openai_completions.py+++ b/packages/sie_server/src/sie_server/adapters/remote/_openai_completions.py@@ -6,7 +6,7 @@ import jsonfrom typing import Any, castfrom sie_server.adapters._generation_base import FinishReason, GenerationChunk-from sie_server.adapters.remote._http import RemoteUpstreamError+from sie_server.adapters.remote._http import RemoteUpstreamError, in_band_failurefrom sie_server.adapters.remote._openai_chat import ChatStreamParser@@ -69,7 +69,9 @@ class CompletionStreamParser:payload = json.loads(data)except (ValueError, RecursionError):raise _invalid() from None- if not isinstance(payload, dict) or "error" in payload or not isinstance(payload.get("choices"), list):+ if isinstance(payload, dict) and "error" in payload:+ raise in_band_failure(payload["error"], instead_of="a completion")+ if not isinstance(payload, dict) or not isinstance(payload.get("choices"), list):raise _invalid()choices = []for choice in payload["choices"]:diff --git a/packages/sie_server/src/sie_server/adapters/remote/openai.py b/packages/sie_server/src/sie_server/adapters/remote/openai.pyindex 5237d12ee..16994b12f 100644--- a/packages/sie_server/src/sie_server/adapters/remote/openai.py+++ b/packages/sie_server/src/sie_server/adapters/remote/openai.py@@ -341,8 +341,13 @@ class OpenAIUpstreamAdapter(BaseAdapter, GenerationAdapter):returnparser.finish()except UpstreamUnavailableError as error:+ logger.warning("remote generation failed: %s", error)if yielded:- raise RemoteUpstreamError("the upstream failed during generation") from None+ raise generation_error(+ RemoteUpstreamError("the upstream failed during generation", upstream_reason=error.upstream_reason)+ ) from None+ raise generation_error(error) from None+ except RemoteUpstreamError as error:logger.warning("remote generation failed: %s", error)raise generation_error(error) from Noneexcept InputTooLongError:diff --git a/packages/sie_server/src/sie_server/adapters/remote/sie.py b/packages/sie_server/src/sie_server/adapters/remote/sie.pyindex e9006cda6..80d5ea1ad 100644--- a/packages/sie_server/src/sie_server/adapters/remote/sie.py+++ b/packages/sie_server/src/sie_server/adapters/remote/sie.py@@ -55,7 +55,14 @@ from sie_server.adapters._generation_base import ()from sie_server.adapters._spec import AdapterSpecfrom sie_server.adapters._types import ERR_NOT_LOADED-from sie_server.adapters.errors import RETRY_AFTER_MAX_S, RETRY_AFTER_MIN_S, InputTooLongError, UpstreamUnavailableError+from sie_server.adapters.errors import (+ RETRY_AFTER_MAX_S,+ RETRY_AFTER_MIN_S,+ InputTooLongError,+ UpstreamFailureReason,+ UpstreamUnavailableError,+ known_upstream_failure_reason,+)from sie_server.adapters.remote._batching import (RequestScores,UpstreamUsage,@@ -116,6 +123,10 @@ _ITEM_ERRORS = {ErrorCode.INPUT_TOO_LONG.value: "the upstream refused this item as too long",}_ITEM_FAILED = "the upstream could not extract from this item"+_ERROR_CODE_REASONS: dict[str, UpstreamFailureReason] = {+ "MODEL_LOADING": "upstream_not_ready",+ "RESOURCE_EXHAUSTED": "upstream_busy",+}@dataclass(frozen=True, slots=True)@@ -129,6 +140,7 @@ class _GenerationEvent:cached_tokens: int | None = Noneerror_code: str | None = Noneretry_after_s: int = DEFAULT_RETRY_AFTER_S+ upstream_reason: UpstreamFailureReason | None = None@dataclass(frozen=True, slots=True)@@ -327,8 +339,13 @@ class SieUpstreamAdapter(BaseAdapter, GenerationAdapter):seen_text = seen_text or bool(event.text)raise RemoteUpstreamError("upstream stream ended before its terminal event")except UpstreamUnavailableError as error:+ logger.warning("remote generation failed: %s", error)if yielded:- raise RemoteUpstreamError("the upstream failed during generation") from None+ raise generation_error(+ RemoteUpstreamError("the upstream failed during generation", upstream_reason=error.upstream_reason)+ ) from None+ raise generation_error(error) from None+ except RemoteUpstreamError as error:logger.warning("remote generation failed: %s", error)raise generation_error(error) from Noneexcept InputTooLongError:@@ -695,12 +712,14 @@ def _generation_event(data: bytes) -> _GenerationEvent:error = event.get("error")error_code = Noneretry_after_s = DEFAULT_RETRY_AFTER_S+ upstream_reason = Noneif error is not None or finish_reason == "error":code = error.get("code") if isinstance(error, dict) else Noneerror_code = client_safe_generation_error_code(code if isinstance(code, str) else None)wait = error.get("retry_after_s") if isinstance(error, dict) else Noneif isinstance(wait, int) and not isinstance(wait, bool) and RETRY_AFTER_MIN_S <= wait <= RETRY_AFTER_MAX_S:retry_after_s = wait+ upstream_reason = known_upstream_failure_reason(error.get("reason")) if isinstance(error, dict) else Nonereturn _GenerationEvent(text=text,done=True,@@ -711,6 +730,7 @@ def _generation_event(data: bytes) -> _GenerationEvent:cached_tokens=cached_tokens,error_code=error_code,retry_after_s=retry_after_s,+ upstream_reason=upstream_reason,)@@ -745,8 +765,16 @@ def _terminal_chunk(event: _GenerationEvent, *, yielded: bool, seen_text: bool)An upstream that reports, before any output, that the model is loading,that it is busy, or that the prompt is too long, raises the matchinggeneration error. Any other upstream error ends the generation with an- allowlisted code and fixed text.+ allowlisted code and fixed text. An ``inference_error`` carries the class+ the upstream named for its own upstream's failure, else+ ``upstream_unavailable``, and ``MODEL_LOADING`` or ``RESOURCE_EXHAUSTED``+ carries ``upstream_not_ready`` or ``upstream_busy``."""+ if event.error_code is not None:+ logger.warning(+ "remote generation failed: upstream ended generation with %s",+ " ".join(part for part in (event.error_code, event.upstream_reason) if part),+ )if event.error_code is None:return GenerationChunk(text_delta=event.text,@@ -760,9 +788,15 @@ def _terminal_chunk(event: _GenerationEvent, *, yielded: bool, seen_text: bool))if not yielded and not event.text:if event.error_code == "MODEL_LOADING":- raise GenerationDrainingError("the upstream is not ready, please retry", retry_after_s=event.retry_after_s)+ raise GenerationDrainingError(+ "the upstream is not ready, please retry",+ retry_after_s=event.retry_after_s,+ upstream_reason="upstream_not_ready",+ )if event.error_code == "RESOURCE_EXHAUSTED":- raise GenerationCapacityError("the upstream is busy, please retry", retry_after_s=event.retry_after_s)+ raise GenerationCapacityError(+ "the upstream is busy, please retry", retry_after_s=event.retry_after_s, upstream_reason="upstream_busy"+ )if event.error_code == "INPUT_TOO_LONG":raise GenerationInputTooLongError("the upstream refused the prompt as too long")return GenerationChunk(@@ -775,6 +809,9 @@ def _terminal_chunk(event: _GenerationEvent, *, yielded: bool, seen_text: bool)cached_tokens=event.cached_tokens,error_code=event.error_code,error_message=f"the upstream ended generation with {event.error_code}",+ upstream_reason=(event.upstream_reason or "upstream_unavailable")+ if event.error_code == "inference_error"+ else _ERROR_CODE_REASONS.get(event.error_code),)diff --git a/packages/sie_server/src/sie_server/api/generate.py b/packages/sie_server/src/sie_server/api/generate.pyindex a49e8201c..2edb9962e 100644--- a/packages/sie_server/src/sie_server/api/generate.py+++ b/packages/sie_server/src/sie_server/api/generate.py@@ -96,6 +96,7 @@ from sie_server.processors.strict_grammar import enforce_strict_grammarfrom sie_server.types.grammar import GrammarSpecfrom sie_server.types.inputs import ImageInputfrom sie_server.types.openapi import (+ GenerateErrorResponse,GenerateInputTooLongErrorResponse,GenerateModelLoadFailedErrorResponse,GenerateResponseModel,@@ -692,6 +693,7 @@ def _generation_http_exception(error: GenerationError, registry: ModelRegistry |param=client_safe_generation_error_param(error),code=client_safe_generation_error_code(error.code),)+ reason = {} if error.upstream_reason is None else {"reason": error.upstream_reason}if isinstance(error, GenerationCapacityError):if error.retry_after_s is not None:retry_after = str(error.retry_after_s)@@ -704,6 +706,7 @@ def _generation_http_exception(error: GenerationError, registry: ModelRegistry |detail={"code": client_safe_generation_error_code(error.code),"message": client_safe_generation_error_message(error.code, str(error)),+ **reason,},headers={"Retry-After": retry_after},)@@ -711,7 +714,8 @@ def _generation_http_exception(error: GenerationError, registry: ModelRegistry |status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail={"code": "inference_error",- "message": client_safe_generation_error_message("inference_error", str(error)),+ "message": client_safe_generation_error_message("inference_error", str(error), error.upstream_reason),+ **reason,},)@@ -849,8 +853,12 @@ async def _stream_generate_events(finish_reason = "error"terminal_error = {"code": client_safe_generation_error_code(chunk.error_code),- "message": client_safe_generation_error_message(chunk.error_code, chunk.error_message),+ "message": client_safe_generation_error_message(+ chunk.error_code, chunk.error_message, chunk.upstream_reason+ ),}+ if chunk.upstream_reason is not None:+ terminal_error["reason"] = chunk.upstream_reasonif pre_output_errors and seq == 0 and (terminal_error is not None or finish_reason == "cancelled"):breakif chunk.prompt_tokens is not None:@@ -894,10 +902,12 @@ async def _stream_generate_events(logger.info("stream_generate refused after preflight: %s", exc)error: dict[str, Any] = {"code": client_safe_generation_error_code(exc.code),- "message": client_safe_generation_error_message(exc.code, str(exc)),+ "message": client_safe_generation_error_message(exc.code, str(exc), exc.upstream_reason),}if (param := client_safe_generation_error_param(exc)) is not None:error["param"] = param+ if exc.upstream_reason is not None:+ error["reason"] = exc.upstream_reasonretry_after_s = exc.retry_after_s if isinstance(exc, GenerationCapacityError) else Noneif retry_after_s is None:retry_after_s = oom_retry_after_s@@ -1038,8 +1048,12 @@ async def _stream_generate_events(),"model": GenerateModelLoadFailedErrorResponse,},- 503: {"description": "Model loading or unavailable"},- 504: {"description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s"},+ 500: {"description": "Generation failed", "model": GenerateErrorResponse},+ 503: {"description": "Model loading or unavailable", "model": GenerateErrorResponse},+ 504: {+ "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s",+ "model": GenerateErrorResponse,+ },},openapi_extra={"requestBody": {@@ -1368,10 +1382,10 @@ async def generate(chunks = enforce_strict_grammar(chunks, grammar)result = await collect_generation(chunks)except GenerationTimeoutError as exc:- raise HTTPException(- status_code=status.HTTP_504_GATEWAY_TIMEOUT,- detail={"code": exc.code, "message": str(exc)},- ) from exc+ timeout: dict[str, Any] = {"code": exc.code, "message": str(exc)}+ if route.upstream is not None:+ timeout["reason"] = "upstream_unavailable"+ raise HTTPException(status_code=status.HTTP_504_GATEWAY_TIMEOUT, detail=timeout) from excexcept GenerationError as exc:raise _generation_http_exception(exc, registry) from excexcept Exception as e:@@ -1401,13 +1415,15 @@ async def generate(client_safe_generation_error_code(result.error_code),model,)- raise HTTPException(- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- detail={- "code": client_safe_generation_error_code(result.error_code),- "message": client_safe_generation_error_message(result.error_code, result.error_message),- },- )+ detail = {+ "code": client_safe_generation_error_code(result.error_code),+ "message": client_safe_generation_error_message(+ result.error_code, result.error_message, result.upstream_reason+ ),+ }+ if result.upstream_reason is not None:+ detail["reason"] = result.upstream_reason+ raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=detail)if result.finish_reason == "cancelled":# 503 Service Unavailable: the generation was cancelled before it# could complete (worker observed a cancel signal mid-stream).diff --git a/packages/sie_server/src/sie_server/api/openai_completions.py b/packages/sie_server/src/sie_server/api/openai_completions.pyindex 20f79c40e..9ab4caf3f 100644--- a/packages/sie_server/src/sie_server/api/openai_completions.py+++ b/packages/sie_server/src/sie_server/api/openai_completions.py@@ -52,7 +52,7 @@ from sie_server.core.runtime_options import (resolve_generation_timeouts,)from sie_server.observability.tracing import tracer-from sie_server.types.openapi import OpenAICompletionResponseModel+from sie_server.types.openapi import OpenAICompletionResponseModel, OpenAIGenerationErrorResponselogger = logging.getLogger(__name__)@@ -92,12 +92,14 @@ class _CompletionError(Exception):code: str = "invalid_request",error_type: str | None = None,headers: dict[str, str] | None = None,+ reason: str | None = None,) -> None:super().__init__(message)self.message = messageself.status_code = status_codeself.param = paramself.code = code+ self.reason = reasonself.error_type = error_type or ("invalid_request_error" if status_code < status.HTTP_500_INTERNAL_SERVER_ERROR else "server_error")@@ -119,19 +121,20 @@ class _CompletionParams:include_usage: bool+def _error_body(error: _CompletionError) -> dict[str, Any]:+ body: dict[str, Any] = {+ "message": error.message,+ "type": error.error_type,+ "param": error.param,+ "code": error.code,+ }+ if error.reason is not None:+ body["reason"] = error.reason+ return body++def _error_response(error: _CompletionError) -> JSONResponse:- return JSONResponse(- status_code=error.status_code,- content={- "error": {- "message": error.message,- "type": error.error_type,- "param": error.param,- "code": error.code,- }- },- headers=error.headers,- )+ return JSONResponse(status_code=error.status_code, content={"error": _error_body(error)}, headers=error.headers)def _from_http_exception(exc: HTTPException) -> _CompletionError:@@ -144,16 +147,20 @@ def _from_http_exception(exc: HTTPException) -> _CompletionError:code = str(detail.get("code", "invalid_request"))param = detail.get("param")param = param if isinstance(param, str) else None+ reason = detail.get("reason")+ reason = reason if isinstance(reason, str) else Noneelse:message = str(detail)code = "invalid_request"param = None+ reason = Nonereturn _CompletionError(message,status_code=exc.status_code,param=param,code=code,headers=dict(exc.headers) if exc.headers is not None else None,+ reason=reason,)@@ -168,8 +175,13 @@ def _from_generation_error(error: GenerationError, registry: Any) -> _Completionreturn _from_http_exception(_generation_http_exception(error, registry))-def _generation_timeout_error(error: GenerationTimeoutError) -> _CompletionError:- return _CompletionError(str(error), status_code=status.HTTP_504_GATEWAY_TIMEOUT, code=error.code)+def _generation_timeout_error(error: GenerationTimeoutError, *, remote: bool) -> _CompletionError:+ return _CompletionError(+ str(error),+ status_code=status.HTTP_504_GATEWAY_TIMEOUT,+ code=error.code,+ reason="upstream_unavailable" if remote else None,+ )def _validated_retry_after_s(error: _CompletionError) -> int | None:@@ -430,11 +442,14 @@ async def _stream_completion(raise _CompletionError("generation was cancelled before completion"if cancelled- else client_safe_generation_error_message(chunk.error_code, chunk.error_message),+ else client_safe_generation_error_message(+ chunk.error_code, chunk.error_message, chunk.upstream_reason+ ),status_code=status.HTTP_503_SERVICE_UNAVAILABLEif cancelledelse status.HTTP_500_INTERNAL_SERVER_ERROR,code="generation_cancelled" if cancelled else client_safe_generation_error_code(chunk.error_code),+ reason=None if cancelled else chunk.upstream_reason,)body = _chunk_body(completion_id=completion_id,@@ -454,11 +469,15 @@ async def _stream_completion(}elif errored:body["error"] = {- "message": client_safe_generation_error_message(chunk.error_code, chunk.error_message),+ "message": client_safe_generation_error_message(+ chunk.error_code, chunk.error_message, chunk.upstream_reason+ ),"type": "server_error","param": None,"code": client_safe_generation_error_code(chunk.error_code),}+ if chunk.upstream_reason is not None:+ body["error"]["reason"] = chunk.upstream_reasondelivered = Trueyield f"data: {json.dumps(body)}\n\n"if chunk.done:@@ -486,12 +505,7 @@ async def _stream_completion(text="",finish_reason=None,)- error_body: dict[str, Any] = {- "message": error.message,- "type": error.error_type,- "param": error.param,- "code": error.code,- }+ error_body = _error_body(error)if (retry_after_s := _validated_retry_after_s(error)) is not None:error_body["retry_after_s"] = retry_after_sbody["error"] = error_body@@ -600,9 +614,10 @@ async def _collect_completion(chunks: AsyncIterator[GenerationChunk]) -> tuple[s)if terminal.finish_reason == "error" or terminal.error_code or terminal.error_message:raise _CompletionError(- client_safe_generation_error_message(terminal.error_code, terminal.error_message),+ client_safe_generation_error_message(terminal.error_code, terminal.error_message, terminal.upstream_reason),status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,code=client_safe_generation_error_code(terminal.error_code),+ reason=terminal.upstream_reason,)if terminal.finish_reason == "cancelled":raise _CompletionError(@@ -629,9 +644,12 @@ async def _collect_completion(chunks: AsyncIterator[GenerationChunk]) -> tuple[s400: {"description": "Invalid or unsupported request"},404: {"description": "Model not found"},413: {"description": "Request body or prompt is too large"},- 500: {"description": "Generation failed"},- 503: {"description": "Model loading or temporarily unavailable"},- 504: {"description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s"},+ 500: {"description": "Generation failed", "model": OpenAIGenerationErrorResponse},+ 503: {"description": "Model loading or temporarily unavailable", "model": OpenAIGenerationErrorResponse},+ 504: {+ "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s",+ "model": OpenAIGenerationErrorResponse,+ },},openapi_extra={"requestBody": {@@ -770,7 +788,7 @@ async def completions(except _CompletionError:raiseexcept GenerationTimeoutError as exc:- raise _generation_timeout_error(exc) from exc+ raise _generation_timeout_error(exc, remote=route.upstream is not None) from excexcept GenerationError as exc:raise _from_generation_error(exc, registry) from excexcept Exception as exc:diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.pyindex bb2113504..28b7b263d 100644--- a/packages/sie_server/src/sie_server/api/openai_local.py+++ b/packages/sie_server/src/sie_server/api/openai_local.py@@ -49,13 +49,19 @@ from sie_server.adapters._generation_base import (GenerationAdapter,GenerationError,GenerationUnsupportedFieldError,+ GenerationUpstreamError,ReasoningFormat,ThinkingBlockStripper,aclose_with_error_precedence,resolve_reasoning_format,thinking_blocks_must_be_hidden,)-from sie_server.adapters.errors import InputTooLongError, UpstreamUnavailableError+from sie_server.adapters.errors import (+ UPSTREAM_FAILURE_MESSAGES,+ InputTooLongError,+ UpstreamFailureReason,+ UpstreamUnavailableError,+)from sie_server.adapters.fake.adapter import FakeAdapterfrom sie_server.adapters.mlx.generation import MLXGenerationAdapter, normalize_mlx_seedfrom sie_server.adapters.remote._http import RemoteUpstreamError@@ -112,6 +118,7 @@ from sie_server.processors.strict_grammar import ()from sie_server.types.grammar import GrammarSpecfrom sie_server.types.inputs import InvalidInputError, Item, item_size_error+from sie_server.types.openapi import OpenAIGenerationErrorResponsefrom sie_server.types.responses import ErrorCodelogger = logging.getLogger(__name__)@@ -307,18 +314,12 @@ def _upstream_error_response(message: str = "upstream generation request failed",*,response_status: int = status.HTTP_502_BAD_GATEWAY,+ reason: UpstreamFailureReason | None = None,) -> JSONResponse:- return JSONResponse(- status_code=response_status,- content={- "error": {- "message": message,- "type": "upstream_error",- "param": None,- "code": "upstream_error",- }- },- )+ error: dict[str, Any] = {"message": message, "type": "upstream_error", "param": None, "code": "upstream_error"}+ if reason is not None:+ error["reason"] = reason+ return JSONResponse(status_code=response_status, content={"error": error})def _translated_upstream_status(upstream_status: int) -> int:@@ -333,18 +334,12 @@ def _upstream_error_event(*,code: str = "upstream_error",error_type: str = "upstream_error",+ reason: UpstreamFailureReason | None = None,) -> bytes:- payload = json.dumps(- {- "error": {- "message": message,- "type": error_type,- "param": None,- "code": code,- }- },- separators=(",", ":"),- )+ error: dict[str, Any] = {"message": message, "type": error_type, "param": None, "code": code}+ if reason is not None:+ error["reason"] = reason+ payload = json.dumps({"error": error}, separators=(",", ":"))return f"data: {payload}\n\ndata: [DONE]\n\n".encode()@@ -1352,7 +1347,12 @@ async def _remote_chat_events(if not delivered:raiselogger.warning("remote chat for %s failed after output: %s", requested_model, exc)- yield _upstream_error_event()+ reason = "upstream_unavailable" if isinstance(exc, GenerationTimeoutError) else exc.upstream_reason+ yield (+ _upstream_error_event()+ if reason is None+ else _upstream_error_event(UPSTREAM_FAILURE_MESSAGES[reason], reason=reason)+ )finally:await aclose_with_error_precedence(iterator, outcome_selected=True, context="remote chat adapter")@@ -1435,15 +1435,24 @@ async def _remote_chat_response(if violation is not None:return _strict_output_error_response(violation)return JSONResponse(content=payload, headers=headers)+ except GenerationUpstreamError as exc:+ return _upstream_error_response(UPSTREAM_FAILURE_MESSAGES[exc.upstream_reason], reason=exc.upstream_reason)except GenerationError as exc:raise _generation_http_exception(exc) from excexcept GenerationTimeoutError:raise HTTPException(- status_code=504, detail={"code": "generation_timeout", "message": "remote generation timed out"}+ status_code=504,+ detail={+ "code": "generation_timeout",+ "message": "remote generation timed out",+ "reason": "upstream_unavailable",+ },) from Noneexcept UpstreamUnavailableError as exc:logger.warning("remote chat for %s failed: %s", requested_model, exc)- raise upstream_unavailable_exception(exc, requested_model) from exc+ unavailable = upstream_unavailable_exception(exc, requested_model)+ cast("dict[str, Any]", unavailable.detail)["reason"] = exc.upstream_reason+ raise unavailable from excexcept (InputTooLongError, InvalidInputError) as exc:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST,@@ -1460,13 +1469,22 @@ async def _remote_chat_response() from excexcept RemoteUpstreamError as exc:logger.warning("remote chat for %s failed: %s", requested_model, exc)- return _upstream_error_response()+ return _upstream_error_response(UPSTREAM_FAILURE_MESSAGES[exc.upstream_reason], reason=exc.upstream_reason)# -- /v1/chat/completions (managed child or remote generation adapter) -------[email protected]("/chat/completions", response_model=None)+ "/chat/completions",+ response_model=None,+ responses={+ 500: {"description": "Generation failed", "model": OpenAIGenerationErrorResponse},+ 502: {"description": "A remote upstream failed the request", "model": OpenAIGenerationErrorResponse},+ 503: {"description": "Model loading or temporarily unavailable", "model": OpenAIGenerationErrorResponse},+ 504: {"description": "Remote generation timed out", "model": OpenAIGenerationErrorResponse},+ },+)async def chat_completions(http_request: Request,x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,diff --git a/packages/sie_server/src/sie_server/api/openai_responses.py b/packages/sie_server/src/sie_server/api/openai_responses.pyindex 7a5247a7a..a414c6938 100644--- a/packages/sie_server/src/sie_server/api/openai_responses.py+++ b/packages/sie_server/src/sie_server/api/openai_responses.py@@ -49,7 +49,7 @@ from sie_server.core.runtime_options import (resolve_generation_timeouts,)from sie_server.observability.tracing import tracer-from sie_server.types.openapi import OpenAIResponsesResponseModel+from sie_server.types.openapi import OpenAIGenerationErrorResponse, OpenAIResponsesResponseModelrouter = APIRouter(prefix="/v1", tags=["openai-compat"], dependencies=[Depends(remote_routing)])logger = logging.getLogger(__name__)@@ -226,9 +226,12 @@ def _parse_params(body: dict[str, Any]) -> _ResponsesParams:400: {"description": "Invalid or unsupported request"},404: {"description": "Model not found"},413: {"description": "Request body or rendered input is too large"},- 500: {"description": "Generation failed"},- 503: {"description": "Model loading or temporarily unavailable"},- 504: {"description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s"},+ 500: {"description": "Generation failed", "model": OpenAIGenerationErrorResponse},+ 503: {"description": "Model loading or temporarily unavailable", "model": OpenAIGenerationErrorResponse},+ 504: {+ "description": "Non-streaming generation exceeded its first_chunk_timeout_s or overall_timeout_s",+ "model": OpenAIGenerationErrorResponse,+ },},openapi_extra={"requestBody": {@@ -355,7 +358,7 @@ async def responses(except _CompletionError:raiseexcept GenerationTimeoutError as exc:- raise _generation_timeout_error(exc) from exc+ raise _generation_timeout_error(exc, remote=route.upstream is not None) from excexcept GenerationError as exc:raise _from_generation_error(exc, registry) from excexcept Exception as exc:diff --git a/packages/sie_server/src/sie_server/processors/remote_chat.py b/packages/sie_server/src/sie_server/processors/remote_chat.pyindex 480d1ed82..653572c87 100644--- a/packages/sie_server/src/sie_server/processors/remote_chat.py+++ b/packages/sie_server/src/sie_server/processors/remote_chat.py@@ -155,7 +155,7 @@ async def _buffered_chunks(),)yield _terminal(usage, [candidate["finish_reason"]])- except UpstreamUnavailableError as exc:+ except (UpstreamUnavailableError, RemoteUpstreamError) as exc:raise generation_error(exc) from Noneexcept InputTooLongError:raise GenerationInputTooLongError("the upstream refused the chat input as too long") from None@@ -227,7 +227,11 @@ async def _stream_chunks(yield _terminal(usage, list(reasons.values()))except UpstreamUnavailableError as exc:if visible:- raise RemoteUpstreamError("the upstream failed during chat generation") from None+ raise generation_error(+ RemoteUpstreamError("the upstream failed during chat generation", upstream_reason=exc.upstream_reason)+ ) from None+ raise generation_error(exc) from None+ except RemoteUpstreamError as exc:raise generation_error(exc) from Noneexcept InputTooLongError:raise GenerationInputTooLongError("the upstream refused the chat input as too long") from Nonediff --git a/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py b/packages/sie_server/src/sie_server/processors/remote_chat_prompt.pyindex f48643145..21080a9a0 100644--- a/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py+++ b/packages/sie_server/src/sie_server/processors/remote_chat_prompt.py@@ -197,7 +197,10 @@ async def _events(if terminal:raise RemoteUpstreamError("upstream rendered chat emitted data after completion")if chunk.error_code or chunk.finish_reason == "cancelled":- raise RemoteUpstreamError("upstream rendered chat did not finish successfully")+ raise RemoteUpstreamError(+ "upstream rendered chat did not finish successfully",+ upstream_reason=chunk.upstream_reason or "upstream_invalid_response",+ )delta: dict[str, Any] = {}if chunk.reasoning_delta:delta["reasoning_content"] = chunk.reasoning_deltadiff --git a/packages/sie_server/src/sie_server/processors/streaming.py b/packages/sie_server/src/sie_server/processors/streaming.pyindex ede015ecc..4828b8b7d 100644--- a/packages/sie_server/src/sie_server/processors/streaming.py+++ b/packages/sie_server/src/sie_server/processors/streaming.py@@ -71,6 +71,7 @@ from sie_server.adapters._generation_base import (suppress_thinking_blocks,thinking_blocks_must_be_hidden,)+from sie_server.adapters.errors import UpstreamFailureReasonfrom sie_server.adapters.remote.openai import OpenAIUpstreamAdapterfrom sie_server.adapters.remote.sie import SieUpstreamAdapterfrom sie_server.api.helpers import oom_retry_after_from_registry@@ -2657,14 +2658,16 @@ class StreamingProcessor:logger.warning("Generate iterator raised for %s/%s", request_id, attempt_id, exc_info=True)if isinstance(exc, GenerationError):error_code = exc.code- error_message = client_safe_generation_error_message(exc.code, str(exc))+ error_message = client_safe_generation_error_message(exc.code, str(exc), exc.upstream_reason)error_param = client_safe_generation_error_param(exc)error_retry_after_s = _generation_error_retry_after_s(exc, self._registry)+ error_reason = exc.upstream_reasonelse:error_code = "inference_error"error_message = _INTERNAL_GENERATION_MESSAGEerror_param = Noneerror_retry_after_s = None+ error_reason = Noneerr_payload = _encode_chunk(kind="chunk",request_id=request_id,@@ -2677,6 +2680,7 @@ class StreamingProcessor:error_message=error_message,error_param=error_param,error_retry_after_s=error_retry_after_s,+ error_reason=error_reason,)try:await _wait_for(@@ -2790,10 +2794,13 @@ class StreamingProcessor:ttft_ms=_compute_ttft_ms(publish_at, first_text_at),error_code=(chunk.error_code or "inference_error") if terminal_has_error else None,error_message=(- client_safe_generation_error_message(chunk.error_code, chunk.error_message)+ client_safe_generation_error_message(+ chunk.error_code, chunk.error_message, chunk.upstream_reason+ )if terminal_has_errorelse None),+ error_reason=chunk.upstream_reason if terminal_has_error else None,candidates=list(chunk.candidates) if chunk.candidates else None,)try:@@ -4649,6 +4656,7 @@ def _encode_chunk(error_message: str | None = None,error_param: str | None = None,error_retry_after_s: int | None = None,+ error_reason: UpstreamFailureReason | None = None,tool_call_delta: ToolCallDelta | None = None,logprobs: list[dict[str, Any]] | None = None,candidates: list[dict[str, Any]] | None = None,@@ -4715,6 +4723,8 @@ def _encode_chunk(and 1 <= error_retry_after_s <= _RESOURCE_EXHAUSTED_RETRY_AFTER_MAX_S):error["retry_after_s"] = error_retry_after_s+ if error_reason is not None:+ error["reason"] = error_reasonpayload["error"] = errorif logprobs:# OpenAI ``ChatCompletionTokenLogprob`` entries, produced by thediff --git a/packages/sie_server/src/sie_server/processors/tool_call_parser.py b/packages/sie_server/src/sie_server/processors/tool_call_parser.pyindex fefa16ba1..b7fe6e8a6 100644--- a/packages/sie_server/src/sie_server/processors/tool_call_parser.py+++ b/packages/sie_server/src/sie_server/processors/tool_call_parser.py@@ -656,6 +656,7 @@ async def _parse_tool_call_stream_impl(logprobs=chunk.logprobs,error_code=chunk.error_code,error_message=chunk.error_message,+ upstream_reason=chunk.upstream_reason,)# Global terminal. Close any choices that did not see a# per-choice finish event (single-candidate path: this is@@ -704,6 +705,7 @@ async def _parse_tool_call_stream_impl(upstream_usage=chunk.upstream_usage,error_code=chunk.error_code,error_message=chunk.error_message,+ upstream_reason=chunk.upstream_reason,# Preserve ``candidates`` (with any per-candidate# ``tool_calls`` injected above for the non-streaming# ``n>1`` + tools path) through the wrap.diff --git a/packages/sie_server/src/sie_server/types/openapi.py b/packages/sie_server/src/sie_server/types/openapi.pyindex fb77b70b0..41e0a5998 100644--- a/packages/sie_server/src/sie_server/types/openapi.py+++ b/packages/sie_server/src/sie_server/types/openapi.py@@ -11,6 +11,7 @@ from typing import Annotated, Any, Literalfrom pydantic import BaseModel, Field+from sie_server.adapters.errors import UpstreamFailureReasonfrom sie_server.core.extract_cost import MAX_EXTRACT_LABELSfrom sie_server.core.score_cost import MAX_SCORE_ITEMSfrom sie_server.types.inputs import DEFAULT_MAX_ITEM_TEXT_BYTES@@ -749,6 +750,43 @@ class OpenAIEmbeddingsModelLoadFailedErrorResponse(BaseModel):error: OpenAIEmbeddingsModelLoadFailedErrorModel+class GenerateErrorDetailModel(BaseModel):+ """Detail returned for a native generation error."""++ code: str = Field(..., description="Stable error code")+ message: str = Field(..., description="Client-safe error message")+ param: str | None = Field(default=None, description="Offending request field, when known")+ reason: UpstreamFailureReason | None = Field(+ default=None,+ description="Class of a remote upstream's failure, when one caused the error",+ )+++class GenerateErrorResponse(BaseModel):+ """FastAPI error envelope for a native generation error."""++ detail: GenerateErrorDetailModel+++class OpenAIGenerationErrorModel(BaseModel):+ """Inner object of the top-level OpenAI ``{"error": {...}}`` envelope of a generation error."""++ message: str = Field(..., description="Client-safe error message")+ type: str = Field(..., description="OpenAI error type, e.g. 'server_error'")+ param: str | None = Field(default=None, description="Offending request field, when known")+ code: str = Field(..., description="Stable error code")+ reason: UpstreamFailureReason | None = Field(+ default=None,+ description="Class of a remote upstream's failure, when one caused the error",+ )+++class OpenAIGenerationErrorResponse(BaseModel):+ """Top-level OpenAI error envelope of a generation error."""++ error: OpenAIGenerationErrorModel++class GenerateChunkErrorModel(BaseModel):"""Terminal error carried by a generation SSE event."""@@ -761,6 +799,10 @@ class GenerateChunkErrorModel(BaseModel):le=60,description=("Authoritative retry hint in seconds for RESOURCE_EXHAUSTED only; null for other terminal errors"),)+ reason: UpstreamFailureReason | None = Field(+ default=None,+ description="Class of a remote upstream's failure, when one ended the generation",+ )class GenerateChunk(BaseModel):diff --git a/packages/sie_server/tests/adapters/test_remote_openai_generation.py b/packages/sie_server/tests/adapters/test_remote_openai_generation.pyindex 568dc97e8..f50063081 100644--- a/packages/sie_server/tests/adapters/test_remote_openai_generation.py+++ b/packages/sie_server/tests/adapters/test_remote_openai_generation.py@@ -11,7 +11,11 @@ import yamlfrom fastapi import FastAPI, Requestfrom fastapi.responses import StreamingResponsefrom sie_sdk import SIEClient-from sie_server.adapters._generation_base import GenerationCapacityError, GenerationUnsupportedFieldError+from sie_server.adapters._generation_base import (+ GenerationCapacityError,+ GenerationUnsupportedFieldError,+ GenerationUpstreamError,+)from sie_server.adapters.remote._http import RemoteUpstreamErrorfrom sie_server.adapters.remote._limits import upstream_limiterfrom sie_server.adapters.remote._openai_completions import CompletionStreamParser@@ -164,8 +168,9 @@ async def test_disconnect_after_text_is_final_and_closes_capacity(adapter: OpenAanswer_with(adapter, lambda _: httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=stream))iterator = adapter.generate("prompt", max_new_tokens=9)assert (await anext(iterator)).text_delta == "answer"- with pytest.raises(RemoteUpstreamError, match="failed during generation"):+ with pytest.raises(GenerationUpstreamError, match="failed during generation") as raised:await anext(iterator)+ assert raised.value.upstream_reason == "upstream_unavailable"assert stream.closedassert upstream_limiter("generation-test")._in_flight == 0diff --git a/packages/sie_server/tests/adapters/test_remote_sie_generation.py b/packages/sie_server/tests/adapters/test_remote_sie_generation.pyindex b305d6b4f..7429474eb 100644--- a/packages/sie_server/tests/adapters/test_remote_sie_generation.py+++ b/packages/sie_server/tests/adapters/test_remote_sie_generation.py@@ -8,9 +8,13 @@ import httpximport pytestimport yamlfrom sie_sdk import SIEClient-from sie_server.adapters._generation_base import GenerationCapacityError, GenerationChunk, GenerationDrainingError+from sie_server.adapters._generation_base import (+ GenerationCapacityError,+ GenerationChunk,+ GenerationDrainingError,+ GenerationUpstreamError,+)from sie_server.adapters.remote import sie as remote_sie-from sie_server.adapters.remote._http import RemoteUpstreamErrorfrom sie_server.adapters.remote._limits import upstream_limiterfrom sie_server.adapters.remote.sie import SieUpstreamAdapterfrom sie_server.api.generate import _generation_http_exception@@ -156,6 +160,32 @@ async def test_upstream_failure_before_output_carries_its_retry_after(assert len(requests) == 1+ ("code", "error_class", "reason"),+ [+ ("MODEL_LOADING", GenerationDrainingError, "upstream_not_ready"),+ ("RESOURCE_EXHAUSTED", GenerationCapacityError, "upstream_busy"),+ ],+)+async def test_a_retryable_terminal_event_before_output_carries_its_reason(+ adapter: SieUpstreamAdapter, code: str, error_class: type[GenerationCapacityError], reason: str+) -> None:+ stream = GenerationStream(+ [{"done": True, "finish_reason": "error", "error": {"code": code, "message": "private", "retry_after_s": 7}}]+ )+ answer_with(+ adapter, lambda _request: httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=stream)+ )+ with pytest.raises(error_class) as raised:+ _ = [chunk async for chunk in adapter.generate("prompt", max_new_tokens=9)]+ exception = _generation_http_exception(raised.value)+ assert exception.status_code == 503+ assert exception.detail["reason"] == reason+ assert exception.headers is not None+ assert exception.headers["Retry-After"] == "7"+ assert "private" not in str(exception.detail)++async def test_a_disconnect_after_output_is_final_and_closes_the_stream(adapter: SieUpstreamAdapter) -> None:stream = GenerationStream([{"done": False, "text_delta": "started"}], disconnect=True)answer_with(@@ -163,8 +193,9 @@ async def test_a_disconnect_after_output_is_final_and_closes_the_stream(adapter:)iterator = adapter.generate("prompt", max_new_tokens=9)assert (await anext(iterator)).text_delta == "started"- with pytest.raises(RemoteUpstreamError, match="failed during generation"):+ with pytest.raises(GenerationUpstreamError, match="failed during generation") as raised:await anext(iterator)+ assert raised.value.upstream_reason == "upstream_unavailable"assert stream.closed@@ -187,8 +218,9 @@ async def test_generation_refuses_missing_or_malformed_terminal_usage(adapter: Sanswer_with(adapter, lambda _request: httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=stream))- with pytest.raises(RemoteUpstreamError, match="usage"):+ with pytest.raises(GenerationUpstreamError, match="usage") as raised:_ = [chunk async for chunk in adapter.generate("prompt", max_new_tokens=9)]+ assert raised.value.upstream_reason == "upstream_invalid_response"assert stream.closeddiff --git a/packages/sie_server/tests/api/test_generation_timeouts.py b/packages/sie_server/tests/api/test_generation_timeouts.pyindex b9427eac5..d8898035c 100644--- a/packages/sie_server/tests/api/test_generation_timeouts.py+++ b/packages/sie_server/tests/api/test_generation_timeouts.py@@ -100,6 +100,7 @@ def test_first_chunk_timeout_aborts_the_engine_and_returns_504(assert response.status_code == 504, response.textassert error_code(response.json()) == "first_chunk_timeout"+ assert "reason" not in response.textassert adapter.closeddiff --git a/packages/sie_server/tests/api/test_remote_chat.py b/packages/sie_server/tests/api/test_remote_chat.pyindex bd059c4d5..b58bd0804 100644--- a/packages/sie_server/tests/api/test_remote_chat.py+++ b/packages/sie_server/tests/api/test_remote_chat.py@@ -2,6 +2,7 @@ import asyncioimport jsonimport loggingfrom collections.abc import AsyncIterator, Callable, Iterator+from pathlib import Pathfrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock@@ -10,6 +11,7 @@ import httpximport pytestfrom fastapi import FastAPIfrom fastapi.testclient import TestClient+from sie_server.adapters.errors import UPSTREAM_FAILURE_MESSAGESfrom sie_server.adapters.remote._limits import upstream_limiterfrom sie_server.adapters.remote.openai import OpenAIUpstreamAdapterfrom sie_server.adapters.remote.sie import SieUpstreamAdapter@@ -223,7 +225,8 @@ def test_a_502_before_output_logs_its_reason(with caplog.at_level(logging.WARNING, logger=openai_local.__name__):response = client.post("/v1/chat/completions", json={**BODY, "stream": streaming})assert response.status_code == 502- assert response.json()["error"]["message"] == "upstream generation request failed"+ assert response.json()["error"]["message"] == "the upstream rejected the server's credential"+ assert response.json()["error"]["reason"] == "upstream_credential_rejected"assert _remote_chat_warnings(caplog) == [f"remote chat for {MODEL} failed: upstream answered 401"]assert "private" not in caplog.text@@ -239,7 +242,8 @@ def test_a_missing_upstream_key_is_a_502_whose_log_names_it(with caplog.at_level(logging.WARNING, logger=openai_local.__name__):response = client.post("/v1/chat/completions", json={**BODY, "stream": streaming})assert response.status_code == 502- assert response.json()["error"]["message"] == "upstream generation request failed"+ assert response.json()["error"]["message"] == "the server has no usable credential for its upstream"+ assert response.json()["error"]["reason"] == "upstream_credential_unavailable"assert _remote_chat_warnings(caplog) == [f"remote chat for {MODEL} failed: the upstream credential is unavailable"]assert not requests@@ -752,7 +756,7 @@ def _render_chat_locally(remote_chat: tuple, monkeypatch: pytest.MonkeyPatch) ->[("chat", "404", 502, "route", f"remote chat for {MODEL} failed: upstream answered 404"),("chat", "connect", 503, "route", f"remote chat for {MODEL} failed: {UNAVAILABLE}"),- ("rendered chat", "401", 502, "route", f"remote chat for {MODEL} failed: upstream answered 401"),+ ("rendered chat", "401", 502, "adapter", "remote generation failed: upstream answered 401"),("rendered chat", "connect", 503, "adapter", f"remote generation failed: {UNAVAILABLE}"),("native", "connect", 503, "adapter", f"remote generation failed: {UNAVAILABLE}"),("completions", "connect", 503, "adapter", f"remote generation failed: {UNAVAILABLE}"),@@ -793,6 +797,11 @@ def test_a_remote_generation_failure_logs_one_warning_with_its_reason(response = client.post(path, json=body)assert response.status_code == status, response.text+ payload = response.json()+ reason = {"401": "upstream_credential_rejected", "404": "upstream_model_not_found"}.get(+ failure, "upstream_unavailable"+ )+ assert payload.get("error", payload.get("detail"))["reason"] == reasonlogger_name = openai_local.__name__ if source == "route" else type(adapter).__module__warnings = [(record.name, record.getMessage()) for record in caplog.records if record.levelno >= logging.WARNING]assert warnings == [(logger_name, message)]@@ -802,14 +811,11 @@ def test_a_remote_generation_failure_logs_one_warning_with_its_reason(assert private not in caplog.text- ("streaming", "message"),- [(False, f"generate failed for {SAFE_MODEL}"), (True, "stream_generate failed before output")],-)[email protected]("streaming", [False, True])def test_a_native_remote_failure_before_output_logs_one_warning_with_its_reason(- remote_chat: tuple, caplog: pytest.LogCaptureFixture, streaming: bool, message: str+ remote_chat: tuple, caplog: pytest.LogCaptureFixture, streaming: bool) -> None:- client, _, config, _ = remote_chat+ client, adapter, config, _ = remote_chatconfig.profiles["default"].adapter_options.runtime.clear()answer_with(remote_chat, json_response(401, {"error": {"message": "private upstream detail"}}))caplog.set_level(logging.DEBUG)@@ -819,9 +825,10 @@ def test_a_native_remote_failure_before_output_logs_one_warning_with_its_reason(assert response.status_code == 500[record] = [record for record in caplog.records if record.levelno >= logging.WARNING]- assert (record.name, record.getMessage()) == ("sie_server.api.generate", message)- assert record.exc_info is not None- assert str(record.exc_info[1]) == "upstream answered 401"+ assert (record.name, record.getMessage()) == (+ type(adapter).__module__,+ "remote generation failed: upstream answered 401",+ )for private in (PROMPT, "private upstream detail"):assert private not in caplog.text@@ -1271,3 +1278,349 @@ def test_onboarded_direct_chat_answers_rendered_reasoning_only_when_asked(assert reasoning == ("PRIVATE_REASONING" if include_reasoning else "")assert "think>" not in response.textassert upstream_stream.closed+++def test_the_upstream_failure_reasons_are_the_wire_fixture() -> None:+ fixture = json.loads(+ (Path(__file__).resolve().parents[3] / "wire-fixtures" / "upstream_failure_reasons.json").read_text(+ encoding="utf-8"+ )+ )+ assert fixture["reasons"] == UPSTREAM_FAILURE_MESSAGES+++ACCOUNT = "acct-7Q2Lw0d9"+_FINAL_FAILURES = {+ "401": "upstream_credential_rejected",+ "402": "upstream_payment_required",+ "403": "upstream_credential_rejected",+ "403 ACCOUNT_SUSPENDED": "upstream_refused",+ "404": "upstream_model_not_found",+ "408": "upstream_unavailable",+ "409": "upstream_refused",+ "429 COLD_START_RATE_LIMITED": "upstream_busy",+ "500 upstream_payment_required": "upstream_payment_required",+ "501": "upstream_unavailable",+ "malformed": "upstream_invalid_response",+}+_UPSTREAM_IDENTIFIERS = ("chat-api", "127.0.0.1", "/prefix", "operator/model", ACCOUNT, "private upstream detail")+_REASON_SURFACES = [*_GENERATION_SURFACES, ("rendered chat", False), ("rendered chat", True)]+++def _reason_request(+ remote_chat: tuple, monkeypatch: pytest.MonkeyPatch, surface: str, *, stream: bool+) -> tuple[str, dict[str, Any]]:+ if not surface.startswith("rendered chat"):+ return _generation_request(surface, stream=stream)+ _render_chat_locally(remote_chat, monkeypatch)+ path, body = _generation_request("chat", stream=stream)+ if surface == "rendered chat with tools":+ body["tools"] = [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}]+ return path, body+++def _final_error(surface: str) -> tuple[int, str]:+ return (502, "upstream_error") if "chat" in surface else (500, "inference_error")+++def _error(response: httpx.Response) -> dict[str, Any]:+ payload = response.json()+ return payload.get("error", payload.get("detail"))+++def _answer_with_failure(remote_chat: tuple, failure: str) -> None:+ _, adapter, _, requests = remote_chat++ def respond(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ detail = f"private upstream detail: account {ACCOUNT} at {request.url}"+ if failure == "connect":+ raise httpx.ConnectError(detail)+ if failure != "malformed":+ status, _, named = failure.partition(" ")+ error: dict[str, Any] = {"message": detail, "code": int(status)}+ if named in UPSTREAM_FAILURE_MESSAGES:+ error.update(code="inference_error", reason=named)+ elif named:+ error["code"] = named+ return json_response(int(status), {"error": error})+ if request.headers["accept"] == "text/event-stream":+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=ChatStream([{"detail": detail}])+ )+ return json_response(200, {"detail": detail})++ adapter._async_client = upstream_client(adapter._upstream, transport=httpx.MockTransport(respond))++[email protected](("surface", "streaming"), _REASON_SURFACES)[email protected]("failure", [*_FINAL_FAILURES, "connect"])+def test_an_upstream_failure_tells_the_caller_its_reason_and_nothing_that_identifies_the_upstream(+ remote_chat: tuple, monkeypatch: pytest.MonkeyPatch, surface: str, streaming: bool, failure: str+) -> None:+ client, adapter, config, requests = remote_chat+ config.profiles["default"].adapter_options.runtime.clear()+ adapter._upstream = adapter._upstream.model_copy(update={"api_key_secret": "CHAT_API_KEY"})+ monkeypatch.setenv("CHAT_API_KEY", CREDENTIAL)+ _answer_with_failure(remote_chat, failure)+ path, body = _reason_request(remote_chat, monkeypatch, surface, stream=streaming)++ response = client.post(path, json=body)++ error = _error(response)+ if failure == "connect":+ assert response.status_code == 503, response.text+ assert error["reason"] == "upstream_unavailable"+ if surface == "chat":+ assert error["code"] == "QUEUE_FULL"+ assert error["message"] == f"The upstream serving model '{MODEL}' is unavailable, please retry"+ else:+ assert error["code"] == "RESOURCE_EXHAUSTED"+ assert error["message"] == "the upstream is unavailable, please retry"+ else:+ reason = _FINAL_FAILURES[failure]+ assert (response.status_code, error["code"]) == _final_error(surface), response.text+ assert error["reason"] == reason+ assert error["message"] == UPSTREAM_FAILURE_MESSAGES[reason]+ assert [request.headers["authorization"] for request in requests] == [f"Bearer {CREDENTIAL}"]+ for private in (*_UPSTREAM_IDENTIFIERS, CREDENTIAL):+ assert private not in response.text+++def _first_output(adapter: Any, path: str) -> dict[str, Any]:+ if path.endswith("/chat/completions"):+ return events()[0]+ if isinstance(adapter, OpenAIUpstreamAdapter):+ return {"choices": [{"index": 0, "text": "answer", "finish_reason": None}]}+ return {"request_id": "upstream-id", "seq": 0, "text_delta": "answer", "done": False}+++def _reported_failure(adapter: Any, path: str, reason: str | None) -> dict[str, Any]:+ detail = f"private upstream detail: account {ACCOUNT}"+ if isinstance(adapter, SieUpstreamAdapter):+ error: dict[str, Any] = {"message": detail, "code": "inference_error"}+ if reason is not None:+ error["reason"] = reason+ if path.endswith("/chat/completions"):+ return {"error": {**error, "code": "upstream_error", "type": "upstream_error"}}+ return {+ "request_id": "upstream-id",+ "seq": 1,+ "text_delta": "",+ "done": True,+ "finish_reason": "error",+ "error": error,+ }+ return {"error": {"message": detail, **({} if reason is None else {"code": 402})}}+++def _answer_with_reported_failure(+ remote_chat: tuple, reason: str | None, *, after_output: bool, streams: list[ChatStream]+) -> None:+ _, adapter, _, requests = remote_chat++ def respond(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ path = request.url.path+ failure = _reported_failure(adapter, path, reason)+ if request.headers["accept"] != "text/event-stream":+ return json_response(200, failure)+ stream = ChatStream([*([_first_output(adapter, path)] if after_output else []), failure])+ streams.append(stream)+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=stream)++ adapter._async_client = upstream_client(adapter._upstream, transport=httpx.MockTransport(respond))+++ ("surface", "streaming"),+ [*_REASON_SURFACES, ("rendered chat with tools", False), ("rendered chat with tools", True)],+)[email protected]("reason", [None, "upstream_payment_required"])+def test_a_failure_the_upstream_reports_in_its_answer_tells_the_caller_its_reason(+ remote_chat: tuple,+ monkeypatch: pytest.MonkeyPatch,+ caplog: pytest.LogCaptureFixture,+ surface: str,+ streaming: bool,+ reason: str | None,+) -> None:+ client, adapter, config, requests = remote_chat+ config.profiles["default"].adapter_options.runtime.clear()+ _answer_with_reported_failure(remote_chat, reason, after_output=False, streams=[])+ path, body = _reason_request(remote_chat, monkeypatch, surface, stream=streaming)++ with caplog.at_level(logging.WARNING):+ response = client.post(path, json=body)++ expected = reason or "upstream_unavailable"+ error = _error(response)+ assert (response.status_code, error["code"]) == _final_error(surface), response.text+ assert error["reason"] == expected+ assert error["message"] == UPSTREAM_FAILURE_MESSAGES[expected]+ for private in _UPSTREAM_IDENTIFIERS:+ assert private not in response.text+ assert len(requests) == 1+ if surface != "chat":+ adapter_lines = [record.getMessage() for record in caplog.records if record.name == type(adapter).__module__]+ if isinstance(adapter, SieUpstreamAdapter):+ ended = " ".join(part for part in ("inference_error", reason) if part)+ assert adapter_lines == [f"remote generation failed: upstream ended generation with {ended}"]+ else:+ sent = "an error" if reason is None else "error 402"+ assert adapter_lines == [f"remote generation failed: upstream sent {sent} instead of a completion"]+ assert ACCOUNT not in caplog.text++[email protected]("remote_chat", ["sie"], indirect=True)[email protected](("surface", "streaming"), [entry for entry in _REASON_SURFACES if entry[0] != "chat"])+ ("code", "reason"), [("RESOURCE_EXHAUSTED", "upstream_busy"), ("MODEL_LOADING", "upstream_not_ready")]+)+def test_a_retryable_terminal_event_before_output_tells_the_caller_its_reason(+ remote_chat: tuple, monkeypatch: pytest.MonkeyPatch, surface: str, streaming: bool, code: str, reason: str+) -> None:+ client, _, config, requests = remote_chat+ config.profiles["default"].adapter_options.runtime.clear()+ terminal = {"text_delta": "", "done": True, "finish_reason": "error", "error": {"code": code, "retry_after_s": 7}}+ answer_with(+ remote_chat,+ lambda: httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=ChatStream([terminal])),+ )+ path, body = _reason_request(remote_chat, monkeypatch, surface, stream=streaming)++ response = client.post(path, json=body)++ assert response.status_code == 503, response.text+ assert response.headers["retry-after"] == "7"+ error = _error(response)+ assert (error["code"], error["reason"]) == (code, reason)+ assert len(requests) == 1++[email protected]("remote_chat", ["sie"], indirect=True)[email protected]("surface", ["native", "completions", "rendered chat"])+ ("code", "reason"), [("RESOURCE_EXHAUSTED", "upstream_busy"), ("MODEL_LOADING", "upstream_not_ready")]+)+def test_a_retryable_terminal_event_after_output_ends_the_stream_with_its_reason(+ remote_chat: tuple, monkeypatch: pytest.MonkeyPatch, surface: str, code: str, reason: str+) -> None:+ client, adapter, config, requests = remote_chat+ config.profiles["default"].adapter_options.runtime.clear()+ terminal = {"text_delta": "", "done": True, "finish_reason": "error", "error": {"code": code, "retry_after_s": 7}}+ stream = ChatStream([_first_output(adapter, "/generate"), terminal])+ answer_with(remote_chat, httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=stream))+ path, body = _reason_request(remote_chat, monkeypatch, surface, stream=True)++ response = client.post(path, json=body)++ assert response.status_code == 200, response.text+ assert "answer" in response.text+ errors = [+ json.loads(line.removeprefix("data: "))["error"]+ for line in response.text.splitlines()+ if line.startswith("data: {") and '"error"' in line+ ]+ assert [error["reason"] for error in errors] == [reason]+ assert errors[0]["code"] == ("upstream_error" if surface == "rendered chat" else code)+ assert len(requests) == 1+++class HangingStream(ChatStream):+ async def __aiter__(self) -> AsyncIterator[bytes]:+ async for chunk in super().__aiter__():+ yield chunk+ await asyncio.sleep(30)+ yield b""+++ ("surface", "streaming", "code"),+ [+ ("native", False, "first_chunk_timeout"),+ ("completions", False, "first_chunk_timeout"),+ ("responses", False, "first_chunk_timeout"),+ ("rendered chat", False, "generation_timeout"),+ ("rendered chat", True, "generation_timeout"),+ ],+)+def test_a_remote_profile_timeout_tells_the_caller_the_upstream_timed_out(+ remote_chat: tuple, monkeypatch: pytest.MonkeyPatch, surface: str, streaming: bool, code: str+) -> None:+ client, _, config, requests = remote_chat+ config.profiles["default"].adapter_options.runtime.clear()+ answer_with(+ remote_chat,+ lambda: httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=HangingStream([])),+ )+ path, body = _reason_request(remote_chat, monkeypatch, surface, stream=streaming)+ served = client.app.state.registry.get_config.return_value+ served.profiles["default"].adapter_options.runtime.update(first_chunk_timeout_s=0.2, overall_timeout_s=10)++ response = client.post(path, json=body)++ assert response.status_code == 504, response.text+ error = _error(response)+ assert (error["code"], error["reason"]) == (code, "upstream_unavailable")+ assert len(requests) == 1+++_ENDINGS_AFTER_OUTPUT = [+ ("disconnect", "upstream_unavailable"),+ ("malformed", "upstream_invalid_response"),+ ("reported", "upstream_unavailable"),+ ("reported 402", "upstream_payment_required"),+ ("timeout", "upstream_unavailable"),+]+++ ("surface", "ending", "reason"),+ [+ (surface, ending, reason)+ for surface in ("native", "chat", "completions", "rendered chat")+ for ending, reason in _ENDINGS_AFTER_OUTPUT+ if ending != "timeout" or surface == "rendered chat"+ ],+)+def test_an_upstream_failure_after_output_ends_the_stream_with_its_reason(+ remote_chat: tuple, monkeypatch: pytest.MonkeyPatch, surface: str, ending: str, reason: str+) -> None:+ client, adapter, config, requests = remote_chat+ config.profiles["default"].adapter_options.runtime.clear()+ path, body = _reason_request(remote_chat, monkeypatch, surface, stream=True)+ streams: list[ChatStream] = []+ if ending.startswith("reported"):+ _answer_with_reported_failure(+ remote_chat,+ "upstream_payment_required" if ending == "reported 402" else None,+ after_output=True,+ streams=streams,+ )+ else:+ first = _first_output(adapter, "/chat/completions" if surface == "chat" else "/generate")+ if ending == "timeout":+ stream: ChatStream = HangingStream([first])+ served = client.app.state.registry.get_config.return_value+ served.profiles["default"].adapter_options.runtime.update(first_chunk_timeout_s=5, overall_timeout_s=0.5)+ else:+ stream = ChatStream([first, "{malformed"] if ending == "malformed" else [first], disconnect=True)+ streams.append(stream)+ answer_with(remote_chat, httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=stream))++ response = client.post(path, json=body)++ assert response.status_code == 200, response.text+ assert "answer" in response.text+ events_with_errors = [+ json.loads(line.removeprefix("data: "))+ for line in response.text.splitlines()+ if line.startswith("data: {") and '"error"' in line+ ]+ assert [event["error"]["reason"] for event in events_with_errors] == [reason]+ assert events_with_errors[0]["error"]["message"] == UPSTREAM_FAILURE_MESSAGES[reason]+ for private in _UPSTREAM_IDENTIFIERS:+ assert private not in response.text+ assert len(requests) == 1+ assert all(stream.closed for stream in streams)diff --git a/packages/sie_server/tests/processors/test_remote_chat.py b/packages/sie_server/tests/processors/test_remote_chat.pyindex 9f6140a75..669e182de 100644--- a/packages/sie_server/tests/processors/test_remote_chat.py+++ b/packages/sie_server/tests/processors/test_remote_chat.py@@ -2,12 +2,14 @@ import asyncioimport jsonimport timefrom collections.abc import AsyncIterator+from pathlib import Pathfrom typing import Anyfrom unittest.mock import AsyncMock, MagicMockimport httpximport msgpackimport pytest+from sie_server.adapters.errors import UPSTREAM_FAILURE_MESSAGESfrom sie_server.adapters.remote._limits import upstream_limiterfrom sie_server.adapters.remote.openai import OpenAIUpstreamAdapterfrom sie_server.adapters.remote.sie import SieUpstreamAdapter@@ -19,6 +21,11 @@ from sie_server.processors.streaming import StreamingProcessorMODEL = "queued/chat"USAGE = {"prompt_tokens": 37, "completion_tokens": 2, "total_tokens": 39}TOOL = {"type": "function", "function": {"name": "lookup", "parameters": {"type": "object"}}}+WORKER_TERMINAL_ERROR = json.loads(+ (Path(__file__).resolve().parents[3] / "wire-fixtures" / "upstream_failure_reasons.json").read_text(+ encoding="utf-8"+ )+)["worker_terminal_error"]def choice(content: str = "answer", *, index: int = 0, finish: str | None = None, **extra: Any) -> dict:@@ -137,8 +144,9 @@ def respond(return stream-async def run(remote: tuple, **fields: Any) -> tuple[AsyncMock, list[dict]]:+async def run(remote: tuple, *, prompt: str | None = None, **fields: Any) -> tuple[AsyncMock, list[dict]]:_adapter, proc, nc, _requests = remote+ request = {"messages": [{"role": "user", "content": "question"}]} if prompt is None else {"prompt": prompt}msg = AsyncMock()msg.data = msgpack.packb({@@ -154,7 +162,7 @@ async def run(remote: tuple, **fields: Any) -> tuple[AsyncMock, list[dict]]:"reply_subject": "_INBOX.router-1.req-1","timestamp": time.time(),"generate": {- "messages": [{"role": "user", "content": "question"}],+ **request,"max_new_tokens": 9,"stream": True,**fields,@@ -437,13 +445,116 @@ async def test_post_output_disconnect_is_final(remote: tuple) -> None:stream = respond(remote, stream=ChatStream([choice()], disconnect=True))_msg, chunks = await run(remote)assert "".join(chunk.get("text_delta", "") for chunk in chunks) == "answer"- assert chunks[-1]["error"]["code"] == "inference_error"+ assert chunks[-1]["error"] == {+ "code": "inference_error",+ "message": UPSTREAM_FAILURE_MESSAGES["upstream_unavailable"],+ "reason": "upstream_unavailable",+ }assert "PRIVATE" not in json.dumps(chunks)assert len(remote[3]) == 1assert stream is not Noneassert stream.closed+_UPSTREAM_DETAIL = "PRIVATE_UPSTREAM_DETAIL for account acct-7Q2Lw0d9"+_FAILURES = [+ ("401", "inference_error", "upstream_credential_rejected"),+ ("402", "inference_error", "upstream_payment_required"),+ ("403", "inference_error", "upstream_credential_rejected"),+ ("404", "inference_error", "upstream_model_not_found"),+ ("connect", "RESOURCE_EXHAUSTED", "upstream_unavailable"),+ ("malformed", "inference_error", "upstream_invalid_response"),+]+++def fail_upstream(remote: tuple, failure: str, *, streaming: bool) -> None:+ adapter, _proc, _nc, requests = remote++ def handler(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ if failure == "connect":+ raise httpx.ConnectError(_UPSTREAM_DETAIL)+ if failure == "malformed" and streaming:+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream"}, stream=ChatStream([{"x": _UPSTREAM_DETAIL}])+ )+ status, payload = (+ (200, {"x": _UPSTREAM_DETAIL})+ if failure == "malformed"+ else (int(failure), {"error": {"message": _UPSTREAM_DETAIL, "code": int(failure)}})+ )+ return httpx.Response(+ status, headers={"content-type": "application/json"}, stream=httpx.ByteStream(json.dumps(payload).encode())+ )++ adapter._async_client = upstream_client(adapter._upstream, transport=httpx.MockTransport(handler))+++def assert_reason_reaches_the_gateway(+ remote: tuple, msg: AsyncMock, chunks: list[dict], code: str, reason: str+) -> None:+ error = chunks[-1]["error"]+ assert (error["code"], error["reason"]) == (code, reason)+ if code == "inference_error":+ assert error["message"] == UPSTREAM_FAILURE_MESSAGES[reason]+ published = json.dumps(chunks)+ for private in ("PRIVATE", "acct-7Q2Lw0d9", "queued-chat", "127.0.0.1", "operator"):+ assert private not in published+ assert len(remote[3]) == 1+ msg.ack.assert_awaited_once()++[email protected]("streaming", [False, True])[email protected](("failure", "code", "reason"), _FAILURES)+async def test_an_upstream_failure_reaches_the_gateway_with_its_reason(+ remote: tuple, streaming: bool, failure: str, code: str, reason: str+) -> None:+ fail_upstream(remote, failure, streaming=streaming)+ msg, chunks = await run(remote, stream=streaming)+ assert_reason_reaches_the_gateway(remote, msg, chunks, code, reason)+ if failure == "402":+ assert chunks[-1]["error"] == WORKER_TERMINAL_ERROR+++def serve_raw_completions(remote: tuple, monkeypatch: pytest.MonkeyPatch) -> None:+ adapter, proc, _nc, _requests = remote+ monkeypatch.setattr(proc, "_check_context_length", AsyncMock(return_value=None))+ if isinstance(adapter, OpenAIUpstreamAdapter):+ adapter._upstream = adapter._upstream.model_copy(update={"endpoints": ["chat", "completions"]})++[email protected](("failure", "code", "reason"), _FAILURES)+async def test_an_upstream_failure_of_a_queued_prompt_reaches_the_gateway_with_its_reason(+ remote: tuple, monkeypatch: pytest.MonkeyPatch, failure: str, code: str, reason: str+) -> None:+ serve_raw_completions(remote, monkeypatch)+ fail_upstream(remote, failure, streaming=True)+ msg, chunks = await run(remote, prompt="question")+ assert_reason_reaches_the_gateway(remote, msg, chunks, code, reason)+ sie = isinstance(remote[0], SieUpstreamAdapter)+ assert remote[3][0].url.path.endswith("/v1/generate/operator__model" if sie else "/completions")++[email protected]("output", [False, True])[email protected]("reason", [None, "upstream_payment_required"])+async def test_a_failure_the_upstream_reports_in_a_queued_prompt_reaches_the_gateway_with_its_reason(+ remote: tuple, monkeypatch: pytest.MonkeyPatch, output: bool, reason: str | None+) -> None:+ serve_raw_completions(remote, monkeypatch)+ sie = isinstance(remote[0], SieUpstreamAdapter)+ if sie:+ first = {"text_delta": "answer", "done": False}+ error = {"code": "inference_error", "message": _UPSTREAM_DETAIL, **({"reason": reason} if reason else {})}+ failure = {"text_delta": "", "done": True, "finish_reason": "error", "error": error}+ else:+ first = {"choices": [{"index": 0, "text": "answer", "finish_reason": None}]}+ failure = {"error": {"message": _UPSTREAM_DETAIL, **({"code": 402} if reason else {})}}+ respond(remote, frames=[first, failure] if output else [failure])+ msg, chunks = await run(remote, prompt="question")+ assert "".join(chunk.get("text_delta", "") for chunk in chunks) == ("answer" if output else "")+ assert_reason_reaches_the_gateway(remote, msg, chunks, "inference_error", reason or "upstream_unavailable")++@pytest.mark.parametrize("usage",[diff --git a/packages/sie_server/tests/test_openapi_export.py b/packages/sie_server/tests/test_openapi_export.pyindex fd95a2b12..9de942565 100644--- a/packages/sie_server/tests/test_openapi_export.py+++ b/packages/sie_server/tests/test_openapi_export.py@@ -5,6 +5,7 @@ from pathlib import Pathimport pytestfrom jsonschema import Draft202012Validator+from sie_server.adapters.errors import UPSTREAM_FAILURE_MESSAGESfrom sie_server.cli import appfrom typer.testing import CliRunner@@ -102,6 +103,9 @@ def test_openapi_documents_generate_contract() -> None:assert retry_after["anyOf"][0]["minimum"] == 1assert retry_after["anyOf"][0]["maximum"] == 60assert "retry_after_s" not in chunk_error_schema["required"]+ reason = chunk_error_schema["properties"]["reason"]+ assert set(reason["anyOf"][0]["enum"]) == set(UPSTREAM_FAILURE_MESSAGES)+ assert "reason" not in chunk_error_schema["required"]responses = operation["responses"]assert "INPUT_TOO_LONG" in responses["413"]["description"]diff --git a/packages/wire-fixtures/README.md b/packages/wire-fixtures/README.mdindex 92ba7a613..6604ea418 100644--- a/packages/wire-fixtures/README.md+++ b/packages/wire-fixtures/README.md@@ -47,6 +47,10 @@ executable.response headers that say which side served (`X-SIE-Served-By`,`X-SIE-Upstream`, `X-SIE-Fallback-Reason`, `X-SIE-Fallback-Error`), each withits allowed values or pattern. An SDK drops a value outside them.+- `upstream_failure_reasons.json` — the `reason` that names the class of a+ remote upstream's failure on a generation error, the fixed message an+ `inference_error` of each class carries in place of the worker's own text,+ and the terminal error object a worker publishes for one of them.- `worker_status.json` — the worker heartbeat the sidecar publishes on`sie.health.<worker_id>`: the exact `fields` it sends, the`omitted_when_empty` fields it leaves out when empty, and a fully populated@@ -101,14 +105,21 @@ fixture set. Current consumers:(asserts that the `X-SIE-Served-By` and `X-SIE-Upstream` names and theserved-by values it emits are the ones `serving_disclosure.json` declares,and checks every gateway vector of `remote_routing.json` through its- handlers and its fallback refusal).+ handlers and its fallback refusal), and+ `packages/sie_gateway/src/queue/streaming.rs` (the reasons it admits and+ their messages are `upstream_failure_reasons.json`, and it reads the reason+ of its worker terminal error).- Server — `packages/sie_server/tests/adapters/test_remote_fallback.py` (eachdisclosure header the single server sends on a response served locally,remotely or through a bridge, and on the local refusal that answers a failedremote attempt, has a value or pattern `serving_disclosure.json` declares),- and `packages/sie_server/tests/api/test_remote_routing.py` (checks every+ `packages/sie_server/tests/api/test_remote_routing.py` (checks everysingle-server vector of `remote_routing.json` through the routing decision- and the refusal that answers a failed remote attempt).+ and the refusal that answers a failed remote attempt), and+ `packages/sie_server/tests/api/test_remote_chat.py` (the reasons and messages+ the server sends are `upstream_failure_reasons.json`), and+ `packages/sie_server/tests/processors/test_remote_chat.py` (a worker whose+ upstream answered 402 publishes its worker terminal error).- Worker sidecar — `packages/sie_server_sidecar/src/health_publisher.rs`(the published key set equals `fields`, minus `omitted_when_empty` when thoseare empty) and gateway — `packages/sie_gateway/src/types/worker.rs` (thediff --git a/packages/wire-fixtures/upstream_failure_reasons.json b/packages/wire-fixtures/upstream_failure_reasons.jsonnew file mode 100644index 000000000..5e80317f8--- /dev/null+++ b/packages/wire-fixtures/upstream_failure_reasons.json@@ -0,0 +1,19 @@+{+ "description": "The class of a remote upstream's failure that ended a generation, as an error's `reason` field names it, with the fixed caller-facing message of an `inference_error` of that class. A worker sends only these names; the gateway forwards only these names and answers with this text, never the worker's own message. `worker_terminal_error` is the error object a worker publishes on its terminal chunk when its upstream answered 402.",+ "reasons": {+ "upstream_credential_unavailable": "the server has no usable credential for its upstream",+ "upstream_credential_rejected": "the upstream rejected the server's credential",+ "upstream_payment_required": "the upstream account cannot pay for the request",+ "upstream_model_not_found": "the upstream has no route for the configured model",+ "upstream_refused": "the upstream refused the request",+ "upstream_unavailable": "the upstream could not be reached, timed out or failed",+ "upstream_busy": "the upstream is busy",+ "upstream_not_ready": "the model is not ready on the upstream",+ "upstream_invalid_response": "the upstream answered with something the server cannot accept"+ },+ "worker_terminal_error": {+ "code": "inference_error",+ "message": "the upstream account cannot pay for the request",+ "reason": "upstream_payment_required"+ }+}