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): name the replacement when a retired model id is requested (#944)
Shai Shmuel70fe04b06929
diff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex ad3c1582e..bd66ee8fc 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -33,6 +33,7 @@"SIE_GATEWAY_GPU_ALIASES""SIE_GATEWAY_HEALTH_MODE""SIE_GATEWAY_MACHINE_PROFILES"+ "SIE_GATEWAY_RETIRED_MODELS""SIE_GATEWAY_STATIC_QUEUE_POOLS""SIE_ADMIN_TOKEN""SIE_CONFIG_SERVICE_TOKEN"@@ -257,6 +258,13 @@ spec:- name: SIE_GATEWAY_MODEL_ALIASESvalue: {{ toJson . | quote }}{{- end }}+ {{- with .Values.gateway.retiredModels }}+ # Retired model id -> replacement id. A request for a retired id+ # gets a 404 that names the replacement. Opt-in: only rendered+ # when gateway.retiredModels is set.+ - name: SIE_GATEWAY_RETIRED_MODELS+ value: {{ toJson . | quote }}+ {{- end }}# Machine profiles (JSON format for pool validation and routing)- name: SIE_GATEWAY_MACHINE_PROFILESvalueFrom:diff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 6fb444830..12828e5e8 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -198,6 +198,16 @@ gateway:# sql: "bf16-27b:/Qwen/Qwen3.6-27B"modelAliases: {}+ # -- Retired model id → replacement model id. A request for a retired id+ # still gets `404 MODEL_NOT_FOUND`, but the message names the replacement:+ # "Model '<id>' was retired. Use '<replacement>'." An alias reroutes a+ # request silently; a retired entry refuses it and explains. The note is+ # shown only when the replacement is in the model registry and the caller may+ # list both ids. An entry stays until you remove it. Example:+ # retiredModels:+ # org/old-model: "org/new-model"+ retiredModels: {}+# -- Number of gateway replicas (default 1; bump to 2+ for HA).# Also used as KEDA's `minReplicaCount` floor (see# templates/keda-scaledobject.yaml). The gateway is stateless on thediff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex ab3a453f6..94825928e 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -5,6 +5,7 @@ use std::time::Duration;use axum::http::HeaderValue;use serde::Deserialize;+use crate::handlers::model_suggestions::{retired_model_declared, retired_model_key};use crate::state::demand_tracker::PhysicalLaneCatalog;use crate::state::pool_manager::PoolLimits;use crate::types::pool::PoolSpec;@@ -206,6 +207,12 @@ pub struct Config {// publishable — those are the names the epic exists to make discoverable.pub published_model_aliases: HashSet<String>,+ // Retired model id -> replacement id, from `SIE_GATEWAY_RETIRED_MODELS`+ // (JSON map). Keys are stored as `retired_model_key` reads them; a request+ // for one gets `MODEL_NOT_FOUND` naming the replacement. See+ // `build_retired_models`.+ pub retired_models: HashMap<String, RetiredModel>,+// Model registry paths (filesystem seed; same volume mounted into sie-config// for consistency, but the gateway never writes to them).pub bundles_dir: String,@@ -349,6 +356,7 @@ impl std::fmt::Debug for Config {.field("configured_physical_lanes", &self.configured_physical_lanes).field("static_queue_pools", &self.static_queue_pools).field("model_aliases", &self.model_aliases)+ .field("retired_models", &self.retired_models).field("bundles_dir", &self.bundles_dir).field("models_dir", &self.models_dir).field("config_service_url", &self.config_service_url)@@ -608,9 +616,17 @@ fn env_csv(key: &str) -> Vec<String> {fn env_json_string_map(key: &str) -> HashMap<String, String> {match env::var(key) {- Ok(s) if !s.trim().is_empty() => {- serde_json::from_str::<HashMap<String, String>>(&s).unwrap_or_default()- }+ Ok(s) if !s.trim().is_empty() => serde_json::from_str::<HashMap<String, String>>(&s)+ .unwrap_or_else(|error| {+ // The value is not logged: it is operator config, and the+ // serde error already says where the JSON broke.+ tracing::warn!(+ env = key,+ %error,+ "ignoring {key}: not a JSON object of strings; using no entries"+ );+ HashMap::new()+ }),_ => HashMap::new(),}}@@ -756,6 +772,59 @@ fn build_model_aliases((map, published)}+/// One `SIE_GATEWAY_RETIRED_MODELS` entry.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct RetiredModel {+ /// The retired id in the operator's case with `__` read as `/`+ /// (`retired_model_declared`). The retired note needs the caller to be+ /// allowed to list this spelling and its lower-cased form (the map key),+ /// plus the replacement.+ pub declared: String,+ /// The id the 404 names instead, trimmed.+ pub replacement: String,+}++/// Retired model id -> replacement id from `SIE_GATEWAY_RETIRED_MODELS`.+///+/// Keys go through `retired_model_key`, the same normalization the lookup+/// applies to the caller's string. The declared id keeps the operator's case+/// with `__` read as `/` (`retired_model_declared`); the replacement is kept+/// as written (trimmed). Entries with an empty key or replacement are+/// skipped. If two entries share a key, the one whose `(declared,+/// replacement)` pair sorts first in byte order wins, so the result never+/// depends on map order. Unlike an alias, which reroutes+/// the request silently, a retired entry refuses it and names the+/// replacement. A string that is also an alias name is treated as the alias:+/// it never gets the retired note (see `not_found_hint`).+pub(crate) fn build_retired_models(+ entries: HashMap<String, String>,+) -> HashMap<String, RetiredModel> {+ let mut map: HashMap<String, RetiredModel> = HashMap::new();+ for (retired, replacement) in entries {+ let key = retired_model_key(&retired);+ let replacement = replacement.trim().to_string();+ if key.is_empty() || replacement.is_empty() {+ continue;+ }+ let entry = RetiredModel {+ declared: retired_model_declared(&retired),+ replacement,+ };+ match map.entry(key) {+ std::collections::hash_map::Entry::Occupied(mut slot) => {+ let held = slot.get();+ if (&entry.declared, &entry.replacement) < (&held.declared, &held.replacement) {+ slot.insert(entry);+ }+ }+ std::collections::hash_map::Entry::Vacant(slot) => {+ slot.insert(entry);+ }+ }+ }+ map+}+fn build_gpu_profile_map(configured_gpus: &[String],aliases: HashMap<String, String>,@@ -856,6 +925,8 @@ impl Config {);let (model_aliases, published_model_aliases) =build_model_aliases(env_json_string_map("SIE_GATEWAY_MODEL_ALIASES"));+ let retired_models =+ build_retired_models(env_json_string_map("SIE_GATEWAY_RETIRED_MODELS"));Self {host: "0.0.0.0".to_string(),@@ -920,6 +991,7 @@ impl Config {static_queue_pools: env_static_queue_pools("SIE_GATEWAY_STATIC_QUEUE_POOLS"),model_aliases,published_model_aliases,+ retired_models,bundles_dir: env_default("SIE_BUNDLES_DIR", "bundles"),models_dir: env_default("SIE_MODELS_DIR", "models"),@@ -1508,6 +1580,99 @@ mod tests {assert!(!published.contains("guard"));}+ #[test]+ fn test_build_retired_models_normalizes_keys_and_keeps_replacements() {+ let mut entries = HashMap::new();+ entries.insert("Qwen__Qwen3-4B".to_string(), "Qwen/Qwen3.6-27B".to_string());+ entries.insert(" Org/Old:fast ".to_string(), " Org/New ".to_string());++ let result = build_retired_models(entries);++ assert_eq!(result.len(), 2);+ assert_eq!(+ result.get("qwen/qwen3-4b"),+ Some(&RetiredModel {+ declared: "Qwen/Qwen3-4B".to_string(),+ replacement: "Qwen/Qwen3.6-27B".to_string(),+ })+ );+ assert_eq!(+ result.get("org/old"),+ Some(&RetiredModel {+ declared: "Org/Old".to_string(),+ replacement: "Org/New".to_string(),+ })+ );+ }++ #[test]+ fn test_build_retired_models_keeps_the_first_sorted_id_on_a_shared_key() {+ let mut entries = HashMap::new();+ entries.insert("org/old".to_string(), "Org/B".to_string());+ entries.insert("Org/Old".to_string(), "Org/A".to_string());+ entries.insert("Org__Old".to_string(), "Org/C".to_string());++ let result = build_retired_models(entries);++ assert_eq!(result.len(), 1);+ assert_eq!(+ result.get("org/old"),+ Some(&RetiredModel {+ declared: "Org/Old".to_string(),+ replacement: "Org/A".to_string(),+ })+ );+ }++ #[test]+ fn test_build_retired_models_breaks_a_declared_id_tie_on_the_replacement() {+ let mut entries = HashMap::new();+ entries.insert("Org/Old:fast".to_string(), "Org/B".to_string());+ entries.insert("Org/Old:slow".to_string(), "Org/A".to_string());+ entries.insert("bundle:/Org/Old".to_string(), "Org/C".to_string());++ let result = build_retired_models(entries);++ assert_eq!(+ result.get("org/old"),+ Some(&RetiredModel {+ declared: "Org/Old".to_string(),+ replacement: "Org/A".to_string(),+ })+ );+ }++ #[test]+ fn test_build_retired_models_skips_empty_entries() {+ let mut entries = HashMap::new();+ entries.insert("".to_string(), "Org/New".to_string());+ entries.insert("Org/Old".to_string(), " ".to_string());+ entries.insert("bundle:/".to_string(), "Org/New".to_string());++ assert!(build_retired_models(entries).is_empty());+ }++ #[test]+ fn test_config_load_reads_retired_models() {+ with_env(+ &[(+ "SIE_GATEWAY_RETIRED_MODELS",+ r#"{"Org__Old":"Org/New","":"Org/Other"}"#,+ )],+ || {+ let cfg = Config::load();+ assert_eq!(cfg.retired_models.len(), 1);+ assert_eq!(+ cfg.retired_models.get("org/old"),+ Some(&RetiredModel {+ declared: "Org/Old".to_string(),+ replacement: "Org/New".to_string(),+ })+ );+ },+ );+ }+#[test]fn test_build_gpu_profile_map_does_not_override_canonical_profile() {let mut aliases = HashMap::new();@@ -2227,6 +2392,7 @@ mod tests {static_queue_pools: Vec::new(),model_aliases: HashMap::new(),published_model_aliases: Default::default(),+ retired_models: HashMap::new(),bundles_dir: String::new(),models_dir: String::new(),config_service_url: None,diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex 1dddf60fe..9dd760e01 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -504,6 +504,7 @@ mod tests {static_queue_pools: Vec::new(),model_aliases: HashMap::new(),published_model_aliases: Default::default(),+ retired_models: HashMap::new(),bundles_dir: bundles_dir.to_string(),models_dir: models_dir.to_string(),payload_store_url: String::new(),diff --git a/packages/sie_gateway/src/handlers/health.rs b/packages/sie_gateway/src/handlers/health.rsindex 7f91b4171..2ea8a141c 100644--- a/packages/sie_gateway/src/handlers/health.rs+++ b/packages/sie_gateway/src/handlers/health.rs@@ -274,6 +274,7 @@ mod tests {static_queue_pools: Vec::new(),model_aliases: HashMap::new(),published_model_aliases: Default::default(),+ retired_models: HashMap::new(),bundles_dir: bundles_dir.to_string(),models_dir: models_dir.to_string(),payload_store_url: String::new(),diff --git a/packages/sie_gateway/src/handlers/model_suggestions.rs b/packages/sie_gateway/src/handlers/model_suggestions.rsindex 3176f5806..c5072bb76 100644--- a/packages/sie_gateway/src/handlers/model_suggestions.rs+++ b/packages/sie_gateway/src/handlers/model_suggestions.rs@@ -1,12 +1,22 @@-//! "Did you mean ...?" hints for the `MODEL_NOT_FOUND` response.+//! Hints for the `MODEL_NOT_FOUND` response: "was retired" or "Did you mean".//!-//! The hint is a function of exactly two inputs: the string the caller sent-//! and the model ids that caller may list. Nothing resolved from the request-//! (an alias target, a canonical id, a governed route) takes part, so a model-//! hidden by a [`ModelAccessPolicy`](crate::server::ModelAccessPolicy), a model-//! that does not exist, and a model whose route was never compiled still-//! produce the same body for the same request string.+//! The hint is a function of exactly three inputs: the string the caller sent,+//! the operator's retired-model map, and the model ids that caller may list.+//! Nothing resolved from the request (an alias target, a canonical id, a+//! governed route) takes part, and the lookup never asks whether the requested+//! id itself exists, so a model hidden by a+//! [`ModelAccessPolicy`](crate::server::ModelAccessPolicy), a model that does+//! not exist, and a model whose route was never compiled still produce the same+//! body for the same request string.+//!+//! A retired id has no registry entry, so its canonical case is unknown. The+//! retired note therefore needs the caller to be allowed to list the retired+//! id both in the operator's spelling (with `__` read as `/`) and in lower+//! case, plus the replacement as the registry spells it.++use std::collections::HashMap;+use crate::config::RetiredModel;use crate::server::AppState;/// Most ids one response suggests.@@ -26,11 +36,25 @@ const MAX_TYPO_DISTANCE: usize = 3;/// One accepted edit per this many normalized characters.const TYPO_CHARS_PER_EDIT: usize = 6;-/// The `MODEL_NOT_FOUND` message for `requested`, with a hint when-/// `suggestions` is not empty.+/// What the `MODEL_NOT_FOUND` message adds after "not found".+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum NotFoundHint {+ /// "Did you mean" ids, closest first. Empty means no hint.+ Suggestions(Vec<String>),+ /// The operator retired the requested id in favour of `replacement`.+ Retired { replacement: String },+}++/// The `MODEL_NOT_FOUND` message for `requested` with its `hint`.////// `requested` is always the caller's own string.-pub(crate) fn unknown_model_message(requested: &str, suggestions: &[String]) -> String {+pub(crate) fn unknown_model_message(requested: &str, hint: &NotFoundHint) -> String {+ let suggestions = match hint {+ NotFoundHint::Retired { replacement } => {+ return format!("Model '{requested}' was retired. Use '{replacement}'.");+ }+ NotFoundHint::Suggestions(suggestions) => suggestions.as_slice(),+ };match suggestions {[] => format!("Model '{requested}' not found"),[only] => format!("Model '{requested}' not found. Did you mean '{only}'?"),@@ -44,30 +68,125 @@ pub(crate) fn unknown_model_message(requested: &str, suggestions: &[String]) ->}}-/// Suggestions for `requested`, drawn only from the ids this caller may list.+/// The hint every `MODEL_NOT_FOUND` site renders for `requested`.///-/// Candidates are the registry's ids that pass the visibility filter-/// `GET /v1/models` applies, so every suggestion is an id that listing shows.+/// A retired note wins when the operator retired the caller's string and this+/// caller may list the retired id in the operator's spelling and in lower+/// case, plus the replacement as the registry spells it. Otherwise the+/// "Did you mean" ids, drawn only from what this caller may list: the+/// registry's ids that pass the visibility filter `GET /v1/models` applies./// The listing can show more: ids only a worker advertises are left out,/// because a request for one gets this same 404 from a populated registry.-pub(crate) fn visible_model_suggestions(+///+/// An alias with the same name as a retired id wins: when `requested` names a+/// configured alias (matched by [`names_model_alias`], the same lookup the+/// request resolution uses), no retired note is given, even if the alias+/// target then answers not found. Only the caller's string and the alias+/// names are consulted, never the alias target or the registry.+///+/// [`names_model_alias`]: crate::handlers::proxy::names_model_alias+pub(crate) fn not_found_hint(state: &AppState,ext: &axum::http::Extensions,requested: &str,-) -> Vec<String> {- let candidates = state- .model_registry- .list_models()+) -> NotFoundHint {+ let visible = |id: &str| {+ state+ .model_access_policy+ .as_ref()+ .is_none_or(|policy| policy.visible(id, ext))+ };+ hint_for(+ requested,+ crate::handlers::proxy::names_model_alias(&state.config.model_aliases, requested),+ &state.config.retired_models,+ state.model_registry.list_models(),+ visible,+ )+}++/// [`not_found_hint`] over plain inputs: `requested_is_alias` says whether+/// the caller's string names a configured alias (then no retired note),+/// `listed` is every registry id and `visible` says which of them this caller+/// may list.+///+/// The retired id is asked about twice, as the operator spelled it (`__` read+/// as `/`) and lower-cased (the map key), because it has no registry entry+/// to fix its canonical case: a case-sensitive policy must allow both. The+/// second call is skipped when the two forms are equal.+fn hint_for(+ requested: &str,+ requested_is_alias: bool,+ retired: &HashMap<String, RetiredModel>,+ listed: Vec<String>,+ visible: impl Fn(&str) -> bool,+) -> NotFoundHint {+ let retired_hit = if requested_is_alias {+ None+ } else {+ retired_entry(retired, requested)+ };+ if let Some((key, entry)) = retired_hit {+ // Never the `__` spelling: the policy contract takes `/`.+ if let Some(replacement) = registered_replacement(&listed, &entry.replacement) {+ if visible(&entry.declared)+ && (key == entry.declared || visible(key))+ && visible(replacement)+ {+ return NotFoundHint::Retired {+ replacement: replacement.to_string(),+ };+ }+ }+ }+ // Variants are never suggested, so the policy is not asked about them.+ let candidates = listed.into_iter()- // Variants are never suggested, so the policy is not asked about them..filter(|id| !id.contains(':'))- .filter(|id| {- state- .model_access_policy- .as_ref()- .is_none_or(|policy| policy.visible(id, ext))- });- suggest_model_ids(requested, candidates)+ .filter(|id| visible(id));+ NotFoundHint::Suggestions(suggest_model_ids(requested, candidates))+}++/// The registry's spelling of `replacement`: the id that matches the whole+/// string ignoring case and reading `__` as `/`, as the gateway resolves ids.+/// A `model:profile` replacement matches only that registered variant, and a+/// base id never matches a variant. If several ids match, the byte-order+/// first wins.+fn registered_replacement<'a>(listed: &'a [String], replacement: &str) -> Option<&'a str> {+ let wanted = replacement.replace("__", "/").to_ascii_lowercase();+ listed+ .iter()+ .filter(|id| id.replace("__", "/").to_ascii_lowercase() == wanted)+ .map(String::as_str)+ .min()+}++/// The retired-map entry for `requested`, matched exactly on+/// [`retired_model_key`]. Never fuzzy.+fn retired_entry<'a>(+ retired: &'a HashMap<String, RetiredModel>,+ requested: &str,+) -> Option<(&'a str, &'a RetiredModel)> {+ if retired.is_empty() || requested.len() > MAX_REQUEST_LEN {+ return None;+ }+ retired+ .get_key_value(&retired_model_key(requested))+ .map(|(key, entry)| (key.as_str(), entry))+}++/// A retired id in the operator's case and in canonical form: trimmed,+/// without a `bundle:/` prefix or `:profile` suffix, `__` read as `/`. This+/// is the form the access policy is asked about.+pub(crate) fn retired_model_declared(id: &str) -> String {+ model_part(id.trim()).replace("__", "/")+}++/// The key a retired-model entry is stored and looked up under: the model id+/// without a `bundle:/` prefix or `:profile` suffix, lower case, `__` read as+/// `/`. Other separators are kept, so only the same id matches.+pub(crate) fn retired_model_key(id: &str) -> String {+ retired_model_declared(id).to_ascii_lowercase()}/// Up to [`MAX_SUGGESTIONS`] ids from `candidates` that `requested` most@@ -289,23 +408,254 @@ mod tests {assert!(suggest_model_ids("acme/secret-modle", visible).is_empty());}+ fn suggested(ids: &[&str]) -> NotFoundHint {+ NotFoundHint::Suggestions(ids.iter().map(|id| id.to_string()).collect())+ }+#[test]fn the_message_keeps_the_plain_form_without_suggestions() {- assert_eq!(unknown_model_message("x/y", &[]), "Model 'x/y' not found");+ assert_eq!(+ unknown_model_message("x/y", &suggested(&[])),+ "Model 'x/y' not found"+ );}#[test]fn the_message_names_one_or_several_suggestions() {assert_eq!(- unknown_model_message("bge-m3", &["BAAI/bge-m3".to_string()]),+ unknown_model_message("bge-m3", &suggested(&["BAAI/bge-m3"])),"Model 'bge-m3' not found. Did you mean 'BAAI/bge-m3'?");assert_eq!(- unknown_model_message("q", &["a/b".to_string(), "c/d".to_string()]),+ unknown_model_message("q", &suggested(&["a/b", "c/d"])),"Model 'q' not found. Did you mean one of: 'a/b', 'c/d'?");}+ #[test]+ fn the_retired_message_echoes_the_request_and_names_the_replacement() {+ let hint = NotFoundHint::Retired {+ replacement: "Qwen/Qwen3.6-27B".to_string(),+ };+ assert_eq!(+ unknown_model_message("qwen__qwen3-4b:fast", &hint),+ "Model 'qwen__qwen3-4b:fast' was retired. Use 'Qwen/Qwen3.6-27B'."+ );+ }++ fn retired_map(entries: &[(&str, &str)]) -> HashMap<String, RetiredModel> {+ crate::config::build_retired_models(+ entries+ .iter()+ .map(|(id, replacement)| (id.to_string(), replacement.to_string()))+ .collect(),+ )+ }++ fn retired() -> HashMap<String, RetiredModel> {+ retired_map(&[("Qwen/Qwen3-4B", "Qwen/Qwen3.6-27B")])+ }++ fn hint(requested: &str) -> NotFoundHint {+ hint_for(requested, false, &retired(), catalog(), |_| true)+ }++ fn retired_hint() -> NotFoundHint {+ NotFoundHint::Retired {+ replacement: "Qwen/Qwen3.6-27B".to_string(),+ }+ }++ #[test]+ fn a_retired_id_names_its_replacement() {+ assert_eq!(hint("Qwen/Qwen3-4B"), retired_hint());+ }++ #[test]+ fn a_retired_id_matches_in_any_case_and_in_the_double_underscore_form() {+ assert_eq!(hint("qwen/qwen3-4b"), retired_hint());+ assert_eq!(hint("Qwen__Qwen3-4B"), retired_hint());+ }++ #[test]+ fn a_retired_id_matches_with_a_bundle_prefix_or_a_profile_suffix() {+ assert_eq!(hint("default:/Qwen/Qwen3-4B"), retired_hint());+ assert_eq!(hint("Qwen/Qwen3-4B:fast"), retired_hint());+ }++ #[test]+ fn a_retired_id_is_matched_exactly_not_by_closeness() {+ // One edit away, and a different separator: both fall back to the+ // "Did you mean" ids.+ assert_eq!(hint("Qwen/Qwen3-4C"), suggested(&["Qwen/Qwen3.5-4B"]));+ assert!(matches!(+ hint("Qwen/Qwen3_4B"),+ NotFoundHint::Suggestions(_)+ ));+ }++ #[test]+ fn without_a_retired_entry_the_suggestions_are_unchanged() {+ assert_eq!(hint("bge-m3"), suggested(&["BAAI/bge-m3"]));+ assert_eq!(+ hint_for("bge-m3", false, &HashMap::new(), catalog(), |_| true),+ suggested(&["BAAI/bge-m3"])+ );+ }++ #[test]+ fn a_replacement_missing_from_the_registry_gives_no_retired_note() {+ let listed = vec!["Qwen/Qwen3.5-4B".to_string()];+ assert_eq!(+ hint_for("Qwen/Qwen3-4B", false, &retired(), listed, |_| true),+ suggested(&["Qwen/Qwen3.5-4B"])+ );+ }++ #[test]+ fn a_retired_or_replacement_id_the_caller_may_not_list_gives_no_retired_note() {+ let hides_replacement = |id: &str| id != "Qwen/Qwen3.6-27B";+ let hides_retired = |id: &str| id != "Qwen/Qwen3-4B";+ for visible in [&hides_replacement as &dyn Fn(&str) -> bool, &hides_retired] {+ let hint = hint_for("Qwen/Qwen3-4B", false, &retired(), catalog(), visible);+ assert!(matches!(hint, NotFoundHint::Suggestions(_)), "{hint:?}");+ }+ }++ #[test]+ fn the_policy_must_allow_the_retired_id_in_the_operators_case_and_in_lower_case() {+ let retired = retired_map(&[("bundle:/Org-42__Old:fast", "Qwen/Qwen3.6-27B")]);+ let asked = std::cell::RefCell::new(Vec::new());+ let records = |id: &str| {+ asked.borrow_mut().push(id.to_string());+ true+ };+ assert_eq!(+ hint_for("org-42/old", false, &retired, catalog(), records),+ retired_hint()+ );+ assert!(asked.borrow().iter().any(|id| id == "Org-42/Old"));+ assert!(asked.borrow().iter().any(|id| id == "org-42/old"));+ assert!(!asked.borrow().iter().any(|id| id == "Org-42__Old"));++ // Hiding either asked form blocks the note.+ for hidden in ["Org-42/Old", "org-42/old"] {+ let hint = hint_for("org-42/old", false, &retired, catalog(), |id: &str| {+ id != hidden+ });+ assert!(+ matches!(hint, NotFoundHint::Suggestions(_)),+ "{hidden}: {hint:?}"+ );+ }+ // The `__` spelling is never asked about, so hiding it changes nothing.+ assert_eq!(+ hint_for("org-42/old", false, &retired, catalog(), |id: &str| id+ != "Org-42__Old"),+ retired_hint()+ );+ }++ #[test]+ fn a_lower_case_declared_id_is_asked_about_once() {+ let retired = retired_map(&[("org/old", "Qwen/Qwen3.6-27B")]);+ let asked = std::cell::RefCell::new(Vec::new());+ let records = |id: &str| {+ asked.borrow_mut().push(id.to_string());+ true+ };+ assert_eq!(+ hint_for("Org/Old", false, &retired, catalog(), records),+ retired_hint()+ );+ assert_eq!(+ asked.borrow().iter().filter(|id| *id == "org/old").count(),+ 1+ );+ }++ #[test]+ fn a_replacement_written_in_another_case_or_spelling_names_the_registered_id() {+ for written in ["qwen/qwen3.6-27b", "QWEN__Qwen3.6-27B"] {+ let retired = retired_map(&[("Qwen/Qwen3-4B", written)]);+ let asked = std::cell::RefCell::new(Vec::new());+ let visible = |id: &str| {+ asked.borrow_mut().push(id.to_string());+ true+ };+ assert_eq!(+ hint_for("Qwen/Qwen3-4B", false, &retired, catalog(), visible),+ retired_hint(),+ "{written}"+ );+ assert!(asked.borrow().iter().any(|id| id == "Qwen/Qwen3.6-27B"));+ assert!(!asked.borrow().iter().any(|id| id == written));+ assert_eq!(+ unknown_model_message("Qwen/Qwen3-4B", &retired_hint()),+ "Model 'Qwen/Qwen3-4B' was retired. Use 'Qwen/Qwen3.6-27B'."+ );+ }+ }++ #[test]+ fn a_replacement_matching_several_registered_ids_names_the_byte_order_first() {+ let retired = retired_map(&[("Org/Old", "org/new")]);+ let listed = vec![+ "org/new".to_string(),+ "Org/New".to_string(),+ "Org/New:fast".to_string(),+ ];+ assert_eq!(+ hint_for("Org/Old", false, &retired, listed, |_| true),+ NotFoundHint::Retired {+ replacement: "Org/New".to_string()+ }+ );+ }++ #[test]+ fn a_variant_replacement_matches_only_that_registered_variant() {+ let listed = vec!["Org/New:fast".to_string()];+ assert_eq!(+ hint_for(+ "Org/Old",+ false,+ &retired_map(&[("Org/Old", "org/new:fast")]),+ listed.clone(),+ |_| true+ ),+ NotFoundHint::Retired {+ replacement: "Org/New:fast".to_string()+ }+ );+ let hint = hint_for(+ "Org/Old",+ false,+ &retired_map(&[("Org/Old", "Org/New")]),+ listed,+ |_| true,+ );+ assert!(matches!(hint, NotFoundHint::Suggestions(_)), "{hint:?}");+ }++ #[test]+ fn a_string_that_names_an_alias_gets_suggestions_not_the_retired_note() {+ assert_eq!(+ hint_for("Qwen/Qwen3-4B", true, &retired(), catalog(), |_| true),+ suggested(&["Qwen/Qwen3.5-4B"])+ );+ }++ #[test]+ fn an_oversized_request_gets_no_retired_note() {+ let long = format!("{}{}", "x".repeat(MAX_REQUEST_LEN), "/model");+ let retired = retired_map(&[(&long, "Qwen/Qwen3.6-27B")]);+ assert_eq!(+ hint_for(&long, false, &retired, catalog(), |_| true),+ suggested(&[])+ );+ }+#[test]fn edit_distance_counts_insertions_deletions_and_substitutions() {assert_eq!(edit_distance(b"", b""), 0);diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 6b9b42a1b..2ca0250c1 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -431,6 +431,7 @@ mod route_tests {static_queue_pools: Vec::new(),model_aliases: HashMap::new(),published_model_aliases: Default::default(),+ retired_models: HashMap::new(),bundles_dir: bundles_dir.to_string(),models_dir: models_dir.to_string(),payload_store_url: String::new(),diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rsindex b453c4215..265feb99b 100644--- a/packages/sie_gateway/src/handlers/proxy.rs+++ b/packages/sie_gateway/src/handlers/proxy.rs@@ -43,7 +43,7 @@ use crate::types::AuditEntry;use crate::middleware::auth::request_token_id;-use super::model_suggestions::{unknown_model_message, visible_model_suggestions};+use super::model_suggestions::{not_found_hint, unknown_model_message, NotFoundHint};use super::serving_disclosure::{remote_forbidden, DeferredFallbackFinish, FallbackAttempt, ServingDisclosure,UnansweredBeforeDeadline,@@ -1548,10 +1548,11 @@ pub async fn proxy_generate(state: State<Arc<AppState>>, req: Request) -> impl I/// `requested` is always the CALLER's string, never a resolved/governed id: a/// resolved id can be an alias target in another org's reserved namespace.///-/// `suggestions` come from [`visible_model_suggestions`] for the same-/// `requested` string at every call site, so the hint depends only on what the-/// caller sent and may list, and the three responses stay identical.-fn unknown_model_response(endpoint: &str, requested: &str, suggestions: &[String]) -> Response {+/// `hint` comes from [`not_found_hint`] for the same `requested` string at+/// every call site, so it depends only on what the caller sent, the operator's+/// retired-model map, and what the caller may list, and the three responses+/// stay identical.+fn unknown_model_response(endpoint: &str, requested: &str, hint: &NotFoundHint) -> Response {endpoint_error_response(endpoint,StatusCode::NOT_FOUND,@@ -1559,7 +1560,7 @@ fn unknown_model_response(endpoint: &str, requested: &str, suggestions: &[Stringoai_type::MODEL_NOT_FOUND,oai_code::MODEL_NOT_FOUND,Some("model"),- unknown_model_message(requested, suggestions),+ unknown_model_message(requested, hint),)}@@ -1591,8 +1592,8 @@ fn absent_from_populated_registry(registry: &ModelRegistry, model_name: &str) ->/// reserved namespace. It also makes this 404 byte-identical to the #1841/// cross-org one, which is the whole point of answering "not found" there.///-/// `suggestions` supplies the "Did you mean" ids for that 404. It is called-/// with `requested` and only when the 404 is built.+/// `hint` supplies the retired note or the "Did you mean" ids for that 404. It+/// is called with `requested` and only when the 404 is built.fn resolve_bundle_for_request(registry: &ModelRegistry,model_name: &str,@@ -1600,7 +1601,7 @@ fn resolve_bundle_for_request(bundle_override: &str,engine_pin: Option<&str>,endpoint: &str,- suggestions: &dyn Fn(&str) -> Vec<String>,+ hint: &dyn Fn(&str) -> NotFoundHint,) -> Result<String, Box<Response>> {let bundle_override_ref = if bundle_override.is_empty() {None@@ -1647,7 +1648,7 @@ fn resolve_bundle_for_request(return Err(Box::new(unknown_model_response(endpoint,requested,- &suggestions(requested),+ &hint(requested),)));} else if bundle_override.is_empty() {"default".to_string()@@ -2209,7 +2210,7 @@ async fn resolve_routing(return Err(Box::new(unknown_model_response(endpoint,&model,- &visible_model_suggestions(state, ext, &model),+ ¬_found_hint(state, ext, &model),)));}// #2542 deployment serving policy on the RESOLVED id: the authoritative@@ -2352,7 +2353,7 @@ async fn resolve_routing(return Err(Box::new(unknown_model_response(endpoint,&model,- &visible_model_suggestions(state, ext, &model),+ ¬_found_hint(state, ext, &model),)));}let governed_route = if let Some(intent) = generation_intent {@@ -2420,7 +2421,7 @@ async fn resolve_routing(effective_bundle_override,engine_pin.as_deref(),endpoint,- &|requested| visible_model_suggestions(state, ext, requested),+ &|requested| not_found_hint(state, ext, requested),)?;let engine = state@@ -8560,10 +8561,7 @@ pub(crate) fn resolve_model_and_bundle(return Err((StatusCode::NOT_FOUND,Json(json_openai_error(- unknown_model_message(- model_spec,- &visible_model_suggestions(state, ext, model_spec),- ),+ unknown_model_message(model_spec, ¬_found_hint(state, ext, model_spec)),oai_type::MODEL_NOT_FOUND,Some("model"),oai_code::MODEL_NOT_FOUND,@@ -8633,10 +8631,7 @@ pub(crate) fn resolve_model_and_bundle(Json(json_openai_error(// The caller's string, never the resolved one — see the// visibility gate above (#2542).- unknown_model_message(- model_spec,- &visible_model_suggestions(state, ext, model_spec),- ),+ unknown_model_message(model_spec, ¬_found_hint(state, ext, model_spec)),oai_type::MODEL_NOT_FOUND,Some("model"),oai_code::MODEL_NOT_FOUND,@@ -12009,6 +12004,21 @@ pub fn resolve_model_spec_with_aliases((req_bundle, model_name)}+/// Whether `spec` names a configured job/friendly alias, matched exactly as+/// [`resolve_model_spec_with_aliases`] matches it: a `bundle:/` prefix is+/// dropped, then [`lookup_alias`] (lower case, then the base before a+/// `:profile`) runs on the id as given and, when it contains `__`, on its+/// `/` form. Unlike the resolution, the registry is never consulted, so the+/// answer depends only on `spec` and the alias names.+pub(crate) fn names_model_alias(+ aliases: &std::collections::HashMap<String, String>,+ spec: &str,+) -> bool {+ let (_bundle, model) = parse_model_spec(spec);+ lookup_alias(aliases, &model).is_some()+ || (model.contains("__") && lookup_alias(aliases, &model.replace("__", "/")).is_some())+}+/// `pub` for the same reason as [`resolve_model_spec_with_aliases`]: the/// estimate receives a target PATH and must decode its model segment the way/// the route does before rating it.@@ -16946,7 +16956,7 @@ mod tests {"",None,"encode",- &|_| Vec::new(),+ &|_| NotFoundHint::Suggestions(Vec::new()),).expect("empty registry + no override resolves");assert_eq!(default, "default");@@ -16958,7 +16968,7 @@ mod tests {"custom-bundle",None,"encode",- &|_| Vec::new(),+ &|_| NotFoundHint::Suggestions(Vec::new()),).expect("empty registry preserves caller bundle");assert_eq!(overridden, "custom-bundle");@@ -17494,6 +17504,7 @@ mod tests {static_queue_pools: Vec::new(),model_aliases: std::collections::HashMap::new(),published_model_aliases: Default::default(),+ retired_models: Default::default(),bundles_dir: bundles_dir.path().to_string_lossy().to_string(),models_dir: models_dir.path().to_string_lossy().to_string(),config_service_url: None,@@ -20163,6 +20174,189 @@ mod tests {assert_eq!(openai["error"]["code"], "model_not_found");}+ /// `state` with `retired` as the operator's retired-model map.+ fn with_retired_models(mut state: AppState, retired: &[(&str, &str)]) -> AppState {+ let mut config = (*state.config).clone();+ config.retired_models = crate::config::build_retired_models(+ retired+ .iter()+ .map(|(id, replacement)| (id.to_string(), replacement.to_string()))+ .collect(),+ );+ state.config = Arc::new(config);+ state+ }++ /// `state` with `aliases` added to the configured job/friendly aliases.+ fn with_model_aliases(mut state: AppState, aliases: &[(&str, &str)]) -> AppState {+ let mut config = (*state.config).clone();+ for (alias, target) in aliases {+ config+ .model_aliases+ .insert(alias.to_ascii_lowercase(), target.to_string());+ }+ state.config = Arc::new(config);+ state+ }++ #[test]+ fn names_model_alias_matches_like_the_alias_resolution() {+ let aliases: std::collections::HashMap<String, String> = [+ ("old-name".to_string(), "vendor/x".to_string()),+ ("org/job".to_string(), "vendor/y".to_string()),+ ]+ .into_iter()+ .collect();+ for spec in [+ "old-name",+ "OLD-NAME",+ "old-name:fast",+ "fp8:/old-name",+ "org__job",+ "Org__Job:fast",+ ] {+ assert!(names_model_alias(&aliases, spec), "{spec}");+ }+ for spec in ["old-name-2", "old", "vendor/x", "old-name:"] {+ assert!(!names_model_alias(&aliases, spec), "{spec}");+ }+ }++ /// A string that is both an alias and a retired id: the alias wins, so+ /// when the alias target answers not found (hidden or absent) the body is+ /// the plain not-found body, with no retired note and no alias target.+ #[tokio::test]+ async fn an_alias_named_like_a_retired_id_gets_no_retired_note() {+ const VISIBLE: &str = "vendor/embedder-large";+ const HIDDEN: &str = "org-42/embedder-next";+ let (registry, _bundles, _models) = registry_with_models(&[VISIBLE, HIDDEN]);+ for target in [HIDDEN, "vendor/embedder-gone"] {+ let aliased = || {+ with_model_aliases(+ state_with_registry_hiding_org_42(Arc::clone(®istry)),+ &[("old-name", target)],+ )+ };+ let plain = not_found_bodies(&aliased(), "old-name").await;+ let with_entry = with_retired_models(aliased(), &[("old-name", VISIBLE)]);+ let got = not_found_bodies(&with_entry, "old-name").await;+ assert_eq!(got, plain, "alias target '{target}'");+ assert!(!got.0.contains("retired") && !got.1.contains("retired"));+ assert!(!got.0.contains(target) && !got.1.contains(target));+ }+ }++ /// Native and OpenAI 404 bodies for `requested`.+ async fn not_found_bodies(state: &AppState, requested: &str) -> (String, String) {+ (+ native_encode_not_found_body(state, requested).await,+ openai_not_found_body(state, requested).await,+ )+ }++ /// A retired entry the caller may not fully see leaves the 404 exactly as+ /// it is without the entry: a hidden replacement, a hidden retired id, or a+ /// replacement the registry does not hold.+ #[tokio::test]+ async fn a_retired_note_needs_both_ids_visible_and_the_replacement_registered() {+ const VISIBLE: &str = "vendor/embedder-large";+ const HIDDEN: &str = "org-42/embedder-next";+ let (registry, _bundles, _models) = registry_with_models(&[VISIBLE, HIDDEN]);+ let plain = state_with_registry_hiding_org_42(Arc::clone(®istry));++ for (requested, retired, replacement) in [+ // The replacement is hidden from this caller.+ ("vendor/embedder-old", "vendor/embedder-old", HIDDEN),+ // The retired id is hidden from this caller.+ ("org-42/embedder-old", "org-42/embedder-old", VISIBLE),+ // Declared with a capital letter the case-sensitive policy does+ // not hide; the lower-cased form is hidden, so no note.+ ("org-42/embedder-old", "Org-42/embedder-old", VISIBLE),+ // The replacement is not in the registry.+ (+ "vendor/embedder-old",+ "vendor/embedder-old",+ "vendor/embedder-gone",+ ),+ ] {+ let with_entry = with_retired_models(+ state_with_registry_hiding_org_42(Arc::clone(®istry)),+ &[(retired, replacement)],+ );+ let expected = not_found_bodies(&plain, requested).await;+ let got = not_found_bodies(&with_entry, requested).await;+ assert_eq!(got, expected, "'{requested}' -> '{replacement}'");+ assert!(!got.0.contains("retired"), "{}", got.0);+ assert!(!got.0.contains(HIDDEN) && !got.1.contains(HIDDEN));+ }+ }++ /// A retired id whose replacement the caller may list reads the same on a+ /// native route and an OpenAI route, and replaces the "Did you mean" ids.+ #[tokio::test]+ async fn a_retired_note_reads_the_same_on_native_and_openai_routes() {+ let (registry, _bundles, _models) = registry_with_models(&["vendor/embedder-large"]);+ let state = with_retired_models(+ state_with_registry_hiding_org_42(registry),+ &[("vendor/embedder-larg", "vendor/embedder-large")],+ );+ let expected = "Model 'vendor/embedder-larg' was retired. Use 'vendor/embedder-large'.";++ let (native, openai) = not_found_bodies(&state, "vendor/embedder-larg").await;+ let native: serde_json::Value = serde_json::from_str(&native).expect("error JSON");+ assert_eq!(native["detail"]["message"], expected);+ assert_eq!(native["detail"]["code"], "MODEL_NOT_FOUND");+ let openai: serde_json::Value = serde_json::from_str(&openai).expect("error JSON");+ assert_eq!(openai["error"]["message"], expected);+ assert_eq!(openai["error"]["code"], "model_not_found");+ assert_eq!(openai["error"]["param"], "model");+ }++ /// The no-oracle property with a retired map in place: the same request+ /// string gets one body whether or not a hidden model with that id, or+ /// with the id of its replacement, exists.+ #[tokio::test]+ async fn retired_note_is_the_same_whether_a_hidden_model_exists_or_not() {+ const VISIBLE: &str = "vendor/embedder-large";+ const HIDDEN: &str = "org-42/embedder-large-tuned";+ let retired = [+ (HIDDEN, VISIBLE),+ ("vendor/embedder-old", HIDDEN),+ ("vendor/embedder-older", VISIBLE),+ ];+ let (with_hidden, _b1, _m1) = registry_with_models(&[VISIBLE, HIDDEN]);+ let (without_hidden, _b2, _m2) = registry_with_models(&[VISIBLE]);+ let holds_hidden =+ with_retired_models(state_with_registry_hiding_org_42(with_hidden), &retired);+ let lacks_hidden =+ with_retired_models(state_with_registry_hiding_org_42(without_hidden), &retired);++ for requested in [+ HIDDEN,+ "org-42/embedder-large",+ "vendor/embedder-old",+ "Vendor__Embedder-Old",+ "vendor/embedder-older",+ "embedder-large-tune",+ ] {+ let held = not_found_bodies(&holds_hidden, requested).await;+ let lacked = not_found_bodies(&lacks_hidden, requested).await;+ assert_eq!(+ held, lacked,+ "'{requested}' must get one response whether or not the hidden model exists"+ );+ if requested != HIDDEN {+ assert!(!held.0.contains(HIDDEN) && !held.1.contains(HIDDEN));+ }+ }++ let (noted, _) = not_found_bodies(&holds_hidden, "vendor/embedder-older").await;+ assert!(+ noted.contains("was retired. Use 'vendor/embedder-large'."),+ "a visible replacement is named: {noted}"+ );+ }+/// The same rule on the OpenAI body seam, and the same/// hidden-vs-absent equality — this time against a REAL populated registry,/// so the comparison is with the live `has_any_models` 404 rather than adiff --git a/packages/sie_gateway/src/handlers/test_support.rs b/packages/sie_gateway/src/handlers/test_support.rsindex f004a7482..022e1a33a 100644--- a/packages/sie_gateway/src/handlers/test_support.rs+++ b/packages/sie_gateway/src/handlers/test_support.rs@@ -1024,6 +1024,7 @@ fn test_config(static_queue_pools: Vec::new(),model_aliases: HashMap::new(),published_model_aliases: Default::default(),+ retired_models: HashMap::new(),bundles_dir: bundles_dir.to_string(),models_dir: models_dir.to_string(),config_service_url: None,diff --git a/packages/sie_gateway/src/middleware/auth.rs b/packages/sie_gateway/src/middleware/auth.rsindex 850d1465f..cd5c0f66a 100644--- a/packages/sie_gateway/src/middleware/auth.rs+++ b/packages/sie_gateway/src/middleware/auth.rs@@ -614,6 +614,7 @@ mod tests {static_queue_pools: Vec::new(),model_aliases: HashMap::new(),published_model_aliases: Default::default(),+ retired_models: HashMap::new(),bundles_dir: String::new(),models_dir: String::new(),config_service_url: None,diff --git a/packages/sie_gateway/src/server.rs b/packages/sie_gateway/src/server.rsindex 9a1eaf556..ef8aa2200 100644--- a/packages/sie_gateway/src/server.rs+++ b/packages/sie_gateway/src/server.rs@@ -1288,6 +1288,7 @@ mod flat_404_tests {static_queue_pools: Vec::new(),model_aliases: HashMap::new(),published_model_aliases: Default::default(),+ retired_models: HashMap::new(),bundles_dir: bundles_dir.to_string(),models_dir: models_dir.to_string(),payload_store_url: String::new(),