diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index bb77625a40..9973736606 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -5664,6 +5664,7 @@ name = "codex-utils-image" version = "0.0.0" dependencies = [ "base64 0.22.1", + "blake3", "codex-utils-cache", "divan", "image", diff --git a/codex-rs/utils/image/Cargo.toml b/codex-rs/utils/image/Cargo.toml index 2be40a8e2e..859be00e0b 100644 --- a/codex-rs/utils/image/Cargo.toml +++ b/codex-rs/utils/image/Cargo.toml @@ -14,6 +14,7 @@ ignored = ["png"] [dependencies] base64 = { workspace = true } +blake3 = { workspace = true } image = { version = "=0.25.9", default-features = false, features = ["jpeg", "png", "gif", "webp"] } moxcms = { version = "=0.7.11", features = ["options"] } png = { version = "=0.18.1", features = ["zlib-rs"] } diff --git a/codex-rs/utils/image/src/image_tests.rs b/codex-rs/utils/image/src/image_tests.rs index 2003f95ade..3272110905 100644 --- a/codex-rs/utils/image/src/image_tests.rs +++ b/codex-rs/utils/image/src/image_tests.rs @@ -99,7 +99,7 @@ async fn returns_original_image_when_within_bounds() { assert_eq!(encoded.width, 64); assert_eq!(encoded.height, 32); assert_eq!(encoded.mime, mime); - assert_eq!(encoded.bytes.as_ref(), original_bytes); + assert_eq!(*encoded.bytes, original_bytes); } } @@ -165,7 +165,7 @@ async fn resizing_preserves_supported_metadata() { assert_eq!((processed.width, processed.height), (2048, 2)); - let mut decoder = ImageReader::with_format(Cursor::new(&processed.bytes), format) + let mut decoder = ImageReader::with_format(Cursor::new(processed.bytes.as_slice()), format) .into_decoder() .expect("create decoder"); assert_eq!( @@ -198,9 +198,10 @@ async fn resizing_drops_non_rgb_icc_profile() { ) .expect("process image"); - let mut decoder = ImageReader::with_format(Cursor::new(&processed.bytes), ImageFormat::Jpeg) - .into_decoder() - .expect("create decoder"); + let mut decoder = + ImageReader::with_format(Cursor::new(processed.bytes.as_slice()), ImageFormat::Jpeg) + .into_decoder() + .expect("create decoder"); assert_eq!( ( decoder.icc_profile().expect("read ICC profile"), @@ -225,7 +226,7 @@ async fn preserves_large_image_in_original_mode() { assert_eq!(processed.width, 4096); assert_eq!(processed.height, 2048); assert_eq!(processed.mime, "image/png"); - assert_eq!(processed.bytes.as_ref(), original_bytes); + assert_eq!(*processed.bytes, original_bytes); } #[tokio::test(flavor = "current_thread")] @@ -246,7 +247,7 @@ async fn data_url_processing_preserves_supported_source_bytes() { assert_eq!(processed.width, 64); assert_eq!(processed.height, 32); assert_eq!(processed.mime, "image/png"); - assert_eq!(processed.bytes.as_ref(), original_bytes); + assert_eq!(*processed.bytes, original_bytes); } #[tokio::test(flavor = "multi_thread")] @@ -335,10 +336,16 @@ async fn fails_cleanly_for_invalid_images() { )); } -#[test] -fn rejects_png_with_readable_dimensions_and_corrupt_pixels() { +#[tokio::test(flavor = "multi_thread")] +async fn rejects_png_with_readable_dimensions_and_corrupt_pixels() { let image = ImageBuffer::from_pixel(100, 100, Rgba([10u8, 20, 30, 255])); let mut bytes = image_bytes(&image, ImageFormat::Png); + load_for_prompt_bytes( + Path::new("corrupt.png"), + bytes.clone(), + PromptImageMode::ORIGINAL_DETAIL, + ) + .expect("warm the cache with valid pixels"); let idat = bytes .windows(4) .position(|chunk_type| chunk_type == b"IDAT") @@ -365,8 +372,6 @@ fn rejects_png_with_readable_dimensions_and_corrupt_pixels() { #[tokio::test(flavor = "multi_thread")] async fn reprocesses_updated_file_contents() { - IMAGE_CACHE.clear(); - let first_image = ImageBuffer::from_pixel(32, 16, Rgba([20u8, 120, 220, 255])); let first_bytes = image_bytes(&first_image, ImageFormat::Png); @@ -394,8 +399,8 @@ async fn reprocesses_updated_file_contents() { assert_ne!(second.bytes, first.bytes); } -#[test] -fn legacy_cache_entry_cannot_bypass_sanitization() { +#[tokio::test(flavor = "multi_thread")] +async fn legacy_cache_entry_cannot_bypass_sanitization() { let image = ImageBuffer::from_pixel(7, 11, Rgba([42, 64, 128, 255])); let bytes = image_bytes_with_metadata(&image, ImageFormat::Jpeg, TEST_RGB_ICC_PROFILE); let path = Path::new("oriented.jpg"); @@ -411,27 +416,107 @@ fn legacy_cache_entry_cannot_bypass_sanitization() { } #[tokio::test(flavor = "multi_thread")] -async fn bounds_cache_by_encoded_byte_size() { +async fn bounds_cache_by_source_length_and_output_capacity() { let cache = ImageCache::new(NonZeroUsize::new(4).expect("non-zero cache capacity")); let key = |digest_byte| ImageCacheKey { - digest: [digest_byte; 20], + digest: blake3::hash(&[digest_byte]), mode: PromptImageMode::Original, decoder: PromptImageDecoder::Legacy, }; - let image = |size| EncodedImage { - bytes: vec![0; size].into(), - mime: "image/png".to_string(), - source_width: 1, - source_height: 1, - width: 1, - height: 1, + let image = |capacity| { + let mut bytes = Vec::with_capacity(capacity); + bytes.push(0); + PreparedImage::Encoded(EncodedImage { + bytes: bytes.into(), + mime: "image/png".to_string(), + source_width: 1, + source_height: 1, + width: 1, + height: 1, + }) }; - cache_image(&cache, key(1), image(3), /*byte_capacity*/ 5); - cache_image(&cache, key(2), image(3), /*byte_capacity*/ 5); - cache_image(&cache, key(3), image(6), /*byte_capacity*/ 5); + let source = PreparedImage::Source { + bytes: Weak::new(), + format: ImageFormat::Png, + width: 1, + height: 1, + encoded_len: 3, + }; + cache_image(&cache, key(1), source, vec![0; 3], /*byte_capacity*/ 5); + cache_image(&cache, key(2), image(3), vec![], /*byte_capacity*/ 5); + cache_image(&cache, key(3), image(6), vec![], /*byte_capacity*/ 5); assert!(cache.get(&key(1)).is_none()); assert!(cache.get(&key(2)).is_some()); assert!(cache.get(&key(3)).is_none()); } + +#[tokio::test(flavor = "multi_thread")] +async fn concurrent_cache_misses_share_the_first_live_buffer() { + let image = ImageBuffer::from_pixel(13, 9, Rgba([14, 50, 213, 255])); + let source = image_bytes(&image, ImageFormat::Png); + let key = ImageCacheKey { + digest: blake3::hash(&source), + mode: PromptImageMode::Original, + decoder: PromptImageDecoder::Legacy, + }; + let cache = ImageCache::new(NonZeroUsize::MIN); + let entry = prepare_for_prompt(Path::new("source.png"), &source, key.mode, key.decoder) + .expect("prepare PNG"); + + // Both callers finished decoding before either inserted its result. + let first = cache_image( + &cache, + key, + entry.clone(), + source.clone(), + MAX_IMAGE_CACHE_BYTES, + ); + let second = cache_image(&cache, key, entry, source, MAX_IMAGE_CACHE_BYTES); + assert!(Arc::ptr_eq(&first.bytes, &second.bytes)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn cache_shares_live_source_bytes_but_only_retains_transformed_output() { + let image = ImageBuffer::from_pixel(13, 9, Rgba([14, 50, 213, 255])); + let source = image_bytes(&image, ImageFormat::Png); + let path = Path::new("source.png"); + let load = |mode| load_for_prompt_bytes(path, source.clone(), mode).expect("prepare PNG"); + + let original = load(PromptImageMode::Original); + let weak = Arc::downgrade(&original.bytes); + let overlap = load(PromptImageMode::Original); + assert!(Arc::ptr_eq(&original.bytes, &overlap.bytes)); + drop((original, overlap)); + assert!(weak.upgrade().is_none()); + + let mut input = source.clone(); + input.reserve(1); + let input_ptr = input.as_ptr(); + let hit = load_for_prompt_bytes(path, input, PromptImageMode::Original).expect("reuse PNG"); + assert_eq!(hit.bytes.as_ptr(), input_ptr); + assert_eq!(*hit.bytes, source); + assert!(Arc::ptr_eq( + &hit.bytes, + &load(PromptImageMode::Original).bytes + )); + assert_eq!(hit.mime, "image/png"); + assert_eq!( + (hit.source_width, hit.source_height, hit.width, hit.height), + (13, 9, 13, 9) + ); + + let mode = PromptImageMode::ResizeWithLimits(PromptImageResizeLimits { + max_dimension: 8, + max_patches: 1, + }); + let resized = load(mode); + assert_ne!(*resized.bytes, source); + let transformed = Arc::downgrade(&resized.bytes); + drop(resized); + assert!(Arc::ptr_eq( + &transformed.upgrade().expect("cached output"), + &load(mode).bytes + )); +} diff --git a/codex-rs/utils/image/src/lib.rs b/codex-rs/utils/image/src/lib.rs index 2ebaaf858e..b21cfc3a6d 100644 --- a/codex-rs/utils/image/src/lib.rs +++ b/codex-rs/utils/image/src/lib.rs @@ -3,11 +3,11 @@ use std::num::NonZeroUsize; use std::path::Path; use std::sync::Arc; use std::sync::LazyLock; +use std::sync::Weak; use base64::Engine; use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use codex_utils_cache::BlockingLruCache; -use codex_utils_cache::sha1_digest; use image::ColorType; use image::DynamicImage; use image::GenericImageView; @@ -41,7 +41,7 @@ pub use crate::error::ImageProcessingError; #[derive(Debug, Clone)] pub struct EncodedImage { - pub bytes: Arc<[u8]>, + pub bytes: Arc>, pub mime: String, pub source_width: u32, pub source_height: u32, @@ -101,12 +101,65 @@ struct ImageMetadata { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] struct ImageCacheKey { - digest: [u8; 20], + // A hit can authorize reusing the supplied bytes, so the key must resist collisions. + digest: blake3::Hash, mode: PromptImageMode, decoder: PromptImageDecoder, } -type ImageCache = BlockingLruCache; +/// A source entry records a successful pixel decode that needed no resizing or re-encoding. +/// Other results, including sanitized images, always retain the decoder's output. +#[derive(Clone)] +enum PreparedImage { + Source { + // The Vec's buffer is separate from the Arc allocation kept alive by this Weak. + bytes: Weak>, + format: ImageFormat, + width: u32, + height: u32, + encoded_len: usize, + }, + Encoded(EncodedImage), +} + +impl PreparedImage { + /// Count the full allocation for retained buffers. Source entries keep their + /// original encoded length for eviction even after the last caller drops the bytes. + fn cache_cost_bytes(&self) -> usize { + match self { + Self::Source { encoded_len, .. } => *encoded_len, + Self::Encoded(image) => image.bytes.capacity(), + } + } + + /// Take the matching input buffer only if no caller still owns the source bytes. + /// Leave unused input with the caller so it can be freed outside the cache lock. + fn resolve(&mut self, source: &mut Vec) -> EncodedImage { + match self { + Self::Source { + bytes, + format, + width, + height, + .. + } => EncodedImage { + bytes: bytes.upgrade().unwrap_or_else(|| { + let shared = Arc::new(std::mem::take(source)); + *bytes = Arc::downgrade(&shared); + shared + }), + mime: format_to_mime(*format), + source_width: *width, + source_height: *height, + width: *width, + height: *height, + }, + Self::Encoded(image) => image.clone(), + } + } +} + +type ImageCache = BlockingLruCache; static IMAGE_CACHE: LazyLock = LazyLock::new(|| BlockingLruCache::new(NonZeroUsize::new(32).unwrap_or(NonZeroUsize::MIN))); @@ -121,129 +174,125 @@ pub fn load_for_prompt_bytes( fn load_for_prompt_bytes_with_decoder( path: &Path, - file_bytes: Vec, + mut file_bytes: Vec, mode: PromptImageMode, decoder: PromptImageDecoder, ) -> Result { let key = ImageCacheKey { - digest: sha1_digest(&file_bytes), + digest: blake3::hash(&file_bytes), mode, decoder, }; - if let Some(image) = IMAGE_CACHE.get(&key) { + if let Some(image) = IMAGE_CACHE.with_mut(|cache| { + cache + .get_mut(&key) + .map(|entry| entry.resolve(&mut file_bytes)) + }) { return Ok(image); } - let image = load_for_prompt_bytes_uncached(path, file_bytes, mode, decoder)?; - cache_image(&IMAGE_CACHE, key, image.clone(), MAX_IMAGE_CACHE_BYTES); - Ok(image) + let image = prepare_for_prompt(path, &file_bytes, mode, decoder)?; + Ok(cache_image( + &IMAGE_CACHE, + key, + image, + file_bytes, + MAX_IMAGE_CACHE_BYTES, + )) } -fn load_for_prompt_bytes_uncached( +/// Validate the pixels before deciding whether the caller can reuse the source bytes. +fn prepare_for_prompt( path: &Path, - file_bytes: Vec, + file_bytes: &[u8], mode: PromptImageMode, decoder: PromptImageDecoder, -) -> Result { +) -> Result { if decoder == PromptImageDecoder::Sanitizer { - return sanitizer::sanitize(path, &file_bytes, mode); + return sanitizer::sanitize(path, file_bytes, mode).map(PreparedImage::Encoded); } - let path_buf = path.to_path_buf(); - (move || { - let guessed_format = image::guess_format(&file_bytes) - .map_err(|source| ImageProcessingError::decode_error(&path_buf, source))?; - let format = match guessed_format { - ImageFormat::Png => Some(ImageFormat::Png), - ImageFormat::Jpeg => Some(ImageFormat::Jpeg), - ImageFormat::Gif => Some(ImageFormat::Gif), - ImageFormat::WebP => Some(ImageFormat::WebP), - _ => None, - }; + let guessed_format = image::guess_format(file_bytes) + .map_err(|source| ImageProcessingError::decode_error(path, source))?; + let mut decoder = ImageReader::with_format(Cursor::new(file_bytes), guessed_format) + .into_decoder() + .map_err(|source| ImageProcessingError::decode_error(path, source))?; + // Preserve the metadata most important for rendering prompt images faithfully: the color + // profile and EXIF data, including orientation. Other format-specific metadata is + // intentionally not copied. + let metadata = ImageMetadata { + // Only RGB profiles are safe across every re-encoding path. For example, JPEG decoding + // can convert CMYK/YCCK pixels to RGB while retaining the source profile; copying it + // would mislabel the output. Bytes 16..20 are the ICC data color space signature. + icc_profile: decoder + .icc_profile() + .ok() + .flatten() + .filter(|profile| profile.get(16..20) == Some(b"RGB ")), + exif: decoder.exif_metadata().ok().flatten(), + }; + let dynamic = DynamicImage::from_decoder(decoder) + .map_err(|source| ImageProcessingError::decode_error(path, source))?; - let mut decoder = ImageReader::with_format(Cursor::new(&file_bytes), guessed_format) - .into_decoder() - .map_err(|source| ImageProcessingError::decode_error(&path_buf, source))?; - // Preserve the metadata most important for rendering prompt images faithfully: the color - // profile and EXIF data, including orientation. Other format-specific metadata is - // intentionally not copied. - let metadata = ImageMetadata { - // Only RGB profiles are safe across every re-encoding path. For example, JPEG decoding - // can convert CMYK/YCCK pixels to RGB while retaining the source profile; copying it - // would mislabel the output. Bytes 16..20 are the ICC data color space signature. - icc_profile: decoder - .icc_profile() - .ok() - .flatten() - .filter(|profile| profile.get(16..20) == Some(b"RGB ")), - exif: decoder.exif_metadata().ok().flatten(), - }; - let dynamic = DynamicImage::from_decoder(decoder) - .map_err(|source| ImageProcessingError::decode_error(&path_buf, source))?; + let (width, height) = dynamic.dimensions(); - let (width, height) = dynamic.dimensions(); - - let encoded = if let Some(resized) = resize_for_prompt(&dynamic, mode) { - let target_format = format - .filter(|format| can_preserve_source_bytes(*format)) - .unwrap_or(ImageFormat::Png); - let (bytes, output_format) = encode_image(&resized, target_format, metadata)?; - let mime = format_to_mime(output_format); - EncodedImage { - bytes: bytes.into(), - mime, - source_width: width, - source_height: height, - width: resized.width(), - height: resized.height(), - } - } else { - if let Some(format) = format.filter(|format| can_preserve_source_bytes(*format)) { - let mime = format_to_mime(format); - EncodedImage { - bytes: file_bytes.into(), - mime, - source_width: width, - source_height: height, - width, - height, - } - } else { - let (bytes, output_format) = encode_image(&dynamic, ImageFormat::Png, metadata)?; - let mime = format_to_mime(output_format); - EncodedImage { - bytes: bytes.into(), - mime, - source_width: width, - source_height: height, - width, - height, - } - } - }; - - Ok(encoded) - })() + let resized = resize_for_prompt(&dynamic, mode); + let target_format = if can_preserve_source_bytes(guessed_format) { + if resized.is_none() { + return Ok(PreparedImage::Source { + bytes: Weak::new(), + format: guessed_format, + width, + height, + encoded_len: file_bytes.len(), + }); + } + guessed_format + } else { + ImageFormat::Png + }; + let output = resized.as_ref().unwrap_or(&dynamic); + let (bytes, output_format) = encode_image(output, target_format, metadata)?; + Ok(PreparedImage::Encoded(EncodedImage { + bytes: Arc::new(bytes), + mime: format_to_mime(output_format), + source_width: width, + source_height: height, + width: output.width(), + height: output.height(), + })) } -fn cache_image(cache: &ImageCache, key: ImageCacheKey, image: EncodedImage, byte_capacity: usize) { - if image.bytes.len() > byte_capacity { - return; +fn cache_image( + cache: &ImageCache, + key: ImageCacheKey, + mut entry: PreparedImage, + mut source: Vec, + byte_capacity: usize, +) -> EncodedImage { + if entry.cache_cost_bytes() > byte_capacity { + return entry.resolve(&mut source); } cache.with_mut(|cache| { - cache.put(key, image); + // Another caller may have inserted the same image while we decoded it. + if let Some(existing) = cache.get_mut(&key) { + return existing.resolve(&mut source); + } + let image = entry.resolve(&mut source); + cache.put(key, entry); let mut cached_bytes = cache .iter() - .map(|(_, image)| image.bytes.len()) + .map(|(_, image)| image.cache_cost_bytes()) .sum::(); while cached_bytes > byte_capacity { let Some((_, evicted)) = cache.pop_lru() else { break; }; - cached_bytes -= evicted.bytes.len(); + cached_bytes -= evicted.cache_cost_bytes(); } - }); + image + }) } pub fn load_data_url_for_prompt( @@ -260,8 +309,11 @@ pub fn load_data_url_for_prompt_uncached( mode: PromptImageMode, decoder: PromptImageDecoder, ) -> Result { - let bytes = decode_data_url(image_url, decoder)?; - load_for_prompt_bytes_uncached(Path::new(""), bytes, mode, decoder) + let mut bytes = decode_data_url(image_url, decoder)?; + Ok( + prepare_for_prompt(Path::new(""), &bytes, mode, decoder)? + .resolve(&mut bytes), + ) } fn decode_data_url(