Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
feat(gateway): let a model access policy admit remote routes (#591)
Krisztian Gajdar7e7050fd94a7
diff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex 625c75650..777ea621f 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -1016,3 +1016,31 @@ is counted once, with the decision that applied, onreasons `no_admission`, `local_unobserved`, `uncovered_identity` and`unmeasured_request`. Configuration load no longer refuses `threshold` routingfor numerical models; the admission gates each request instead.++### Remote routes under a model access policy++A deployment that installs a `ModelAccessPolicy` decides the implicit remote+routes of a bare model, whether a fallback trigger or a `threshold` decision+would take the route. A request that names the remote profile, directly or+through an alias, is governed by `visible` and `serving_refusal` like any other+model, so a caller who can see the remote profile can name it.++- **When the gateway asks.** Only about a route it admits on its own: a bare+ model whose routing names the remote profile and permits the reason, no+ caller profile, bundle, pool or engine selector, no `X-SIE-Remote: forbid`,+ a transport with execution authority v1, and no bridge already active.+- **The remote profile first.** The gateway requires+ `ModelAccessPolicy::visible` and `ModelAccessPolicy::serving_refusal` to+ pass for the remote profile. It asks `serving_refusal` with the request+ extensions minus the admission-outcome slot. A refusal keeps the local route,+ and it is neither returned nor recorded.+- **The question.** `ModelAccessPolicy::remote_route_admitted` receives the+ canonical model, the remote profile and a `RemoteRouteReason`:+ `Fallback(trigger)` or `Threshold`.+- **Once per request.** The gateway decides once per request, remote profile+ and reason, and reuses that decision.+- **The answer.** `false`, the default, keeps the local route. The caller+ 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.diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex 5d3da2497..21c2b423d 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -32,6 +32,7 @@ use crate::queue::streaming::{use crate::server::{AppState, GenerationRequestIntent, GovernedGenerationRoute, ModelAccessPolicy,+ RemoteRouteReason,};use crate::state::demand_tracker::PhysicalLane;use crate::state::model_registry::{ModelRegistry, ResolveError};@@ -2334,7 +2335,6 @@ fn fallback_plan_candidate(|| ext.get::<RemoteFallbackOverride>().is_some()|| ext.get::<ExplicitProfileSelector>().is_some()|| remote_forbidden(headers).unwrap_or(true)- || state.model_access_policy.is_some()|| ["x-sie-machine-profile", "x-sie-pool", "x-sie-engine"].iter().any(|name| headers.contains_key(*name))@@ -2345,7 +2345,50 @@ fn fallback_plan_candidate({return None;}- state.model_registry.remote_fallback_plan(model, trigger)+ state+ .model_registry+ .remote_fallback_plan(model, trigger)+ .filter(|plan| {+ remote_route_admitted(state, ext, plan, RemoteRouteReason::Fallback(trigger))+ })+}++/// A deployment policy decides each implicit remote route of a bare model,+/// once per request. It is asked only about a remote profile the caller may+/// see and the deployment serves.+fn remote_route_admitted(+ state: &AppState,+ ext: &axum::http::Extensions,+ plan: &crate::state::model_registry::RemoteFallbackPlan,+ reason: RemoteRouteReason,+) -> bool {+ let Some(policy) = state.model_access_policy.as_deref() else {+ return true;+ };+ FallbackAttempt::remote_route_decision(ext, &plan.model, reason, || {+ policy.visible(&plan.model, ext)+ && policy+ .serving_refusal(&plan.model, &without_admission_outcome(ext))+ .is_none()+ && policy.remote_route_admitted(&plan.local_model, &plan.model, reason, ext)+ })+}++/// The request's extensions for asking about a profile it may not use. A+/// refusal recorded there must not become the request's own outcome.+fn without_admission_outcome(ext: &axum::http::Extensions) -> axum::http::Extensions {+ let mut probe = ext.clone();+ probe.remove::<crate::observability::metrics::AdmissionOutcomeSlot>();+ probe+}++/// A deployment-governed generation route has no remote route.+fn generation_bridge_allowed(state: &AppState) -> bool {+ state+ .model_access_policy+ .as_deref()+ .and_then(ModelAccessPolicy::generation_route_policy)+ .is_none()}/// Threshold decisions are counted only after caller validation and before@@ -2365,7 +2408,6 @@ fn threshold_remote_plan_for_request(|| !explicit_bundle.is_empty()|| ext.get::<RemoteFallbackOverride>().is_some()|| ext.get::<ExplicitProfileSelector>().is_some()- || state.model_access_policy.is_some()|| ["x-sie-machine-profile", "x-sie-pool", "x-sie-engine"].iter().any(|name| headers.contains_key(*name))@@ -2381,6 +2423,7 @@ fn threshold_remote_plan_for_request(if state.config_epoch.get() != epoch|| remote_forbidden(headers).unwrap_or(true)|| (plan.numerical.is_some() && !matches!(operation, "encode" | "score"))+ || !remote_route_admitted(state, ext, &plan, RemoteRouteReason::Threshold){return None;}@@ -2681,7 +2724,8 @@ fn native_fallback_plan(body_held: bool,trigger: FallbackTrigger,) -> Option<crate::state::model_registry::RemoteFallbackPlan> {- let eligible = native_bridge_eligible(endpoint, parsed, body_held);+ let eligible = native_bridge_eligible(endpoint, parsed, body_held)+ && (endpoint != "generate" || generation_bridge_allowed(state));fallback_plan_candidate(state,req.headers(),@@ -3070,7 +3114,8 @@ async fn proxy_request_inner(&model_name,endpoint,prepared_native_parsed.as_ref(),- native_bridge_eligible(endpoint, prepared_native_parsed.as_ref(), body_held),+ native_bridge_eligible(endpoint, prepared_native_parsed.as_ref(), body_held)+ && (endpoint != "generate" || generation_bridge_allowed(&state)),"",) {req.extensions_mut().insert(RemoteFallbackOverride(plan));@@ -8112,6 +8157,7 @@ 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 = ext.get::<RemoteFallbackOverride>();let dispatch_model = bridge.map_or(dispatch_model, |RemoteFallbackOverride(plan)| {plan.model.as_str()diff --git a/packages/sie_gateway/src/handlers/serving_disclosure.rs b/packages/sie_gateway/src/handlers/serving_disclosure.rsindex a99c71c53..ea7c8b282 100644--- a/packages/sie_gateway/src/handlers/serving_disclosure.rs+++ b/packages/sie_gateway/src/handlers/serving_disclosure.rs@@ -14,7 +14,7 @@ use axum::response::Response;use futures_util::FutureExt;use crate::observability::metrics as telemetry;-use crate::server::AppState;+use crate::server::{AppState, RemoteRouteReason};use crate::types::model::{FallbackTrigger, ServedBy};pub(crate) const SERVED_BY_HEADER: HeaderName = HeaderName::from_static("x-sie-served-by");@@ -103,6 +103,7 @@ pub(crate) struct FallbackAttempt(Arc<Mutex<FallbackState>>);struct FallbackState {original: Option<LocalRefusal>,observation: Option<ServingObservation>,+ route_decisions: Vec<(String, RemoteRouteReason, bool)>,}struct ServingObservation {@@ -259,6 +260,41 @@ impl FallbackAttempt {.is_some()}+ /// A deployment's decision on routing this request to `remote_model` for+ /// `reason`. It is made once per request, remote profile and reason, and+ /// every later question gets the same answer.+ pub(crate) fn remote_route_decision(+ extensions: &Extensions,+ remote_model: &str,+ reason: RemoteRouteReason,+ decide: impl FnOnce() -> bool,+ ) -> bool {+ let Some(attempt) = extensions.get::<Self>() else {+ return decide();+ };+ let known = |state: &FallbackState| {+ state+ .route_decisions+ .iter()+ .find(|(model, decided_reason, _)| {+ model == remote_model && *decided_reason == reason+ })+ .map(|(_, _, admitted)| *admitted)+ };+ if let Some(admitted) = known(&attempt.0.lock().unwrap_or_else(PoisonError::into_inner)) {+ return admitted;+ }+ let admitted = decide();+ let mut state = attempt.0.lock().unwrap_or_else(PoisonError::into_inner);+ if let Some(first) = known(&state) {+ return first;+ }+ state+ .route_decisions+ .push((remote_model.to_string(), reason, admitted));+ admitted+ }+/// 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> {@@ -3678,4 +3714,375 @@ mod tests {assert!(gateway.dispatcher.numerical_admissions().is_empty());}}++ use crate::observability::metrics::{AdmissionOutcome, AdmissionOutcomeSlot};+ use crate::server::{+ GenerationRequestIntent, GenerationRoutePolicy, GovernedGenerationRoute, ModelAccessPolicy,+ };++ /// A deployment policy that records every remote route the gateway asks+ /// about and answers `admit`.+ #[derive(Default)]+ struct RoutePolicy {+ admit: bool,+ admit_first_only: bool,+ hide_remote: bool,+ refuse_remote_serving: bool,+ govern_generation: bool,+ asked: std::sync::Mutex<Vec<(String, String, RemoteRouteReason)>>,+ }++ impl RoutePolicy {+ fn asked(&self) -> Vec<(String, String, RemoteRouteReason)> {+ self.asked.lock().unwrap().clone()+ }+ }++ impl ModelAccessPolicy for RoutePolicy {+ fn visible(&self, resolved_model: &str, _ext: &axum::http::Extensions) -> bool {+ !(self.hide_remote && resolved_model.ends_with(":remote"))+ }++ fn serving_refusal(+ &self,+ resolved_model: &str,+ ext: &axum::http::Extensions,+ ) -> Option<Response> {+ (self.refuse_remote_serving && resolved_model.ends_with(":remote")).then(|| {+ if let Some(slot) = ext.get::<AdmissionOutcomeSlot>() {+ slot.set(AdmissionOutcome::Forbidden);+ }+ StatusCode::FORBIDDEN.into_response()+ })+ }++ fn generation_route_policy(&self) -> Option<&dyn GenerationRoutePolicy> {+ self.govern_generation+ .then_some(self as &dyn GenerationRoutePolicy)+ }++ fn remote_route_admitted(+ &self,+ model: &str,+ remote_model: &str,+ reason: RemoteRouteReason,+ _ext: &axum::http::Extensions,+ ) -> bool {+ let mut asked = self.asked.lock().unwrap();+ asked.push((model.to_string(), remote_model.to_string(), reason));+ if self.admit_first_only {+ return asked.len() == 1;+ }+ self.admit+ }+ }++ impl GenerationRoutePolicy for RoutePolicy {+ fn resolve(+ &self,+ customer_model: &str,+ intent: GenerationRequestIntent,+ ) -> Option<GovernedGenerationRoute> {+ (intent == GenerationRequestIntent::Default).then(|| GovernedGenerationRoute {+ model: customer_model.to_string(),+ bundle: LOCAL_LANE.2.to_string(),+ pool: LOCAL_LANE.0.to_string(),+ machine_profile: LOCAL_LANE.1.to_string(),+ })+ }+ }++ /// A policy that only decides visibility, so remote routes take the+ /// trait's default answer.+ struct VisibilityOnlyPolicy;++ impl ModelAccessPolicy for VisibilityOnlyPolicy {+ fn visible(&self, _resolved_model: &str, _ext: &axum::http::Extensions) -> bool {+ true+ }+ }++ fn fallback_config(model: &str) -> String {+ format!("{model}\nrouting:\n policy: fallback\n fallback_profile: remote\n")+ }++ /// A gateway with no local worker and one verified remote worker.+ async fn cold_gateway(models: &[&str], policy: Arc<dyn ModelAccessPolicy>) -> TestGateway {+ let mut gateway = TestGateway::new(models).await;+ gateway.install_policy(policy);+ gateway+ .add_verified_worker("remote-1", REMOTE_LANE, &[])+ .await;+ gateway+ }++ async fn extract(gateway: &TestGateway, request: Request) -> Response {+ proxy_request(State(Arc::clone(&gateway.state)), request, "extract").await+ }++ fn assert_local_provisioning(response: &Response, gateway: &TestGateway) {+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert_eq!(response.headers()["retry-after"], "60");+ assert!(!response.headers().contains_key("x-sie-fallback-reason"));+ assert!(gateway.dispatcher.dispatched().is_empty());+ }++ #[tokio::test]+ async fn a_policy_that_does_not_admit_remote_routes_keeps_the_local_answer() {+ let config = fallback_config(HYBRID_EXTRACT_MODEL);+ let gateway = cold_gateway(&[&config], Arc::new(VisibilityOnlyPolicy)).await;++ let response = extract(&gateway, extraction_request(false, json!({}))).await;++ assert_local_provisioning(&response, &gateway);+ }++ #[tokio::test]+ async fn an_admitting_policy_is_asked_once_with_canonical_ids_and_the_trigger() {+ let config = fallback_config(HYBRID_EXTRACT_MODEL);+ for msgpack in [false, true] {+ let policy = Arc::new(RoutePolicy {+ admit: true,+ ..Default::default()+ });+ let gateway = cold_gateway(&[&config], policy.clone()).await;++ let response = extract(&gateway, extraction_request(msgpack, json!({}))).await;++ assert_eq!(response.status(), StatusCode::OK, "msgpack={msgpack}");+ assert_eq!(response.headers()["x-sie-fallback-reason"], "provisioning");+ assert_eq!(+ gateway.dispatcher.dispatched(),+ vec![dispatched("extract", REMOTE_LANE, "acme/extract:remote")]+ );+ assert_eq!(+ policy.asked(),+ vec![(+ "acme/extract".to_string(),+ "acme/extract:remote".to_string(),+ RemoteRouteReason::Fallback(FallbackTrigger::Provisioning),+ )]+ );+ }+ }++ #[tokio::test]+ async fn a_remote_profile_hidden_from_the_caller_is_never_asked_about_or_routed_to() {+ let config = fallback_config(HYBRID_EXTRACT_MODEL);+ let policy = Arc::new(RoutePolicy {+ admit: true,+ hide_remote: true,+ ..Default::default()+ });+ let gateway = cold_gateway(&[&config], policy.clone()).await;++ let response = extract(&gateway, extraction_request(false, json!({}))).await;++ assert_local_provisioning(&response, &gateway);+ assert!(policy.asked().is_empty());+ }++ #[tokio::test]+ async fn remote_forbid_never_asks_the_policy() {+ let config = fallback_config(HYBRID_EXTRACT_MODEL);+ let policy = Arc::new(RoutePolicy {+ admit: true,+ ..Default::default()+ });+ let gateway = cold_gateway(&[&config], policy.clone()).await;+ let mut request = extraction_request(false, json!({}));+ request+ .headers_mut()+ .insert(REMOTE_HEADER, HeaderValue::from_static("forbid"));++ let response = extract(&gateway, request).await;++ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert!(gateway.dispatcher.dispatched().is_empty());+ assert!(policy.asked().is_empty());+ }++ #[tokio::test]+ async fn a_governed_generation_policy_keeps_generation_local_and_still_bridges_extraction() {+ let generate = fallback_config(HYBRID_GENERATE_MODEL);+ let extraction = fallback_config(HYBRID_EXTRACT_MODEL);+ let policy = Arc::new(RoutePolicy {+ admit: true,+ govern_generation: true,+ ..Default::default()+ });+ let gateway = cold_gateway(&[&generate, &extraction], policy.clone()).await;++ for surface in ["native", "chat", "completions", "responses"] {+ let response = buffered_surface(&gateway, surface, json!({})).await;+ assert_eq!(+ response.status(),+ StatusCode::SERVICE_UNAVAILABLE,+ "{surface}"+ );+ assert!(+ !response.headers().contains_key("x-sie-fallback-reason"),+ "{surface}"+ );+ }+ assert!(gateway.dispatcher.dispatched().is_empty());+ assert!(policy.asked().is_empty());++ let response = extract(&gateway, extraction_request(false, json!({}))).await;+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ gateway.dispatcher.dispatched(),+ vec![dispatched("extract", REMOTE_LANE, "acme/extract:remote")]+ );+ assert_eq!(policy.asked().len(), 1);+ }++ #[tokio::test]+ async fn a_threshold_route_asks_the_policy_before_routing_remotely() {+ use crate::handlers::test_support::ThresholdBroker;+ use crate::state::threshold_coordinator::ThresholdSampler;+ let config = format!("{HYBRID_EXTRACT_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 admit in [true, false] {+ let Some(broker) = ThresholdBroker::start().await else {+ return;+ };+ let policy = Arc::new(RoutePolicy {+ admit,+ ..Default::default()+ });+ let mut gateway = TestGateway::with_threshold_routing(&[&config], true).await;+ gateway.install_policy(policy.clone());+ 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 = extract(&gateway, extraction_request(false, json!({}))).await;++ let asked = policy.asked();+ assert_eq!(+ asked.first(),+ Some(&(+ "acme/extract".to_string(),+ "acme/extract:remote".to_string(),+ RemoteRouteReason::Threshold,+ )),+ "admit={admit}"+ );+ if admit {+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(response.headers()["x-sie-served-by"], "remote");+ assert_eq!(+ gateway.dispatcher.dispatched(),+ vec![dispatched("extract", REMOTE_LANE, "acme/extract:remote")]+ );+ } else {+ assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);+ assert!(gateway.dispatcher.dispatched().is_empty());+ }+ }+ }++ #[tokio::test]+ async fn a_remote_profile_the_deployment_does_not_serve_keeps_the_bare_model_local() {+ let config = fallback_config(HYBRID_EXTRACT_MODEL);+ for (refuse_remote_serving, admit, bridged, asked) in [+ (true, true, false, 0),+ (false, false, false, 1),+ (false, true, true, 1),+ ] {+ let case = format!("refuse_remote_serving={refuse_remote_serving} admit={admit}");+ let policy = Arc::new(RoutePolicy {+ admit,+ refuse_remote_serving,+ ..Default::default()+ });+ let gateway = cold_gateway(&[&config], policy.clone()).await;+ let outcome = AdmissionOutcomeSlot::default();+ let mut request = extraction_request(false, json!({}));+ request.extensions_mut().insert(outcome.clone());++ let response = extract(&gateway, request).await;++ if bridged {+ assert_eq!(response.status(), StatusCode::OK, "{case}");+ assert_eq!(stamped(&response).0, Some("remote"), "{case}");+ } else {+ assert_local_provisioning(&response, &gateway);+ }+ assert_eq!(policy.asked().len(), asked, "{case}");+ assert_eq!(outcome.get(), None, "{case}");+ }+ }++ #[tokio::test]+ async fn a_named_remote_profile_is_never_asked_and_follows_visible_and_serving_refusal() {+ let config = fallback_config(HYBRID_EXTRACT_MODEL);+ for refuse_remote_serving in [false, true] {+ let policy = Arc::new(RoutePolicy {+ refuse_remote_serving,+ ..Default::default()+ });+ let gateway = cold_gateway(&[&config], policy.clone()).await;+ let mut request = extraction_request(false, json!({}));+ *request.uri_mut() = "/v1/extract/acme/extract:remote".parse().unwrap();++ let response = extract(&gateway, request).await;++ if refuse_remote_serving {+ assert_eq!(response.status(), StatusCode::FORBIDDEN);+ assert!(gateway.dispatcher.dispatched().is_empty());+ } else {+ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(+ gateway.dispatcher.dispatched(),+ vec![dispatched("extract", REMOTE_LANE, "acme/extract:remote")]+ );+ }+ assert!(policy.asked().is_empty());+ }+ }++ #[tokio::test]+ async fn a_policy_is_decided_once_per_request_and_reason() {+ let config = fallback_config(HYBRID_EXTRACT_MODEL);+ let policy = Arc::new(RoutePolicy {+ admit_first_only: true,+ ..Default::default()+ });+ let mut gateway = TestGateway::new(&[&config]).await;+ gateway.install_policy(policy.clone());+ gateway+ .add_verified_worker("local-1", LOCAL_LANE, &[])+ .await;+ gateway+ .add_verified_worker("remote-1", REMOTE_LANE, &[])+ .await;++ let response = extract(&gateway, extraction_request(false, json!({}))).await;++ assert_eq!(response.status(), StatusCode::OK);+ assert_eq!(response.headers()["x-sie-fallback-reason"], "model_loading");+ assert_eq!(+ gateway.dispatcher.dispatched(),+ vec![+ dispatched("load", LOCAL_LANE, "acme/extract"),+ dispatched("extract", REMOTE_LANE, "acme/extract:remote"),+ ]+ );+ assert_eq!(+ policy.asked(),+ vec![(+ "acme/extract".to_string(),+ "acme/extract:remote".to_string(),+ RemoteRouteReason::Fallback(FallbackTrigger::ModelLoading),+ )]+ );+ }}diff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rsindex 781c11162..c95ebad3b 100644--- a/packages/sie_gateway/src/handlers/test_support.rs+++ b/packages/sie_gateway/src/handlers/test_support.rs@@ -744,6 +744,13 @@ impl TestGateway {}}+ /// Install a deployment's model access policy.+ pub(crate) fn install_policy(&mut self, policy: Arc<dyn crate::server::ModelAccessPolicy>) {+ Arc::get_mut(&mut self.state)+ .expect("the gateway state is not shared yet")+ .model_access_policy = Some(policy);+ }+/// Wait at most `seconds` for queued results.pub(crate) fn set_request_timeout(&mut self, seconds: f64) {let state = Arc::get_mut(&mut self.state).expect("the gateway state is not shared yet");diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex bd2b764ee..9dd46bfd9 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -71,9 +71,12 @@ pub trait ModelAccessPolicy: Send + Sync {/// alias expansion, `__`→`/`, and case folding. A gate that decides on the/// caller's raw string cannot see through a registry alias, so an alias/// pointing at a refused model would dispatch it; deciding here is what- /// makes the verdict authoritative for every surface that resolves a model.- /// Edge gates upstream may still refuse early, but they are an optimisation,- /// not the decision.+ /// makes the verdict authoritative for the model a request resolves to.+ /// Before a bridge, the gateway also asks it about the remote profile the+ /// bridge would serve, with the request extensions minus the+ /// admission-outcome slot; a refusal there keeps the local route and is+ /// neither returned nor recorded. Edge gates upstream may still refuse+ /// early, but they are an optimisation, not the decision.////// `ext` carries the request extensions, so an implementation can record the/// refusal on whatever per-request observability slot the deployment@@ -109,6 +112,46 @@ pub trait ModelAccessPolicy: Send + Sync {fn generation_route_policy(&self) -> Option<&dyn GenerationRoutePolicy> {None}++ /// Whether the request for `model` may be served through its remote+ /// profile `remote_model` for `reason`, for the caller in `ext`.+ ///+ /// It governs only the implicit routes of a bare model: a fallback bridge+ /// and a `threshold` route. A request that names the remote profile,+ /// directly or through an alias, is governed by [`Self::visible`] and+ /// [`Self::serving_refusal`] like any other model, so a caller who can see+ /// the remote profile can name it.+ ///+ /// The gateway asks only about a route it admits on its own: a bare model+ /// whose routing names `remote_model` and permits `reason`, no caller+ /// profile, bundle, pool or engine selector, no `X-SIE-Remote: forbid`, and+ /// a transport with execution authority v1. [`Self::visible`] and+ /// [`Self::serving_refusal`] have passed for `model` and for `remote_model`.+ /// Both ids are canonical and come from the registry snapshot that holds+ /// the route's worker hash. The gateway decides once per request, remote+ /// profile and reason, and reuses that decision.+ ///+ /// `false` keeps the local route: the caller receives the answer it would+ /// have received without a remote route. The default is `false`.+ fn remote_route_admitted(+ &self,+ _model: &str,+ _remote_model: &str,+ _reason: RemoteRouteReason,+ _ext: &axum::http::Extensions,+ ) -> bool {+ false+ }+}++/// Why the gateway would serve a bare-model request through the model's+/// remote profile.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum RemoteRouteReason {+ /// The local route refused before accepting the work, for this trigger.+ Fallback(crate::types::model::FallbackTrigger),+ /// A `threshold` decision routes the request remotely.+ Threshold,}/// Customer-visible generation intent selected from a validated request.diff --git a/packages/sie_gateway/src/state/model_registry.rs b/packages/sie_gateway/src/state/model_registry.rsindex 010f4cfe6..ab7394d78 100644--- a/packages/sie_gateway/src/state/model_registry.rs+++ b/packages/sie_gateway/src/state/model_registry.rs@@ -212,6 +212,8 @@ impl ModelRegistryGeneration {/// The remote profile and worker contract chosen from one registry snapshot.#[derive(Clone, Debug)]pub(crate) struct RemoteFallbackPlan {+ /// The canonical bare model the route stands in for.+ pub local_model: String,pub model: String,pub bundle: String,pub pool: String,@@ -1834,6 +1836,7 @@ impl ModelRegistry {admitted: None,});Some(RemoteFallbackPlan {+ local_model: local.canonical_base_model.clone(),model: remote_name,engine: snap.bundles.get(&bundle)?.engine.clone(),bundle,diff --git a/packages/sie_server/REMOTE_BACKENDS.md b/packages/sie_server/REMOTE_BACKENDS.mdindex b5bc1c8b6..b5a68fc64 100644--- a/packages/sie_server/REMOTE_BACKENDS.md+++ b/packages/sie_server/REMOTE_BACKENDS.md@@ -590,7 +590,11 @@ can bridge `provisioning` and `model_loading` refusals on native generation,chat, completions and supported buffered Responses. Native generation, chatand completions also support streaming bridges. Explicit profiles, bundlepins, machine or pool overrides, and `X-SIE-Remote: forbid` retain their selected-route. Deployment-governed routes require separate admission.+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+that names the remote profile follows the same visibility and serving rules as+any other model.Cold capacity retains local pending demand. An available local worker whosemodel is unloaded receives load-only work, and the gateway waits for broker