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): carry the fallback reason on every bridged work item (#567)

Krisztian Gajdar8823a895228f
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index 6320e3ca6..a6f55f543 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -421,7 +421,7 @@ The `ConfigNotification` JSON payload carries the following fields, verified aga
The hot path is always **msgpack** (`rmp_serde` on the gateway, `msgpack-python` / `msgpack-numpy` on workers). Specifically:
-- `WorkItem` (gateway → worker on JetStream): msgpack. `model_id` is the route the work runs on. When routing dispatched the request to another route of the requested model (a profile variant), `display_model` carries the model id the caller asked for, so logs and accounting downstream can report it; it is omitted otherwise. `WorkDispatcher::publish_work` takes the same `display_model`.
+- `WorkItem` (gateway → worker on JetStream): msgpack. `model_id` is the route the work runs on. When routing dispatched the request to another route of the requested model (a profile variant), `display_model` carries the model id the caller asked for, so logs and accounting downstream can report it; it is omitted otherwise. `WorkDispatcher::publish_work` takes the same `display_model`. A remote attempt that stands in for a local refusal the gateway holds carries `fallback_reason`, the trigger of that refusal (`provisioning`, `model_loading`, `saturated` or `unhealthy`), on every fallback bridge and on a threshold bridge while local capacity wakes. The remote worker answers such an item it cannot serve now with a retryable error instead of redelivering it, so the gateway restores the local refusal at once. Other work, including a low-demand threshold route, omits the field.
- `WorkResult` (worker → gateway on the inbox subject): msgpack. Numpy arrays use `msgpack-numpy`'s extension-free encoding (maps with a `nd: true` sentinel + `type`, `shape`, `data`). When the gateway advertises `WorkItem.accepts_result_chunks: true`, a result that does not fit one NATS message may instead arrive as named-msgpack `result_chunk_v1` envelopes. This boolean negotiates v1 only; a future envelope version requires a new capability rather than reinterpreting the existing field. The gateway reassembles v1 transfers within the pending request lifetime, with a SHA-256 digest and fixed item/chunk/request/process memory limits, then decodes the reconstructed bytes as the same `WorkResult`. The gateway transcodes to native JSON arrays only when the client's `Accept` header asks for JSON.
JSON (`serde_json`) is used where payloads are low-frequency or human-oriented:
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 48b463712..99a5df58b 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -1867,6 +1867,13 @@ fn native_request_has_profile_selector(body: &[u8], msgpack: bool) -> bool {
#[derive(Clone)]
struct RemoteFallbackOverride(crate::state::model_registry::RemoteFallbackPlan);
+/// The trigger a bridged remote attempt carries to its worker. A remote route
+/// with no held local refusal, such as a low-demand threshold route, has none.
+fn bridged_fallback_reason(ext: &axum::http::Extensions) -> Option<FallbackTrigger> {
+ ext.get::<RemoteFallbackOverride>()?;
+ ext.get::<FallbackAttempt>()?.trigger()
+}
+
/// The routing decision for a request: canonical model name, serving bundle,
/// and engine. Produced by [`resolve_routing`].
struct RoutingResult {
@@ -3686,6 +3693,7 @@ async fn queue_mode_proxy(
};
params.require_execution_authority_v1 = require_execution_authority_v1;
+ params.fallback_reason = bridged_fallback_reason(request_extensions);
if items.is_empty() && endpoint != "score" && endpoint != "generate" {
return endpoint_error_response(
@@ -7723,6 +7731,7 @@ pub(crate) fn resolve_model_and_bundle(
struct ResolvedRoute {
dispatch_model: String,
require_execution_authority_v1: bool,
+ fallback_reason: Option<FallbackTrigger>,
physical_lane: PhysicalLane,
bundle: String,
gpu: String,
@@ -8263,6 +8272,7 @@ async fn resolve_generation_route(
hdr,
customer_model,
) || bridge.is_some(),
+ fallback_reason: bridged_fallback_reason(ext),
physical_lane,
bundle,
gpu,
@@ -8703,6 +8713,7 @@ async fn proxy_chat_inner(
let ResolvedRoute {
dispatch_model,
require_execution_authority_v1,
+ fallback_reason,
physical_lane,
bundle,
gpu,
@@ -8744,6 +8755,7 @@ async fn proxy_chat_inner(
let stream_include_usage = params.stream_include_usage;
let mut work_params = params.into_work_params();
work_params.require_execution_authority_v1 = require_execution_authority_v1;
+ work_params.fallback_reason = fallback_reason;
// SSE branch — when `stream: true` we hand off to the SSE
// response builder. The non-streaming aggregating path below is
@@ -9382,6 +9394,7 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response
let ResolvedRoute {
dispatch_model,
require_execution_authority_v1,
+ fallback_reason,
physical_lane,
bundle,
gpu,
@@ -9419,6 +9432,7 @@ async fn proxy_completions_inner(state: Arc<AppState>, req: Request) -> Response
let stream_include_usage = params.stream_include_usage;
let mut work_params = params.into_work_params();
work_params.require_execution_authority_v1 = require_execution_authority_v1;
+ work_params.fallback_reason = fallback_reason;
// SSE streaming → emit `text_completion` chunks. Single-candidate
// (completions rejects n>1), so no per-candidate interleave.
@@ -10046,6 +10060,7 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {
let ResolvedRoute {
dispatch_model,
require_execution_authority_v1,
+ fallback_reason,
physical_lane,
bundle,
gpu,
@@ -10080,6 +10095,7 @@ async fn proxy_responses_inner(state: Arc<AppState>, req: Request) -> Response {
let mut work_params = params.into_work_params();
work_params.require_execution_authority_v1 = require_execution_authority_v1;
+ work_params.fallback_reason = fallback_reason;
let driver = run_streaming_generate(
&state,
@@ -12253,6 +12269,7 @@ fn work_params_from_json(
generate: None,
routing_key: None,
prompt_cache_key: None,
+ fallback_reason: None,
});
}
@@ -12307,6 +12324,7 @@ fn work_params_from_json(
generate: None,
routing_key: None,
prompt_cache_key: None,
+ fallback_reason: None,
})
}
@@ -13153,6 +13171,7 @@ fn work_params_from_rmpv(
generate: None,
routing_key: None,
prompt_cache_key: None,
+ fallback_reason: None,
});
}
@@ -13213,6 +13232,7 @@ fn work_params_from_rmpv(
generate: None,
routing_key: None,
prompt_cache_key: None,
+ fallback_reason: None,
})
}
diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rs
index f98fde9d5..5332981f3 100644
--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs
+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs
@@ -190,6 +190,17 @@ impl FallbackAttempt {
.is_some()
}
+ /// The trigger of the local refusal this request's remote attempt stands
+ /// in for, while that refusal is held.
+ pub(crate) fn trigger(&self) -> Option<FallbackTrigger> {
+ self.0
+ .lock()
+ .unwrap_or_else(PoisonError::into_inner)
+ .original
+ .as_ref()
+ .map(|original| original.trigger)
+ }
+
/// Called after normal disclosure stamping and before HTTP success/output.
/// A failed bridge preserves the original body and Retry-After verbatim.
pub(crate) fn finish(&self, mut response: Response) -> Response {
@@ -1599,6 +1610,169 @@ mod tests {
assert!(gateway.dispatcher.dispatched().is_empty());
}
+ #[tokio::test]
+ async fn every_bridged_work_item_carries_the_trigger_of_the_refusal_it_stands_in_for() {
+ for trigger in [
+ FallbackTrigger::Provisioning,
+ FallbackTrigger::ModelLoading,
+ FallbackTrigger::Saturated,
+ FallbackTrigger::Unhealthy,
+ ] {
+ let routing = format!(
+ "\nrouting:\n policy: fallback\n fallback_profile: remote\n triggers: [{}]\n",
+ trigger.as_str()
+ );
+ let generate = format!("{HYBRID_GENERATE_MODEL}{routing}");
+ let extract = format!("{HYBRID_EXTRACT_MODEL}{routing}");
+ let gateway = TestGateway::new(&[&generate, &extract]).await;
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ let loaded = ["acme/chat", "acme/extract"];
+ match trigger {
+ FallbackTrigger::Provisioning => {}
+ FallbackTrigger::ModelLoading => {
+ gateway
+ .add_verified_worker("local-1", LOCAL_LANE, &[])
+ .await;
+ }
+ FallbackTrigger::Saturated => {
+ gateway
+ .add_saturated_worker("local-1", LOCAL_LANE, &loaded)
+ .await;
+ }
+ FallbackTrigger::Unhealthy => {
+ gateway
+ .add_verified_worker("local-1", LOCAL_LANE, &loaded)
+ .await;
+ gateway
+ .state
+ .registry
+ .mark_unhealthy("http://local-1:8080")
+ .await;
+ }
+ }
+ let mut responses = Vec::new();
+ for surface in ["native", "chat", "completions", "responses"] {
+ responses.push(buffered_surface(&gateway, surface, json!({})).await);
+ }
+ for (uri, body) in [
+ (
+ "/v1/generate/acme/chat",
+ json!({"prompt":"hello", "max_new_tokens":4, "stream":true}),
+ ),
+ (
+ "/v1/chat/completions",
+ json!({"model":"acme/chat", "messages":[{"role":"user", "content":"hello"}], "stream":true}),
+ ),
+ (
+ "/v1/completions",
+ json!({"model":"acme/chat", "prompt":"hello", "max_tokens":4, "stream":true}),
+ ),
+ ] {
+ let state = State(Arc::clone(&gateway.state));
+ let request = json_request(uri, body);
+ responses.push(match uri {
+ "/v1/generate/acme/chat" => proxy_request(state, request, "generate").await,
+ "/v1/chat/completions" => proxy_chat(state, request).await,
+ _ => proxy_completions(state, request).await,
+ });
+ }
+ responses.push(
+ proxy_request(
+ State(Arc::clone(&gateway.state)),
+ extraction_request(false, json!({})),
+ "extract",
+ )
+ .await,
+ );
+ let bridged = responses.len();
+ for response in responses {
+ assert_eq!(response.status(), StatusCode::OK, "{trigger:?}");
+ assert_eq!(
+ response.headers()["x-sie-fallback-reason"],
+ trigger.as_str()
+ );
+ let _ = axum::body::to_bytes(response.into_body(), 16384)
+ .await
+ .unwrap();
+ }
+ assert!(gateway
+ .dispatcher
+ .dispatched()
+ .iter()
+ .filter(|work| work.endpoint != "load")
+ .all(|work| work.bundle == REMOTE_LANE.2));
+ assert_eq!(
+ gateway.dispatcher.fallback_reasons(),
+ vec![Some(trigger); bridged],
+ "{trigger:?}"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn a_remote_attempt_refused_by_its_upstream_restores_the_local_refusal_at_once() {
+ let config = format!(
+ "{HYBRID_EXTRACT_MODEL}\nrouting:\n policy: fallback\n fallback_profile: remote\n"
+ );
+ for (refusal, remote_code, retry_after_s) in [
+ ("capped", "QUEUE_FULL", 1),
+ ("breaker_open", "QUEUE_FULL", 60),
+ ("not_ready", "QUEUE_FULL", 5),
+ ("not_ready", "MODEL_LOADING", 5),
+ ] {
+ for local in ["cold", "loading"] {
+ let gateway = TestGateway::new(&[&config]).await;
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ if local == "loading" {
+ gateway
+ .add_verified_worker("local-1", LOCAL_LANE, &[])
+ .await;
+ }
+ gateway
+ .dispatcher
+ .answer_only_bridged_remote_work(remote_code, retry_after_s);
+ let response = tokio::time::timeout(
+ Duration::from_secs(5),
+ proxy_request(
+ State(Arc::clone(&gateway.state)),
+ extraction_request(false, json!({})),
+ "extract",
+ ),
+ )
+ .await
+ .unwrap_or_else(|_| {
+ panic!("{refusal}/{remote_code}/{local}: the local refusal waited")
+ });
+ let (trigger, retry_after, code) = if local == "cold" {
+ ("provisioning", "60", "PROVISIONING")
+ } else {
+ ("model_loading", "5", "MODEL_LOADING")
+ };
+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
+ assert_eq!(response.headers()["retry-after"], retry_after);
+ assert_eq!(response.headers()["x-sie-fallback-reason"], trigger);
+ assert!(response.headers().contains_key("x-sie-fallback-error"));
+ assert_eq!(stamped(&response), (Some("local"), None));
+ let body: serde_json::Value = serde_json::from_slice(
+ &axum::body::to_bytes(response.into_body(), 8192)
+ .await
+ .unwrap(),
+ )
+ .unwrap();
+ let detail = body.get("detail").unwrap_or(&body["error"]);
+ assert_eq!(detail["code"], code, "{refusal}/{local}");
+ assert_eq!(
+ gateway.dispatcher.dispatched().last().unwrap(),
+ &dispatched("extract", REMOTE_LANE, "acme/extract:remote")
+ );
+ }
+ }
+ }
+
fn stamped(response: &Response) -> (Option<&str>, Option<&str>) {
let header = |name: &HeaderName| {
response
@@ -1972,6 +2146,7 @@ mod tests {
&& work.model.ends_with(":remote")
&& work.endpoint != "load"));
assert_eq!(gateway.dispatcher.execution_authority(), vec![true; 6]);
+ assert_eq!(gateway.dispatcher.fallback_reasons(), vec![None; 6]);
for surface in ["native", "chat", "completions"] {
let state = State(Arc::clone(&gateway.state));
@@ -1990,6 +2165,7 @@ mod tests {
}
assert!(gateway.state.demand_tracker.active_lanes().is_empty());
assert_eq!(gateway.dispatcher.execution_authority(), vec![true; 9]);
+ assert_eq!(gateway.dispatcher.fallback_reasons(), vec![None; 9]);
// Demand from two gateways reaches one decision, rather than dividing
// the configured rate independently at each gateway.
@@ -2026,6 +2202,10 @@ mod tests {
dispatched("generate", REMOTE_LANE, "acme/chat:remote"),
]
);
+ assert_eq!(
+ gateway.dispatcher.fallback_reasons().last(),
+ Some(&Some(FallbackTrigger::ModelLoading))
+ );
gateway
.add_verified_worker("local-1", LOCAL_LANE, &["acme/chat"])
.await;
@@ -2036,6 +2216,7 @@ mod tests {
gateway.dispatcher.dispatched().last().unwrap().model,
"acme/chat"
);
+ assert_eq!(gateway.dispatcher.fallback_reasons().last(), Some(&None));
}
#[tokio::test]
async fn threshold_authority_preserves_selectors_validation_and_configuration_fences() {
diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rs
index 4612fd307..e3056c927 100644
--- a/packages/sie_gateway/src/handlers/test_support.rs
+++ b/packages/sie_gateway/src/handlers/test_support.rs
@@ -23,6 +23,7 @@ use crate::state::demand_tracker::{DemandTracker, PhysicalLane, PhysicalLaneCata
use crate::state::model_registry::ModelRegistry;
use crate::state::pool_manager::PoolManager;
use crate::state::worker_registry::WorkerRegistry;
+use crate::types::model::FallbackTrigger;
use crate::types::WorkerStatusMessage;
/// The local lane's `(pool, machine_profile, bundle)`.
@@ -162,8 +163,11 @@ pub(crate) struct RecordingDispatcher {
stream_mid_error: AtomicBool,
stream_terminal_failure: Mutex<Option<&'static str>>,
remote_refusal: Mutex<Option<(&'static str, Option<u32>)>>,
+ bridged_refusal: Mutex<Option<(&'static str, u32)>>,
+ redelivered: Mutex<Vec<oneshot::Sender<Vec<WorkResult>>>>,
dispatched: Mutex<Vec<Dispatched>>,
execution_authority: Mutex<Vec<bool>>,
+ fallback_reasons: Mutex<Vec<Option<FallbackTrigger>>>,
}
impl RecordingDispatcher {
@@ -181,6 +185,19 @@ impl RecordingDispatcher {
self.execution_authority.lock().unwrap().clone()
}
+ /// The fallback reason each published work request carried, in order.
+ pub(crate) fn fallback_reasons(&self) -> Vec<Option<FallbackTrigger>> {
+ self.fallback_reasons.lock().unwrap().clone()
+ }
+
+ /// Answer remote-lane work the way a remote worker whose backend asks for
+ /// redelivery does: a remote attempt that carries a fallback reason gets a
+ /// retryable `code` result with the upstream's hint at once, while other
+ /// work is redelivered, so its result never arrives.
+ pub(crate) fn answer_only_bridged_remote_work(&self, code: &'static str, retry_after_s: u32) {
+ *self.bridged_refusal.lock().unwrap() = Some((code, retry_after_s));
+ }
+
/// Behave as a transport that cannot keep the execution-authority fence.
pub(crate) fn withdraw_execution_authority(&self) {
self.without_execution_authority
@@ -357,10 +374,29 @@ impl WorkDispatcher for RecordingDispatcher {
> {
self.record_authority(&target, params);
self.record(Dispatched::new(endpoint, &target));
+ self.fallback_reasons
+ .lock()
+ .unwrap()
+ .push(params.fallback_reason);
if self.work_refused.load(Ordering::SeqCst) {
return Err(DispatchError::Other("private upstream failure".into()));
}
let request_id = "request-1".to_string();
+ let bridged_refusal = *self.bridged_refusal.lock().unwrap();
+ if let Some((code, retry_after_s)) =
+ bridged_refusal.filter(|_| target.bundle() == REMOTE_LANE.2)
+ {
+ let (tx, rx) = oneshot::channel();
+ if params.fallback_reason.is_some() {
+ let refused = (0..items.len().max(1) as u32)
+ .map(|index| refused_result(&request_id, index, (code, Some(retry_after_s))))
+ .collect();
+ tx.send(refused).unwrap();
+ } else {
+ self.redelivered.lock().unwrap().push(tx);
+ }
+ return Ok((request_id, rx, DispatchDurability::accepted()));
+ }
let remote_refusal = *self.remote_refusal.lock().unwrap();
let results = if let Some(refusal) =
remote_refusal.filter(|_| target.bundle() == REMOTE_LANE.2)
@@ -422,6 +458,10 @@ impl WorkDispatcher for RecordingDispatcher {
}
self.record_authority(&target, params);
self.record(Dispatched::new("generate", &target));
+ self.fallback_reasons
+ .lock()
+ .unwrap()
+ .push(params.fallback_reason);
let (rx, _tap) = terminal_chunk_collector(display_model, bundle_config_hash);
Ok((
"request-1".to_string(),
@@ -450,6 +490,10 @@ impl WorkDispatcher for RecordingDispatcher {
> {
self.record_authority(&target, params);
self.record(Dispatched::new("generate", &target));
+ self.fallback_reasons
+ .lock()
+ .unwrap()
+ .push(params.fallback_reason);
if self.generate_refused.load(Ordering::SeqCst) {
return Err("private upstream failure".into());
}
diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rs
index 3a970fb5b..55dff6680 100644
--- a/packages/sie_gateway/src/queue/publisher.rs
+++ b/packages/sie_gateway/src/queue/publisher.rs
@@ -30,6 +30,7 @@ use crate::endpoint::InferenceEndpoint;
use crate::observability::metrics::{
self as telemetry, QueueEvent, QueueEventOutcome, QueuePublishObservation, QueuePublishOutcome,
};
+use crate::types::model::FallbackTrigger;
const PAYLOAD_OFFLOAD_THRESHOLD: usize = 1_024 * 1_024; // 1 MB
/// Public queue request contract. This is deliberately much larger than the
@@ -199,6 +200,11 @@ pub struct WorkParams {
/// Prompt-cache hint. Same semantics as
/// :attr:`routing_key`.
pub prompt_cache_key: Option<String>,
+ /// The trigger of the local refusal a remote attempt stands in for. The
+ /// worker answers such an item instead of redelivering it, because the
+ /// gateway holds that refusal for the caller.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub fallback_reason: Option<FallbackTrigger>,
}
/// Discriminated input for a generate work item.
@@ -562,6 +568,10 @@ struct WorkItemRef<'a> {
/// workers ignore the unknown map field.
#[serde(skip_serializing_if = "Option::is_none")]
pub deadline: Option<f64>,
+ /// Present only on a remote attempt that stands in for a local refusal.
+ /// Older workers ignore the unknown map field.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub fallback_reason: Option<FallbackTrigger>,
/// Rolling-upgrade negotiation for `result_chunk_v1` specifically. Older
/// workers ignore this unknown map field; workers must keep publishing the
/// legacy one-shot ``WorkResult`` unless it is true. A future chunk version
@@ -3042,6 +3052,7 @@ impl WorkPublisher {
reply_subject: &reply_subject,
timestamp,
deadline: Some(timestamp + self.result_timeout.as_secs_f64()),
+ fallback_reason: None,
accepts_result_chunks: false,
traceparent: None,
tracestate: None,
@@ -3562,6 +3573,7 @@ impl WorkPublisher {
reply_subject: shared.reply_subject,
timestamp: shared.timestamp,
deadline: shared.deadline,
+ fallback_reason: shared.params.fallback_reason,
accepts_result_chunks: true,
traceparent: shared.traceparent,
tracestate: shared.tracestate,
@@ -4192,6 +4204,7 @@ impl WorkPublisher {
reply_subject: shared.reply_subject,
timestamp: shared.timestamp,
deadline: shared.deadline,
+ fallback_reason: shared.params.fallback_reason,
accepts_result_chunks: true,
traceparent: shared.traceparent,
tracestate: shared.tracestate,
@@ -4488,6 +4501,7 @@ impl WorkPublisher {
reply_subject: shared.reply_subject,
timestamp: shared.timestamp,
deadline: shared.deadline,
+ fallback_reason: shared.params.fallback_reason,
accepts_result_chunks: true,
traceparent: shared.traceparent,
tracestate: shared.tracestate,
@@ -6383,6 +6397,8 @@ mod tests {
pub timestamp: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub deadline: Option<f64>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub fallback_reason: Option<String>,
#[serde(default)]
pub accepts_result_chunks: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -7729,6 +7745,7 @@ mod tests {
reply_subject: "_INBOX.r1.req-1".to_string(),
timestamp: 1700000000.0,
deadline: None,
+ fallback_reason: None,
accepts_result_chunks: true,
traceparent: None,
tracestate: None,
@@ -7737,14 +7754,17 @@ mod tests {
let encoded = rmp_serde::to_vec_named(&item).unwrap();
let decoded: WorkItem = rmp_serde::from_slice(&encoded).unwrap();
let wire: rmpv::Value = rmp_serde::from_slice(&encoded).unwrap();
- assert!(
- wire.as_map()
- .unwrap()
- .iter()
- .all(|(key, _)| key.as_str() != Some("deadline")),
- "an unknown deadline must stay off the wire"
- );
+ for absent in ["deadline", "fallback_reason"] {
+ assert!(
+ wire.as_map()
+ .unwrap()
+ .iter()
+ .all(|(key, _)| key.as_str() != Some(absent)),
+ "an absent {absent} must stay off the wire"
+ );
+ }
assert_eq!(decoded.deadline, None);
+ assert_eq!(decoded.fallback_reason, None);
assert_eq!(decoded.work_item_id, "req-1.0");
assert_eq!(decoded.request_id, "req-1");
@@ -7861,6 +7881,7 @@ mod tests {
reply_subject: "_INBOX.router-1.req-ref".to_string(),
timestamp: 1_700_000_000.5,
deadline: Some(1_700_000_120.5),
+ fallback_reason: Some("saturated".to_string()),
accepts_result_chunks: true,
traceparent: None,
tracestate: None,
@@ -7904,6 +7925,7 @@ mod tests {
reply_subject: &owned.reply_subject,
timestamp: owned.timestamp,
deadline: owned.deadline,
+ fallback_reason: Some(FallbackTrigger::Saturated),
accepts_result_chunks: true,
traceparent: owned.traceparent.as_deref(),
tracestate: owned.tracestate.as_deref(),
@@ -8086,6 +8108,7 @@ mod tests {
reply_subject: "_INBOX.r1.req-2".to_string(),
timestamp: 0.0,
deadline: None,
+ fallback_reason: None,
accepts_result_chunks: true,
traceparent: None,
tracestate: None,
@@ -8773,6 +8796,7 @@ mod tests {
reply_subject: "_INBOX.r.req-x".to_string(),
timestamp: 1.0,
deadline: None,
+ fallback_reason: None,
accepts_result_chunks: true,
traceparent: None,
tracestate: None,
@@ -8925,6 +8949,7 @@ mod tests {
reply_subject: "_INBOX.r.req-tp".to_string(),
timestamp: 1.0,
deadline: None,
+ fallback_reason: None,
accepts_result_chunks: true,
traceparent: Some(tp.to_string()),
tracestate: Some(ts.to_string()),
@@ -8972,6 +8997,7 @@ mod tests {
reply_subject: "_INBOX.r.req-tp2".to_string(),
timestamp: 1.0,
deadline: None,
+ fallback_reason: None,
accepts_result_chunks: true,
traceparent: None,
tracestate: None,
@@ -9548,6 +9574,136 @@ mod tests {
.await;
}
+ /// NATS-gated: a remote attempt carries the trigger of the refusal it
+ /// stands in for, on the batch and on the generation publish path alike;
+ /// other work carries none.
+ #[tokio::test]
+ async fn remote_attempts_carry_their_fallback_reason_on_the_wire() {
+ use futures_util::StreamExt;
+
+ let Ok(url) = std::env::var("NATS_URL") else {
+ assert_ne!(
+ std::env::var("SIE_RUN_NATS_PUBLISHER_TEST").as_deref(),
+ Ok("1"),
+ "mandatory publisher tests require NATS_URL"
+ );
+ return;
+ };
+ let client = async_nats::connect(url)
+ .await
+ .expect("test NATS connection");
+ let pool = format!("itfallback{}", uuid::Uuid::now_v7().simple());
+ let publisher = Arc::new(WorkPublisher::new(
+ jetstream::new(client.clone()),
+ "it-router".to_string(),
+ Arc::new(crate::queue::payload_store::DisabledPayloadStore),
+ Duration::from_secs(5),
+ 1024,
+ WorkStreamConfig {
+ max_age: Duration::from_secs(300),
+ storage: jetstream::stream::StorageType::Memory,
+ num_replicas: 1,
+ },
+ ));
+ let subjects = format!("sie.work.{pool}.>");
+ let stream = jetstream::new(client.clone())
+ .get_or_create_stream(jetstream::stream::Config {
+ name: stream_name(&pool),
+ subjects: vec![subjects.clone()],
+ retention: jetstream::stream::RetentionPolicy::WorkQueue,
+ storage: jetstream::stream::StorageType::Memory,
+ max_age: Duration::from_secs(300),
+ max_messages: 100_000,
+ discard: jetstream::stream::DiscardPolicy::New,
+ ..Default::default()
+ })
+ .await
+ .expect("create work stream");
+ stream
+ .create_consumer(jetstream::consumer::pull::Config {
+ durable_name: Some("itworker".to_string()),
+ filter_subject: subjects.clone(),
+ ..Default::default()
+ })
+ .await
+ .expect("create work consumer");
+ let mut sub = client.subscribe(subjects).await.expect("subscribe");
+ client.flush().await.expect("flush");
+ let target = || PublishTarget::Pool {
+ pool: pool.clone(),
+ machine_profile: "cpu".to_string(),
+ bundle: "remote".to_string(),
+ model: "acme/model:remote".to_string(),
+ };
+ async fn next_reason(sub: &mut async_nats::Subscriber) -> Option<String> {
+ let msg = tokio::time::timeout(Duration::from_secs(5), sub.next())
+ .await
+ .expect("timed out waiting for the published work item")
+ .expect("subscription closed before a message arrived");
+ let work: WorkItem = rmp_serde::from_slice(&msg.payload).expect("decode work item");
+ work.fallback_reason
+ }
+
+ let mut published = Vec::new();
+ let mut expected = Vec::new();
+ for reason in [
+ None,
+ Some(FallbackTrigger::Provisioning),
+ Some(FallbackTrigger::ModelLoading),
+ Some(FallbackTrigger::Saturated),
+ Some(FallbackTrigger::Unhealthy),
+ ] {
+ let items = vec![rmpv::Value::Map(vec![(
+ rmpv::Value::from("text"),
+ rmpv::Value::from("hello"),
+ )])];
+ let extract = WorkParams {
+ fallback_reason: reason,
+ ..WorkParams::default()
+ };
+ let (_request_id, _rx, durability) = publisher
+ .publish_work(
+ target(),
+ &pool,
+ "extract",
+ "acme/model:remote",
+ "acme/model",
+ "pytorch",
+ "",
+ items,
+ &extract,
+ )
+ .await
+ .expect("publish_work");
+ durability.wait().await.expect("durable publish ACK");
+ published.push(next_reason(&mut sub).await);
+ let generate = WorkParams {
+ generate: Some(GenerateParams {
+ input: GenerateInput::Prompt {
+ prompt: "hi".to_string(),
+ },
+ max_new_tokens: 4,
+ ..Default::default()
+ }),
+ fallback_reason: reason,
+ ..WorkParams::default()
+ };
+ let (_request_id, _rx, _notify, durability) = publisher
+ .publish_generate_streaming(target(), "acme/model", "pytorch", "", &generate, &pool)
+ .await
+ .expect("publish_generate_streaming");
+ durability.wait().await.expect("durable publish ACK");
+ published.push(next_reason(&mut sub).await);
+ let wire = reason.map(|reason| reason.as_str().to_string());
+ expected.extend([wire.clone(), wire]);
+ }
+
+ assert_eq!(published, expected);
+ let _ = jetstream::new(client.clone())
+ .delete_stream(stream_name(&pool))
+ .await;
+ }
+
/// Integration test (issue #1500): drive a real `WorkPublisher` encode
/// publish over a live NATS/JetStream broker, with the inbound trace
/// context scoped over the publish via `with_context` exactly as
@@ -9668,6 +9824,7 @@ mod tests {
generate: None,
routing_key: None,
prompt_cache_key: None,
+ fallback_reason: None,
};
let items = vec![rmpv::Value::Map(vec![(
rmpv::Value::String("text".into()),
@@ -9949,6 +10106,7 @@ mod tests {
generate: None,
routing_key: None,
prompt_cache_key: None,
+ fallback_reason: None,
};
let items = vec![rmpv::Value::Map(vec![(
rmpv::Value::String("image".into()),
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index 928a18d9c..88dda4a88 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -493,7 +493,9 @@ caller receives the local loading refusal. A loaded local model serves locally.
The remote attempt pins a fresh worker with the exact current configuration
hash and positive versioned execution capability. It cannot retry on the ordinary
-pool subject. Remote failure restores the original local refusal body and
+pool subject. Its work item names the trigger in `fallback_reason`, so the remote
+worker answers it at once whenever it cannot serve it now, rather than
+redelivering it until the gateway's request timeout. Remote failure restores the original local refusal body and
`Retry-After`, with `X-SIE-Fallback-Reason` and a bounded
`X-SIE-Fallback-Error`; success discloses the remote profile's upstream. The
customer model name remains the requested model.
diff --git a/packages/sie_server_sidecar/docs/architecture-guide.md b/packages/sie_server_sidecar/docs/architecture-guide.md
index a3e047724..561ecdb46 100644
--- a/packages/sie_server_sidecar/docs/architecture-guide.md
+++ b/packages/sie_server_sidecar/docs/architecture-guide.md
@@ -72,16 +72,18 @@ Message settlement:
- A `load` work item carries no input. It goes through the same admission,
config and readiness checks as other work for that model. Once
`EnsureModelReady` reports ready, it is ACKed without inference or a result.
- This is the NATS worker-side warm-up primitive; the gateway does not yet
- produce these items. Local-ingest `publish_work` rejects `load` before
+ This is the NATS worker-side warm-up primitive; the gateway publishes one
+ before a `model_loading` bridge. Local-ingest `publish_work` rejects `load` before
dispatch because that request/response lane requires a result.
-- A work item may carry `fallback_reason` for a future gateway remote fallback
- attempt. If the backend returns `nak_retry`, the sidecar publishes an error
- result with the outcome's `error_code` (`QUEUE_FULL` when absent) and
- `retry_after_s` (the NAK delay rounded up to seconds when absent), then ACKs
- after successful publication. Ordinary items retain NAK behavior. Admission,
- config/readiness barriers and failed result publication retain their existing
- retry behavior; this does not yet provide the full cluster fallback contract.
+- The gateway sets `fallback_reason` on a remote attempt that stands in for a
+ local refusal it holds: every fallback bridge, and a threshold bridge while
+ local capacity wakes. If the backend returns `nak_retry` for such an item,
+ the sidecar publishes an error result with the outcome's `error_code`
+ (`QUEUE_FULL` when absent) and `retry_after_s` (the NAK delay rounded up to
+ seconds when absent), then ACKs after successful publication, so the gateway
+ restores its local refusal at once. Ordinary items retain NAK behavior.
+ Admission, config/readiness barriers and failed result publication retain
+ their existing retry behavior.
- An outcome's optional `retry_after_s` is published on the `WorkResult`
unchanged. For a `QUEUE_FULL`, `MODEL_LOADING` or `RESOURCE_EXHAUSTED`
answer the gateway uses a hint of 1 to 60 seconds as `Retry-After`; without
diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rs
index 2e1c5bd10..af98a9223 100644
--- a/packages/sie_server_sidecar/src/dispatcher.rs
+++ b/packages/sie_server_sidecar/src/dispatcher.rs
@@ -6652,6 +6652,43 @@ mod tests {
assert_eq!(result.retry_after_s, Some(7));
}
+ #[tokio::test]
+ async fn a_gateway_bridge_whose_upstream_refuses_is_answered_with_the_upstreams_wait() {
+ let fixture: serde_json::Value =
+ serde_json::from_str(include_str!("../../wire-fixtures/serving_disclosure.json"))
+ .unwrap();
+ let dispatcher = dispatcher_with_backend(naking_backend(
+ Some(QUEUE_FULL_ERROR_CODE),
+ Some(7),
+ Some(base_nak_delay_ms()),
+ ));
+ for trigger in fixture["response_headers"]["fallback_reason"]["values"]
+ .as_array()
+ .unwrap()
+ {
+ let mut wire: rmpv::Value = rmp_serde::from_slice(
+ &rmp_serde::to_vec_named(&wi("bridge", 0, "acme/model:remote", "encode")).unwrap(),
+ )
+ .unwrap();
+ let rmpv::Value::Map(fields) = &mut wire else {
+ unreachable!("a work item is a msgpack map")
+ };
+ fields.push(("fallback_reason".into(), trigger.as_str().unwrap().into()));
+ let work: WorkItem =
+ rmp_serde::from_slice(&rmp_serde::to_vec_named(&wire).unwrap()).unwrap();
+
+ let events = settle_one(&dispatcher, work).await;
+
+ let [crate::delivery::LocalDeliveryEvent::Result { result, .. }] = events.as_slice()
+ else {
+ panic!("{trigger}: a bridged item must settle with a result: {events:?}");
+ };
+ assert!(!result.success);
+ assert_eq!(result.error_code.as_deref(), Some(QUEUE_FULL_ERROR_CODE));
+ assert_eq!(result.retry_after_s, Some(7), "{trigger}");
+ }
+ }
+
#[tokio::test]
async fn a_load_only_work_item_settles_once_its_model_is_ready_without_running() {
let backend = naking_backend(None, None, None);