Skip to content

armgit / sie

Public Imported from GitHub
0

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

feat(gateway): restore cluster stream refusals before output (#548)

Krisztian Gajdar0ebc55c087ba
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 298e69fc0..8e1252c18 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -2277,8 +2277,8 @@ fn model_loading_refusal(endpoint: &str) -> Response {
refusal
}
-/// Begin one buffered generation bridge only at a typed pre-dispatch refusal.
-/// Fleet numerical and streaming admission are separately gated; no failure
+/// Begin one generation bridge only at a typed pre-dispatch refusal.
+/// Fleet numerical admission remains separately gated; no failure
/// after a work item was published reaches this helper.
#[allow(clippy::result_large_err, clippy::too_many_arguments)]
fn native_fallback_plan(
@@ -2289,19 +2289,14 @@ fn native_fallback_plan(
parsed: Option<&(Vec<rmpv::Value>, publisher::WorkParams)>,
trigger: FallbackTrigger,
) -> Option<crate::state::model_registry::RemoteFallbackPlan> {
- let buffered_generation = endpoint == "generate"
- && parsed.is_some_and(|(_, params)| {
- params
- .generate
- .as_ref()
- .is_some_and(|generate| !generate.stream)
- });
+ let generation =
+ endpoint == "generate" && parsed.is_some_and(|(_, params)| params.generate.is_some());
fallback_plan_for_request(
state,
req.headers(),
req.extensions(),
model,
- buffered_generation,
+ generation,
"",
trigger,
)
@@ -2412,6 +2407,10 @@ async fn proxy_request_inner(
provisioning_surface: ProvisioningSurface,
inbound_publish_cx: Option<opentelemetry::Context>,
) -> Response {
+ let prefetch_first_output = req
+ .extensions()
+ .get::<FallbackAttempt>()
+ .is_some_and(FallbackAttempt::active);
// Native generation routing depends on request intent (default vs grammar),
// including in the no-policy OSS composition where grammar selects a
// profile-qualified model. Inspect the bounded body once before worker
@@ -2923,6 +2922,7 @@ async fn proxy_request_inner(
model_revision.as_deref(),
batch_target,
require_execution_authority_v1,
+ prefetch_first_output,
&physical_lane,
);
// Scope an OTel context over the publish so the work-item envelope
@@ -3229,6 +3229,7 @@ async fn queue_mode_proxy(
model_revision: Option<&str>,
batch_target: Option<publisher::PublishTarget>,
require_execution_authority_v1: bool,
+ prefetch_first_output: bool,
physical_lane: &PhysicalLane,
) -> Response {
// Parse body once, extract items + params (avoids double parse)
@@ -3285,6 +3286,7 @@ async fn queue_mode_proxy(
};
if params.generate.as_ref().is_some_and(|params| params.stream) {
return super::sse::build_sse_response(super::sse::SseParams {
+ prefetch_first_output,
state,
work_publisher: work_publisher_arc,
physical_lane: physical_lane.clone(),
@@ -8167,7 +8169,7 @@ async fn proxy_chat_inner(
},
&explicit_bundle_override,
&parts.extensions,
- !params.stream && !native_request_has_profile_selector(&body_bytes, false),
+ !native_request_has_profile_selector(&body_bytes, false),
(params.max_new_tokens, "max_completion_tokens"),
metric_labels_slot.as_ref(),
)
@@ -8194,6 +8196,10 @@ async fn proxy_chat_inner(
// arrives instead of being aggregated.
if stream {
return super::sse::build_sse_response(super::sse::SseParams {
+ prefetch_first_output: parts
+ .extensions
+ .get::<FallbackAttempt>()
+ .is_some_and(FallbackAttempt::active),
state: state.as_ref(),
work_publisher: work_publisher_arc,
physical_lane: physical_lane.clone(),
@@ -8837,7 +8843,7 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response
GenerationRequestIntent::Default,
&explicit_bundle_override,
&parts.extensions,
- !params.stream && !native_request_has_profile_selector(&body_bytes, false),
+ !native_request_has_profile_selector(&body_bytes, false),
(params.max_new_tokens, "max_tokens"),
metric_labels_slot.as_ref(),
)
@@ -8858,6 +8864,10 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response
// (completions rejects n>1), so no per-candidate interleave.
if stream {
return super::sse::build_sse_response(super::sse::SseParams {
+ prefetch_first_output: parts
+ .extensions
+ .get::<FallbackAttempt>()
+ .is_some_and(FallbackAttempt::active),
state: state.as_ref(),
work_publisher: work_publisher_arc,
physical_lane: physical_lane.clone(),
diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rs
index 4f1d4b73e..96749357f 100644
--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs
+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs
@@ -377,6 +377,118 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn streaming_cluster_fallback_commits_only_after_first_valid_event() {
+ let config = format!(
+ "{HYBRID_GENERATE_MODEL}\nrouting:\n policy: fallback\n fallback_profile: remote\n"
+ );
+ for surface in ["native", "chat", "completions"] {
+ for unloaded in [false, true] {
+ for failure in [None, Some(false), Some(true)] {
+ let gateway = TestGateway::new(&[&config]).await;
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ if unloaded {
+ gateway
+ .add_verified_worker("local-1", LOCAL_LANE, &[])
+ .await;
+ }
+ if let Some(after_output) = failure {
+ gateway.dispatcher.fail_stream(after_output);
+ }
+ let state = State(Arc::clone(&gateway.state));
+ let response = match surface {
+ "native" => proxy_request(state, json_request("/v1/generate/acme/chat", json!({"prompt":"hello","max_new_tokens":4,"stream":true})), "generate").await,
+ "chat" => proxy_chat(state, json_request("/v1/chat/completions", json!({"model":"acme/chat","messages":[{"role":"user","content":"hello"}],"stream":true}))).await,
+ "completions" => proxy_completions(state, json_request("/v1/completions", json!({"model":"acme/chat","prompt":"hello","max_tokens":4,"stream":true}))).await,
+ _ => unreachable!(),
+ };
+ if failure == Some(false) {
+ assert_eq!(
+ response.status(),
+ StatusCode::SERVICE_UNAVAILABLE,
+ "{surface}"
+ );
+ assert_eq!(
+ response.headers()["retry-after"],
+ if unloaded { "5" } else { "60" }
+ );
+ assert_eq!(stamped(&response), (Some("local"), None));
+ assert_eq!(
+ response.headers()["x-sie-fallback-error"],
+ "INFERENCE_ERROR"
+ );
+ } else {
+ assert_eq!(response.status(), StatusCode::OK, "{surface}");
+ assert_eq!(stamped(&response), (Some("remote"), Some("team-sie")));
+ assert_eq!(response.headers()["content-type"], "text/event-stream");
+ assert!(!response.headers().contains_key("x-sie-fallback-error"));
+ }
+ let body = axum::body::to_bytes(response.into_body(), 8192)
+ .await
+ .unwrap();
+ let body = String::from_utf8_lossy(&body);
+ assert!(!body.contains("private upstream failure"));
+ if failure == Some(true) {
+ assert!(body.contains("ok"));
+ assert!(body.contains("inference_error"), "{surface}: {body}");
+ assert!(body.contains("[DONE]"));
+ }
+ assert_eq!(
+ gateway.dispatcher.dispatched(),
+ if unloaded {
+ vec![
+ dispatched("load", LOCAL_LANE, "acme/chat"),
+ dispatched("generate", REMOTE_LANE, "acme/chat:remote"),
+ ]
+ } else {
+ vec![dispatched("generate", REMOTE_LANE, "acme/chat:remote")]
+ }
+ );
+ }
+ }
+ }
+ }
+
+ #[tokio::test]
+ async fn streaming_cluster_fallback_restores_refusal_for_terminal_only_failures() {
+ let config = format!(
+ "{HYBRID_GENERATE_MODEL}\nrouting:\n policy: fallback\n fallback_profile: remote\n"
+ );
+ for surface in ["native", "chat", "completions"] {
+ for reason in ["cancelled", "error"] {
+ let gateway = TestGateway::new(&[&config]).await;
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ gateway.dispatcher.fail_stream_terminal(reason);
+ let state = State(Arc::clone(&gateway.state));
+ let response = match surface {
+ "native" => proxy_request(state, json_request("/v1/generate/acme/chat", json!({"prompt":"hello","max_new_tokens":4,"stream":true})), "generate").await,
+ "chat" => proxy_chat(state, json_request("/v1/chat/completions", json!({"model":"acme/chat","messages":[{"role":"user","content":"hello"}],"stream":true}))).await,
+ "completions" => proxy_completions(state, json_request("/v1/completions", json!({"model":"acme/chat","prompt":"hello","max_tokens":4,"stream":true}))).await,
+ _ => unreachable!(),
+ };
+ assert_eq!(
+ response.status(),
+ StatusCode::SERVICE_UNAVAILABLE,
+ "{surface}, {reason}"
+ );
+ assert_eq!(response.headers()["retry-after"], "60");
+ assert_eq!(
+ response.headers()["x-sie-fallback-error"],
+ "INFERENCE_ERROR"
+ );
+ assert_eq!(stamped(&response), (Some("local"), None));
+ assert_eq!(
+ gateway.dispatcher.dispatched(),
+ vec![dispatched("generate", REMOTE_LANE, "acme/chat:remote")]
+ );
+ }
+ }
+ }
+
#[tokio::test]
async fn native_cluster_fallback_bridges_a_cold_model_and_retains_local_pending_demand() {
let config = format!(
diff --git a/packages/sie_gateway/src/handlers/sse.rs b/packages/sie_gateway/src/handlers/sse.rs
index e9badcb65..d8332e3e9 100644
--- a/packages/sie_gateway/src/handlers/sse.rs
+++ b/packages/sie_gateway/src/handlers/sse.rs
@@ -53,6 +53,7 @@ use std::sync::Arc;
use std::time::Duration;
use crate::observability::lifecycle::{ErrorClass, Lifecycle, Outcome};
+use axum::http::StatusCode;
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use opentelemetry::trace::FutureExt;
@@ -91,6 +92,8 @@ pub enum SseEndpoint {
/// Parameters passed from the chat / generate handler to
/// :func:`build_sse_response`.
pub struct SseParams<'a> {
+ /// A bridge retains HTTP refusal authority until a valid event is ready.
+ pub prefetch_first_output: bool,
pub state: &'a AppState,
pub work_publisher: Arc<dyn WorkDispatcher>,
pub physical_lane: PhysicalLane,
@@ -124,6 +127,7 @@ pub struct SseParams<'a> {
/// a final error chunk + ``[DONE]``.
pub async fn build_sse_response(params: SseParams<'_>) -> Response {
let SseParams {
+ prefetch_first_output,
state,
work_publisher,
physical_lane,
@@ -307,6 +311,9 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
// than a synthetic timeout.
let (event_tx, event_rx) = tokio::sync::mpsc::channel::<Result<Event, Infallible>>(256);
+ let (first_output_tx, first_output_rx) = tokio::sync::oneshot::channel();
+ let first_output = prefetch_first_output.then_some(first_output_tx);
+
let driver_publisher = Arc::clone(&work_publisher);
let driver_request_id = request_id.clone();
let driver_model = model.clone();
@@ -325,6 +332,7 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
tokio::spawn(
async move {
run_sse_driver(SseDriverArgs {
+ first_output,
event_tx,
chunk_rx,
outcome_rx,
@@ -351,6 +359,27 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
.with_context(context),
);
+ if prefetch_first_output {
+ match first_output_rx.await {
+ Ok(Ok(())) => {}
+ outcome => {
+ let status = match outcome {
+ Ok(Err(status)) => status,
+ _ => StatusCode::SERVICE_UNAVAILABLE,
+ };
+ // Only a request-owned bridge enables this gate. Its outer
+ // handler restores the original local refusal and retry hint.
+ return (
+ status,
+ axum::Json(json!({"error": {
+ "code": "transport_failure", "message": "Bridge failed before output"
+ }})),
+ )
+ .into_response();
+ }
+ }
+ }
+
let stream = ReceiverStream::new(event_rx);
let sse = Sse::new(stream).keep_alive(KeepAlive::default());
@@ -385,7 +414,10 @@ pub async fn build_sse_response(params: SseParams<'_>) -> Response {
response
}
+type FirstOutputGate = Option<tokio::sync::oneshot::Sender<Result<(), StatusCode>>>;
+
struct SseDriverArgs {
+ first_output: FirstOutputGate,
event_tx: tokio::sync::mpsc::Sender<Result<Event, Infallible>>,
chunk_rx: broadcast::Receiver<ChunkEnvelope>,
outcome_rx: tokio::sync::oneshot::Receiver<StreamOutcome>,
@@ -537,6 +569,7 @@ async fn run_sse_driver(args: SseDriverArgs) {
async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Option<Lifecycle>) {
let SseDriverArgs {
+ mut first_output,
event_tx,
mut chunk_rx,
outcome_rx,
@@ -649,7 +682,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
// Cheap early-fire to mirror `run_streaming_generate`.
let now = tokio::time::Instant::now();
if now >= overall_deadline {
- send_error_chunk(
+ send_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -733,7 +767,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
);
continue;
}
- send_error_chunk(
+ send_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -753,7 +788,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
}
if let Some(la) = last_chunk_at {
if la.elapsed() >= inter_chunk_timeout {
- send_error_chunk(
+ send_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -789,7 +825,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
match completion {
Ok(Ok(())) => None,
Ok(Err(error)) => {
- send_error_chunk(
+ send_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -806,7 +843,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
return;
}
Err(_) => {
- send_error_chunk(
+ send_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -877,7 +915,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
// the stream) instead of a generic
// transport_failure. Same error shape as the
// worker-error chunk path below.
- send_synthetic_error_chunk(
+ send_synthetic_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -942,7 +981,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
succeeded = stream_succeeded,
"SSE consumer lagged behind chunk tap; response is incomplete"
);
- send_error_chunk(
+ send_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -975,7 +1015,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
// arm — guard against a double `[DONE]` by checking
// `first_seen`.
if !first_seen {
- send_error_chunk(
+ send_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -1032,7 +1073,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
{
TerminalDurabilityWait::Confirmed => {}
TerminalDurabilityWait::Failed(error) => {
- send_error_chunk(
+ send_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -1057,7 +1099,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
return;
}
TerminalDurabilityWait::MonitorStopped => {
- send_error_chunk(
+ send_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -1094,7 +1137,8 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
return;
}
TerminalDurabilityWait::OverallTimeout => {
- send_error_chunk(
+ send_error_chunk_before_output(
+ &mut first_output,
&event_tx,
&endpoint,
&stream_chat_id,
@@ -1170,6 +1214,23 @@ async fn run_sse_driver_with_lifecycle(args: SseDriverArgs, mut lifecycle: Optio
role_emitted.insert(chunk.choice_index);
}
if !skip_forward {
+ if let Some(gate) = first_output.take() {
+ let ready = match chunk.error.as_ref() {
+ Some(error) => Err(crate::handlers::proxy::worker_error_http_status(
+ error.client_safe_code(),
+ )),
+ None if chunk.done
+ && matches!(
+ chunk.finish_reason.as_deref(),
+ Some("cancelled" | "error")
+ ) =>
+ {
+ Err(StatusCode::SERVICE_UNAVAILABLE)
+ }
+ None => Ok(()),
+ };
+ let _ = gate.send(ready);
+ }
let ev = Event::default().data(event_body.to_string());
if !send_event(&event_tx, ev).await {
// Client disconnected — fire the cancel deterministically
@@ -1525,6 +1586,47 @@ fn worker_error_value(error: &ChunkError, include_openai_type: bool) -> Value {
Value::Object(object)
}
+/// Preserve the bridge's pre-output HTTP refusal before enqueuing an error event.
+#[allow(clippy::too_many_arguments)]
+async fn send_error_chunk_before_output(
+ first_output: &mut FirstOutputGate,
+ tx: &tokio::sync::mpsc::Sender<Result<Event, Infallible>>,
+ endpoint: &SseEndpoint,
+ chat_id: &str,
+ created: u64,
+ model: &str,
+ request_id: &str,
+ code: &str,
+ message: &str,
+) {
+ if let Some(gate) = first_output.take() {
+ let _ = gate.send(Err(StatusCode::SERVICE_UNAVAILABLE));
+ }
+ send_error_chunk(
+ tx, endpoint, chat_id, created, model, request_id, code, message,
+ )
+ .await;
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn send_synthetic_error_chunk_before_output(
+ first_output: &mut FirstOutputGate,
+ tx: &tokio::sync::mpsc::Sender<Result<Event, Infallible>>,
+ endpoint: &SseEndpoint,
+ chat_id: &str,
+ created: u64,
+ model: &str,
+ request_id: &str,
+ error: &ChunkError,
+) {
+ if let Some(gate) = first_output.take() {
+ let _ = gate.send(Err(crate::handlers::proxy::worker_error_http_status(
+ error.client_safe_code(),
+ )));
+ }
+ send_synthetic_error_chunk(tx, endpoint, chat_id, created, model, request_id, error).await;
+}
+
/// Emit a synthesized error chunk (gateway-side timeout or
/// transport failure) onto the SSE stream. Wraps the right shape
/// for each endpoint.
@@ -2081,6 +2183,7 @@ mod tests {
let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(8);
let args = SseDriverArgs {
+ first_output: None,
event_tx,
chunk_rx,
outcome_rx,
@@ -2335,6 +2438,7 @@ mod tests {
let (event_tx, mut event_rx) = tokio::sync::mpsc::channel(4);
run_sse_driver(SseDriverArgs {
+ first_output: None,
event_tx,
chunk_rx,
outcome_rx,
diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rs
index 8faf82f40..02a7f2031 100644
--- a/packages/sie_gateway/src/handlers/test_support.rs
+++ b/packages/sie_gateway/src/handlers/test_support.rs
@@ -110,6 +110,9 @@ impl Dispatched {
pub(crate) struct RecordingDispatcher {
load_refused: AtomicBool,
generate_refused: AtomicBool,
+ stream_error: AtomicBool,
+ stream_mid_error: AtomicBool,
+ stream_terminal_failure: Mutex<Option<&'static str>>,
dispatched: Mutex<Vec<Dispatched>>,
}
@@ -125,6 +128,15 @@ impl RecordingDispatcher {
self.generate_refused.store(true, Ordering::SeqCst);
}
+ pub(crate) fn fail_stream(&self, after_output: bool) {
+ self.stream_error.store(true, Ordering::SeqCst);
+ self.stream_mid_error.store(after_output, Ordering::SeqCst);
+ }
+
+ pub(crate) fn fail_stream_terminal(&self, reason: &'static str) {
+ *self.stream_terminal_failure.lock().unwrap() = Some(reason);
+ }
+
fn record(&self, dispatched: Dispatched) {
self.dispatched.lock().unwrap().push(dispatched);
}
@@ -148,14 +160,36 @@ fn terminal_chunk_collector(
) -> (
oneshot::Receiver<StreamOutcome>,
broadcast::Receiver<ChunkEnvelope>,
+) {
+ stream_chunk_collector(display_model, bundle_config_hash, false, false, None)
+}
+
+fn stream_chunk_collector(
+ display_model: &str,
+ bundle_config_hash: &str,
+ fail: bool,
+ after_output: bool,
+ terminal_failure: Option<&str>,
+) -> (
+ oneshot::Receiver<StreamOutcome>,
+ broadcast::Receiver<ChunkEnvelope>,
) {
let (tx, rx) = oneshot::channel();
let mut collector = StreamCollector::new(tx, display_model.to_string(), "default".to_string());
let tap = collector.install_chunk_tap();
+ if fail && after_output {
+ let delta = serde_json::from_value(json!({
+ "kind":"chunk", "request_id":"request-1", "attempt_id":"attempt-1",
+ "seq":0, "text_delta":"ok", "done":false, "is_first":true,
+ }))
+ .unwrap();
+ assert_eq!(collector.apply(delta), ChunkApplied::Delta);
+ }
let terminal = serde_json::from_value(json!({
"kind": "chunk", "request_id": "request-1", "attempt_id": "attempt-1",
- "seq": 0, "text_delta": "ok", "done": true, "is_first": true,
- "finish_reason": "stop",
+ "seq": u64::from(fail && after_output), "text_delta": if fail || terminal_failure.is_some() {""} else {"ok"}, "done": true, "is_first": !(fail && after_output),
+ "finish_reason": terminal_failure.unwrap_or(if fail {"error"} else {"stop"}),
+ "error": if fail {json!({"code":"inference_error","message":"private upstream failure"})} else {json!(null)},
"usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
"executed_bundle_config_hash": bundle_config_hash,
}))
@@ -272,7 +306,16 @@ impl WorkDispatcher for RecordingDispatcher {
String,
> {
self.record(Dispatched::new("generate", &target));
- let (rx, tap) = terminal_chunk_collector(display_model, bundle_config_hash);
+ if self.generate_refused.load(Ordering::SeqCst) {
+ return Err("private upstream failure".into());
+ }
+ let (rx, tap) = stream_chunk_collector(
+ display_model,
+ bundle_config_hash,
+ self.stream_error.load(Ordering::SeqCst),
+ self.stream_mid_error.load(Ordering::SeqCst),
+ *self.stream_terminal_failure.lock().unwrap(),
+ );
Ok((
"request-1".to_string(),
rx,
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index ce64a338c..a3f45b589 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -49,7 +49,7 @@ A request that names a profile bypasses the bare-model policy, including an
explicit `default`. Single-node OpenAI hybrid `encode` and `score` require the
operator-owned equivalence admission described below. SIE hybrid encode and
score require the fresh identity admission described below; `threshold` remains
-a separate delivery. Cluster remote profiles use the queue. Buffered cluster
+a separate delivery. Cluster remote profiles use the queue. Cluster
generation fallback is described below; other cluster bridge surfaces remain
separate deliveries.
@@ -376,11 +376,12 @@ error. After the first event the stream reports failure without replaying work.
An explicitly named remote profile is served directly.
-## Cluster buffered generation fallback
+## Cluster generation fallback
A bare generation model with `routing: {policy: fallback, fallback_profile: remote}`
can bridge `provisioning` and `model_loading` refusals on native generation,
-chat, completions and supported buffered Responses. Explicit profiles, bundle
+chat, completions and supported buffered Responses. Native generation, chat
+and completions also support streaming bridges. Explicit profiles, bundle
pins, machine or pool overrides, and `X-SIE-Remote: forbid` retain their selected
route. Deployment-governed routes require separate admission.
@@ -396,5 +397,11 @@ pool subject. Remote failure restores the original local refusal body and
`X-SIE-Fallback-Error`; success discloses the remote profile's upstream. The
customer model name remains the requested model.
-Streaming, extraction, numerical fleet equivalence, and opt-in saturation or
-unhealthy spill are not activated by this buffered generation path.
+A streaming bridge waits for its first valid event before returning HTTP success.
+A worker error, cancelled/failed terminal, transport failure or durability failure
+before output restores the local refusal. Once an event is ready, subsequent
+errors remain in the stream, with cleanup and no replay of inference. Explicit
+profiles keep ordinary streaming behavior.
+
+Extraction, numerical fleet equivalence, and opt-in saturation or unhealthy
+spill are not activated by this generation path.