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): bridge governed generation to the remote route a policy names (#607)

Krisztian Gajdare875a65eda3a
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.md
index 728ce7326..10a3ffe0b 100644
--- a/packages/sie_gateway/docs/architecture-guide.md
+++ b/packages/sie_gateway/docs/architecture-guide.md
@@ -1049,7 +1049,15 @@ model, so a caller who can see the remote profile can name it.
receives the answer it would have received without a remote route.
- **Without a policy.** The gateway's own checks decide.
- **Governed generation.** A policy that governs generation routes keeps
- generation local, because a governed route has no remote route.
+ generation local unless its `GenerationRoutePolicy::resolve_remote` names a
+ governed route for the model's remote profile and intent.
+ - The policy is asked once per request, so planning and the bridged
+ dispatch use the same route.
+ - A bridge is planned only when that route names the same model, bundle and
+ pool as the registry's remote plan, and its coordinates are ones the
+ gateway can dispatch on. The check runs before the policy's admission
+ hook and before a threshold request is counted as demand.
+ - The bridged request dispatches on that route, with its machine profile.
- **Model listing.** `/v1/models` and `/v1/models/{model}` show a bare model
to a caller who may not see its remote profile without that profile and with
the routing of a model that has no remote route, so the listing does not
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 10612ed36..fb21aa430 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -31,8 +31,8 @@ use crate::queue::streaming::{
};
use crate::server::{
- AppState, GenerationRequestIntent, GovernedGenerationRoute, ModelAccessPolicy,
- RemoteRouteReason,
+ AppState, GenerationRequestIntent, GenerationRoutePolicy, GovernedGenerationRoute,
+ ModelAccessPolicy, RemoteRouteReason,
};
use crate::state::demand_tracker::PhysicalLane;
use crate::state::model_registry::{ModelRegistry, ResolveError};
@@ -1717,6 +1717,46 @@ fn governed_generation_route(
"compiled physical model disagrees with registry intent rewrite",
));
}
+ checked_governed_route(state, customer_model, intent, route).map(Some)
+}
+
+/// The governed route a bridged generation request dispatches on: the
+/// deployment's remote route, which must still agree with the admitted plan.
+#[allow(clippy::result_large_err)]
+fn governed_bridge_route(
+ state: &AppState,
+ ext: &axum::http::Extensions,
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+ plan: &crate::state::model_registry::RemoteFallbackPlan,
+) -> Result<Option<GovernedGenerationRoute>, Response> {
+ if generation_route_policy(state).is_none() {
+ return Ok(None);
+ }
+ let Some(route) = governed_remote_route(state, ext, customer_model, intent) else {
+ return Err(governed_generation_route_failure(
+ customer_model,
+ intent,
+ "missing remote route for model/intent",
+ ));
+ };
+ if !remote_route_agrees(&route, plan) {
+ return Err(governed_generation_route_failure(
+ customer_model,
+ intent,
+ "remote route disagrees with the admitted bridge",
+ ));
+ }
+ checked_governed_route(state, customer_model, intent, route).map(Some)
+}
+
+#[allow(clippy::result_large_err)]
+fn checked_governed_route(
+ state: &AppState,
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+ route: GovernedGenerationRoute,
+) -> Result<GovernedGenerationRoute, Response> {
if route.bundle.trim().is_empty()
|| route.pool.trim().is_empty()
|| route.machine_profile.trim().is_empty()
@@ -1739,7 +1779,7 @@ fn governed_generation_route(
"route machine profile is absent from the configured GPU catalog",
));
}
- Ok(Some(route))
+ Ok(route)
}
/// Validate caller overrides against one exact deployment-owned route.
@@ -2066,13 +2106,19 @@ async fn resolve_routing(
});
}
if let Some(RemoteFallbackOverride(plan)) = ext.get::<RemoteFallbackOverride>() {
+ let governed = match generation_intent {
+ Some(intent) => {
+ governed_bridge_route(state, ext, &model_name, intent, plan).map_err(Box::new)?
+ }
+ None => None,
+ };
return Ok(RoutingResult {
caller_selected_route,
model_name,
dispatch_model: plan.model.clone(),
bundle: plan.bundle.clone(),
engine: plan.engine.clone(),
- gpu: String::new(),
+ gpu: governed.map_or_else(String::new, |route| route.machine_profile),
pool_name: plan.pool.clone(),
gpu_configured: true,
});
@@ -2303,6 +2349,7 @@ fn fallback_plan_for_request(
allowed: bool,
explicit_bundle: &str,
trigger: FallbackTrigger,
+ intent: GenerationRequestIntent,
) -> Option<crate::state::model_registry::RemoteFallbackPlan> {
fallback_plan_candidate(
state,
@@ -2312,6 +2359,7 @@ fn fallback_plan_for_request(
allowed,
explicit_bundle,
trigger,
+ Some(intent),
)
.filter(|plan| plan.numerical.is_none())
}
@@ -2327,6 +2375,7 @@ fn fallback_plan_candidate(
allowed: bool,
explicit_bundle: &str,
trigger: FallbackTrigger,
+ generation: Option<GenerationRequestIntent>,
) -> Option<crate::state::model_registry::RemoteFallbackPlan> {
let attempt = ext.get::<FallbackAttempt>()?;
if !allowed
@@ -2348,6 +2397,10 @@ fn fallback_plan_candidate(
state
.model_registry
.remote_fallback_plan(model, trigger)
+ .filter(|plan| {
+ generation
+ .is_none_or(|intent| governed_generation_plan(state, ext, model, intent, plan))
+ })
.filter(|plan| {
remote_route_admitted(state, ext, plan, RemoteRouteReason::Fallback(trigger))
})
@@ -2382,13 +2435,76 @@ fn without_admission_outcome(ext: &axum::http::Extensions) -> axum::http::Extens
probe
}
-/// A deployment-governed generation route has no remote route.
-fn generation_bridge_allowed(state: &AppState) -> bool {
+fn generation_route_policy(state: &AppState) -> Option<&dyn GenerationRoutePolicy> {
state
.model_access_policy
.as_deref()
.and_then(ModelAccessPolicy::generation_route_policy)
- .is_none()
+}
+
+/// The deployment's governed remote route for a generation request, the same
+/// for every question within one request.
+fn governed_remote_route(
+ state: &AppState,
+ ext: &axum::http::Extensions,
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+) -> Option<GovernedGenerationRoute> {
+ let policy = generation_route_policy(state)?;
+ FallbackAttempt::governed_remote_route(ext, customer_model, intent, || {
+ policy.resolve_remote(customer_model, intent)
+ })
+}
+
+/// A deployment-governed generation request is bridged only to the remote
+/// route the deployment names for its model and intent.
+fn generation_bridge_allowed(
+ state: &AppState,
+ ext: &axum::http::Extensions,
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+) -> bool {
+ generation_route_policy(state).is_none()
+ || governed_remote_route(state, ext, customer_model, intent).is_some()
+}
+
+/// A governed generation bridge must agree with the deployment's remote
+/// route, the same model, bundle and pool, and that route must be one the
+/// bridged request can dispatch on. It is checked before the deployment's
+/// admission hooks are asked.
+fn governed_generation_plan(
+ state: &AppState,
+ ext: &axum::http::Extensions,
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+ plan: &crate::state::model_registry::RemoteFallbackPlan,
+) -> bool {
+ generation_route_policy(state).is_none()
+ || governed_remote_route(state, ext, customer_model, intent).is_some_and(|route| {
+ remote_route_agrees(&route, plan)
+ && checked_governed_route(state, customer_model, intent, route).is_ok()
+ })
+}
+
+fn remote_route_agrees(
+ route: &GovernedGenerationRoute,
+ plan: &crate::state::model_registry::RemoteFallbackPlan,
+) -> bool {
+ route.model == plan.model && route.bundle == plan.bundle && route.pool == plan.pool
+}
+
+/// The generation intent of a native request, as routing derives it.
+fn generation_intent_of(params: &publisher::WorkParams) -> GenerationRequestIntent {
+ if params
+ .generate
+ .as_ref()
+ .and_then(|generate| generate.grammar.as_ref())
+ .is_some()
+ {
+ GenerationRequestIntent::Grammar
+ } else {
+ GenerationRequestIntent::Default
+ }
}
/// A transport that manages its own capacity can report a cold lane that the
@@ -2433,6 +2549,7 @@ fn threshold_remote_plan_for_request(
parsed: Option<&(Vec<rmpv::Value>, publisher::WorkParams)>,
allowed: bool,
explicit_bundle: &str,
+ generation: Option<GenerationRequestIntent>,
) -> Option<crate::state::model_registry::RemoteFallbackPlan> {
if !allowed
|| !explicit_bundle.is_empty()
@@ -2449,7 +2566,16 @@ fn threshold_remote_plan_for_request(
return None;
}
let epoch = state.config_epoch.get();
- let plan = state.model_registry.threshold_remote_route(model, epoch)?;
+ let governed = |plan: &crate::state::model_registry::RemoteFallbackPlan| {
+ generation.is_none_or(|intent| governed_generation_plan(state, ext, model, intent, plan))
+ };
+ let plan = state.model_registry.threshold_remote_route(
+ model,
+ epoch,
+ generation.is_some().then_some(
+ &governed as &dyn Fn(&crate::state::model_registry::RemoteFallbackPlan) -> bool,
+ ),
+ )?;
if state.config_epoch.get() != epoch
|| remote_forbidden(headers).unwrap_or(true)
|| (plan.numerical.is_some() && !matches!(operation, "encode" | "score"))
@@ -2760,8 +2886,13 @@ fn native_fallback_plan(
body_held: bool,
trigger: FallbackTrigger,
) -> Option<crate::state::model_registry::RemoteFallbackPlan> {
+ let intent = parsed.map_or(GenerationRequestIntent::Default, |(_, params)| {
+ generation_intent_of(params)
+ });
+ let generation = (endpoint == "generate").then_some(intent);
let eligible = native_bridge_eligible(endpoint, parsed, body_held)
- && (endpoint != "generate" || generation_bridge_allowed(state));
+ && generation
+ .is_none_or(|intent| generation_bridge_allowed(state, req.extensions(), model, intent));
fallback_plan_candidate(
state,
req.headers(),
@@ -2770,6 +2901,7 @@ fn native_fallback_plan(
eligible,
"",
trigger,
+ generation,
)
.filter(|plan| {
plan.numerical.as_ref().is_none_or(|route| {
@@ -2957,16 +3089,7 @@ async fn proxy_request_inner(
if native_request_has_profile_selector(&body_bytes, is_msgpack) {
req.extensions_mut().insert(ExplicitProfileSelector);
}
- let intent = if params
- .generate
- .as_ref()
- .and_then(|generate| generate.grammar.as_ref())
- .is_some()
- {
- GenerationRequestIntent::Grammar
- } else {
- GenerationRequestIntent::Default
- };
+ let intent = generation_intent_of(&params);
prepared_native_body = Some(body_bytes);
prepared_native_parsed = Some((items, params));
(endpoint == "generate").then_some(intent)
@@ -3169,6 +3292,12 @@ async fn proxy_request_inner(
);
}
+ let native_intent = prepared_native_parsed
+ .as_ref()
+ .map_or(GenerationRequestIntent::Default, |(_, params)| {
+ generation_intent_of(params)
+ });
+ let native_generation = (endpoint == "generate").then_some(native_intent);
if let Some(plan) = threshold_remote_plan_for_request(
&state,
req.headers(),
@@ -3177,8 +3306,11 @@ async fn proxy_request_inner(
endpoint,
prepared_native_parsed.as_ref(),
native_bridge_eligible(endpoint, prepared_native_parsed.as_ref(), body_held)
- && (endpoint != "generate" || generation_bridge_allowed(&state)),
+ && native_generation.is_none_or(|intent| {
+ generation_bridge_allowed(&state, req.extensions(), &model_name, intent)
+ }),
"",
+ native_generation,
) {
req.extensions_mut().insert(RemoteFallbackOverride(plan));
if let Some(body) = prepared_native_body {
@@ -8283,7 +8415,8 @@ async fn resolve_generation_route(
token_limit: (u32, &'static str),
metric_labels_slot: Option<&telemetry::MetricLabelsSlot>,
) -> Result<ResolvedRoute, Response> {
- let bridge_allowed = bridge_allowed && generation_bridge_allowed(state);
+ let bridge_allowed =
+ bridge_allowed && generation_bridge_allowed(state, ext, customer_model, request_intent);
let bridge = ext.get::<RemoteFallbackOverride>();
let dispatch_model = bridge.map_or(dispatch_model, |RemoteFallbackOverride(plan)| {
plan.model.as_str()
@@ -8308,10 +8441,14 @@ async fn resolve_generation_route(
.model_access_policy
.as_ref()
.and_then(|p| p.sealed_route(customer_model, ext));
- let governed = if sealed.is_none() {
- governed_generation_route(state, customer_model, dispatch_model, request_intent)?
- } else {
- None
+ let governed = match (&sealed, bridge) {
+ (Some(_), _) => None,
+ (None, Some(RemoteFallbackOverride(plan))) => {
+ governed_bridge_route(state, ext, customer_model, request_intent, plan)?
+ }
+ (None, None) => {
+ governed_generation_route(state, customer_model, dispatch_model, request_intent)?
+ }
};
if let Some(route) = governed.as_ref() {
if !explicit_bundle_override.is_empty() && explicit_bundle_override != route.bundle {
@@ -8496,6 +8633,7 @@ async fn resolve_generation_route(
None,
bridge_allowed,
explicit_bundle_override,
+ Some(request_intent),
) {
let mut remote_ext = ext.clone();
remote_ext.insert(RemoteFallbackOverride(plan));
@@ -8565,6 +8703,7 @@ async fn resolve_generation_route(
bridge_allowed,
explicit_bundle_override,
trigger,
+ request_intent,
);
let Some(plan) = plan else {
return Err(refusal);
@@ -8653,6 +8792,7 @@ async fn resolve_generation_route(
bridge_allowed,
explicit_bundle_override,
FallbackTrigger::Provisioning,
+ request_intent,
) {
let refusal = build_openai_provisioning_response(&gpu, &bundle);
let target = lane_wake_target(
@@ -8704,6 +8844,7 @@ async fn resolve_generation_route(
bridge_allowed,
explicit_bundle_override,
FallbackTrigger::Saturated,
+ request_intent,
)
.is_some()
|| fallback_plan_for_request(
@@ -8714,6 +8855,7 @@ async fn resolve_generation_route(
bridge_allowed,
explicit_bundle_override,
FallbackTrigger::Unhealthy,
+ request_intent,
)
.is_some()
{
@@ -8736,6 +8878,7 @@ async fn resolve_generation_route(
bridge_allowed,
explicit_bundle_override,
trigger,
+ request_intent,
) {
state.demand_tracker.record(&physical_lane);
let attempt = ext
@@ -8770,6 +8913,7 @@ async fn resolve_generation_route(
bridge_allowed,
explicit_bundle_override,
FallbackTrigger::ModelLoading,
+ request_intent,
) {
let admitted = state
.pool_manager
@@ -29091,3 +29235,223 @@ mod tests {
);
}
}
+
+#[cfg(test)]
+mod governed_bridge_route_tests {
+ use super::*;
+ use crate::handlers::test_support::{TestGateway, HYBRID_GENERATE_MODEL, REMOTE_LANE};
+
+ struct RemoteRoute(Option<GovernedGenerationRoute>);
+
+ impl ModelAccessPolicy for RemoteRoute {
+ fn visible(&self, _resolved_model: &str, _ext: &axum::http::Extensions) -> bool {
+ true
+ }
+
+ fn generation_route_policy(&self) -> Option<&dyn GenerationRoutePolicy> {
+ Some(self)
+ }
+ }
+
+ impl GenerationRoutePolicy for RemoteRoute {
+ fn resolve(
+ &self,
+ _customer_model: &str,
+ _intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute> {
+ None
+ }
+
+ fn resolve_remote(
+ &self,
+ _customer_model: &str,
+ _intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute> {
+ self.0.clone()
+ }
+ }
+
+ fn route(
+ model: &str,
+ (pool, machine_profile, bundle): (&str, &str, &str),
+ ) -> GovernedGenerationRoute {
+ GovernedGenerationRoute {
+ model: model.to_string(),
+ bundle: bundle.to_string(),
+ pool: pool.to_string(),
+ machine_profile: machine_profile.to_string(),
+ }
+ }
+
+ #[tokio::test]
+ async fn a_bridged_generation_request_dispatches_only_on_an_agreeing_remote_route() {
+ let config = format!(
+ "{HYBRID_GENERATE_MODEL}\nrouting:\n policy: fallback\n fallback_profile: remote\n"
+ );
+ let mut gateway = TestGateway::new(&[&config]).await;
+ let plan = gateway
+ .state
+ .model_registry
+ .remote_fallback_plan("acme/chat", FallbackTrigger::Provisioning)
+ .expect("remote plan");
+ let intent = GenerationRequestIntent::Default;
+ assert_eq!(
+ governed_bridge_route(
+ &gateway.state,
+ &axum::http::Extensions::new(),
+ "acme/chat",
+ intent,
+ &plan
+ )
+ .ok(),
+ Some(None),
+ "an ungoverned bridge keeps the plan's coordinates"
+ );
+
+ let agreeing = route("acme/chat:remote", REMOTE_LANE);
+ gateway.install_policy(Arc::new(RemoteRoute(Some(agreeing.clone()))));
+ assert_eq!(
+ governed_bridge_route(
+ &gateway.state,
+ &axum::http::Extensions::new(),
+ "acme/chat",
+ intent,
+ &plan
+ )
+ .ok(),
+ Some(Some(agreeing))
+ );
+
+ for (case, remote) in [
+ ("no remote route", None),
+ (
+ "another model",
+ Some(route("acme/other:remote", REMOTE_LANE)),
+ ),
+ (
+ "another bundle",
+ Some(route("acme/chat:remote", ("default", "cpu", "default"))),
+ ),
+ (
+ "another pool",
+ Some(route("acme/chat:remote", ("other", "cpu", "remote"))),
+ ),
+ (
+ "an unconfigured machine profile",
+ Some(route("acme/chat:remote", ("default", "tpu", "remote"))),
+ ),
+ ] {
+ gateway.install_policy(Arc::new(RemoteRoute(remote)));
+ assert!(
+ governed_bridge_route(
+ &gateway.state,
+ &axum::http::Extensions::new(),
+ "acme/chat",
+ intent,
+ &plan
+ )
+ .is_err(),
+ "{case}"
+ );
+ }
+ }
+
+ /// A deployment policy that reads the registry while it names the remote
+ /// route.
+ struct RegistryReadingRoute {
+ route: GovernedGenerationRoute,
+ registry: Arc<crate::state::model_registry::ModelRegistry>,
+ }
+
+ impl ModelAccessPolicy for RegistryReadingRoute {
+ fn visible(&self, _resolved_model: &str, _ext: &axum::http::Extensions) -> bool {
+ true
+ }
+
+ fn remote_route_admitted(
+ &self,
+ _model: &str,
+ _remote_model: &str,
+ _reason: RemoteRouteReason,
+ _ext: &axum::http::Extensions,
+ ) -> bool {
+ true
+ }
+
+ fn generation_route_policy(&self) -> Option<&dyn GenerationRoutePolicy> {
+ Some(self)
+ }
+ }
+
+ impl GenerationRoutePolicy for RegistryReadingRoute {
+ fn resolve(
+ &self,
+ _customer_model: &str,
+ _intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute> {
+ None
+ }
+
+ fn resolve_remote(
+ &self,
+ _customer_model: &str,
+ _intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute> {
+ self.registry
+ .with_current_generation(&self.registry.capture_generation(), || self.route.clone())
+ }
+ }
+
+ #[test]
+ fn a_threshold_plan_may_ask_a_policy_that_reads_the_registry() {
+ use crate::handlers::test_support::ThresholdBroker;
+ use crate::state::threshold_coordinator::ThresholdSampler;
+ let (done_tx, done_rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let runtime = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap();
+ let planned = runtime.block_on(async {
+ let broker = ThresholdBroker::start().await?;
+ let config = format!("{HYBRID_GENERATE_MODEL}\nrouting:\n policy: threshold\n fallback_profile: remote\n wake_above: 1\n sleep_below: 0.5\n window_s: 1\n cooldown_s: 1\n");
+ let mut gateway = TestGateway::with_threshold_routing(&[&config], true).await;
+ let registry = Arc::clone(&gateway.state.model_registry);
+ gateway.install_policy(Arc::new(RegistryReadingRoute {
+ route: route("acme/chat:remote", REMOTE_LANE),
+ registry,
+ }));
+ let binding = broker.bind(&gateway).await;
+ let mut sampler = ThresholdSampler::default();
+ binding.coordinator.sample(&mut sampler).await.unwrap();
+ for _ in 0..2 {
+ tokio::time::sleep(std::time::Duration::from_millis(1050)).await;
+ binding.coordinator.sample(&mut sampler).await.unwrap();
+ }
+ Some(
+ threshold_remote_plan_for_request(
+ &gateway.state,
+ &HeaderMap::new(),
+ &axum::http::Extensions::new(),
+ "acme/chat",
+ "generate",
+ None,
+ true,
+ "",
+ Some(GenerationRequestIntent::Default),
+ )
+ .map(|plan| plan.model),
+ )
+ });
+ let _ = done_tx.send(planned);
+ });
+
+ // A policy that re-enters a held registry lock blocks its thread forever.
+ let planned = done_rx
+ .recv_timeout(std::time::Duration::from_secs(30))
+ .expect("planning finished");
+ if let Some(planned) = planned {
+ assert_eq!(planned.as_deref(), Some("acme/chat:remote"));
+ }
+ }
+}
diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rs
index 534864216..018009397 100644
--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs
+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs
@@ -14,7 +14,9 @@ use axum::response::Response;
use futures_util::FutureExt;
use crate::observability::metrics as telemetry;
-use crate::server::{AppState, RemoteRouteReason};
+use crate::server::{
+ AppState, GenerationRequestIntent, GovernedGenerationRoute, RemoteRouteReason,
+};
use crate::types::model::{FallbackTrigger, ServedBy};
pub(crate) const SERVED_BY_HEADER: HeaderName = HeaderName::from_static("x-sie-served-by");
@@ -104,6 +106,11 @@ struct FallbackState {
original: Option<LocalRefusal>,
observation: Option<ServingObservation>,
route_decisions: Vec<(String, RemoteRouteReason, bool)>,
+ governed_remote_routes: Vec<(
+ String,
+ GenerationRequestIntent,
+ Option<GovernedGenerationRoute>,
+ )>,
}
struct ServingObservation {
@@ -296,6 +303,41 @@ impl FallbackAttempt {
admitted
}
+ /// A deployment's governed remote route for a generation request. It is
+ /// decided once per request, model and intent, so planning and the bridged
+ /// dispatch use the same route.
+ pub(crate) fn governed_remote_route(
+ extensions: &Extensions,
+ customer_model: &str,
+ intent: GenerationRequestIntent,
+ decide: impl FnOnce() -> Option<GovernedGenerationRoute>,
+ ) -> Option<GovernedGenerationRoute> {
+ let Some(attempt) = extensions.get::<Self>() else {
+ return decide();
+ };
+ let known = |state: &FallbackState| {
+ state
+ .governed_remote_routes
+ .iter()
+ .find(|(model, decided_intent, _)| {
+ model == customer_model && *decided_intent == intent
+ })
+ .map(|(_, _, route)| route.clone())
+ };
+ if let Some(route) = known(&attempt.0.lock().unwrap_or_else(PoisonError::into_inner)) {
+ return route;
+ }
+ let route = decide();
+ let mut state = attempt.0.lock().unwrap_or_else(PoisonError::into_inner);
+ if let Some(first) = known(&state) {
+ return first;
+ }
+ state
+ .governed_remote_routes
+ .push((customer_model.to_string(), intent, route.clone()));
+ route
+ }
+
/// 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> {
@@ -3274,12 +3316,12 @@ mod tests {
assert!(gateway
.state
.model_registry
- .threshold_remote_route("acme/chat", 1)
+ .threshold_remote_route("acme/chat", 1, None)
.is_none());
assert!(gateway
.state
.model_registry
- .threshold_remote_route("acme/chat", 2)
+ .threshold_remote_route("acme/chat", 2, None)
.is_none());
gateway.state.model_registry.clear_threshold_binding();
let response = buffered_surface(&gateway, "chat", json!({})).await;
@@ -3853,6 +3895,9 @@ mod tests {
hide_remote: bool,
refuse_remote_serving: bool,
govern_generation: bool,
+ remote_generation: Option<GovernedGenerationRoute>,
+ flip_remote_generation: bool,
+ remote_generation_asks: std::sync::atomic::AtomicUsize,
asked: std::sync::Mutex<Vec<(String, String, RemoteRouteReason)>>,
}
@@ -3914,6 +3959,34 @@ mod tests {
machine_profile: LOCAL_LANE.1.to_string(),
})
}
+
+ fn resolve_remote(
+ &self,
+ _customer_model: &str,
+ intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute> {
+ let asks = self
+ .remote_generation_asks
+ .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ if self.flip_remote_generation && asks > 0 {
+ return None;
+ }
+ self.remote_generation
+ .clone()
+ .filter(|_| intent == GenerationRequestIntent::Default)
+ }
+ }
+
+ fn governed(
+ model: &str,
+ (pool, machine_profile, bundle): (&str, &str, &str),
+ ) -> GovernedGenerationRoute {
+ GovernedGenerationRoute {
+ model: model.to_string(),
+ bundle: bundle.to_string(),
+ pool: pool.to_string(),
+ machine_profile: machine_profile.to_string(),
+ }
}
/// A policy that only decides visibility, so remote routes take the
@@ -4395,6 +4468,220 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn a_governed_generation_bridge_dispatches_on_the_remote_route_it_names() {
+ let policy = Arc::new(RoutePolicy {
+ admit: true,
+ govern_generation: true,
+ remote_generation: Some(governed("acme/chat:remote", REMOTE_LANE)),
+ ..Default::default()
+ });
+ let gateway = transport_cold_gateway(Some(policy.clone())).await;
+
+ let mut expected = Vec::new();
+ for surface in ["native", "chat", "completions", "responses"] {
+ let response = buffered_surface(&gateway, surface, json!({})).await;
+ assert_eq!(response.status(), StatusCode::OK, "{surface}");
+ assert_eq!(
+ response.headers()["x-sie-fallback-reason"],
+ "provisioning",
+ "{surface}"
+ );
+ expected.push(dispatched("load", LOCAL_LANE, "acme/chat"));
+ expected.push(dispatched("generate", REMOTE_LANE, "acme/chat:remote"));
+ }
+ assert_eq!(gateway.dispatcher.dispatched(), expected);
+ assert!(gateway
+ .dispatcher
+ .fallback_reasons()
+ .iter()
+ .all(|reason| *reason == Some(FallbackTrigger::Provisioning)));
+ let admitted = (
+ "acme/chat".to_string(),
+ "acme/chat:remote".to_string(),
+ RemoteRouteReason::Fallback(FallbackTrigger::Provisioning),
+ );
+ assert_eq!(
+ policy.asked(),
+ vec![admitted; 4],
+ "one admission per surface"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_governed_generation_bridge_takes_the_machine_profile_of_its_route() {
+ let policy = Arc::new(RoutePolicy {
+ admit: true,
+ govern_generation: true,
+ remote_generation: Some(governed("acme/chat:remote", ("default", "l4", "remote"))),
+ ..Default::default()
+ });
+ let gateway = transport_cold_gateway(Some(policy)).await;
+
+ let mut expected = Vec::new();
+ for surface in ["native", "chat", "completions", "responses"] {
+ let response = buffered_surface(&gateway, surface, json!({})).await;
+ assert_eq!(
+ response.status(),
+ StatusCode::SERVICE_UNAVAILABLE,
+ "{surface}: no verified worker serves the governed route's machine profile"
+ );
+ assert_eq!(
+ response.headers()["x-sie-fallback-reason"],
+ "provisioning",
+ "{surface}"
+ );
+ expected.push(dispatched("load", LOCAL_LANE, "acme/chat"));
+ }
+ assert_eq!(gateway.dispatcher.dispatched(), expected);
+ }
+
+ #[tokio::test]
+ async fn governed_generation_without_an_agreeing_remote_route_stays_local() {
+ for (case, remote) in [
+ ("no remote route", None),
+ (
+ "another model",
+ Some(governed("acme/other:remote", REMOTE_LANE)),
+ ),
+ (
+ "another bundle",
+ Some(governed("acme/chat:remote", ("default", "cpu", "default"))),
+ ),
+ (
+ "another pool",
+ Some(governed("acme/chat:remote", ("other", "cpu", "remote"))),
+ ),
+ (
+ "an unconfigured machine profile",
+ Some(governed("acme/chat:remote", ("default", "tpu", "remote"))),
+ ),
+ ] {
+ let policy = Arc::new(RoutePolicy {
+ admit: true,
+ govern_generation: true,
+ remote_generation: remote,
+ ..Default::default()
+ });
+ let gateway = transport_cold_gateway(Some(policy.clone())).await;
+
+ let mut expected = Vec::new();
+ for surface in ["native", "chat", "completions", "responses"] {
+ let response = buffered_surface(&gateway, surface, json!({})).await;
+ assert_eq!(response.status(), StatusCode::OK, "{case}: {surface}");
+ assert!(
+ !response.headers().contains_key("x-sie-fallback-reason"),
+ "{case}: {surface}"
+ );
+ expected.push(dispatched("generate", LOCAL_LANE, "acme/chat"));
+ }
+ assert_eq!(gateway.dispatcher.dispatched(), expected, "{case}");
+ assert!(
+ policy.asked().is_empty(),
+ "{case}: a route that cannot be used never reaches admission"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn a_governed_generation_bridge_keeps_the_route_it_planned_with() {
+ for surface in ["native", "chat", "completions", "responses"] {
+ let policy = Arc::new(RoutePolicy {
+ admit: true,
+ govern_generation: true,
+ remote_generation: Some(governed("acme/chat:remote", REMOTE_LANE)),
+ flip_remote_generation: true,
+ ..Default::default()
+ });
+ let gateway = transport_cold_gateway(Some(policy.clone())).await;
+
+ let response = buffered_surface(&gateway, surface, json!({})).await;
+
+ assert_eq!(response.status(), StatusCode::OK, "{surface}");
+ assert_eq!(response.headers()["x-sie-served-by"], "remote", "{surface}");
+ assert_eq!(
+ gateway.dispatcher.dispatched(),
+ vec![
+ dispatched("load", LOCAL_LANE, "acme/chat"),
+ dispatched("generate", REMOTE_LANE, "acme/chat:remote"),
+ ],
+ "{surface}"
+ );
+ assert_eq!(
+ policy
+ .remote_generation_asks
+ .load(std::sync::atomic::Ordering::SeqCst),
+ 1,
+ "{surface}: one answer per request"
+ );
+ }
+ }
+
+ #[tokio::test]
+ async fn a_governed_threshold_route_goes_remote_only_on_an_agreeing_route() {
+ use crate::handlers::test_support::ThresholdBroker;
+ use crate::state::threshold_coordinator::ThresholdSampler;
+ let config = format!("{HYBRID_GENERATE_MODEL}\nrouting:\n policy: threshold\n fallback_profile: remote\n wake_above: 1\n sleep_below: 0.5\n window_s: 1\n cooldown_s: 1\n");
+ for (case, remote, served_remotely) in [
+ (
+ "an agreeing route",
+ Some(governed("acme/chat:remote", REMOTE_LANE)),
+ true,
+ ),
+ ("no remote route", None, false),
+ (
+ "another bundle",
+ Some(governed("acme/chat:remote", ("default", "cpu", "default"))),
+ false,
+ ),
+ ] {
+ let Some(broker) = ThresholdBroker::start().await else {
+ return;
+ };
+ let policy = Arc::new(RoutePolicy {
+ admit: true,
+ govern_generation: true,
+ remote_generation: remote,
+ ..Default::default()
+ });
+ let mut gateway = TestGateway::with_threshold_routing(&[&config], true).await;
+ gateway.install_policy(policy.clone());
+ gateway
+ .add_verified_worker("local-1", LOCAL_LANE, &["acme/chat"])
+ .await;
+ gateway
+ .add_verified_worker("remote-1", REMOTE_LANE, &[])
+ .await;
+ let binding = broker.bind(&gateway).await;
+ let mut sampler = ThresholdSampler::default();
+ binding.coordinator.sample(&mut sampler).await.unwrap();
+ for _ in 0..2 {
+ tokio::time::sleep(Duration::from_millis(1050)).await;
+ binding.coordinator.sample(&mut sampler).await.unwrap();
+ }
+
+ let response = buffered_surface(&gateway, "chat", json!({})).await;
+
+ assert_eq!(response.status(), StatusCode::OK, "{case}");
+ if served_remotely {
+ assert_eq!(response.headers()["x-sie-served-by"], "remote", "{case}");
+ assert_eq!(
+ gateway.dispatcher.dispatched(),
+ vec![dispatched("generate", REMOTE_LANE, "acme/chat:remote")],
+ "{case}"
+ );
+ } else {
+ assert_eq!(response.headers()["x-sie-served-by"], "local", "{case}");
+ assert_eq!(
+ gateway.dispatcher.dispatched(),
+ vec![dispatched("generate", LOCAL_LANE, "acme/chat")],
+ "{case}"
+ );
+ assert!(policy.asked().is_empty(), "{case}");
+ }
+ }
+ }
+
#[tokio::test]
async fn a_warm_lane_or_a_refusing_policy_keeps_the_request_local() {
let warm = TestGateway::new(&[&fallback_config(HYBRID_EXTRACT_MODEL)]).await;
diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rs
index 9dd46bfd9..f20679ac1 100644
--- a/packages/sie_gateway/src/server.rs
+++ b/packages/sie_gateway/src/server.rs
@@ -195,6 +195,20 @@ pub trait GenerationRoutePolicy: Send + Sync {
customer_model: &str,
intent: GenerationRequestIntent,
) -> Option<GovernedGenerationRoute>;
+
+ /// The governed route of `customer_model`'s remote profile for `intent`.
+ ///
+ /// `None` means generation for that model and intent is never bridged
+ /// while this policy governs generation. A bridge is planned only when
+ /// this route names the same model, bundle and pool as the registry's
+ /// remote plan, and the bridged request dispatches on this route.
+ fn resolve_remote(
+ &self,
+ _customer_model: &str,
+ _intent: GenerationRequestIntent,
+ ) -> Option<GovernedGenerationRoute> {
+ None
+ }
}
pub struct AppState {
diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rs
index d235f6132..47f1ec790 100644
--- a/packages/sie_gateway/src/state/model_registry.rs
+++ b/packages/sie_gateway/src/state/model_registry.rs
@@ -1903,28 +1903,46 @@ impl ModelRegistry {
self.threshold_binding.store(None);
}
+ /// `accept`, when given, decides the plan before the request is counted
+ /// as demand. It runs while no registry lock is held, so it may read the
+ /// registry. The plan is counted only while its binding and snapshot are
+ /// still current.
pub(crate) fn threshold_remote_route(
&self,
model: &str,
epoch: u64,
+ accept: Option<&dyn Fn(&RemoteFallbackPlan) -> bool>,
) -> Option<RemoteFallbackPlan> {
let binding = self.threshold_binding.load_full()?;
if binding.epoch != epoch || model.contains(':') {
return None;
}
+ let snap = &binding.generation.snapshot;
+ let canonical = Self::canonical_model_name(snap, model)?;
+ let plan = snap
+ .models
+ .get(&canonical)
+ .and_then(|entry| Self::remote_plan_from_snapshot(snap, entry));
+ if accept.is_some_and(|accept| !plan.as_ref().is_some_and(accept)) {
+ return None;
+ }
// A snapshot writer must never block a request thread. Contention is
// unavailable authority and retains the ordinary local/fallback path.
let _fence = self.write_lock.try_lock().ok()?;
- if !Arc::ptr_eq(&self.snapshot.load_full(), &binding.generation.snapshot) {
+ if !Arc::ptr_eq(&self.snapshot.load_full(), snap)
+ || !self
+ .threshold_binding
+ .load()
+ .as_ref()
+ .is_some_and(|current| Arc::ptr_eq(current, &binding))
+ {
return None;
}
- let snap = &binding.generation.snapshot;
- let canonical = Self::canonical_model_name(snap, model)?;
binding.coordinator.record_request(&canonical).ok()?;
if binding.coordinator.decision(&canonical).ok()? != ThresholdDecision::Remote {
return None;
}
- Self::remote_plan_from_snapshot(snap, snap.models.get(&canonical)?)
+ plan
}
pub fn get_model_pool_name(&self, model: &str) -> Option<String> {
@@ -3117,7 +3135,7 @@ mod tests {
assert!(gateway
.state
.model_registry
- .threshold_remote_route("acme/chat", 1)
+ .threshold_remote_route("acme/chat", 1, None)
.is_some());
let registry = Arc::clone(&gateway.state.model_registry);
@@ -3133,17 +3151,64 @@ mod tests {
let route = gateway
.state
.model_registry
- .threshold_remote_route("acme/chat", 1);
+ .threshold_remote_route("acme/chat", 1, None);
release_tx.send(()).unwrap();
writer.join().unwrap();
assert!(route.is_none());
assert!(gateway
.state
.model_registry
- .threshold_remote_route("acme/chat", 1)
+ .threshold_remote_route("acme/chat", 1, None)
.is_some());
}
+ #[tokio::test]
+ async fn a_threshold_accept_callback_runs_outside_the_registry_lock() {
+ let Some(broker) = ThresholdBroker::start().await else {
+ return;
+ };
+ let model = format!(
+ "{HYBRID_GENERATE_MODEL}\nrouting:\n policy: threshold\n fallback_profile: remote\n wake_above: 1\n sleep_below: 0.5\n window_s: 1\n cooldown_s: 1\n"
+ );
+ let gateway = TestGateway::with_threshold_routing(&[&model], true).await;
+ let binding = broker.bind(&gateway).await;
+ let mut sampler = ThresholdSampler::default();
+ binding.coordinator.sample(&mut sampler).await.unwrap();
+ for _ in 0..2 {
+ tokio::time::sleep(Duration::from_millis(1050)).await;
+ binding.coordinator.sample(&mut sampler).await.unwrap();
+ }
+ let route = |clear_binding: bool| {
+ let registry = Arc::clone(&gateway.state.model_registry);
+ let (done_tx, done_rx) = mpsc::channel();
+ std::thread::spawn(move || {
+ let accept = |_: &RemoteFallbackPlan| {
+ let read =
+ registry.with_current_generation(&registry.capture_generation(), || ());
+ if clear_binding {
+ registry.clear_threshold_binding();
+ }
+ read.is_some()
+ };
+ let _ = done_tx.send(
+ registry
+ .threshold_remote_route("acme/chat", 1, Some(&accept))
+ .is_some(),
+ );
+ });
+ // Bound a regression's deadlock so this test cannot hang.
+ done_rx
+ .recv_timeout(Duration::from_secs(5))
+ .expect("the callback ran without the registry lock")
+ };
+
+ assert!(route(false), "a callback may read the registry");
+ assert!(
+ !route(true),
+ "a binding that changed while the callback ran is not counted"
+ );
+ }
+
#[test]
fn remote_routing_policy_survives_snapshots_and_is_scoped_to_bare_model() {
let (_dir, registry, mut config) = remote_routing_fixture();
diff --git a/packages/sie_gateway/src/state/threshold_runtime.rs b/packages/sie_gateway/src/state/threshold_runtime.rs
index b5ac920ee..389d7f50c 100644
--- a/packages/sie_gateway/src/state/threshold_runtime.rs
+++ b/packages/sie_gateway/src/state/threshold_runtime.rs
@@ -209,7 +209,7 @@ mod tests {
assert!(gateway
.state
.model_registry
- .threshold_remote_route("acme/chat", 7)
+ .threshold_remote_route("acme/chat", 7, None)
.is_none());
gateway.state.config_epoch.mark_bootstrapped();
tokio::time::timeout(Duration::from_secs(4), async {
diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.md
index 6c6352faa..f9d01f56f 100644
--- a/packages/sie_server/REMOTE_BACKENDS.md
+++ b/packages/sie_server/REMOTE_BACKENDS.md
@@ -594,8 +594,10 @@ 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. Under a model access policy, a bare model goes to its remote profile
-only when the policy admits that route and serves the remote profile, and
-generation stays local while the policy governs generation routes. A request
+only when the policy admits that route and serves the remote profile. While
+the policy governs generation routes, generation stays local unless the policy
+also names a governed route for the remote profile that agrees with the
+registry's remote plan. A request
that names the remote profile follows the same visibility and serving rules as
any other model. A caller who may not see the remote profile gets the bare model
from `/v1/models` without that profile and with no remote routing.