From bdb340c21cbcbf60bcb05c5042244fd167f5cc1f Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 23 Nov 2026 22:30:00 +0000 Subject: [PATCH] Engine tests before the vector cut: source cache statistics, core cache tests in core, pattern fill placement in the paint tests Step 8 of the engine split moves the vector commands into their own crate. The tests in those files that read core's cfg(test) counters, or test core's own smart-object caches, are changed first: - smart_cmds::source_cache_statistics() counts SVG source renders and native source bytes hashed per thread; it replaces the cfg(test) counters, and the test-only memo limit override goes. - The WarningRenderSources memo tests and the native digest test move to core's smart_cmds source_work tests; the digest test sets up the source and its verified preview through the document instead of running the vector update, with the same assertions. - The ignored 24 MP update timing test is removed: its memo-off pass needed a test-only production setting. - rasterize_style's tests fill their layer through a local helper instead of core's test helper. - The pattern placement checks for edit.fill and paint.bucket move to the paint tests in tests/it, where those commands are installed. --- crates/engine-core/src/cmd/pattern_cmds.rs | 10 +- .../src/cmd/rasterize_style_cmds/tests.rs | 16 +- crates/engine-core/src/cmd/smart_cmds.rs | 3 +- .../src/cmd/smart_cmds/rendering.rs | 50 +++-- .../src/cmd/smart_cmds/tests/source_work.rs | 168 +++++++++++++++- .../cmd/smart_svg_cmds/source_cache_tests.rs | 190 +----------------- .../src/cmd/smart_svg_cmds/tests.rs | 34 +--- .../engine/tests/it/paint_in_pattern_cmds.rs | 18 +- 8 files changed, 247 insertions(+), 242 deletions(-) diff --git a/crates/engine-core/src/cmd/pattern_cmds.rs b/crates/engine-core/src/cmd/pattern_cmds.rs index eac87ebf7d..2f7b42a686 100644 --- a/crates/engine-core/src/cmd/pattern_cmds.rs +++ b/crates/engine-core/src/cmd/pattern_cmds.rs @@ -651,12 +651,10 @@ mod tests { // 1e39 overflowed f32 to infinity: a NaN render, and a fill layer .pcraft refused to save. let mut s = session(8); let n = s.active().unwrap().doc.layers.len(); - for cmd in ["layer.newFillLayer.pattern", "edit.fill", "paint.bucket"] { - for bad in [json!({"angle": 1e39}), json!({"angle": "x"}), json!({"phase": [1e39, 0]}), json!({"phase": [0, -1e300]})] { - let mut p = json!({"pattern": "Checkerboard", "contents": "pattern", "x": 1, "y": 1}); - p.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone()); - assert!(s.execute(cmd, p).is_err(), "{cmd} {bad}"); - } + for bad in [json!({"angle": 1e39}), json!({"angle": "x"}), json!({"phase": [1e39, 0]}), json!({"phase": [0, -1e300]})] { + let mut p = json!({"pattern": "Checkerboard", "contents": "pattern", "x": 1, "y": 1}); + p.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone()); + assert!(s.execute("layer.newFillLayer.pattern", p).is_err(), "{bad}"); } assert_eq!(s.active().unwrap().doc.layers.len(), n); // The angle is normalised to (-180, 180] like the Pattern Fill dialog's. diff --git a/crates/engine-core/src/cmd/rasterize_style_cmds/tests.rs b/crates/engine-core/src/cmd/rasterize_style_cmds/tests.rs index 4e475417f8..b80c2b40a7 100644 --- a/crates/engine-core/src/cmd/rasterize_style_cmds/tests.rs +++ b/crates/engine-core/src/cmd/rasterize_style_cmds/tests.rs @@ -27,13 +27,27 @@ fn tolerance(depth: u32) -> f32 { } } +/// Sets the pixels of `area` on the active layer to `hex`, through the document (the state +/// `edit.fill` leaves). +fn fill_active(s: &mut Session, area: photocraft_geom::Rect, hex: &str) { + let rgba = crate::commands::parse_hex(hex).unwrap(); + s.edit("setup", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + let px = photocraft_raster::from_rgba(&surf.format(), rgba); + let data: Vec = (0..(area.width() * area.height()) as usize).flat_map(|_| px.iter().copied()).collect(); + surf.write_region(area, &data); + Ok(()) + }) + .unwrap(); +} + /// A white Background and a red rectangle (partly off the right edge of the canvas) with a /// Normal-mode drop shadow, outer glow, inner shadow, outside stroke and a half colour overlay. fn scene(depth: u32) -> (Session, u64) { let mut s = crate::session(); s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth})).unwrap(); let id = s.execute("layer.new.layer", json!({"name": "a"})).unwrap()["layer"].as_u64().unwrap(); - crate::tests::fill_active(&mut s, Some(photocraft_geom::Rect::new(14, 10, 64, 30)), "#e02010"); + fill_active(&mut s, photocraft_geom::Rect::new(14, 10, 64, 30), "#e02010"); s.execute("layer.layerStyle.dropShadow", json!({"blend": "normal", "distance": 6, "size": 4, "color": "#102040"})).unwrap(); s.execute("layer.layerStyle.outerGlow", json!({"blend": "normal", "size": 5, "color": "#20c040", "add": true})).unwrap(); s.execute("layer.layerStyle.innerShadow", json!({"blend": "normal", "distance": 3, "size": 3, "add": true})).unwrap(); diff --git a/crates/engine-core/src/cmd/smart_cmds.rs b/crates/engine-core/src/cmd/smart_cmds.rs index 30e2a274c5..add6248c27 100644 --- a/crates/engine-core/src/cmd/smart_cmds.rs +++ b/crates/engine-core/src/cmd/smart_cmds.rs @@ -197,9 +197,8 @@ use placing::{convert, reset_transform, shift_layer, via_copy}; pub use placing::{layer_to_smart, layers_to_smart, placement}; use rendering::refresh_or_fail; #[cfg(test)] -pub(crate) use rendering::{DISPLAY_NATIVE_HASH_BYTES, WARNING_SOURCE_DECODES, WARNING_SOURCE_LIMIT}; -#[cfg(test)] use rendering::{NativeDigests, blend_surfaces, place, render_in}; +pub use rendering::{SourceCacheStatistics, source_cache_statistics}; pub(crate) use rendering::{WarningRenderSources, render_with_warnings, render_with_warnings_using, source_box}; pub use rendering::{apply_smart_filters, purge_stack_cache, refresh, refresh_layer, render, render_below_filter, stack_cache_bytes, stack_image}; #[cfg(test)] diff --git a/crates/engine-core/src/cmd/smart_cmds/rendering.rs b/crates/engine-core/src/cmd/smart_cmds/rendering.rs index 0b3e93b988..3c7fa52d2f 100644 --- a/crates/engine-core/src/cmd/smart_cmds/rendering.rs +++ b/crates/engine-core/src/cmd/smart_cmds/rendering.rs @@ -233,8 +233,36 @@ fn place_with_svg( }) } -#[cfg(test)] -thread_local! { pub(crate) static DISPLAY_NATIVE_HASH_BYTES: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// Work the smart-object source caches have done on the calling thread. Each field counts a +/// cache miss, so the difference around an operation states how often the caches let it repeat +/// expensive work: an SVG update renders each source once per scale however many instances share +/// it, and a native vector source is hashed once per allocation however often it is drawn. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct SourceCacheStatistics { + /// SVG sources rendered by [`WarningRenderSources`] (renders its memo did not hold). + pub svg_decodes: usize, + /// Bytes of native vector sources hashed to verify their preview (digests not remembered + /// for that source allocation). + pub native_hash_bytes: usize, +} + +thread_local! { + static STATISTICS: std::cell::Cell = const { std::cell::Cell::new(SourceCacheStatistics { svg_decodes: 0, native_hash_bytes: 0 }) }; +} + +/// The calling thread's [`SourceCacheStatistics`] so far. Counted per thread, so work on other +/// threads never mixes in. +pub fn source_cache_statistics() -> SourceCacheStatistics { + STATISTICS.with(std::cell::Cell::get) +} + +fn record(update: impl FnOnce(&mut SourceCacheStatistics)) { + STATISTICS.with(|cell| { + let mut statistics = cell.get(); + update(&mut statistics); + cell.set(statistics); + }); +} /// BLAKE3 digests of native vector sources, remembered per source allocation so explicit /// refreshes and warp source frames of shared contents hash a (up to 16 MiB) source once. @@ -290,8 +318,7 @@ fn native_digest(bytes: &Arc>) -> [u8; 32] { if let Some(digest) = lock().get(bytes) { return digest; } - #[cfg(test)] - DISPLAY_NATIVE_HASH_BYTES.with(|count| count.set(count.get().saturating_add(bytes.len()))); + record(|statistics| statistics.native_hash_bytes = statistics.native_hash_bytes.saturating_add(bytes.len())); let digest = *blake3::hash(bytes).as_bytes(); lock().insert(bytes, digest); digest @@ -366,19 +393,9 @@ pub(crate) struct WarningRenderSources<'a> { bytes: usize, } -#[cfg(test)] -thread_local! { - pub(crate) static WARNING_SOURCE_DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; - pub(crate) static WARNING_SOURCE_LIMIT: std::cell::Cell> = const { std::cell::Cell::new(None) }; -} - impl<'a> WarningRenderSources<'a> { pub(crate) fn new(document: &'a Document) -> Self { - #[cfg(test)] - let limit = WARNING_SOURCE_LIMIT.with(|limit| limit.get().unwrap_or(32)); - #[cfg(not(test))] - let limit = 32; - Self { document, srgb: None, entries: VecDeque::new(), budget: if cfg!(target_arch = "wasm32") { 128 << 20 } else { 384 << 20 }, limit, bytes: 0 } + Self { document, srgb: None, entries: VecDeque::new(), budget: if cfg!(target_arch = "wasm32") { 128 << 20 } else { 384 << 20 }, limit: 32, bytes: 0 } } #[cfg(test)] @@ -410,8 +427,7 @@ impl<'a> WarningRenderSources<'a> { doc.mode == photocraft_color::ColorMode::Rgb && crate::color_cmds::document_profile(doc).to_bytes().as_ref() == craft_cms::Builtin::Srgb.profile().to_bytes().as_ref() }); - #[cfg(test)] - WARNING_SOURCE_DECODES.with(|count| count.set(count.get().saturating_add(1))); + record(|statistics| statistics.svg_decodes = statistics.svg_decodes.saturating_add(1)); let (buf, warnings) = photocraft_io::svg::rasterize_bounded_with_warnings(bytes, scale as f32, 24_000_000) .map_err(|e| other(format!("can't render the SVG smart object: {e}")))?; // Charge owned native tiles, entry and warning storage, not borrowed encoded bytes. diff --git a/crates/engine-core/src/cmd/smart_cmds/tests/source_work.rs b/crates/engine-core/src/cmd/smart_cmds/tests/source_work.rs index da9c0cef81..467dc03c46 100644 --- a/crates/engine-core/src/cmd/smart_cmds/tests/source_work.rs +++ b/crates/engine-core/src/cmd/smart_cmds/tests/source_work.rs @@ -85,13 +85,13 @@ fn memo_prices_owned_output_and_does_not_retain_encoded_capacity() { let sm = object("reserved.svg", bytes); let tile = photocraft_raster::tile_storage_bytes(doc.bounds(), &doc.pixel_format()) as usize; let mut memo = WarningRenderSources::with_limits(&doc, tile + 4096, 32); - WARNING_SOURCE_DECODES.with(|value| value.set(0)); + let decodes = source_cache_statistics().svg_decodes; let first = render_with_warnings_using(&sm, &mut memo).unwrap(); assert!(first.1.is_empty()); assert_eq!(memo.entries.len(), 1, "encoded spare capacity is borrowed, not retained memo storage"); assert!(memo.bytes <= tile + 4096); assert_eq!(render_with_warnings_using(&sm, &mut memo).unwrap(), first); - assert_eq!(WARNING_SOURCE_DECODES.with(std::cell::Cell::get), 1); + assert_eq!(source_cache_statistics().svg_decodes - decodes, 1); assert_eq!(weak.strong_count(), 1, "only the caller owns its source allocation"); drop(sm); assert!(weak.upgrade().is_none(), "the memo must not pin an encoded body after its owner drops it"); @@ -122,3 +122,167 @@ fn raster_named_svg_keeps_the_ordinary_import_path() { assert_eq!(reported.unwrap(), rendered); assert!(warnings.is_empty()); } + +/// The bounded source memo of [`WarningRenderSources`] (one SVG update's source-space renders). +mod warning_sources { + use super::*; + use base64::Engine as _; + use photocraft_color::PixelFormat; + use serde_json::json; + + fn artwork(width: u32, height: u32) -> String { + let image = + photocraft_codecs::Image::from_u8(width, height, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat((width * height) as usize)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let encoded = base64::engine::general_purpose::STANDARD.encode(png); + format!( + r##""## + ) + } + + fn memo_object(svg: &str) -> SmartObject { + object("Memo.svg", Arc::new(svg.as_bytes().to_vec())) + } + + fn decodes() -> usize { + source_cache_statistics().svg_decodes + } + + fn draw(sources: &mut WarningRenderSources<'_>, sm: &SmartObject) -> Surface { + let (surface, warnings) = render_with_warnings_using(sm, sources).unwrap(); + assert_eq!(warnings.len(), 1); + surface.unwrap() + } + + #[test] + fn warning_source_profile_context_stays_lazy_for_non_svg_and_missing_sources() { + let doc = Document::new("Raster", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let sm = object("Raster.png", Arc::new(png)); + let expected = render(&doc, &sm).unwrap(); + let mut sources = WarningRenderSources::new(&doc); + assert!(!sources.profile_initialized()); + let start = decodes(); + let (surface, warnings) = render_with_warnings_using(&sm, &mut sources).unwrap(); + assert_eq!(surface, expected); + assert!(warnings.is_empty()); + assert!(!sources.profile_initialized(), "a strict non-SVG cache hit needs no SVG color context"); + let missing = SmartObject::new(SmartSource::Linked { path: String::new() }, Affine::IDENTITY, None); + let (surface, warnings) = render_with_warnings_using(&missing, &mut sources).unwrap(); + assert!(surface.is_none()); + assert!(warnings.is_empty()); + assert!(!sources.profile_initialized()); + assert_eq!(decodes() - start, 0); + draw(&mut sources, &memo_object(&artwork(4, 4))); + assert!(sources.profile_initialized()); + assert_eq!(decodes() - start, 1); + } + + #[test] + fn local_svg_sources_separate_scale_and_profile_but_keep_instance_filters_and_placement() { + // Reads the command registry before any session exists. + crate::install().unwrap(); + let mut doc = Document::new("Profile", Size::new(64, 64), ColorMode::Rgb, SampleType::F32); + doc.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes()); + let mut linear = doc.clone(); + linear.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes()); + let first = memo_object(&artwork(4, 4)); + let mut moved = first.clone(); + moved.transform = Affine::translate(20., 0.); + moved.smart_filters.push(SmartFilter { + command: "image.adjustments.invert".into(), + params: json!({}), + blend: BlendMode::Normal, + opacity: 0.5, + visible: true, + }); + let mut sources = WarningRenderSources::new(&doc); + let start = decodes(); + let a = draw(&mut sources, &first); + let b = draw(&mut sources, &moved); + assert_eq!(decodes() - start, 1); + assert_eq!(a.rgba(3, 3), [0., 1., 0., 1.]); + assert_eq!(b.rgba(3, 3), [0.; 4]); + assert!(b.rgba(23, 3).iter().take(3).all(|value| (*value - 0.5).abs() < 0.01)); + let mut scaled = first.clone(); + scaled.transform = Affine { m: [2., 0., 0., 2., 0., 0.] }; + draw(&mut sources, &scaled); + assert_eq!(decodes() - start, 2, "different raster scales require different source renders"); + let corrected = draw(&mut WarningRenderSources::new(&linear), &first); + assert_eq!(decodes() - start, 3, "a different document interpretation cannot reuse the earlier source"); + assert!((a.rgba(12, 3)[0] - 0.502).abs() < 0.01); + assert!((corrected.rgba(12, 3)[0] - 0.216).abs() < 0.01); + assert_eq!(draw(&mut sources, &first), a); + assert_eq!(decodes() - start, 3); + } + + #[test] + fn local_svg_source_memo_evicts_and_oversize_entries_render_without_retention() { + let mut doc = Document::new("Budget", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); + doc.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes()); + let first = memo_object(&artwork(4, 4)); + let mut scaled = first.clone(); + scaled.transform = Affine { m: [2., 0., 0., 2., 0., 0.] }; + let tile = photocraft_raster::tile_storage_bytes(Rect::new(0, 0, 32, 32), &PixelFormat::RGBA8) as usize; + for (budget, limit) in [(tile + 4096, 32), (usize::MAX, 1)] { + let mut sources = WarningRenderSources::with_limits(&doc, budget, limit); + let start = decodes(); + let expected = draw(&mut sources, &first); + draw(&mut sources, &scaled); + assert_eq!(draw(&mut sources, &first), expected); + assert_eq!(decodes() - start, 3, "byte and entry limits both evict the old scale"); + } + let huge_source = artwork(4, 4).replace("", &format!("", " ".repeat(tile + 8192))); + let encoded = memo_object(&huge_source); + let mut sources = WarningRenderSources::with_limits(&doc, tile + 4096, 32); + let start = decodes(); + let expected = draw(&mut sources, &encoded); + assert_eq!(draw(&mut sources, &encoded), expected); + assert_eq!(decodes() - start, 1, "the immutable document owns encoded bytes; only rendered output belongs to the memo budget"); + let mut output_too_large = WarningRenderSources::with_limits(&doc, tile - 1, 32); + let start = decodes(); + let expected = draw(&mut output_too_large, &first); + assert_eq!(draw(&mut output_too_large, &first), expected); + assert_eq!(decodes() - start, 2, "oversize rendered output remains an uncached success"); + let mut disabled = WarningRenderSources::with_limits(&doc, 0, 0); + assert_eq!(draw(&mut disabled, &first), draw(&mut WarningRenderSources::new(&doc), &first)); + } +} + +/// Explicit refreshes and warp frames of one shared native source verify its preview hash once, +/// not once per call; a replaced source is verified again and a forged preview still fails. +#[test] +fn native_preview_digest_is_reused_per_source_allocation_and_rechecked_after_replacement() { + const RED: &[u8] = br#""#; + const BLUE: &[u8] = br#""#; + let mut s = crate::session(); + s.execute("file.new", serde_json::json!({"width":32,"height":24,"depth":8})).unwrap(); + let placed = crate::file_cmds::place_bytes(&mut s, "Artwork.svg", RED.to_vec(), None, &serde_json::json!({"smartObject":true})).unwrap(); + let id = LayerId(placed["layer"].as_u64().unwrap()); + let original = b"%!PS-Adobe-3.0 EPSF-3.0\noriginal"; + let mut changed = vec![b' '; 1024 * 1024]; + changed[..original.len()].copy_from_slice(original); + let doc = s.active().unwrap().doc.clone(); + let LayerContent::Smart(sm) = &doc.layer(id).unwrap().content else { panic!("smart") }; + let mut sm = sm.clone(); + // What saving an EPS with its SVG preview stores: the source and the preview verified for it. + sm.vector_preview = Some(photocraft_doc::VectorPreview { source_hash: *blake3::hash(&changed).as_bytes(), svg: Arc::new(BLUE.to_vec()) }); + // A fresh allocation of the same bytes: nothing about it can be remembered yet. + sm.source = SmartSource::Embedded { file_name: "Logo.eps".into(), bytes: Arc::new(changed.clone()) }; + let hashed = || source_cache_statistics().native_hash_bytes; + let start = hashed(); + let frame = source_box(&doc, &sm).unwrap(); + for _ in 0..3 { + assert_eq!(source_box(&doc, &sm), Some(frame)); + assert_eq!(render(&doc, &sm).unwrap().unwrap().pixel(15, 11), vec![0.0, 0.0, 1.0, 1.0], "the verified preview is drawn"); + } + assert_eq!(hashed() - start, changed.len(), "one verification for one source allocation"); + // Different bytes in a new allocation never inherit the verified digest. + let mut other = changed.clone(); + other[original.len()] = b'%'; + sm.source = SmartSource::Embedded { file_name: "Logo.eps".into(), bytes: Arc::new(other) }; + let before = hashed(); + assert!(render(&doc, &sm).is_err(), "a stale preview must not draw a different source"); + assert_eq!(hashed() - before, changed.len()); +} diff --git a/crates/engine-core/src/cmd/smart_svg_cmds/source_cache_tests.rs b/crates/engine-core/src/cmd/smart_svg_cmds/source_cache_tests.rs index f21b685c0c..073adca240 100644 --- a/crates/engine-core/src/cmd/smart_svg_cmds/source_cache_tests.rs +++ b/crates/engine-core/src/cmd/smart_svg_cmds/source_cache_tests.rs @@ -1,6 +1,5 @@ use super::*; -use crate::smart_cmds::{WARNING_SOURCE_DECODES, WARNING_SOURCE_LIMIT, WarningRenderSources, render_with_warnings_using}; -use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use crate::smart_cmds::source_cache_statistics; use photocraft_doc::SmartFilter; use photocraft_geom::Affine; @@ -13,16 +12,8 @@ fn artwork(width: u32, height: u32) -> String { ) } -fn object(svg: &str) -> SmartObject { - SmartObject::new(SmartSource::Embedded { file_name: "Memo.svg".into(), bytes: Arc::new(svg.as_bytes().to_vec()) }, Affine::IDENTITY, None) -} - -fn count() -> usize { - WARNING_SOURCE_DECODES.with(std::cell::Cell::get) -} - -fn reset() { - WARNING_SOURCE_DECODES.with(|count| count.set(0)); +fn decodes() -> usize { + source_cache_statistics().svg_decodes } fn assert_update_warnings(result: &Value) { @@ -36,12 +27,6 @@ fn assert_update_warnings(result: &Value) { })); } -fn draw(sources: &mut WarningRenderSources<'_>, sm: &SmartObject) -> photocraft_raster::Surface { - let (surface, warnings) = render_with_warnings_using(sm, sources).unwrap(); - assert_eq!(warnings.len(), 1); - surface.unwrap() -} - fn shared_session(instances: usize) -> (Session, LayerId) { let mut s = crate::session(); s.execute("file.new", json!({"width":32,"height":32})).unwrap(); @@ -65,40 +50,15 @@ fn request(s: &mut Session, id: LayerId, svg: &str) -> Value { json!({"document":handoff["document"],"layer":id.0,"contentsId":handoff["contentsId"],"fingerprint":handoff["fingerprint"],"svg":svg}) } -#[test] -fn warning_source_profile_context_stays_lazy_for_non_svg_and_missing_sources() { - let doc = Document::new("Raster", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); - let image = photocraft_codecs::Image::from_u8(2, 2, photocraft_codecs::ChannelLayout::Rgb, [0, 255, 0].repeat(4)).unwrap(); - let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); - let sm = SmartObject::new(SmartSource::Embedded { file_name: "Raster.png".into(), bytes: Arc::new(png) }, Affine::IDENTITY, None); - let expected = crate::smart_cmds::render(&doc, &sm).unwrap(); - let mut sources = WarningRenderSources::new(&doc); - assert!(!sources.profile_initialized()); - reset(); - let (surface, warnings) = render_with_warnings_using(&sm, &mut sources).unwrap(); - assert_eq!(surface, expected); - assert!(warnings.is_empty()); - assert!(!sources.profile_initialized(), "a strict non-SVG cache hit needs no SVG color context"); - let missing = SmartObject::new(SmartSource::Linked { path: String::new() }, Affine::IDENTITY, None); - let (surface, warnings) = render_with_warnings_using(&missing, &mut sources).unwrap(); - assert!(surface.is_none()); - assert!(warnings.is_empty()); - assert!(!sources.profile_initialized()); - assert_eq!(count(), 0); - draw(&mut sources, &object(&artwork(4, 4))); - assert!(sources.profile_initialized()); - assert_eq!(count(), 1); -} - #[test] fn shared_svg_update_decodes_one_source_for_equal_scale_and_keeps_warning_caches_private() { let (mut s, id) = shared_session(100); let before = s.active().unwrap().doc.clone(); let svg = artwork(8, 8); let params = request(&mut s, id, &svg); - reset(); + let start = decodes(); let result = s.execute(UPDATE, params).unwrap(); - assert_eq!(count(), 1, "each placement must reuse the update's source-space render"); + assert_eq!(decodes() - start, 1, "each placement must reuse the update's source-space render"); assert_update_warnings(&result); let doc = &s.active().unwrap().doc; let instances: Vec<_> = doc.layers.iter().filter(|layer| matches!(&layer.content, LayerContent::Smart(_))).collect(); @@ -124,76 +84,6 @@ fn shared_svg_update_decodes_one_source_for_equal_scale_and_keeps_warning_caches assert_eq!(embedded(&s.active().unwrap().doc, smart(&s.active().unwrap().doc, id).unwrap()).unwrap().1, svg.as_bytes()); } -#[test] -fn local_svg_sources_separate_scale_and_profile_but_keep_instance_filters_and_placement() { - // Reads the command registry before any session exists. - crate::install().unwrap(); - let mut doc = Document::new("Profile", Size::new(64, 64), ColorMode::Rgb, SampleType::F32); - doc.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes()); - let mut linear = doc.clone(); - linear.icc_profile = Some(craft_cms::Builtin::LinearSrgb.profile().to_bytes()); - let first = object(&artwork(4, 4)); - let mut moved = first.clone(); - moved.transform = Affine::translate(20., 0.); - moved.smart_filters.push(SmartFilter { - command: "image.adjustments.invert".into(), - params: json!({}), - blend: photocraft_color::BlendMode::Normal, - opacity: 0.5, - visible: true, - }); - let mut sources = WarningRenderSources::new(&doc); - reset(); - let a = draw(&mut sources, &first); - let b = draw(&mut sources, &moved); - assert_eq!(count(), 1); - assert_eq!(a.rgba(3, 3), [0., 1., 0., 1.]); - assert_eq!(b.rgba(3, 3), [0.; 4]); - assert!(b.rgba(23, 3).iter().take(3).all(|value| (*value - 0.5).abs() < 0.01)); - let mut scaled = first.clone(); - scaled.transform = Affine { m: [2., 0., 0., 2., 0., 0.] }; - draw(&mut sources, &scaled); - assert_eq!(count(), 2, "different raster scales require different source renders"); - let corrected = draw(&mut WarningRenderSources::new(&linear), &first); - assert_eq!(count(), 3, "a different document interpretation cannot reuse the earlier source"); - assert!((a.rgba(12, 3)[0] - 0.502).abs() < 0.01); - assert!((corrected.rgba(12, 3)[0] - 0.216).abs() < 0.01); - assert_eq!(draw(&mut sources, &first), a); - assert_eq!(count(), 3); -} - -#[test] -fn local_svg_source_memo_evicts_and_oversize_entries_render_without_retention() { - let mut doc = Document::new("Budget", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); - doc.icc_profile = Some(craft_cms::Builtin::Srgb.profile().to_bytes()); - let first = object(&artwork(4, 4)); - let mut scaled = first.clone(); - scaled.transform = Affine { m: [2., 0., 0., 2., 0., 0.] }; - let tile = photocraft_raster::tile_storage_bytes(Rect::new(0, 0, 32, 32), &PixelFormat::RGBA8) as usize; - for (budget, limit) in [(tile + 4096, 32), (usize::MAX, 1)] { - let mut sources = WarningRenderSources::with_limits(&doc, budget, limit); - reset(); - let expected = draw(&mut sources, &first); - draw(&mut sources, &scaled); - assert_eq!(draw(&mut sources, &first), expected); - assert_eq!(count(), 3, "byte and entry limits both evict the old scale"); - } - let huge_source = artwork(4, 4).replace("", &format!("", " ".repeat(tile + 8192))); - let encoded = object(&huge_source); - let mut sources = WarningRenderSources::with_limits(&doc, tile + 4096, 32); - reset(); - let expected = draw(&mut sources, &encoded); - assert_eq!(draw(&mut sources, &encoded), expected); - assert_eq!(count(), 1, "the immutable document owns encoded bytes; only rendered output belongs to the memo budget"); - let mut output_too_large = WarningRenderSources::with_limits(&doc, tile - 1, 32); - reset(); - let expected = draw(&mut output_too_large, &first); - assert_eq!(draw(&mut output_too_large, &first), expected); - assert_eq!(count(), 2, "oversize rendered output remains an uncached success"); - let mut disabled = WarningRenderSources::with_limits(&doc, 0, 0); - assert_eq!(draw(&mut disabled, &first), draw(&mut WarningRenderSources::new(&doc), &first)); -} - #[test] fn shared_svg_update_render_failure_and_cancelled_authorization_preserve_document_history() { for cancel in [false, true] { @@ -214,7 +104,7 @@ fn shared_svg_update_render_failure_and_cancelled_authorization_preserve_documen let history = s.active().unwrap().history.entries(); let revision = s.active().unwrap().revision; let params = request(&mut s, id, &artwork(4, 4)); - reset(); + let start = decodes(); let error = s.execute(UPDATE, params).unwrap_err(); if cancel { assert!(matches!(error, EngineError::Cancelled), "expected the authority cancellation, got {error}"); @@ -224,7 +114,7 @@ fn shared_svg_update_render_failure_and_cancelled_authorization_preserve_documen assert_eq!(s.active().unwrap().doc, before); assert_eq!(s.active().unwrap().history.entries(), history); assert_eq!(s.active().unwrap().revision, revision); - assert_eq!(count(), if cancel { 0 } else { 1 }); + assert_eq!(decodes() - start, if cancel { 0 } else { 1 }); } } @@ -237,72 +127,10 @@ fn shared_svg_update_keeps_the_existing_placed_pixel_budget_atomic() { let history = s.active().unwrap().history.entries(); let revision = s.active().unwrap().revision; let params = request(&mut s, id, &artwork(4, 4)); - reset(); + let start = decodes(); assert!(s.execute(UPDATE, params).is_err()); - assert_eq!(count(), 0, "placed-frame admission precedes source rendering"); + assert_eq!(decodes() - start, 0, "placed-frame admission precedes source rendering"); assert_eq!(s.active().unwrap().doc, before); assert_eq!(s.active().unwrap().history.entries(), history); assert_eq!(s.active().unwrap().revision, revision); } - -#[test] -#[ignore = "24MP embedded PNG / 100 shared instances; run once in release for performance qualification"] -fn shared_svg_update_24mp_source_timing() { - struct MemoLimit(Option); - impl MemoLimit { - fn set(limit: usize) -> Self { - Self(WARNING_SOURCE_LIMIT.with(|current| current.replace(Some(limit)))) - } - } - impl Drop for MemoLimit { - fn drop(&mut self) { - WARNING_SOURCE_LIMIT.with(|current| current.set(self.0)); - } - } - let previous_limit = WARNING_SOURCE_LIMIT.with(std::cell::Cell::get); - // Encode once. Each pass builds the same initial document and handoff outside - // the clock; UPDATE includes its normal import and all instance rendering. - let svg = artwork(6000, 4000); - let mut expected = None; - let mut timings = Vec::new(); - for (label, limit, decodes) in [("optimized-before", 32, 1), ("memo-off", 0, 100), ("optimized-after", 32, 1)] { - let (mut s, id) = shared_session(100); - let params = request(&mut s, id, &svg); - let _restore = MemoLimit::set(limit); - reset(); - let start = std::time::Instant::now(); - let result = s.execute(UPDATE, params).unwrap(); - let elapsed = start.elapsed().as_secs_f64() * 1000.; - assert_eq!(count(), decodes, "{label}"); - assert_update_warnings(&result); - let doc = &s.active().unwrap().doc; - let mut pixels = blake3::Hasher::new(); - let mut sources = blake3::Hasher::new(); - let mut samples = Vec::new(); - for layer in doc.layers.iter().filter(|layer| matches!(&layer.content, LayerContent::Smart(_))) { - let sm = smart(doc, layer.id).unwrap(); - let source = embedded(doc, sm).unwrap().1; - assert_eq!(source, svg.as_bytes()); - sources.update(blake3::hash(source).as_bytes()); - let cache = sm.cache.as_ref().unwrap(); - for value in cache.read_region(doc.bounds()) { - pixels.update(&value.to_bits().to_le_bytes()); - } - let (x, y) = (sm.transform.m[4] as i32, sm.transform.m[5] as i32); - let sample = cache.rgba(x + 3, y + 3); - assert_eq!(sample, [0., 1., 0., 1.]); - samples.push(sample); - } - assert_eq!(samples.len(), 100); - let signature = (*pixels.finalize().as_bytes(), *sources.finalize().as_bytes(), samples, result["warnings"].clone()); - if let Some(expected) = &expected { - assert_eq!(&signature, expected, "pixels, samples, encoded sources and warnings must match: {label}"); - } else { - expected = Some(signature); - } - eprintln!("24MP PNG / 16x16 SVG / 100 shared instances: {label}: {elapsed:.3} ms, {decodes} source renders"); - timings.push(elapsed); - } - eprintln!("optimized median of two: {:.3} ms; memo-off: {:.3} ms", (timings[0] + timings[2]) / 2., timings[1]); - assert_eq!(WARNING_SOURCE_LIMIT.with(std::cell::Cell::get), previous_limit, "test override restored"); -} diff --git a/crates/engine-core/src/cmd/smart_svg_cmds/tests.rs b/crates/engine-core/src/cmd/smart_svg_cmds/tests.rs index cb3c73ddb8..8d8823c6e8 100644 --- a/crates/engine-core/src/cmd/smart_svg_cmds/tests.rs +++ b/crates/engine-core/src/cmd/smart_svg_cmds/tests.rs @@ -622,9 +622,9 @@ fn native_save_refreshes_shared_caches_without_rehashing_the_native_payload_per_ let mut changed = vec![b' '; MAX_VECTOR_SOURCE_BYTES]; changed[..original.len()].copy_from_slice(&original); let params = native_request(&mut s, id, "eps", &changed); - let hashed = crate::smart_cmds::DISPLAY_NATIVE_HASH_BYTES.with(std::cell::Cell::get); + let hashed = crate::smart_cmds::source_cache_statistics().native_hash_bytes; assert_eq!(s.execute(UPDATE_VECTOR, params).unwrap()["updated"], true); - assert_eq!(crate::smart_cmds::DISPLAY_NATIVE_HASH_BYTES.with(std::cell::Cell::get) - hashed, 0, "cache refresh must not hash 16 MiB for every copy"); + assert_eq!(crate::smart_cmds::source_cache_statistics().native_hash_bytes - hashed, 0, "cache refresh must not hash 16 MiB for every copy"); let after = s.active().unwrap().doc.clone(); let target = smart(&after, id).unwrap(); let SmartSource::Embedded { file_name, bytes } = &target.source else { panic!("native source lost") }; @@ -648,36 +648,6 @@ fn native_save_refreshes_shared_caches_without_rehashing_the_native_payload_per_ assert_eq!(s.active().unwrap().doc, after); } -/// Explicit refreshes and warp frames of one shared native source verify its preview hash once, -/// not once per call; a replaced source is verified again and a forged preview still fails. -#[test] -fn native_preview_digest_is_reused_per_source_allocation_and_rechecked_after_replacement() { - let (mut s, id, original) = native_session("eps", 8); - let mut changed = vec![b' '; 1024 * 1024]; - changed[..original.len()].copy_from_slice(&original); - let params = native_request(&mut s, id, "eps", &changed); - s.execute(UPDATE_VECTOR, params).unwrap(); - let doc = s.active().unwrap().doc.clone(); - let mut sm = smart(&doc, id).unwrap().clone(); - // A fresh allocation of the same bytes: nothing about it can be remembered yet. - sm.source = SmartSource::Embedded { file_name: "Logo.eps".into(), bytes: Arc::new(changed.clone()) }; - let hashed = || crate::smart_cmds::DISPLAY_NATIVE_HASH_BYTES.with(std::cell::Cell::get); - let start = hashed(); - let frame = crate::smart_cmds::source_box(&doc, &sm).unwrap(); - for _ in 0..3 { - assert_eq!(crate::smart_cmds::source_box(&doc, &sm), Some(frame)); - assert_eq!(crate::smart_cmds::render(&doc, &sm).unwrap().unwrap().pixel(15, 11), vec![0.0, 0.0, 1.0, 1.0], "the verified preview is drawn"); - } - assert_eq!(hashed() - start, changed.len(), "one verification for one source allocation"); - // Different bytes in a new allocation never inherit the verified digest. - let mut other = changed.clone(); - other[original.len()] = b'%'; - sm.source = SmartSource::Embedded { file_name: "Logo.eps".into(), bytes: Arc::new(other) }; - let before = hashed(); - assert!(crate::smart_cmds::render(&doc, &sm).is_err(), "a stale preview must not draw a different source"); - assert_eq!(hashed() - before, changed.len()); -} - #[test] fn native_source_replacement_never_uses_a_forged_or_stale_preview() { let (mut s, id, original) = native_session("ai", 8); diff --git a/crates/engine/tests/it/paint_in_pattern_cmds.rs b/crates/engine/tests/it/paint_in_pattern_cmds.rs index 497286d9da..6118b14c83 100644 --- a/crates/engine/tests/it/paint_in_pattern_cmds.rs +++ b/crates/engine/tests/it/paint_in_pattern_cmds.rs @@ -1,4 +1,4 @@ -//! Tests that run paint commands, moved from the engine-core `pattern_cmds` tests: 7 test(s). +//! Tests that run paint commands, moved from the engine-core `pattern_cmds` tests: 8 test(s). use photocraft_doc::{Pattern, Rect}; use photocraft_engine::Session; @@ -168,3 +168,19 @@ fn pattern_overlay_renders_and_brush_texture_uses_library() { assert!(s.tools.brush.texture.enabled); assert!(matches!(s.tools.brush.texture.pattern, photocraft_paint::Pattern::Tile(_))); } + +#[test] +fn pattern_fill_and_bucket_reject_non_finite_angle_and_phase() { + // 1e39 overflowed f32 to infinity: a NaN render. + let mut s = session(8); + let n = s.active().unwrap().doc.layers.len(); + for cmd in ["edit.fill", "paint.bucket"] { + for bad in [json!({"angle": 1e39}), json!({"angle": "x"}), json!({"phase": [1e39, 0]}), json!({"phase": [0, -1e300]})] { + let mut p = json!({"pattern": "Checkerboard", "contents": "pattern", "x": 1, "y": 1}); + p.as_object_mut().unwrap().extend(bad.as_object().unwrap().clone()); + let e = s.execute(cmd, p).unwrap_err().to_string(); + assert!(e.contains("`angle`") || e.contains("`phase`"), "{cmd} {bad}: {e}"); + } + } + assert_eq!(s.active().unwrap().doc.layers.len(), n); +}