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): suggest the closest visible model ids on MODEL_NOT_FOUND (#942)

Shai Shmuela64c300fef40
diff --git a/packages/sie_gateway/src/handlers/mod.rs b/packages/sie_gateway/src/handlers/mod.rs
index 6b4746a44..dc5547077 100644
--- a/packages/sie_gateway/src/handlers/mod.rs
+++ b/packages/sie_gateway/src/handlers/mod.rs
@@ -14,3 +14,4 @@ pub mod systemone;
pub(crate) mod test_support;
pub(crate) mod lora;
+pub(crate) mod model_suggestions;
diff --git a/packages/sie_gateway/src/handlers/model_suggestions.rs b/packages/sie_gateway/src/handlers/model_suggestions.rs
new file mode 100644
index 000000000..3176f5806
--- /dev/null
+++ b/packages/sie_gateway/src/handlers/model_suggestions.rs
@@ -0,0 +1,316 @@
+//! "Did you mean ...?" hints for the `MODEL_NOT_FOUND` response.
+//!
+//! 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.
+
+use crate::server::AppState;
+
+/// Most ids one response suggests.
+const MAX_SUGGESTIONS: usize = 3;
+
+/// Shortest normalized request that may match by prefix or by edit distance.
+/// Below this, almost every id is "close".
+const MIN_FUZZY_LEN: usize = 4;
+
+/// Requests longer than this get no hint, which bounds the work one 404 can
+/// cost.
+const MAX_REQUEST_LEN: usize = 256;
+
+/// Largest edit distance accepted as a typo, whatever the id length.
+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.
+///
+/// `requested` is always the caller's own string.
+pub(crate) fn unknown_model_message(requested: &str, suggestions: &[String]) -> String {
+ match suggestions {
+ [] => format!("Model '{requested}' not found"),
+ [only] => format!("Model '{requested}' not found. Did you mean '{only}'?"),
+ many => {
+ let quoted: Vec<String> = many.iter().map(|id| format!("'{id}'")).collect();
+ format!(
+ "Model '{requested}' not found. Did you mean one of: {}?",
+ quoted.join(", ")
+ )
+ }
+ }
+}
+
+/// Suggestions for `requested`, drawn only from the ids this caller may list.
+///
+/// Candidates are the registry's ids that pass the visibility filter
+/// `GET /v1/models` applies, so every suggestion is an id that listing shows.
+/// 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(
+ state: &AppState,
+ ext: &axum::http::Extensions,
+ requested: &str,
+) -> Vec<String> {
+ let candidates = state
+ .model_registry
+ .list_models()
+ .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)
+}
+
+/// Up to [`MAX_SUGGESTIONS`] ids from `candidates` that `requested` most
+/// likely meant, closest first. Empty when nothing is close.
+///
+/// A registry also lists `model:profile` variants. Those are skipped: the
+/// request is matched without its own `:profile`, and naming every variant of
+/// one model would crowd out other models.
+pub(crate) fn suggest_model_ids(
+ requested: &str,
+ candidates: impl IntoIterator<Item = String>,
+) -> Vec<String> {
+ if requested.len() > MAX_REQUEST_LEN {
+ return Vec::new();
+ }
+ let wanted = normalize(model_part(requested));
+ if wanted.is_empty() {
+ return Vec::new();
+ }
+ let mut scored: Vec<(Closeness, String)> = candidates
+ .into_iter()
+ .filter(|id| !id.contains(':'))
+ .filter_map(|id| closeness(&wanted, &normalize(&id)).map(|score| (score, id)))
+ .collect();
+ scored.sort();
+ scored.dedup_by(|a, b| a.1 == b.1);
+ scored.truncate(MAX_SUGGESTIONS);
+ scored.into_iter().map(|(_, id)| id).collect()
+}
+
+/// How a candidate matched, best first; the `usize` breaks ties inside a kind.
+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
+enum Closeness {
+ /// Same id once case and separators are ignored.
+ SameId,
+ /// Same model name; the organization is missing or different.
+ SameName,
+ /// The request is the start of the id; fewer missing characters first.
+ Prefix(usize),
+ /// A few edits apart; fewer edits first.
+ Typo(usize),
+}
+
+fn closeness(wanted: &str, candidate: &str) -> Option<Closeness> {
+ if wanted == candidate {
+ return Some(Closeness::SameId);
+ }
+ let candidate_name = name_part(candidate);
+ let wanted_name = name_part(wanted);
+ if wanted_name.len() >= MIN_FUZZY_LEN && wanted_name == candidate_name {
+ return Some(Closeness::SameName);
+ }
+ // A request without an organization is compared with the model name alone.
+ let target = if wanted.contains('/') {
+ candidate
+ } else {
+ candidate_name
+ };
+ if wanted.len() < MIN_FUZZY_LEN {
+ return None;
+ }
+ if target.starts_with(wanted) {
+ return Some(Closeness::Prefix(target.len() - wanted.len()));
+ }
+ let allowed = (wanted.len() / TYPO_CHARS_PER_EDIT).clamp(1, MAX_TYPO_DISTANCE);
+ if wanted.len().abs_diff(target.len()) > allowed {
+ return None;
+ }
+ let distance = edit_distance(wanted.as_bytes(), target.as_bytes());
+ (distance <= allowed).then_some(Closeness::Typo(distance))
+}
+
+/// The model id inside a request string: drops a leading `bundle:/` and a
+/// trailing `:profile`. Purely syntactic, so it never consults the registry.
+fn model_part(requested: &str) -> &str {
+ let without_bundle = requested
+ .split_once(":/")
+ .map_or(requested, |(_, rest)| rest);
+ without_bundle
+ .split_once(':')
+ .map_or(without_bundle, |(model, _)| model)
+}
+
+/// Lower case, `__` read as `/`, and every other separator dropped, so ids
+/// that differ only in case or punctuation compare equal.
+fn normalize(id: &str) -> String {
+ id.replace("__", "/")
+ .chars()
+ .filter(|c| c.is_ascii_alphanumeric() || *c == '/')
+ .map(|c| c.to_ascii_lowercase())
+ .collect()
+}
+
+fn name_part(normalized: &str) -> &str {
+ normalized
+ .rsplit_once('/')
+ .map_or(normalized, |(_, name)| name)
+}
+
+/// Levenshtein distance over bytes; inputs are ASCII after [`normalize`].
+fn edit_distance(a: &[u8], b: &[u8]) -> usize {
+ let mut previous: Vec<usize> = (0..=b.len()).collect();
+ let mut current = vec![0; b.len() + 1];
+ for (i, &left) in a.iter().enumerate() {
+ current[0] = i + 1;
+ for (j, &right) in b.iter().enumerate() {
+ let substitution = previous[j] + usize::from(left != right);
+ current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
+ }
+ std::mem::swap(&mut previous, &mut current);
+ }
+ previous[b.len()]
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn catalog() -> Vec<String> {
+ [
+ "BAAI/bge-m3",
+ "BAAI/bge-reranker-v2-m3",
+ "Qwen/Qwen3.5-4B",
+ "Qwen/Qwen3.6-27B",
+ "Qwen/Qwen3.8-27B-FP8",
+ "google/gemma-4-E4B-it",
+ ]
+ .into_iter()
+ .map(String::from)
+ .collect()
+ }
+
+ fn suggest(requested: &str) -> Vec<String> {
+ suggest_model_ids(requested, catalog())
+ }
+
+ #[test]
+ fn a_missing_organization_suggests_the_full_id() {
+ assert_eq!(suggest("bge-m3"), ["BAAI/bge-m3"]);
+ }
+
+ #[test]
+ fn a_wrong_organization_suggests_the_id_with_the_same_name() {
+ assert_eq!(suggest("bge/bge-m3"), ["BAAI/bge-m3"]);
+ }
+
+ #[test]
+ fn a_missing_suffix_suggests_the_longer_id_first() {
+ // The id that only adds a suffix ranks ahead of a sibling one edit away.
+ assert_eq!(
+ suggest("Qwen/Qwen3.8-27B"),
+ ["Qwen/Qwen3.8-27B-FP8", "Qwen/Qwen3.6-27B"]
+ );
+ }
+
+ #[test]
+ fn a_typo_suggests_the_nearest_id() {
+ assert_eq!(suggest("BAAI/bge-n3"), ["BAAI/bge-m3"]);
+ assert_eq!(suggest("gogle/gemma-4-E4B-it"), ["google/gemma-4-E4B-it"]);
+ }
+
+ #[test]
+ fn case_and_separator_differences_suggest_the_canonical_id() {
+ assert_eq!(suggest("baai/BGE_M3"), ["BAAI/bge-m3"]);
+ assert_eq!(suggest("BAAI__bge.m3"), ["BAAI/bge-m3"]);
+ }
+
+ #[test]
+ fn a_bundle_prefix_and_a_profile_suffix_are_ignored_when_matching() {
+ assert_eq!(suggest("default:/bge-m3"), ["BAAI/bge-m3"]);
+ assert_eq!(suggest("BAAI/bge-n3:banking"), ["BAAI/bge-m3"]);
+ }
+
+ #[test]
+ fn profile_variants_of_a_model_are_not_suggested() {
+ let listed = ["BAAI/bge-m3", "BAAI/bge-m3:dense", "BAAI/bge-m3:candle"]
+ .into_iter()
+ .map(String::from);
+ assert_eq!(suggest_model_ids("bge-m3", listed), ["BAAI/bge-m3"]);
+ }
+
+ #[test]
+ fn nothing_close_suggests_nothing() {
+ assert!(suggest("acme/unrelated-model").is_empty());
+ assert!(suggest("m3").is_empty());
+ assert!(suggest("").is_empty());
+ assert!(suggest(":/").is_empty());
+ }
+
+ #[test]
+ fn an_oversized_request_suggests_nothing() {
+ let requested = format!("BAAI/bge-m3{}", "x".repeat(MAX_REQUEST_LEN));
+ assert!(suggest(&requested).is_empty());
+ }
+
+ #[test]
+ fn suggestions_are_capped_and_ordered_closest_first() {
+ // Three ids start with the request; the one with the fewest missing
+ // characters comes first, and the order does not depend on input order.
+ let expected = [
+ "Qwen/Qwen3.5-4B",
+ "Qwen/Qwen3.6-27B",
+ "Qwen/Qwen3.8-27B-FP8",
+ ];
+ assert_eq!(suggest("Qwen/Qwen3"), expected);
+ let mut reversed = catalog();
+ reversed.reverse();
+ assert_eq!(suggest_model_ids("Qwen/Qwen3", reversed), expected);
+
+ let many = (0..10).map(|n| format!("org/model-{n}"));
+ assert_eq!(suggest_model_ids("org/model", many).len(), MAX_SUGGESTIONS);
+ }
+
+ #[test]
+ fn only_offered_candidates_are_ever_suggested() {
+ // The caller's string is one edit from an id that is not in the
+ // candidate set, so the hint cannot name it.
+ let visible = vec!["BAAI/bge-m3".to_string()];
+ assert!(suggest_model_ids("acme/secret-modle", visible).is_empty());
+ }
+
+ #[test]
+ fn the_message_keeps_the_plain_form_without_suggestions() {
+ assert_eq!(unknown_model_message("x/y", &[]), "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()]),
+ "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()]),
+ "Model 'q' not found. Did you mean one of: 'a/b', 'c/d'?"
+ );
+ }
+
+ #[test]
+ fn edit_distance_counts_insertions_deletions_and_substitutions() {
+ assert_eq!(edit_distance(b"", b""), 0);
+ assert_eq!(edit_distance(b"abc", b""), 3);
+ assert_eq!(edit_distance(b"kitten", b"sitting"), 3);
+ assert_eq!(edit_distance(b"bgem3", b"bgen3"), 1);
+ }
+}
diff --git a/packages/sie_gateway/src/handlers/proxy.rs b/packages/sie_gateway/src/handlers/proxy.rs
index 756d9bf4b..b453c4215 100644
--- a/packages/sie_gateway/src/handlers/proxy.rs
+++ b/packages/sie_gateway/src/handlers/proxy.rs
@@ -43,6 +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::serving_disclosure::{
remote_forbidden, DeferredFallbackFinish, FallbackAttempt, ServingDisclosure,
UnansweredBeforeDeadline,
@@ -1534,22 +1535,6 @@ pub async fn proxy_generate(state: State<Arc<AppState>>, req: Request) -> impl I
proxy_request(state, req, "generate").await
}
-/// Resolve a request's model id to its serving bundle.
-///
-/// Extracted from `proxy_request` (#1543) so the model→bundle decision is one
-/// testable unit instead of being inlined in the 2000-line handler. Behaviour
-/// is identical to the block it replaces: on any failure it returns the exact
-/// caller-facing error `Response` (boxed to keep the `Result` small) that the
-/// inline code produced — model-not-found 404, bundle-routing-conflict 409, or
-/// the unknown-model 404 when the registry is populated. With an empty registry
-/// it falls back to the caller's bundle override (or `"default"`).
-///
-/// `requested` is the string the CALLER sent; `model_name` is what it resolved
-/// to. The unknown-model 404 echoes `requested`, never `model_name` (#2542): a
-/// resolved id can be a registry alias's target, and a 404 that names it hands
-/// every caller a read of the alias table — including targets in another org's
-/// 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.
/// The one native-surface `MODEL_NOT_FOUND` body.
///
/// Three native call sites answer "this model is not here": the #1841
@@ -1562,7 +1547,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.
-fn unknown_model_response(endpoint: &str, requested: &str) -> Response {
+///
+/// `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 {
endpoint_error_response(
endpoint,
StatusCode::NOT_FOUND,
@@ -1570,7 +1559,7 @@ fn unknown_model_response(endpoint: &str, requested: &str) -> Response {
oai_type::MODEL_NOT_FOUND,
oai_code::MODEL_NOT_FOUND,
Some("model"),
- format!("Model '{}' not found", requested),
+ unknown_model_message(requested, suggestions),
)
}
@@ -1585,6 +1574,25 @@ fn absent_from_populated_registry(registry: &ModelRegistry, model_name: &str) ->
!registry.model_exists(model_name) && registry.has_any_models()
}
+/// Resolve a request's model id to its serving bundle.
+///
+/// Extracted from `proxy_request` (#1543) so the model→bundle decision is one
+/// testable unit instead of being inlined in the 2000-line handler. Behaviour
+/// is identical to the block it replaces: on any failure it returns the exact
+/// caller-facing error `Response` (boxed to keep the `Result` small) that the
+/// inline code produced — model-not-found 404, bundle-routing-conflict 409, or
+/// the unknown-model 404 when the registry is populated. With an empty registry
+/// it falls back to the caller's bundle override (or `"default"`).
+///
+/// `requested` is the string the CALLER sent; `model_name` is what it resolved
+/// to. The unknown-model 404 echoes `requested`, never `model_name` (#2542): a
+/// resolved id can be a registry alias's target, and a 404 that names it hands
+/// every caller a read of the alias table — including targets in another org's
+/// 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.
fn resolve_bundle_for_request(
registry: &ModelRegistry,
model_name: &str,
@@ -1592,6 +1600,7 @@ fn resolve_bundle_for_request(
bundle_override: &str,
engine_pin: Option<&str>,
endpoint: &str,
+ suggestions: &dyn Fn(&str) -> Vec<String>,
) -> Result<String, Box<Response>> {
let bundle_override_ref = if bundle_override.is_empty() {
None
@@ -1635,7 +1644,11 @@ fn resolve_bundle_for_request(
}
}
} else if registry.has_any_models() {
- return Err(Box::new(unknown_model_response(endpoint, requested)));
+ return Err(Box::new(unknown_model_response(
+ endpoint,
+ requested,
+ &suggestions(requested),
+ )));
} else if bundle_override.is_empty() {
"default".to_string()
} else {
@@ -2193,7 +2206,11 @@ async fn resolve_routing(
.as_ref()
.is_some_and(|p| !p.visible(&model_name, ext))
{
- return Err(Box::new(unknown_model_response(endpoint, &model)));
+ return Err(Box::new(unknown_model_response(
+ endpoint,
+ &model,
+ &visible_model_suggestions(state, ext, &model),
+ )));
}
// #2542 deployment serving policy on the RESOLVED id: the authoritative
// "we do not serve this model here" verdict (the managed service's §6.5
@@ -2332,7 +2349,11 @@ async fn resolve_routing(
if generation_intent.is_some()
&& absent_from_populated_registry(&state.model_registry, &model_name)
{
- return Err(Box::new(unknown_model_response(endpoint, &model)));
+ return Err(Box::new(unknown_model_response(
+ endpoint,
+ &model,
+ &visible_model_suggestions(state, ext, &model),
+ )));
}
let governed_route = if let Some(intent) = generation_intent {
match governed_generation_route(state, &model_name, &dispatch_model, intent) {
@@ -2399,6 +2420,7 @@ async fn resolve_routing(
effective_bundle_override,
engine_pin.as_deref(),
endpoint,
+ &|requested| visible_model_suggestions(state, ext, requested),
)?;
let engine = state
@@ -8538,7 +8560,10 @@ pub(crate) fn resolve_model_and_bundle(
return Err((
StatusCode::NOT_FOUND,
Json(json_openai_error(
- format!("Model '{model_spec}' not found"),
+ unknown_model_message(
+ model_spec,
+ &visible_model_suggestions(state, ext, model_spec),
+ ),
oai_type::MODEL_NOT_FOUND,
Some("model"),
oai_code::MODEL_NOT_FOUND,
@@ -8608,7 +8633,10 @@ 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).
- format!("Model '{model_spec}' not found"),
+ unknown_model_message(
+ model_spec,
+ &visible_model_suggestions(state, ext, model_spec),
+ ),
oai_type::MODEL_NOT_FOUND,
Some("model"),
oai_code::MODEL_NOT_FOUND,
@@ -16911,9 +16939,16 @@ mod tests {
let registry = ModelRegistry::new(bundles_dir.path(), models_dir.path(), true);
assert!(!registry.has_any_models());
- let default =
- resolve_bundle_for_request(&registry, "org/model", "org/model", "", None, "encode")
- .expect("empty registry + no override resolves");
+ let default = resolve_bundle_for_request(
+ &registry,
+ "org/model",
+ "org/model",
+ "",
+ None,
+ "encode",
+ &|_| Vec::new(),
+ )
+ .expect("empty registry + no override resolves");
assert_eq!(default, "default");
let overridden = resolve_bundle_for_request(
@@ -16923,6 +16958,7 @@ mod tests {
"custom-bundle",
None,
"encode",
+ &|_| Vec::new(),
)
.expect("empty registry preserves caller bundle");
assert_eq!(overridden, "custom-bundle");
@@ -19949,6 +19985,184 @@ mod tests {
);
}
+ /// A registry holding exactly `ids`, in temp dirs the CALLER owns (see
+ /// [`populated_registry`] for why the dirs must outlive the registry).
+ fn registry_with_models(
+ ids: &[&str],
+ ) -> (Arc<ModelRegistry>, tempfile::TempDir, tempfile::TempDir) {
+ let bundles_dir = tempfile::TempDir::new().unwrap();
+ let models_dir = tempfile::TempDir::new().unwrap();
+ std::fs::write(
+ bundles_dir.path().join("default.yaml"),
+ "name: default\nadapters:\n - module\ndefault: true\n",
+ )
+ .unwrap();
+ for (index, id) in ids.iter().enumerate() {
+ std::fs::write(
+ models_dir.path().join(format!("model-{index}.yaml")),
+ format!(
+ "sie_id: {id}\nprofiles:\n default:\n adapter_path: sie_server.adapters.sentence_transformer:Adapter\n"
+ ),
+ )
+ .unwrap();
+ }
+ let registry = Arc::new(ModelRegistry::new(
+ bundles_dir.path(),
+ models_dir.path(),
+ true,
+ ));
+ for id in ids {
+ assert!(registry.model_exists(id), "{id} must be registered");
+ }
+ (registry, bundles_dir, models_dir)
+ }
+
+ /// Hides every id under one organization prefix and shows the rest: one
+ /// caller's view of a deployment that also holds another tenant's models.
+ struct HidesOrganization(&'static str);
+ impl crate::server::ModelAccessPolicy for HidesOrganization {
+ fn visible(&self, resolved_model: &str, _ext: &axum::http::Extensions) -> bool {
+ !resolved_model.starts_with(self.0)
+ }
+ }
+
+ fn state_with_registry_hiding_org_42(registry: Arc<ModelRegistry>) -> AppState {
+ let pm = Arc::new(PoolManager::new(vec!["l4".to_string()]));
+ let mut state = admission_test_state(pm);
+ state.model_registry = registry;
+ state.model_access_policy = Some(
+ Arc::new(HidesOrganization("org-42/")) as Arc<dyn crate::server::ModelAccessPolicy>
+ );
+ state
+ }
+
+ async fn native_encode_not_found_body(state: &AppState, model: &str) -> String {
+ let response = match resolve_routing(
+ state,
+ &HeaderMap::new(),
+ &axum::http::Extensions::new(),
+ &format!("/v1/encode/{model}"),
+ "encode",
+ None,
+ )
+ .await
+ {
+ Ok(_) => panic!("{model} must 404"),
+ Err(response) => *response,
+ };
+ assert_eq!(response.status(), StatusCode::NOT_FOUND);
+ let body = to_bytes(response.into_body(), 64 * 1024)
+ .await
+ .expect("body");
+ String::from_utf8(body.to_vec()).expect("utf8")
+ }
+
+ async fn openai_not_found_body(state: &AppState, model: &str) -> String {
+ let response = match resolve_model_and_bundle(state, model, &axum::http::Extensions::new())
+ {
+ Ok(_) => panic!("{model} must 404"),
+ Err(response) => response,
+ };
+ assert_eq!(response.status(), StatusCode::NOT_FOUND);
+ let body = to_bytes(response.into_body(), 64 * 1024)
+ .await
+ .expect("body");
+ String::from_utf8(body.to_vec()).expect("utf8")
+ }
+
+ /// The "Did you mean" hint keeps the no-oracle property. The same caller
+ /// sends the same strings to a deployment that holds another tenant's model
+ /// and to one that does not; every body must match on the native and the
+ /// OpenAI routes, and the hidden id must never be the hint.
+ ///
+ /// The strings cover both arms that build this 404. One under the hidden
+ /// organization is stopped by the visibility gate. One without it reaches
+ /// the unknown-model arm, where only the candidate filter keeps the hidden
+ /// id out, so that arm needs a string one edit from the hidden model's name.
+ #[tokio::test]
+ async fn not_found_hint_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 (with_hidden, _b1, _m1) = registry_with_models(&[VISIBLE, HIDDEN]);
+ let (without_hidden, _b2, _m2) = registry_with_models(&[VISIBLE]);
+ let holds_hidden = state_with_registry_hiding_org_42(with_hidden);
+ let lacks_hidden = state_with_registry_hiding_org_42(without_hidden);
+
+ for requested in [
+ // Visibility gate: the hidden id itself, and near misses under the
+ // hidden organization.
+ HIDDEN,
+ "org-42/embedder-large-tune",
+ "org-42/embedder-large",
+ // Unknown-model arm: no organization, or a visible one, so the
+ // gate lets the string through. Each is one edit from the hidden
+ // model's name and not close to any visible id.
+ "embedder-large-tune",
+ "vendor/embedder-large-tune",
+ "acme/embedder-large-tuned",
+ ] {
+ let native = (
+ native_encode_not_found_body(&holds_hidden, requested).await,
+ native_encode_not_found_body(&lacks_hidden, requested).await,
+ );
+ let openai = (
+ openai_not_found_body(&holds_hidden, requested).await,
+ openai_not_found_body(&lacks_hidden, requested).await,
+ );
+ for (route, (hidden_exists, hidden_absent)) in [("native", native), ("openai", openai)]
+ {
+ assert_eq!(
+ hidden_exists, hidden_absent,
+ "{route}: '{requested}' must get one response whether or not the hidden model exists"
+ );
+ if requested != HIDDEN {
+ assert!(
+ !hidden_exists.contains(HIDDEN),
+ "{route}: the hidden id must never be suggested: {hidden_exists}"
+ );
+ }
+ }
+ }
+
+ let hinted = native_encode_not_found_body(&holds_hidden, "org-42/embedder-large").await;
+ assert!(
+ hinted.contains("Did you mean 'vendor/embedder-large'?"),
+ "a visible id close to the request is suggested: {hinted}"
+ );
+ let unhinted = native_encode_not_found_body(&holds_hidden, HIDDEN).await;
+ assert!(
+ !unhinted.contains("Did you mean"),
+ "nothing visible is close to the hidden id: {unhinted}"
+ );
+ }
+
+ /// The native routes and the OpenAI body routes render the hint through one
+ /// function, so the same input reads the same on both.
+ #[tokio::test]
+ async fn not_found_hint_reads_the_same_on_native_and_openai_routes() {
+ let (registry, _bundles, _models) = registry_with_models(&["vendor/embedder-large"]);
+ let state = state_with_registry_hiding_org_42(registry);
+ let expected = "Model 'embedder-large' not found. Did you mean 'vendor/embedder-large'?";
+
+ let native = native_encode_not_found_body(&state, "embedder-large").await;
+ let native: serde_json::Value = serde_json::from_str(&native).expect("error JSON");
+ assert_eq!(native["detail"]["message"], expected);
+
+ let openai = match resolve_model_and_bundle(
+ &state,
+ "embedder-large",
+ &axum::http::Extensions::new(),
+ ) {
+ Ok(_) => panic!("an unknown model must 404"),
+ Err(response) => response,
+ };
+ assert_eq!(openai.status(), StatusCode::NOT_FOUND);
+ let openai = to_bytes(openai.into_body(), 64 * 1024).await.expect("body");
+ let openai: serde_json::Value = serde_json::from_slice(&openai).expect("error JSON");
+ assert_eq!(openai["error"]["message"], expected);
+ assert_eq!(openai["error"]["code"], "model_not_found");
+ }
+
/// 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 a