Repository navigation
fix(multimodal): follow-ups to the 2026-09-22 merges #2642
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
664c877
5c54cee
36d43d9
3a00b1f
5bac697
e0dff57
c1a9234
7c20fd8
e8f1d80
76bdde1
3ac330c
d50f12e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| use std::{collections::HashMap, sync::OnceLock}; | ||
|
|
||
| use base64::{engine::general_purpose::STANDARD as BASE64_STANDARD, Engine}; | ||
| use serde_json::Value; | ||
| use thiserror::Error; | ||
|
|
||
|
|
@@ -8,7 +9,8 @@ use crate::{ | |
| encoder_inputs::PreprocessedEncoderInputs, | ||
| media::FrameSampling, | ||
| types::{ | ||
| EncoderFieldLayouts, FieldLayout, Modality, PromptReplacement, TokenId, VideoSamplingInfo, | ||
| EncoderFieldLayouts, FieldLayout, MediaContentPart, Modality, PromptReplacement, TokenId, | ||
| VideoSamplingInfo, | ||
| }, | ||
| vision::PreProcessorConfig, | ||
| }; | ||
|
|
@@ -42,6 +44,8 @@ pub enum ModelRegistryError { | |
| spec: &'static str, | ||
| modality: Modality, | ||
| }, | ||
| #[error("{format} images are not accepted by model spec {spec}")] | ||
| UnsupportedImageFormat { spec: &'static str, format: String }, | ||
| } | ||
|
|
||
| pub type RegistryResult<T> = Result<T, ModelRegistryError>; | ||
|
|
@@ -73,6 +77,52 @@ fn modality_limit_override(modality: Modality) -> Option<usize> { | |
| } | ||
| } | ||
|
|
||
| /// Base64 characters decoded to sniff a data URL's format: 96 bytes, past | ||
| /// every magic signature `image::guess_format` reads. | ||
| const SNIFF_BASE64_CHARS: usize = 128; | ||
|
|
||
| /// The image format a content part names: sniffed from the bytes (inline, | ||
| /// or decoded from a data URL) before the client's media type is believed, | ||
| /// else the media type in any case, else the URL path's extension. `None` | ||
| /// when nothing says (a URL without an extension, another modality). | ||
| fn image_format_of(part: &MediaContentPart) -> Option<image::ImageFormat> { | ||
| let from_media_type = |media_type: &str| { | ||
| image::ImageFormat::from_mime_type(media_type.trim().to_ascii_lowercase()) | ||
| }; | ||
| match part { | ||
| MediaContentPart::ImageData { | ||
| data, mime_type, .. | ||
| } => image::guess_format(data) | ||
| .ok() | ||
| .or_else(|| mime_type.as_deref().and_then(from_media_type)), | ||
| MediaContentPart::ImageUrl { url, .. } => { | ||
| if let Some(rest) = url.strip_prefix("data:") { | ||
| let (header, payload) = rest.split_once(',').unwrap_or((rest, "")); | ||
| let mut parameters = header.split(';'); | ||
| let media_type = parameters.next().unwrap_or_default(); | ||
| // The magic bytes sit in the first few dozen bytes: decode a | ||
| // bounded prefix (whole base64 quads), not a copy of the image. | ||
| let sniffed = parameters | ||
| .any(|parameter| parameter.trim().eq_ignore_ascii_case("base64")) | ||
| .then(|| { | ||
| // Bytes, not chars: base64 is ASCII, anything else | ||
| // fails to decode, and a byte prefix cannot panic. | ||
| let payload = payload.trim().as_bytes(); | ||
| let end = payload.len().min(SNIFF_BASE64_CHARS); | ||
| BASE64_STANDARD.decode(&payload[..end - end % 4]).ok() | ||
| }) | ||
| .flatten() | ||
| .and_then(|bytes| image::guess_format(&bytes).ok()); | ||
| return sniffed.or_else(|| from_media_type(media_type)); | ||
| } | ||
| let path = url.split(['?', '#']).next().unwrap_or_default(); | ||
|
Comment on lines
+94
to
+118
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Nit: MIME types are case-insensitive (RFC 2045), but image::ImageFormat::from_mime_type(media_type.to_ascii_lowercase())(
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 76bdde1: the media type is trimmed and ASCII-lowercased before |
||
| let extension = path.rsplit('/').next()?.rsplit_once('.')?.1; | ||
| image::ImageFormat::from_extension(extension) | ||
| } | ||
| _ => None, | ||
| } | ||
| } | ||
|
|
||
| fn check_media_counts( | ||
| spec: &'static str, | ||
| limits: &HashMap<Modality, usize>, | ||
|
|
@@ -255,6 +305,34 @@ pub trait ModelProcessorSpec: Send + Sync { | |
| }) | ||
| } | ||
|
|
||
| /// Image formats the model's vendor refuses; the gateway refuses them | ||
| /// up front, judged from the bytes, the data URL's type or the URL path. | ||
| fn rejected_image_formats(&self) -> &'static [image::ImageFormat] { | ||
| &[] | ||
| } | ||
|
|
||
| /// Refuse an image part whose format is one of | ||
| /// [`Self::rejected_image_formats`]. | ||
| fn validate_image_formats(&self, parts: &[MediaContentPart]) -> RegistryResult<()> { | ||
| let rejected = self.rejected_image_formats(); | ||
| if rejected.is_empty() { | ||
| return Ok(()); | ||
| } | ||
| for part in parts { | ||
| if let Some(format) = image_format_of(part).filter(|f| rejected.contains(f)) { | ||
| return Err(ModelRegistryError::UnsupportedImageFormat { | ||
| spec: self.name(), | ||
| format: format | ||
| .extensions_str() | ||
| .first() | ||
| .map_or("unknown", |s| *s) | ||
| .to_string(), | ||
| }); | ||
| } | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn processor_kwargs(&self, metadata: &ModelMetadata) -> RegistryResult<Value>; | ||
|
|
||
| /// Build the audio preprocessor for this model, if it supports audio. | ||
|
|
@@ -506,6 +584,123 @@ mod tests { | |
| assert!(!TestSpec.worker_expandable(Modality::Video)); | ||
| } | ||
|
|
||
| #[test] | ||
| fn image_formats_are_accepted_unless_a_spec_rejects_them() { | ||
| assert!(TestSpec.rejected_image_formats().is_empty()); | ||
| let bmp = MediaContentPart::ImageData { | ||
| data: b"BM\x00\x00".to_vec(), | ||
| mime_type: None, | ||
| uuid: None, | ||
| detail: None, | ||
| }; | ||
| assert!(TestSpec | ||
| .validate_image_formats(std::slice::from_ref(&bmp)) | ||
| .is_ok()); | ||
|
|
||
| struct NoBmp; | ||
| impl ModelProcessorSpec for NoBmp { | ||
| fn name(&self) -> &'static str { | ||
| "no-bmp" | ||
| } | ||
| fn matches(&self, _metadata: &ModelMetadata) -> bool { | ||
| true | ||
| } | ||
| fn placeholder_token(&self, _metadata: &ModelMetadata) -> RegistryResult<String> { | ||
| Ok("<img>".to_string()) | ||
| } | ||
| fn placeholder_token_id(&self, _metadata: &ModelMetadata) -> RegistryResult<TokenId> { | ||
| Ok(1) | ||
| } | ||
| fn modality_limits( | ||
| &self, | ||
| _metadata: &ModelMetadata, | ||
| ) -> RegistryResult<HashMap<Modality, usize>> { | ||
| Ok(HashMap::from([(Modality::Image, 1)])) | ||
| } | ||
| fn processor_kwargs(&self, _metadata: &ModelMetadata) -> RegistryResult<Value> { | ||
| Ok(Value::Null) | ||
| } | ||
| fn prompt_replacements( | ||
| &self, | ||
| _metadata: &ModelMetadata, | ||
| _preprocessed: &PreprocessedEncoderInputs, | ||
| ) -> RegistryResult<Vec<PromptReplacement>> { | ||
| Ok(Vec::new()) | ||
| } | ||
| fn rejected_image_formats(&self) -> &'static [image::ImageFormat] { | ||
| &[image::ImageFormat::Bmp] | ||
| } | ||
| } | ||
| let png = MediaContentPart::ImageUrl { | ||
| url: "https://a/x.png".to_string(), | ||
| detail: None, | ||
| uuid: None, | ||
| max_long_side_pixel: None, | ||
| }; | ||
| assert!(NoBmp | ||
| .validate_image_formats(std::slice::from_ref(&png)) | ||
| .is_ok()); | ||
| // Sniffed from the bytes (inline, or decoded from a data URL, before | ||
| // the client's media type is believed), from a data URL's type in | ||
| // any case, or from the URL path. | ||
| let data_url = |url: &str| MediaContentPart::ImageUrl { | ||
| url: url.to_string(), | ||
| detail: None, | ||
| uuid: None, | ||
| max_long_side_pixel: None, | ||
| }; | ||
| let rejected = [ | ||
| bmp, | ||
| MediaContentPart::ImageData { | ||
| data: b"zz".to_vec(), | ||
| mime_type: Some("IMAGE/BMP".to_string()), | ||
| uuid: None, | ||
| detail: None, | ||
| }, | ||
| data_url("data:image/bmp;base64,Qk0AAA=="), | ||
| data_url("data:image/BMP;base64,Qk0AAA=="), | ||
| // BMP bytes behind a lying media type, short and past the sniffed prefix. | ||
| data_url("data:image/png;base64,Qk0AAAAA"), | ||
| data_url(&format!( | ||
| "data:image/png;base64,{}", | ||
| BASE64_STANDARD.encode([b"BM".as_slice(), &[0u8; 4096]].concat()) | ||
| )), | ||
| data_url("https://a/scan.BMP?x=1"), | ||
| ]; | ||
| for part in &rejected { | ||
| assert_eq!( | ||
| NoBmp.validate_image_formats(std::slice::from_ref(part)), | ||
| Err(ModelRegistryError::UnsupportedImageFormat { | ||
| spec: "no-bmp", | ||
| format: "bmp".to_string(), | ||
| }), | ||
| "{part:?}" | ||
| ); | ||
| } | ||
| // Client-supplied payloads that are not base64 at all, multi-byte | ||
| // characters included, are sniffed without panicking and fall back | ||
| // to the media type. | ||
| for url in [ | ||
| "data:image/png;base64,aéé", | ||
| "data:image/bmp;base64,ééé", | ||
| "data:image/bmp;base64,", | ||
| ] { | ||
| let expected = url.starts_with("data:image/bmp").then(|| { | ||
| ModelRegistryError::UnsupportedImageFormat { | ||
| spec: "no-bmp", | ||
| format: "bmp".to_string(), | ||
| } | ||
| }); | ||
| assert_eq!( | ||
| NoBmp | ||
| .validate_image_formats(std::slice::from_ref(&data_url(url))) | ||
| .err(), | ||
| expected, | ||
| "{url}" | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn validation_accepts_any_declared_modality_subset() { | ||
| assert_eq!(validate(&TestSpec, &[(Modality::Image, 2)]), Ok(())); | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.