From 0456bc3f22e1b4baf1d934a9ea20f8070ddc4a73 Mon Sep 17 00:00:00 2001 From: vistaero Date: Sat, 10 Oct 2026 06:32:13 +0200 Subject: [PATCH 1/9] Add guarded scratch storage with owned memory supervision --- Cargo.lock | 215 +++++++-- crates/algo/src/lib.rs | 24 + crates/algo/src/selection.rs | 8 +- crates/algo/src/selection/marquee.rs | 12 +- crates/algo/src/tests.rs | 9 + crates/compose/src/bounds.rs | 11 +- crates/compose/src/lib.rs | 15 + crates/compose/src/masks.rs | 12 +- crates/compose/src/shape_split.rs | 8 + crates/compose/tests/scratch_retry.rs | 49 ++ crates/engine/src/color_cmds.rs | 33 +- crates/engine/src/fill_cmds.rs | 12 +- crates/engine/src/filters.rs | 29 ++ crates/engine/src/jobs.rs | 8 + crates/engine/src/lens_cmds.rs | 2 + crates/engine/src/lib.rs | 11 + crates/engine/src/pixels.rs | 14 +- crates/engine/src/prefs.rs | 32 +- crates/engine/src/scratch.rs | 142 ++++++ crates/engine/tests/memory_prefs.rs | 24 + crates/engine/tests/scratch_disk.rs | 90 ++++ crates/format/src/store.rs | 49 +- crates/format/tests/scratch_retry.rs | 48 ++ crates/gpu/src/lib.rs | 6 +- crates/io/src/lib.rs | 8 + crates/ops/src/lib.rs | 2 +- crates/plugins/src/apply.rs | 4 +- crates/raster/Cargo.toml | 5 + crates/raster/examples/scratch_bench.rs | 52 +++ crates/raster/src/lib.rs | 259 ++++++++--- crates/raster/src/memory.rs | 181 ++++++++ crates/raster/src/scratch_file.rs | 430 +++++++++++++++++ crates/raster/src/spill.rs | 563 +++++++++++++++++++++++ crates/raster/tests/scratch_translate.rs | 44 ++ crates/raster/tests/spill.rs | 149 ++++++ crates/ui-egui/src/canvas.rs | 8 +- crates/ui-egui/src/control.rs | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sr.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/lib.rs | 8 + crates/ui-egui/src/prefs_ui.rs | 21 +- docs/development.md | 4 + docs/roadmap.md | 2 + docs/scorecard.md | 8 +- docs/scratch-disks.md | 39 ++ scorecard/reliability.toml | 2 +- 64 files changed, 2543 insertions(+), 151 deletions(-) create mode 100644 crates/compose/tests/scratch_retry.rs create mode 100644 crates/engine/src/scratch.rs create mode 100644 crates/engine/tests/memory_prefs.rs create mode 100644 crates/engine/tests/scratch_disk.rs create mode 100644 crates/format/tests/scratch_retry.rs create mode 100644 crates/raster/examples/scratch_bench.rs create mode 100644 crates/raster/src/memory.rs create mode 100644 crates/raster/src/scratch_file.rs create mode 100644 crates/raster/src/spill.rs create mode 100644 crates/raster/tests/scratch_translate.rs create mode 100644 crates/raster/tests/spill.rs create mode 100644 docs/scratch-disks.md diff --git a/Cargo.lock b/Cargo.lock index 6820d6dee5..79b80aae04 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -99,8 +99,8 @@ dependencies = [ "accesskit_consumer 0.35.0", "hashbrown 0.16.1", "static_assertions", - "windows", - "windows-core", + "windows 0.62.2", + "windows-core 0.62.2", ] [[package]] @@ -898,7 +898,7 @@ dependencies = [ "iana-time-zone", "num-traits", "serde", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -2080,7 +2080,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ "rustix 1.1.5", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -2267,7 +2267,7 @@ dependencies = [ "log", "presser", "thiserror 2.0.21", - "windows", + "windows 0.62.2", ] [[package]] @@ -2371,7 +2371,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core", + "windows-core 0.62.2", ] [[package]] @@ -2709,7 +2709,7 @@ dependencies = [ "simd_cesu8", "thiserror 2.0.21", "walkdir", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3059,7 +3059,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" dependencies = [ "cfg-if", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -3188,6 +3188,12 @@ dependencies = [ "imgref", ] +[[package]] +name = "lz4_flex" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "373f5eceeeab7925e0c1098212f2fbc4d416adec9d35051a6ab251e824c1854a" + [[package]] name = "maybe-owned" version = "0.3.4" @@ -3416,6 +3422,15 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -3822,6 +3837,16 @@ dependencies = [ "objc2-core-graphics", ] +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-io-surface" version = "0.3.2" @@ -4062,7 +4087,7 @@ dependencies = [ "libc", "redox_syscall 0.5.18", "smallvec", - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -4519,10 +4544,13 @@ dependencies = [ name = "photocraft-raster" version = "0.8.2" dependencies = [ + "crc32fast", + "lz4_flex", "photocraft-color", "photocraft-geom", "proptest", "serde", + "sysinfo", ] [[package]] @@ -5885,6 +5913,20 @@ dependencies = [ "libc", ] +[[package]] +name = "sysinfo" +version = "0.37.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16607d5caffd1c07ce073528f9ed972d88db15dd44023fa57142963be3feb11f" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows 0.61.3", +] + [[package]] name = "system-deps" version = "7.0.8" @@ -6913,9 +6955,9 @@ dependencies = [ "web-sys", "wgpu-naga-bridge", "wgpu-types", - "windows", - "windows-core", - "windows-result", + "windows 0.62.2", + "windows-core 0.62.2", + "windows-result 0.4.1", ] [[package]] @@ -6950,6 +6992,22 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -6959,16 +7017,44 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections 0.2.0", + "windows-core 0.61.2", + "windows-future 0.2.1", + "windows-link 0.1.3", + "windows-numerics 0.2.0", +] + [[package]] name = "windows" version = "0.62.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" dependencies = [ - "windows-collections", - "windows-core", - "windows-future", - "windows-numerics", + "windows-collections 0.3.2", + "windows-core 0.62.2", + "windows-future 0.3.2", + "windows-numerics 0.3.1", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core 0.61.2", ] [[package]] @@ -6977,7 +7063,20 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" dependencies = [ - "windows-core", + "windows-core 0.62.2", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.1.3", + "windows-result 0.3.4", + "windows-strings 0.4.2", ] [[package]] @@ -6988,9 +7087,20 @@ checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" dependencies = [ "windows-implement", "windows-interface", - "windows-link", - "windows-result", - "windows-strings", + "windows-link 0.2.1", + "windows-result 0.4.1", + "windows-strings 0.5.1", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", + "windows-threading 0.1.0", ] [[package]] @@ -6999,9 +7109,9 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" dependencies = [ - "windows-core", - "windows-link", - "windows-threading", + "windows-core 0.62.2", + "windows-link 0.2.1", + "windows-threading 0.2.1", ] [[package]] @@ -7026,20 +7136,45 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core 0.61.2", + "windows-link 0.1.3", +] + [[package]] name = "windows-numerics" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" dependencies = [ - "windows-core", - "windows-link", + "windows-core 0.62.2", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", ] [[package]] @@ -7048,7 +7183,16 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" dependencies = [ - "windows-link", + "windows-link 0.2.1", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", ] [[package]] @@ -7057,7 +7201,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -7093,7 +7237,7 @@ version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -7118,7 +7262,7 @@ version = "0.53.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ - "windows-link", + "windows-link 0.2.1", "windows_aarch64_gnullvm 0.53.1", "windows_aarch64_msvc 0.53.1", "windows_i686_gnu 0.53.1", @@ -7129,13 +7273,22 @@ dependencies = [ "windows_x86_64_msvc 0.53.1", ] +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + [[package]] name = "windows-threading" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" dependencies = [ - "windows-link", + "windows-link 0.2.1", ] [[package]] @@ -7408,7 +7561,7 @@ dependencies = [ "thiserror 2.0.21", "url", "widestring", - "windows", + "windows 0.62.2", "xcb", "zbus", ] diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index 78dae7b06f..9e2bc9c702 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -962,6 +962,30 @@ fn auto_tile(params: &FilterParams, bounds: Rect) -> i32 { } } +/// Conservative transient allocation estimate for filter admission. Output tiles remain in +/// the paged store; whole-image kernels must admit their float input before reading it. +pub fn working_bytes(params: &FilterParams, area: Rect, bounds: Rect, channels: usize) -> u64 { + if area.is_empty() { + return 0; + } + #[cfg(not(target_arch = "wasm32"))] + let threads = rayon::current_num_threads().max(1) as u64; + #[cfg(target_arch = "wasm32")] + let threads = 1u64; + let tile = auto_tile(params, bounds).max(1) as u64; + let floats = (channels as u64).saturating_mul(4); + let base = (RESULT_BUDGET as u64).saturating_mul(3); + match params.halo_for(bounds) { + Halo::Bounds => base.saturating_add(bounds.union(&area).size().area().saturating_mul(floats)), + Halo::Radius(r) => { + let side = tile.saturating_add((r.max(0) as u64).saturating_mul(2)); + base.saturating_add( + side.saturating_mul(side).saturating_add(tile.saturating_mul(tile).saturating_mul(3)).saturating_mul(floats).saturating_mul(threads), + ) + } + } +} + /// [`apply`] / [`apply_in`] with an explicit tile size (tests use it to check tile independence). pub fn apply_tiled( surface: &Surface, diff --git a/crates/algo/src/selection.rs b/crates/algo/src/selection.rs index ad858df2a2..5b3f629715 100644 --- a/crates/algo/src/selection.rs +++ b/crates/algo/src/selection.rs @@ -53,9 +53,10 @@ pub fn mask_from_surface(s: Option<&Surface>, area: Rect) -> Vec { let tc = TileCoord::containing(x, y); let x1 = (tc.rect().x1).min(area.x1); let dst = row.get_mut((x - area.x0) as usize..(x1 - area.x0) as usize).unwrap_or_default(); - let src = s.tile(tc).and_then(|t| { + let guard = s.tile(tc).map(|t| t.bytes()); + let src = guard.as_deref().and_then(|bytes| { let base = (y - tc.ty * TILE_SIZE) as usize * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize; - t.bytes().get(base..base + dst.len()) + bytes.get(base..base + dst.len()) }); match src { Some(src) => dst.iter_mut().zip(src).for_each(|(d, b)| *d = lut[*b as usize]), @@ -115,7 +116,7 @@ fn surface_from_masks(area: Rect, new: &[f32], prev: Option<&[f32]>, f: impl Fn( let tr = tc.rect().intersect(&area); let (lx, span) = ((tr.x0 - area.x0) as usize, tr.width() as usize); let mut tile = Arc::clone(blank); - let data = Arc::make_mut(&mut tile).bytes_mut(); + let mut data = Arc::make_mut(&mut tile).bytes_mut(); let (mut lo, mut hi) = (if tr == tc.rect() { u8::MAX } else { 0 }, 0u8); for y in tr.y0..tr.y1 { let o = (y - tc.ty * TILE_SIZE) as usize * ts + (tr.x0 - tc.tx * TILE_SIZE) as usize; @@ -123,6 +124,7 @@ fn surface_from_masks(area: Rect, new: &[f32], prev: Option<&[f32]>, f: impl Fn( row((y - area.y0) as usize * w + lx, dst); (lo, hi) = dst.iter().fold((lo, hi), |(lo, hi), b| (lo.min(*b), hi.max(*b))); } + drop(data); (hi > 0).then(|| (*tc, if lo == u8::MAX { Arc::clone(&full) } else { tile })) }); s.put_tiles(built.into_iter().flatten()); diff --git a/crates/algo/src/selection/marquee.rs b/crates/algo/src/selection/marquee.rs index 7dd861164a..12db42b505 100644 --- a/crates/algo/src/selection/marquee.rs +++ b/crates/algo/src/selection/marquee.rs @@ -217,19 +217,25 @@ pub fn combine_surfaces(a: &Surface, b: &Surface, area: Rect, f: impl Fn(f32, f3 } } let mut tile = Tile::clone(&blank); - let data = tile.bytes_mut(); + let mut data = tile.bytes_mut(); + let same_tile = ta.zip(tb).is_some_and(|(left, right)| Arc::ptr_eq(left, right)); + let read_a = ta.map(|tile| tile.bytes()); + let read_b = tb.filter(|_| !same_tile).map(|tile| tile.bytes()); + let bytes_a = read_a.as_deref(); + let bytes_b = if same_tile { bytes_a } else { read_b.as_deref() }; let (mut lo, mut hi) = (if tr == rect { u8::MAX } else { 0 }, 0u8); let (x0, x1) = ((tr.x0 - rect.x0) as usize, (tr.x1 - rect.x0) as usize); for ly in (tr.y0 - rect.y0) as usize..(tr.y1 - rect.y0) as usize { let (s, e) = (ly * TS + x0, ly * TS + x1); - let src_a = ta.and_then(|t| t.bytes().get(s..e)).unwrap_or(&row_a[..x1 - x0]); - let src_b = tb.and_then(|t| t.bytes().get(s..e)).unwrap_or(&row_b[..x1 - x0]); + let src_a = bytes_a.and_then(|bytes| bytes.get(s..e)).unwrap_or(&row_a[..x1 - x0]); + let src_b = bytes_b.and_then(|bytes| bytes.get(s..e)).unwrap_or(&row_b[..x1 - x0]); let Some(dst) = data.get_mut(s..e) else { continue }; for (d, (x, y)) in dst.iter_mut().zip(src_a.iter().zip(src_b)) { *d = pair(*x, *y); (lo, hi) = (lo.min(*d), hi.max(*d)); } } + drop(data); (hi > 0).then(|| (tc, if lo == u8::MAX { Arc::clone(&full) } else { Arc::new(tile) })) }); out.put_tiles(built.into_iter().flatten()); diff --git a/crates/algo/src/tests.rs b/crates/algo/src/tests.rs index 9a90012df9..abca6e3b86 100644 --- a/crates/algo/src/tests.rs +++ b/crates/algo/src/tests.rs @@ -1,6 +1,15 @@ use super::*; use photocraft_color::{PixelFormat, SampleType}; +#[test] +fn relight_admission_tracks_the_document_dependent_working_set() { + let params = FilterParams::Relight { angle: 0.0, elevation: 45.0, intensity: 50.0, ambient: 50.0, warmth: 0.0, softness: 100.0 }; + let small = Rect::new(0, 0, 128, 128); + let large = Rect::new(0, 0, 86400, 43200); + assert!(working_bytes(¶ms, small, small, 4) < working_bytes(¶ms, small, large, 4)); + assert_eq!(working_bytes(¶ms, Rect::EMPTY, large, 4), 0); +} + fn fmt(s: SampleType) -> PixelFormat { PixelFormat::new(ColorMode::Rgb, s, true) } diff --git a/crates/compose/src/bounds.rs b/crates/compose/src/bounds.rs index 985a400e08..dec2d868d9 100644 --- a/crates/compose/src/bounds.rs +++ b/crates/compose/src/bounds.rs @@ -34,6 +34,12 @@ fn cache() -> &'static Mutex { C.get_or_init(|| Mutex::new(Cache { entries: HashMap::new(), sweep_at: MIN_SWEEP })) } +pub(crate) fn purge() { + let mut cache = cache().lock().unwrap_or_else(|e| e.into_inner()); + cache.entries.clear(); + cache.sweep_at = MIN_SWEEP; +} + /// `Surface::content_bounds`, cached per tile. pub fn content_bounds(s: &Surface) -> Rect { if s.tile_count() == 0 { @@ -54,8 +60,11 @@ pub fn content_bounds(s: &Surface) -> Rect { let b = match hit { Some(b) => b, None => { + let generation = photocraft_raster::spill::read_error_generation(); let b = t.content_bounds(&dp); - c.entries.insert(key, Entry { tile: Arc::downgrade(t), default: dp.clone().into_boxed_slice(), bounds: b }); + if photocraft_raster::spill::check_since(generation).is_ok() { + c.entries.insert(key, Entry { tile: Arc::downgrade(t), default: dp.clone().into_boxed_slice(), bounds: b }); + } b } }; diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 8813b122d9..d05766bc43 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1563,6 +1563,17 @@ pub fn purge_effect_cache() -> usize { freed } +/// Discard derived pixels and their source pins after a scratch read failure. This also lets +/// closing the affected document release its failed tiles instead of keeping them in a cache. +pub fn discard_unreadable_pixel_caches() { + if photocraft_raster::spill::check_integrity().is_err() { + purge_effect_cache(); + bounds::purge(); + masks::purge(); + shape_split::purge(); + } +} + fn fx_cache() -> &'static std::sync::Mutex { static C: std::sync::OnceLock> = std::sync::OnceLock::new(); C.get_or_init(|| std::sync::Mutex::new(FxCache { map: Default::default(), order: Default::default(), bytes: 0 })) @@ -1623,6 +1634,7 @@ fn effect_maps(layer: &Layer, rect: Rect, cx: &Ctx) -> std::sync::Arc std::sync::Arc { + let generation = photocraft_raster::spill::read_error_generation(); let slot = { let mut c = fx_cache().lock().unwrap_or_else(|e| e.into_inner()); if let Some(s) = c.map.get(&key) { @@ -1641,6 +1653,9 @@ fn cached_effect_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx) -> std::s let maps = effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns); let bytes = maps.bytes(); let maps = std::sync::Arc::new(maps); + if photocraft_raster::spill::check_since(generation).is_err() { + return maps; + } if slot.set(FxEntry { maps: maps.clone(), _pin: layer.clone(), bytes }).is_ok() { // Counted exactly once, by the build that filled the slot, and only while the // slot is still cached (eviction may have dropped it meanwhile). diff --git a/crates/compose/src/masks.rs b/crates/compose/src/masks.rs index d70947ec7c..c8c73df866 100644 --- a/crates/compose/src/masks.rs +++ b/crates/compose/src/masks.rs @@ -81,6 +81,12 @@ fn cache() -> &'static Mutex { C.get_or_init(|| Mutex::new(Cache::default())) } +pub(crate) fn purge() { + let mut c = cache().lock().unwrap_or_else(|e| e.into_inner()); + c.clear(); + c.in_flight.clear(); +} + /// Entries kept (least recently used dropped first). const CAPACITY: usize = 64; @@ -116,7 +122,11 @@ fn lookup(c: &Mutex, k: u64) -> CachedMask { fn finish_mask(c: &Mutex, k: u64, slot: &Arc>, generation: u64, build: impl FnOnce() -> (Surface, Option)) -> Surface { slot.get_or_init(|| { // Never hold the global cache mutex while rasterizing or feathering. + let read_generation = photocraft_raster::spill::read_error_generation(); let (surface, pixel_input) = build(); + if photocraft_raster::spill::check_since(read_generation).is_err() { + return surface; + } let bytes = entry_bytes(&surface, pixel_input.as_ref()); let mut c = c.lock().unwrap_or_else(|e| e.into_inner()); if c.in_flight.get(&k).and_then(Weak::upgrade).is_some_and(|active| Arc::ptr_eq(&active, slot)) { @@ -135,7 +145,7 @@ fn cached_mask(c: &Mutex, k: u64, build: impl FnOnce() -> (Surface, Optio } fn surface_bytes(surface: &Surface) -> usize { - surface.tiles().fold(surface.default_bytes().len(), |bytes, (_, tile)| bytes.saturating_add(tile.bytes().len())) + surface.tiles().fold(surface.default_bytes().len(), |bytes, (_, tile)| bytes.saturating_add(tile.len())) } fn entry_bytes(surface: &Surface, pixel_input: Option<&Surface>) -> usize { diff --git a/crates/compose/src/shape_split.rs b/crates/compose/src/shape_split.rs index 9f0143f889..52b76ccd41 100644 --- a/crates/compose/src/shape_split.rs +++ b/crates/compose/src/shape_split.rs @@ -20,6 +20,10 @@ fn cache() -> &'static Mutex<(HashMap, u64)> { C.get_or_init(|| Mutex::new((HashMap::new(), 0))) } +pub(crate) fn purge() { + cache().lock().unwrap_or_else(|e| e.into_inner()).0.clear(); +} + const CAPACITY: usize = 32; /// Most pixel bytes the split parts may hold (#4530): each entry is two canvas-sized surfaces, /// so 32 of them at 24 MP could hold several GB outside every memory budget. @@ -48,6 +52,7 @@ pub fn purge_cache() -> usize { /// (Photoshop's rendering, `sh.cache`) reach past our fill, the part the fill doesn't explain is /// stroke: the stroke follows Photoshop's coverage (psd-tools double-stroke-effects). pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surface, Surface)> { + let generation = photocraft_raster::spill::read_error_generation(); sh.stroke.as_ref()?; let mut h = std::collections::hash_map::DefaultHasher::new(); (canvas.x0, canvas.y0, canvas.x1, canvas.y1).hash(&mut h); @@ -76,6 +81,9 @@ pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surfac if let Some(cache) = &sh.cache { fit_stroke(&parts.0, &mut parts.1, cache, canvas); } + if photocraft_raster::spill::check_since(generation).is_err() { + return Some(parts); + } let mut c = cache().lock().unwrap_or_else(|e| e.into_inner()); // Least recently used first, until the new entry fits both the count and the byte budget. let new_bytes = entry_bytes(&parts); diff --git a/crates/compose/tests/scratch_retry.rs b/crates/compose/tests/scratch_retry.rs new file mode 100644 index 0000000000..51fe07b1e9 --- /dev/null +++ b/crates/compose/tests/scratch_retry.rs @@ -0,0 +1,49 @@ +#![cfg(not(target_arch = "wasm32"))] + +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Effect, Layer}; +use photocraft_geom::{Rect, Size}; +use photocraft_raster::spill; +use std::io::{Read, Seek, SeekFrom, Write}; + +#[test] +fn failed_effect_build_is_not_reused_after_original_pixels_recover() { + let dir = std::env::temp_dir().join(format!("photocraft-compose-scratch-retry-{}", std::process::id())); + spill::configure(Some(&dir), 1).unwrap(); + let mut doc = Document::new("Shadow", Size::new(64, 64), ColorMode::Rgb, SampleType::U8); + let mut background = Layer::raster("Background", PixelFormat::RGBA8); + background.surface_mut().unwrap().fill_rect(Rect::from_xywh(0, 0, 64, 64), &[1.0; 4]); + let mut foreground = Layer::raster("Shadow", PixelFormat::RGBA8); + foreground.surface_mut().unwrap().fill_rect(Rect::new(16, 16, 48, 48), &[1.0, 0.0, 0.0, 1.0]); + foreground.effects.items.push(Effect::default_drop_shadow()); + doc.layers.extend([background, foreground]); + let expected = photocraft_compose::flatten(&doc).px; + // Keep the known-good bounds, but force a new effect-map build from the damaged source. + photocraft_compose::purge_effect_cache(); + spill::settle(); + assert_eq!(spill::stats().resident_bytes, 0); + let path = std::fs::read_dir(&dir).unwrap().filter_map(Result::ok).map(|e| e.path()).find(|p| p.extension().is_some_and(|e| e == "scratch")).unwrap(); + let mut file = std::fs::OpenOptions::new().read(true).write(true).open(path).unwrap(); + let mut good = Vec::new(); + file.read_to_end(&mut good).unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&vec![0; good.len()]).unwrap(); + file.sync_all().unwrap(); + drop(photocraft_compose::flatten(&doc)); + assert!(spill::check_integrity().is_err()); + + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&good).unwrap(); + file.sync_all().unwrap(); + for layer in &doc.layers { + for (_, tile) in layer.surface().unwrap().tiles() { + tile.try_bytes().unwrap(); + } + } + assert!(spill::check_integrity().is_ok()); + assert_eq!(photocraft_compose::flatten(&doc).px, expected); + photocraft_compose::purge_effect_cache(); + drop((doc, file)); + spill::configure(None, 0).unwrap(); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rs index d3a6d36931..d739e74fe4 100644 --- a/crates/engine/src/color_cmds.rs +++ b/crates/engine/src/color_cmds.rs @@ -641,24 +641,29 @@ pub fn convert_surface(s: &Surface, from: ColorMode, to: PixelFormat, t: &Transf .collect(); let tile_px = (photocraft_geom::TILE_SIZE * photocraft_geom::TILE_SIZE) as usize; let dst_len = tile_px * to.bytes_per_pixel(); - let mut staging = vec![0u8; dst_len * distinct.len()]; - let jobs: Vec<(&[u8], &mut [u8])> = distinct.iter().map(|t| t.bytes()).zip(staging.chunks_mut(dst_len.max(1))).collect(); let kind = match sf.sample { SampleType::U8 => SampleKind::U8, SampleType::U16 => SampleKind::U16, SampleType::F32 => SampleKind::F32, }; - t.convert_bytes_many(kind, jobs, ss, ds, true); - let mut converted: Vec>> = vec![None; distinct.len()]; - for (c, i) in tiles { - if let Some(Some(tile)) = converted.get(i) { - out.put_tiles([(c, tile.clone())]); - continue; + let mut converted = Vec::with_capacity(distinct.len()); + for batch in distinct.chunks(32) { + let mut staging = vec![0u8; dst_len * batch.len()]; + { + let sources: Vec<_> = batch.iter().map(|tile| tile.bytes()).collect(); + let jobs: Vec<(&[u8], &mut [u8])> = sources.iter().map(|bytes| &**bytes).zip(staging.chunks_mut(dst_len.max(1))).collect(); + t.convert_bytes_many(kind, jobs, ss, ds, true); } - let Some(bytes) = staging.chunks(dst_len.max(1)).nth(i) else { continue }; - out.tile_mut(c).bytes_mut().copy_from_slice(bytes); - if let Some(slot) = converted.get_mut(i) { - *slot = out.tile(c).cloned(); + for bytes in staging.chunks(dst_len.max(1)) { + let coord = photocraft_geom::TileCoord::new(0, 0); + let mut surface = Surface::new(to); + surface.tile_mut(coord).bytes_mut().copy_from_slice(bytes); + converted.push(surface.tile(coord).cloned()); + } + } + for (coord, index) in tiles { + if let Some(Some(tile)) = converted.get(index) { + out.put_tiles([(coord, tile.clone())]); } } out @@ -824,7 +829,7 @@ fn ink_surface(s: &Surface, d: &Duotone) -> Surface { let (mut px, mut o) = ([0.0f32; 2], [0.0f32; 4]); for i in 0..n { for (k, v) in px.iter_mut().enumerate().take(ss) { - *v = photocraft_color::read_sample(src, sf.sample, i * ss + k); + *v = photocraft_color::read_sample(&src, sf.sample, i * ss + k); } ink(&px[..ss], &mut o[..ds]); for (k, v) in o.iter().enumerate().take(ds) { @@ -835,7 +840,7 @@ fn ink_surface(s: &Surface, d: &Duotone) -> Surface { }) .collect(); for ((c, _), bytes) in tiles.iter().zip(inked) { - let tile = out.tile_mut(*c).bytes_mut(); + let mut tile = out.tile_mut(*c).bytes_mut(); if tile.len() == bytes.len() { tile.copy_from_slice(&bytes); } diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rs index 68e617bc8c..e14e62c8e9 100644 --- a/crates/engine/src/fill_cmds.rs +++ b/crates/engine/src/fill_cmds.rs @@ -410,7 +410,7 @@ fn blend_into(surf: &mut Surface, area: Rect, source: &Source, sel: Option<&Surf .try_clone() .map_err(|e| EngineError::Other(format!("not enough memory while blending a pixel tile ({e}); the document was not changed")))?, }; - blend_tile(tile.bytes_mut(), &fmt, tc.rect(), tr, source, mask.as_ref(), b); + blend_tile(&mut tile.bytes_mut(), &fmt, tc.rect(), tr, source, mask.as_ref(), b); done.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((tc, std::sync::Arc::new(tile))); Ok(()) })?; @@ -421,7 +421,8 @@ fn blend_into(surf: &mut Surface, area: Rect, source: &Source, sel: Option<&Surf /// The selection's coverage over one tile (its channel 0). pub(crate) struct Mask<'a> { - bytes: &'a [u8], + bytes: Option>, + default: &'a [u8], fmt: photocraft_color::PixelFormat, origin: Rect, } @@ -429,13 +430,14 @@ pub(crate) struct Mask<'a> { impl<'a> Mask<'a> { /// `sel` over the tile at `tc` (its default pixel where it has no tile there). pub(crate) fn of(sel: &'a Surface, tc: photocraft_geom::TileCoord) -> Self { - Mask { bytes: sel.tile(tc).map_or(sel.default_bytes(), |t| t.bytes()), fmt: sel.format(), origin: tc.rect() } + Mask { bytes: sel.tile(tc).map(|t| t.bytes()), default: sel.default_bytes(), fmt: sel.format(), origin: tc.rect() } } pub(crate) fn at(&self, x: i32, y: i32) -> f32 { + let bytes = self.bytes.as_deref().unwrap_or(self.default); let bpp = self.fmt.bytes_per_pixel(); // A default-pixel mask is one pixel long: every position reads it. - let i = if self.bytes.len() == bpp { 0 } else { ((y - self.origin.y0) as usize * TILE_SIZE as usize + (x - self.origin.x0) as usize) * bpp }; - self.bytes.get(i..i + bpp).map_or(0.0, |px| photocraft_color::read_sample(px, self.fmt.sample, 0)) + let i = if bytes.len() == bpp { 0 } else { ((y - self.origin.y0) as usize * TILE_SIZE as usize + (x - self.origin.x0) as usize) * bpp }; + bytes.get(i..i + bpp).map_or(0.0, |px| photocraft_color::read_sample(px, self.fmt.sample, 0)) } /// Fully selected over `r`? pub(crate) fn full(&self, r: Rect) -> bool { diff --git a/crates/engine/src/filters.rs b/crates/engine/src/filters.rs index a9b6564309..30366cb286 100644 --- a/crates/engine/src/filters.rs +++ b/crates/engine/src/filters.rs @@ -252,6 +252,8 @@ pub(crate) fn run_filter(s: &mut Session, id: &str, p: &Value) -> Result &label, move |doc, _, ctx| { let filter = |surf: &photocraft_raster::Surface, fp: &FilterParams, area, bounds, sel: Option<&photocraft_raster::Surface>, extent| { + let _working = photocraft_raster::memory::try_reserve_operation(algo::working_bytes(fp, area, bounds, surf.format().channels())) + .map_err(EngineError::Other)?; ctx.stage(0.0, 1.0, &msg, |ctl| algo::apply_in_with(surf, fp, area, bounds, sel, extent, ctl)).ok_or(EngineError::Cancelled) }; let selection = doc.selection.clone(); @@ -520,6 +522,33 @@ mod tests { "filter.other.offset", ]; + #[test] + fn enormous_global_filter_is_refused_before_allocating_and_preserves_document() { + let mut s = Session::new(); + // A sparse document exercises admission without allocating a giant background first. + s.add_document( + photocraft_doc::Document::new( + "large", + photocraft_doc::Size::new(300000, 300000), + photocraft_color::ColorMode::Rgb, + photocraft_color::SampleType::U8, + ), + None, + ); + s.execute("layer.new.layer", json!({})).unwrap(); + s.edit("one pixel", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().write_pixel(0, 0, &[0.2, 0.4, 0.6, 1.0]); + Ok(()) + }) + .unwrap(); + let before = s.active().unwrap().doc.clone(); + let revision = s.active().unwrap().revision; + let err = s.execute("filter.distort.twirl", json!({})).unwrap_err().to_string(); + assert!(err.contains("working memory"), "{err}"); + assert_eq!(s.active().unwrap().revision, revision); + assert_eq!(s.active().unwrap().doc, before); + } + #[test] fn every_filter_command_runs_changes_pixels_and_undoes() { for id in ALL { diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index dc43f4d794..1fc75ead29 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -284,6 +284,14 @@ pub fn run( work: impl FnOnce(&JobCtx) -> Result + Send + 'static, apply: impl FnOnce(&mut Session, T) -> Result + Send + 'static, ) -> Result { + let work = move |ctx: &JobCtx| -> Result { + photocraft_compose::discard_unreadable_pixel_caches(); + photocraft_raster::spill::check_integrity().map_err(EngineError::Other)?; + let generation = photocraft_raster::spill::read_error_generation(); + let value = work(ctx)?; + photocraft_raster::spill::check_since(generation).map_err(EngineError::Other)?; + Ok(value) + }; if !s.jobs.spawn || cfg!(target_arch = "wasm32") { let t = work(&s.jobs.inline.clone().unwrap_or_default())?; return apply(s, t); diff --git a/crates/engine/src/lens_cmds.rs b/crates/engine/src/lens_cmds.rs index 379ca2402a..76881428e9 100644 --- a/crates/engine/src/lens_cmds.rs +++ b/crates/engine/src/lens_cmds.rs @@ -278,6 +278,8 @@ fn raw_enabled(s: &Session) -> std::result::Result<(), String> { /// Runs `f` on the target layer (pixel layer edited in place inside the selection; smart object /// gets a smart filter with `stored` params). fn run_filter(s: &mut Session, cmd: &str, label: &str, stored: Value, float_bg: bool, f: &dyn Fn(&Surface, Rect) -> Surface) -> Result { + let state = s.active().ok_or(EngineError::NoDocument)?; + let _working = photocraft_raster::memory::try_reserve_operation(state.doc.size.area().saturating_mul(64)).map_err(EngineError::Other)?; let id = target(s, &stored)?; let mut stored = stored; if let Value::Object(m) = &mut stored { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ff3cde6e4c..5b86a64040 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -98,6 +98,7 @@ pub mod render_cmds; pub mod retouch_cmds; pub mod sample_cmds; pub mod sampler_cmds; +mod scratch; pub mod select_extra_cmds; pub mod selection_cmds; pub mod slice_cmds; @@ -464,6 +465,8 @@ pub struct Session { /// document, source read-only)`. The shell takes them with [`Session::take_held_open`]. held_opens: Vec<(u64, Document, bool)>, next_held_open: u64, + /// Shared native memory supervision, owned and stopped by the last session using it. + scratch_runtime: Option, } /// Move item `i` of `v` to position `to`, clamped to the end. Returns where it went; `None` when @@ -690,6 +693,9 @@ impl Session { /// Apply an undoable edit to the active document. pub fn edit(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Option) -> Result) -> Result { + photocraft_compose::discard_unreadable_pixel_caches(); + photocraft_raster::spill::check_integrity().map_err(EngineError::Other)?; + let scratch_generation = photocraft_raster::spill::read_error_generation(); let restrict = self.color_restrict; let sampler_map = self.sampler_map.take(); let st = self.active_mut().ok_or(EngineError::NoDocument)?; @@ -697,12 +703,17 @@ impl Session { // Selecting layers is not a step, so the state this edit leaves behind targets what was // selected just before it (#1356): undoing a stroke keeps the painted layer active. let prior = st.layer_target(); + let previous_active_layer = st.active_layer; let mut doc = (*before).clone(); let mut active = st.active_layer; let r = f(&mut doc, &mut active)?; if let (Some(k), Some(id)) = (restrict, active) { channel_cmds::restrict_to_color(&before, &mut doc, id, k); } + if let Err(error) = photocraft_raster::spill::check_since(scratch_generation) { + st.active_layer = previous_active_layer; + return Err(EngineError::Other(error)); + } st.doc = Arc::new(doc); st.active_layer = active; fix_selection(st); diff --git a/crates/engine/src/pixels.rs b/crates/engine/src/pixels.rs index cde7fa41db..f5ee5ec3c8 100644 --- a/crates/engine/src/pixels.rs +++ b/crates/engine/src/pixels.rs @@ -278,6 +278,7 @@ fn edit_tiles( None => {} } let Some(src) = current.map(|t| &**t).or(blank.as_ref()) else { return Ok(None) }; + let source = src.try_bytes().map_err(|e| crate::EngineError::Other(format!("could not read pixels while {purpose}: {e}")))?; let mut out: Option = None; let (mut px, mut enc) = ([0.0f32; 8], [0u8; 32]); let (Some(px), Some(enc)) = (px.get_mut(..n), enc.get_mut(..bpp)) else { return Ok(None) }; @@ -285,7 +286,7 @@ fn edit_tiles( let row = (y - tc.ty * TILE_SIZE) as usize * TILE_SIZE as usize; for x in tr.x0..tr.x1 { let i = (row + (x - tc.tx * TILE_SIZE) as usize) * bpp; - let Some(old) = src.bytes().get(i..i + bpp) else { continue }; + let Some(old) = source.get(i..i + bpp) else { continue }; for (c, v) in px.iter_mut().enumerate() { *v = photocraft_color::read_sample(old, fmt.sample, c); } @@ -297,10 +298,15 @@ fn edit_tiles( continue; } if out.is_none() { - out = Some(src.try_clone().map_err(oom)?); + let mut tile = surf.try_default_tile().map_err(oom)?; + tile.bytes_mut().copy_from_slice(&source); + out = Some(tile); } - if let Some(dst) = out.as_mut().and_then(|t| t.bytes_mut().get_mut(i..i + bpp)) { - dst.copy_from_slice(enc); + if let Some(tile) = out.as_mut() { + let mut bytes = tile.bytes_mut(); + if let Some(dst) = bytes.get_mut(i..i + bpp) { + dst.copy_from_slice(enc); + } } } } diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 5e728cb546..3bf19692dc 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -582,6 +582,11 @@ pub struct Performance { /// Memory PhotoCraft may use, in MB: bounds each document's pixels plus its History (the /// oldest states are dropped beyond it). pub memory_usage_mb: u32, + /// Percent of physical RAM for the complete process; None preserves the legacy MB limit. + #[serde(default)] + pub memory_usage_percent: Option, + /// Independent graphics budget, including canvas pages and compositor working sets. + pub gpu_memory_mb: u32, /// Undo steps kept per document (History panel states). pub history_states: u32, /// Display cache levels (mip levels kept for zoomed-out views). @@ -612,16 +617,34 @@ impl Performance { } /// Pixel memory a document and its History may hold (Memory Usage), in bytes: beyond it - /// the oldest history states are dropped. + /// the oldest history states are dropped. 0 (no byte limit, only History States) while the + /// scratch disk is on: tiles only History holds go to disk instead. pub fn history_budget_bytes(&self) -> usize { + if photocraft_raster::spill::enabled() { + return 0; + } (self.memory_usage_mb as usize).saturating_mul(1 << 20) } + + /// Pixel bytes kept in memory before tiles move to the scratch disk: half of Memory Usage + /// (the rest is for the GPU canvas, caches and the app). `PHOTOCRAFT_TILE_BUDGET_MB` + /// overrides it (tests, stress runs). + pub fn tile_budget_bytes(&self) -> usize { + let bytes = std::env::var("PHOTOCRAFT_TILE_BUDGET_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map(|mb| mb.saturating_mul(1 << 20)) + .unwrap_or_else(|| u64::from(self.memory_usage_mb).saturating_mul(1 << 20) / 2); + usize::try_from(bytes).unwrap_or(usize::MAX) + } } impl Default for Performance { fn default() -> Self { Self { memory_usage_mb: 8192, + memory_usage_percent: Some(70), + gpu_memory_mb: 1024, history_states: 50, cache_levels: 4, cache_tile_size: 8192, @@ -1061,7 +1084,6 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[ "performance.cacheLevels", "performance.effectCacheMb", "performance.legacyCompositing", - "scratchDisks.disks", "unitsAndRulers.columnWidth", "unitsAndRulers.gutter", "plugIns.showExtensionPanels", @@ -1141,6 +1163,8 @@ pub fn range(path: &str) -> Option<(f64, f64)> { "interface.notificationDurationSeconds" => (1.0, 120.0), "export.jpegQuality" | "export.webpQuality" => (1.0, 100.0), "performance.memoryUsageMb" => (256.0, 1_048_576.0), + "performance.memoryUsagePercent" => (1.0, 95.0), + "performance.gpuMemoryMb" => (64.0, 65536.0), "performance.historyStates" => (1.0, 1000.0), "performance.cacheLevels" => (1.0, 8.0), "performance.cacheTileSize" => (256.0, 16384.0), @@ -1248,7 +1272,7 @@ fn check_value(path: &str, v: &Value) -> std::result::Result<(), String> { seen.push(theme); } } - if path == "performance.renderingMode" && v.is_null() { + if matches!(path, "performance.renderingMode" | "performance.memoryUsagePercent") && v.is_null() { return Ok(()); // Legacy policy, resolved from useGpu and gpuBackend. } if let Some(c) = choices(path) { @@ -1504,6 +1528,8 @@ impl Session { /// Push engine-relevant preferences into live state: every document's history limit, the /// layer-effect cache budget and the text engine's missing-glyph protection. pub fn apply_prefs(&mut self) { + self.scratch_runtime.get_or_insert_with(crate::scratch::Runtime::default); + crate::scratch::configure(self.prefs()); let n = self.prefs().performance.history_states.max(1) as usize; let bytes = self.prefs().performance.history_budget_bytes(); let budget = self.prefs().performance.effect_cache_mb as usize; diff --git a/crates/engine/src/scratch.rs b/crates/engine/src/scratch.rs new file mode 100644 index 0000000000..79d67ab0db --- /dev/null +++ b/crates/engine/src/scratch.rs @@ -0,0 +1,142 @@ +//! Native tile storage configuration, kept out of the preference data model. + +use crate::prefs::Preferences; + +/// A web session has no filesystem or memory-supervision thread. +#[cfg(target_arch = "wasm32")] +#[derive(Default)] +pub(crate) struct Runtime; + +#[cfg(not(target_arch = "wasm32"))] +pub(crate) use native::Runtime; + +#[cfg(not(target_arch = "wasm32"))] +mod native { + use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError, Weak}; + use std::thread::JoinHandle; + use std::time::{Duration, Instant}; + + // Weak ownership: the process-wide cache cannot keep a session's worker alive. + pub(crate) struct Runtime { + _worker: Arc, + } + + impl Default for Runtime { + fn default() -> Self { + static SHARED: OnceLock>> = OnceLock::new(); + let mut shared = SHARED.get_or_init(Mutex::default).lock().unwrap_or_else(PoisonError::into_inner); + let worker = shared.upgrade().unwrap_or_else(|| { + let worker = Arc::new(Worker::start()); + *shared = Arc::downgrade(&worker); + worker + }); + Self { _worker: worker } + } + } + + struct Worker { + stop: Arc<(Mutex, Condvar)>, + thread: Option>, + } + + impl Worker { + fn start() -> Self { + let stop = Arc::new((Mutex::new(false), Condvar::new())); + let flag = stop.clone(); + let thread = std::thread::Builder::new() + .name("pc-memory-residency".into()) + .spawn(move || { + let _maintenance = photocraft_raster::spill::background_maintenance(); + let mut measured = Instant::now(); + loop { + let (lock, wake) = &*flag; + let stopped = lock.lock().unwrap_or_else(PoisonError::into_inner); + let (stopped, _) = wake.wait_timeout_while(stopped, Duration::from_millis(100), |stop| !*stop).unwrap_or_else(PoisonError::into_inner); + if *stopped { + break; + } + drop(stopped); + if measured.elapsed() >= Duration::from_secs(2) { + photocraft_raster::memory::refresh(); + measured = Instant::now(); + } + photocraft_raster::spill::maintain_budget(); + } + }) + .ok(); + // If spawning fails, raster's synchronous fallback still enforces the budget. + Self { stop, thread } + } + } + + impl Drop for Worker { + fn drop(&mut self) { + let (lock, wake) = &*self.stop; + *lock.lock().unwrap_or_else(PoisonError::into_inner) = true; + wake.notify_all(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn workers_stop_join_and_can_restart() { + for _ in 0..3 { + let worker = Worker::start(); + assert!(worker.thread.is_some()); + let stop = worker.stop.clone(); + let began = Instant::now(); + drop(worker); + assert!(*stop.0.lock().unwrap()); + assert!(began.elapsed() < Duration::from_secs(2)); + } + } + + #[test] + fn sessions_share_supervision_without_static_ownership() { + let a = Runtime::default(); + let b = Runtime::default(); + assert!(Arc::ptr_eq(&a._worker, &b._worker)); + let weak = Arc::downgrade(&a._worker); + drop((a, b)); + // Other engine tests can hold the shared runtime concurrently; a private worker + // proves the same ownership contract without depending on their timing. + let worker = Arc::new(Worker::start()); + let private = Arc::downgrade(&worker); + drop(worker); + assert!(private.upgrade().is_none()); + drop(weak); + } + } +} + +pub(crate) fn configure(prefs: &Preferences) { + let budget = photocraft_raster::memory::configure(photocraft_raster::memory::Policy { + percent: prefs.performance.memory_usage_percent, + absolute_bytes: u64::from(prefs.performance.memory_usage_mb).saturating_mul(1 << 20), + }); + #[cfg(not(target_arch = "wasm32"))] + { + let dir = prefs + .scratch_disks + .disks + .iter() + .find(|d| d.enabled && !d.path.trim().is_empty()) + .map(|d| if d.path.trim() == "(system temp)" { std::env::temp_dir() } else { std::path::PathBuf::from(d.path.trim()) }); + // An unusable directory disables eviction without dropping resident pixels. + // The reason is exposed in ui.inspect and the application's status bar. + let tiles = if std::env::var_os("PHOTOCRAFT_TILE_BUDGET_MB").is_some() { + prefs.performance.tile_budget_bytes() + } else { + usize::try_from(budget.tile_bytes).unwrap_or(usize::MAX) + }; + let _ = photocraft_raster::spill::configure(dir.as_deref(), tiles); + } + #[cfg(target_arch = "wasm32")] + let _ = (prefs, budget); +} diff --git a/crates/engine/tests/memory_prefs.rs b/crates/engine/tests/memory_prefs.rs new file mode 100644 index 0000000000..4ef6dc1728 --- /dev/null +++ b/crates/engine/tests/memory_prefs.rs @@ -0,0 +1,24 @@ +use photocraft_engine::prefs::{Performance, Preferences}; +use serde_json::json; + +#[test] +fn old_preferences_keep_their_absolute_limit() { + let p: Performance = serde_json::from_value(json!({"memoryUsageMb": 2048})).unwrap(); + assert_eq!(p.memory_usage_percent, None); + assert_eq!(p.memory_usage_mb, 2048); + assert_eq!(Performance::default().memory_usage_percent, Some(70)); +} + +#[test] +fn memory_preferences_validate_and_can_restore_absolute_mode() { + let mut p = Preferences::default(); + assert!(p.set("performance.memoryUsagePercent", json!(96)).is_err()); + assert!(p.set("performance.memoryUsagePercent", json!(0)).is_err()); + assert!(p.set("performance.gpuMemoryMb", json!(1)).is_err()); + p.set("performance.memoryUsagePercent", json!(75)).unwrap(); + assert_eq!(p.performance.memory_usage_percent, Some(75)); + p.set("performance.memoryUsagePercent", json!(null)).unwrap(); + assert_eq!(p.performance.memory_usage_percent, None); + p.set("performance.gpuMemoryMb", json!(512)).unwrap(); + assert_eq!(p.performance.gpu_memory_mb, 512); +} diff --git a/crates/engine/tests/scratch_disk.rs b/crates/engine/tests/scratch_disk.rs new file mode 100644 index 0000000000..5f9a392380 --- /dev/null +++ b/crates/engine/tests/scratch_disk.rs @@ -0,0 +1,90 @@ +//! Disk-backed current pixels and history: lossless undo, and failed reads never commit. +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer}; +use photocraft_engine::Session; +use photocraft_geom::{Rect, Size, TileCoord}; +use photocraft_raster::spill; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::sync::Arc; + +#[test] +fn scratch_pixels_history_and_failed_save_are_transactional() { + let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-{}", std::process::id())); + let mut session = Session::new(); + session.edit_prefs(|p| { + p.scratch_disks.disks = vec![photocraft_engine::prefs::ScratchDisk { path: dir.to_string_lossy().into(), enabled: true }]; + p.performance.memory_usage_mb = 1; + }); + assert!(spill::enabled()); + assert_eq!(session.prefs().performance.history_budget_bytes(), 0); + let mut doc = Document::new("Scratch fixture", Size::new(2048, 256), ColorMode::Rgb, SampleType::U8); + let mut layer = Layer::raster("Pixels", PixelFormat::RGBA8); + let id = layer.id; + for i in 0..8 { + let mut bytes = layer.surface_mut().unwrap().tile_mut(TileCoord::new(i, 0)).bytes_mut(); + for (j, b) in bytes.iter_mut().enumerate() { + *b = (j as u32).wrapping_mul(17).wrapping_add(i as u32 * 43) as u8; + } + } + doc.layers.push(layer); + session.add_document(doc, None); + session.select_layer(id).unwrap(); + let before = session.active().unwrap().doc.clone(); + session + .edit("Paint", |d, _| { + d.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(Rect::from_xywh(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + spill::settle(); + assert!(session.undo()); + assert_eq!(*session.active().unwrap().doc, *before); + assert!(session.redo()); + assert_eq!(session.active().unwrap().doc.layer(id).unwrap().surface().unwrap().pixel(1, 1), vec![1.0, 0.0, 0.0, 1.0]); + spill::settle(); + + // Force all tiles to disk, including the tile the failed edit will touch. + spill::configure(Some(&dir), 1).unwrap(); + spill::settle(); + assert_eq!(spill::stats().resident_bytes, 0); + // Damage only this test's scratch file; retain its exact contents to restore the backing. + let path = std::fs::read_dir(&dir).unwrap().filter_map(Result::ok).map(|e| e.path()).find(|p| p.extension().is_some_and(|e| e == "scratch")).unwrap(); + let mut file = std::fs::OpenOptions::new().read(true).write(true).open(path).unwrap(); + let mut good = Vec::new(); + file.read_to_end(&mut good).unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&vec![0; good.len()]).unwrap(); + file.sync_all().unwrap(); + let retained = session.active().unwrap().doc.clone(); + let revision = session.active().unwrap().revision; + let failed = session.edit("Failed paint", |d, active| { + let discarded = Layer::raster("Discarded", PixelFormat::RGBA8); + *active = Some(discarded.id); + d.layers.push(discarded); + d.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(Rect::from_xywh(1800, 0, 4, 4), &[0.0, 1.0, 0.0, 1.0]); + Ok(()) + }); + assert!(failed.is_err()); + assert!(Arc::ptr_eq(&session.active().unwrap().doc, &retained)); + assert_eq!(session.active().unwrap().revision, revision); + assert_eq!(session.active().unwrap().active_layer, Some(id)); + let mut writer = photocraft_format::PcraftWriter::new(); + assert!(writer.save_zip(&retained, &Default::default()).is_err()); + assert!(photocraft_io::export(&retained, "png", &Default::default()).is_err()); + + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&good).unwrap(); + file.sync_all().unwrap(); + for d in [&before, &retained] { + for (_, tile) in d.layer(id).unwrap().surface().unwrap().tiles() { + tile.try_bytes().unwrap(); + } + } + assert!(spill::check_integrity().is_ok()); + let (bytes, _) = writer.save_zip(&retained, &Default::default()).unwrap(); + let loaded = photocraft_format::load_from_bytes(&bytes).unwrap(); + assert_eq!(loaded.layers, retained.layers); + drop((session, before, retained, loaded, writer, file)); + spill::configure(None, 0).unwrap(); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index d047668cb0..19ba8a1eb8 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -333,13 +333,32 @@ impl Sink for Collect<'_> { } } -fn tile_le(t: &Tile, sample: SampleType) -> std::borrow::Cow<'_, [u8]> { +/// A tile's bytes in little-endian order: the tile itself (kept in memory while this lives), or +/// a byte-swapped copy on big-endian machines. +enum LeBytes<'a> { + Native(photocraft_raster::TileBytes<'a>), + Swapped(Vec), + Borrowed(&'a [u8]), +} + +impl std::ops::Deref for LeBytes<'_> { + type Target = [u8]; + fn deref(&self) -> &[u8] { + match self { + LeBytes::Native(b) => b, + LeBytes::Swapped(b) => b, + LeBytes::Borrowed(b) => b, + } + } +} + +fn tile_le(t: &Tile, sample: SampleType) -> LeBytes<'_> { if cfg!(target_endian = "big") { let mut b = t.bytes().to_vec(); swap_to_le(&mut b, sample); - std::borrow::Cow::Owned(b) + LeBytes::Swapped(b) } else { - std::borrow::Cow::Borrowed(t.bytes()) + LeBytes::Native(t.bytes()) } } @@ -417,10 +436,10 @@ impl Object { } /// The bytes this object stores (tiles little-endian). - fn content(&self) -> std::borrow::Cow<'_, [u8]> { + fn content(&self) -> LeBytes<'_> { match self { Object::Tile(tile, sample) => tile_le(tile, *sample), - Object::Blob(blob) => std::borrow::Cow::Borrowed(blob.as_slice()), + Object::Blob(blob) => LeBytes::Borrowed(blob.as_slice()), } } } @@ -726,6 +745,19 @@ impl PcraftWriter { } fn prepare(&mut self, doc: &Document, opts: &SaveOptions) -> Result { + photocraft_raster::spill::check_integrity().map_err(FormatError::corrupt)?; + let generation = photocraft_raster::spill::read_error_generation(); + let prepared = self.prepare_inner(doc, opts); + if let Err(error) = photocraft_raster::spill::check_since(generation) { + // Failed reads may have hashed display placeholders. Never reuse those hashes + // when the original backing becomes readable and the same writer retries. + self.hash_cache.clear(); + return Err(FormatError::corrupt(error)); + } + prepared + } + + fn prepare_inner(&mut self, doc: &Document, opts: &SaveOptions) -> Result { self.hash_cache.retain(|_, (w, _)| w.strong_count() > 0); convert::check_nesting(&doc.layers)?; let mut c = Collect { hash_cache: Some(&mut self.hash_cache), ..Default::default() }; @@ -760,6 +792,7 @@ impl PcraftWriter { for (h, b) in c.blobs { objects.insert(blob_path(&h), Object::Blob(b)); } + photocraft_raster::spill::check_integrity().map_err(FormatError::corrupt)?; Ok(Prepared { manifest, objects, previews, stats }) } @@ -795,6 +828,7 @@ impl PcraftWriter { z.add(path, &data)?; next.insert(path.clone(), data); } + photocraft_raster::spill::check_integrity().map_err(FormatError::corrupt)?; self.compressed = next; Ok((z.finish()?, stats)) } @@ -858,7 +892,9 @@ impl PcraftWriter { Object::Tile(..) => stats.tiles_written += 1, Object::Blob(_) => stats.blobs_written += 1, } - write_bundle_file(dir, &object_path, &obj.compressed())?; + let compressed = obj.compressed(); + photocraft_raster::spill::check_integrity().map_err(FormatError::corrupt)?; + write_bundle_file(dir, &object_path, &compressed)?; let written = path_signature(&object_path)?; if let Some(cache) = &mut self.verified_directory { match written { @@ -887,6 +923,7 @@ impl PcraftWriter { } } } + photocraft_raster::spill::check_integrity().map_err(FormatError::corrupt)?; write_bundle_file(dir, &dir.join(MANIFEST), &p.manifest)?; // The manifest is committed: the save has succeeded. Removing objects it no longer // references is best-effort housekeeping (a vanished or locked file must not turn a diff --git a/crates/format/tests/scratch_retry.rs b/crates/format/tests/scratch_retry.rs new file mode 100644 index 0000000000..1bb06110ec --- /dev/null +++ b/crates/format/tests/scratch_retry.rs @@ -0,0 +1,48 @@ +#![cfg(not(target_arch = "wasm32"))] + +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer}; +use photocraft_geom::{Size, TileCoord}; +use photocraft_raster::spill; +use std::io::{Read, Seek, SeekFrom, Write}; + +#[test] +fn retry_after_failed_hashing_never_reuses_placeholder_hashes() { + let dir = std::env::temp_dir().join(format!("photocraft-format-scratch-retry-{}", std::process::id())); + spill::configure(Some(&dir), 1).unwrap(); + let mut doc = Document::new("Retry", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); + let mut layer = Layer::raster("Pixels", PixelFormat::RGBA8); + for i in 0..2 { + let mut bytes = layer.surface_mut().unwrap().tile_mut(TileCoord::new(i, 0)).bytes_mut(); + for (j, byte) in bytes.iter_mut().enumerate() { + *byte = (j as u8).wrapping_mul(17).wrapping_add((i * 43) as u8); + } + } + doc.layers.push(layer); + spill::settle(); + assert_eq!(spill::stats().resident_bytes, 0); + let path = std::fs::read_dir(&dir).unwrap().filter_map(Result::ok).map(|e| e.path()).find(|p| p.extension().is_some_and(|e| e == "scratch")).unwrap(); + let mut file = std::fs::OpenOptions::new().read(true).write(true).open(path).unwrap(); + let mut good = Vec::new(); + file.read_to_end(&mut good).unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&vec![0; good.len()]).unwrap(); + file.sync_all().unwrap(); + + let mut writer = photocraft_format::PcraftWriter::new(); + // This save discovers the failure itself, after entering the hash collection stage. + assert!(writer.save_zip(&doc, &Default::default()).is_err()); + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&good).unwrap(); + file.sync_all().unwrap(); + for (_, tile) in doc.layers[0].surface().unwrap().tiles() { + tile.try_bytes().unwrap(); + } + assert!(spill::check_integrity().is_ok()); + let (saved, _) = writer.save_zip(&doc, &Default::default()).unwrap(); + let loaded = photocraft_format::load_from_bytes(&saved).unwrap(); + assert_eq!(loaded.layers, doc.layers); + drop((doc, loaded, writer, file)); + spill::configure(None, 0).unwrap(); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rs index 223d4ed983..cedaf77cd8 100644 --- a/crates/gpu/src/lib.rs +++ b/crates/gpu/src/lib.rs @@ -2093,7 +2093,7 @@ fn convert_tile(surface: &Surface, tile: Option<&Arc>, kind: TexKind, c: T let fmt = surface.format(); let ch = fmt.channels(); if let (Some(t), TexKind::Rgba16F) = (tile, kind) - && let Some(out) = rgb_gray16_to_f16(&fmt, t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, t.bytes())) + && let Some(out) = rgb_gray16_to_f16(&fmt, &t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, &t.bytes())) { return out; } @@ -2231,7 +2231,7 @@ fn words(v: &[W]) -> Vec { .collect() } -/// IEEE half from f32 (round to nearest even; overflow → inf). +/// IEEE half from f32 (round to nearest even; overflow → inf). pub fn f32_to_f16(x: f32) -> u16 { let b = x.to_bits(); let sign = ((b >> 16) & 0x8000) as u16; @@ -2519,7 +2519,7 @@ mod tests { let data: Vec = (0..n).map(|i| (i as u32).wrapping_mul(2_654_435_761) as f32 / u32::MAX as f32 * hdr - (hdr - 1.0) / 4.0).collect(); s.write_region(r, &data); let t = s.tile(TileCoord::new(0, 0)).expect("written").clone(); - let fast = rgb_gray16_to_f16(&fmt, t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, t.bytes())).expect("fast path"); + let fast = rgb_gray16_to_f16(&fmt, &t.bytes()).or_else(|| rgb_gray32_to_f16(&fmt, &t.bytes())).expect("fast path"); let raw = s.read_region(r); let general: Vec = raw.chunks_exact(fmt.channels()).flat_map(|px| photocraft_raster::to_rgba(&fmt, px).map(|x| f32_to_f16(x).to_le_bytes())).flatten().collect(); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 49e4bb60e2..936bab32b9 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -260,10 +260,14 @@ pub fn import_with_svg_group_depth_and_interrupt( max_group_depth: usize, ctl: &photocraft_raster::Interrupt, ) -> Result { + photocraft_compose::discard_unreadable_pixel_caches(); + photocraft_raster::spill::check_integrity().map_err(IoError::Unsupported)?; + let scratch_generation = photocraft_raster::spill::read_error_generation(); ctl.check().map_err(|_| IoError::Cancelled)?; let r = import_stages(name, bytes, ctl, max_group_depth)?; ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(1.0); + photocraft_raster::spill::check_since(scratch_generation).map_err(IoError::Unsupported)?; Ok(r) } @@ -355,7 +359,11 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result /// export fails with [`IoError::Cancelled`]; otherwise the bytes are exactly [`export`]'s. pub fn export_with(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result { ctl.check().map_err(|_| IoError::Cancelled)?; + photocraft_compose::discard_unreadable_pixel_caches(); + photocraft_raster::spill::check_integrity().map_err(IoError::Unsupported)?; + let scratch_generation = photocraft_raster::spill::read_error_generation(); let r = export_stages(doc, name_or_ext, opts, ctl)?; + photocraft_raster::spill::check_since(scratch_generation).map_err(IoError::Unsupported)?; ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(1.0); Ok(r) diff --git a/crates/ops/src/lib.rs b/crates/ops/src/lib.rs index a20b841c17..f9671fbb48 100644 --- a/crates/ops/src/lib.rs +++ b/crates/ops/src/lib.rs @@ -254,7 +254,7 @@ fn tile_bytes(doc: &Document, seen: &mut HashSet) -> usize { tiles::surfaces(doc, |surface| { for (_, tile) in surface.tiles() { if seen.insert(Arc::as_ptr(tile) as usize) { - n = n.saturating_add(tile.bytes().len()); + n = n.saturating_add(tile.len()); } } }); diff --git a/crates/plugins/src/apply.rs b/crates/plugins/src/apply.rs index 7a144a28b9..250faf9ef5 100644 --- a/crates/plugins/src/apply.rs +++ b/crates/plugins/src/apply.rs @@ -145,7 +145,7 @@ impl Plugin { let results: Vec> = chunk.iter().map(run).collect(); for r in results { for (c, t) in r?.tiles() { - out.tile_mut(*c).bytes_mut().copy_from_slice(t.bytes()); + out.tile_mut(*c).bytes_mut().copy_from_slice(&t.bytes()); } } } @@ -215,7 +215,7 @@ fn encode_band(surface: &Surface, band: Rect, data: &[f32]) -> Surface { let mut s = Surface::with_default(surface.format(), &surface.default_pixel()); for c in band.tiles() { if let Some(t) = surface.tile(c) { - s.tile_mut(c).bytes_mut().copy_from_slice(t.bytes()); + s.tile_mut(c).bytes_mut().copy_from_slice(&t.bytes()); } else { s.tile_mut(c); } diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml index 956d1c9545..5fe5b0dd5b 100644 --- a/crates/raster/Cargo.toml +++ b/crates/raster/Cargo.toml @@ -11,6 +11,11 @@ workspace = true photocraft-geom = { workspace = true } photocraft-color = { workspace = true } serde = { workspace = true } +crc32fast = "1" +lz4_flex = { version = "0.11", default-features = false, features = ["std", "safe-encode", "safe-decode"] } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +sysinfo = { version = "0.37", default-features = false, features = ["system"] } [dev-dependencies] proptest = { workspace = true } diff --git a/crates/raster/examples/scratch_bench.rs b/crates/raster/examples/scratch_bench.rs new file mode 100644 index 0000000000..c7d04a56c4 --- /dev/null +++ b/crates/raster/examples/scratch_bench.rs @@ -0,0 +1,52 @@ +//! 24 MP release benchmark: identical pixel access with RAM-only and disk-backed tiles. +use photocraft_color::PixelFormat; +use photocraft_geom::{Rect, TILE_SIZE}; +use photocraft_raster::{Surface, spill}; +use std::time::Instant; + +fn run(dir: Option<&std::path::Path>) -> Result<(), String> { + spill::configure(dir, 16 << 20)?; + let start = Instant::now(); + let area = Rect::from_xywh(0, 0, 6000, 4000); + let mut surface = Surface::new(PixelFormat::RGBA8); + let mut random = 0x1234abcd_u32; + for tc in area.tiles() { + let mut bytes = surface.tile_mut(tc).bytes_mut(); + for byte in bytes.iter_mut() { + random ^= random << 13; + random ^= random >> 17; + random ^= random << 5; + *byte = random as u8; + } + } + spill::settle(); + let build_ms = start.elapsed().as_secs_f64() * 1000.0; + let resident = spill::stats().resident_bytes; + let disk = spill::stats().scratch_bytes; + let read = Instant::now(); + let mut checksum = 0u64; + // Rows exercise the same locks and conversions the CPU renderer uses. + let mut row = vec![[0; 4]; 6000]; + for y in 0..4000 { + surface.read_rgba8_into(Rect::from_xywh(0, y, 6000, 1), &mut row); + for pixel in &row { + checksum = checksum.wrapping_add(u32::from_le_bytes(*pixel) as u64); + } + } + spill::check_integrity()?; + println!( + "mode={} build_ms={build_ms:.2} read_ms={:.2} resident_bytes={resident} scratch_bytes={disk} checksum={checksum} tile_side={TILE_SIZE}", + if dir.is_some() { "scratch" } else { "ram" }, + read.elapsed().as_secs_f64() * 1000.0 + ); + drop(surface); + spill::configure(None, 0)?; + Ok(()) +} + +fn main() -> Result<(), String> { + run(None)?; + let dir = std::env::temp_dir().join(format!("photocraft-24mp-{}", std::process::id())); + run(Some(&dir))?; + std::fs::remove_dir(&dir).map_err(|e| e.to_string()) +} diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index ff45764980..2019cd7773 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -12,14 +12,16 @@ pub use interrupt::{Cancelled, Interrupt}; use std::collections::BTreeMap; use std::fmt; -use std::sync::Arc; +use std::ops::{Deref, DerefMut}; +use std::sync::{Arc, RwLockReadGuard, RwLockWriteGuard}; use photocraft_color::{ColorMode, PixelFormat, SampleType, read_sample, write_sample}; use photocraft_geom::{Rect, TILE_SIZE, TileCoord}; /// A checked surface allocation could not be represented or reserved. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum AllocationError { + ScratchRead(String), SizeOverflow, NotEnoughMemory { bytes: usize }, } @@ -27,6 +29,7 @@ pub enum AllocationError { impl fmt::Display for AllocationError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::ScratchRead(error) => write!(f, "scratch tile could not be read: {error}"), Self::SizeOverflow => f.write_str("requested surface allocation is too large"), Self::NotEnoughMemory { bytes } => write!(f, "not enough memory to allocate {} bytes", bytes), } @@ -34,11 +37,17 @@ impl fmt::Display for AllocationError { } impl std::error::Error for AllocationError {} +pub mod memory; +mod scratch_file; +pub mod spill; /// Pixel storage for one tile: `TILE_SIZE² × bytes_per_pixel`, row-major, interleaved channels. -#[derive(Clone, Debug, PartialEq, Eq)] +/// +/// The bytes may live on the scratch disk ([`spill`]); [`Tile::bytes`] and [`Tile::bytes_mut`] +/// bring them back and keep them in memory while the returned guard lives. Take one guard per +/// tile, not per pixel, in hot loops. pub struct Tile { - data: Box<[u8]>, + cell: Arc, } impl Tile { @@ -53,16 +62,17 @@ impl Tile { px.copy_from_slice(pixel); } } - Ok(Tile { data: data.into_boxed_slice() }) + Ok(Tile::from_vec(data)) } /// Clone this tile's pixel buffer with a fallible reservation. pub fn try_clone(&self) -> Result { - let bytes = self.data.len(); + let source = self.try_bytes().map_err(AllocationError::ScratchRead)?; + let bytes = source.len(); let mut data = Vec::new(); data.try_reserve_exact(bytes).map_err(|_| AllocationError::NotEnoughMemory { bytes })?; - data.extend_from_slice(&self.data); - Ok(Tile { data: data.into_boxed_slice() }) + data.extend_from_slice(&source); + Ok(Tile::from_vec(data)) } fn filled(format: &PixelFormat, pixel: &[u8]) -> Self { @@ -73,15 +83,30 @@ impl Tile { px.copy_from_slice(pixel); } } - Tile { data: data.into_boxed_slice() } + Tile::from_vec(data) } - pub fn bytes(&self) -> &[u8] { - &self.data + fn from_vec(data: Vec) -> Self { + Tile { cell: spill::Cell::new(data) } } - pub fn bytes_mut(&mut self) -> &mut [u8] { - &mut self.data + /// The tile's bytes (read back from the scratch disk if needed). + pub fn bytes(&self) -> TileBytes<'_> { + let guard = self.cell.read(); + let placeholder = if guard.is_none() { vec![0; self.len()] } else { Vec::new() }; + TileBytes(guard, placeholder) + } + pub fn bytes_mut(&mut self) -> TileBytesMut<'_> { + let guard = self.cell.write(); + let placeholder = if guard.is_none() { vec![0; self.len()] } else { Vec::new() }; + TileBytesMut(guard, placeholder) + } + /// Fallible pixel access for callers that can propagate a scratch read failure. + pub fn try_bytes(&self) -> Result, String> { + let bytes = self.bytes(); + match self.cell.read_error() { + Some(error) => Err(error), + None => Ok(bytes), + } } - /// Tile-local half-open bounds `(x0, y0, x1, y1)` of the pixels that differ from the encoded /// pixel `dp` (one pixel of the tile's format), or `None` when every pixel equals it (or `dp` /// is empty). @@ -92,7 +117,7 @@ impl Tile { } let ts = TILE_SIZE as usize; let (mut x0, mut y0, mut x1, mut y1) = (usize::MAX, usize::MAX, 0usize, 0usize); - for (y, row) in self.data.chunks_exact(ts * bpp).enumerate() { + for (y, row) in self.bytes().chunks_exact(ts * bpp).enumerate() { let Some(first) = row.chunks_exact(bpp).position(|px| px != dp) else { continue }; let last = ts - 1 - row.chunks_exact(bpp).rev().position(|px| px != dp).unwrap_or(0); x0 = x0.min(first); @@ -102,6 +127,65 @@ impl Tile { } (x0 != usize::MAX).then_some((x0 as u16, y0 as u16, x1 as u16, y1 as u16)) } + /// Byte length, without touching the pixels (they may be on disk). + pub fn len(&self) -> usize { + self.cell.len() + } + pub fn is_empty(&self) -> bool { + self.cell.len() == 0 + } +} + +impl Clone for Tile { + fn clone(&self) -> Self { + match self.try_bytes() { + Ok(bytes) => Tile::from_vec(bytes.to_vec()), + // Preserve the original backing; the transaction will reject this poisoned tile. + Err(_) => Tile { cell: self.cell.clone() }, + } + } +} + +impl PartialEq for Tile { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.cell, &other.cell) || (self.len() == other.len() && *self.bytes() == *other.bytes()) + } +} + +impl Eq for Tile {} + +impl std::fmt::Debug for Tile { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Tile").field("len", &self.len()).finish_non_exhaustive() + } +} + +/// Read guard over a tile's bytes; derefs to `[u8]`. +pub struct TileBytes<'a>(RwLockReadGuard<'a, Option>>, Vec); + +impl Deref for TileBytes<'_> { + type Target = [u8]; + fn deref(&self) -> &[u8] { + self.0.as_deref().unwrap_or(&self.1) + } +} + +/// Write guard over a tile's bytes; derefs to `[u8]`. +pub struct TileBytesMut<'a>(RwLockWriteGuard<'a, Option>>, Vec); + +impl Deref for TileBytesMut<'_> { + type Target = [u8]; + fn deref(&self) -> &[u8] { + self.0.as_deref().unwrap_or(&self.1) + } +} + +impl DerefMut for TileBytesMut<'_> { + fn deref_mut(&mut self) -> &mut [u8] { + self.0.as_deref_mut().unwrap_or(&mut self.1) + } + + } #[derive(Clone, Debug)] @@ -141,8 +225,9 @@ impl UniformTiles { if let Some(k) = self.of.get(&Arc::as_ptr(t)) { return *k; } - let mut px = t.data.chunks_exact(bpp); - let k = px.next().filter(|p0| px.all(|p| p == *p0)).map(|p0| match self.canonical.iter().position(|c| c.data.get(..bpp) == Some(p0)) { + let bytes = t.try_bytes().ok()?; + let mut px = bytes.chunks_exact(bpp); + let k = px.next().filter(|p0| px.all(|p| p == *p0)).map(|p0| match self.canonical.iter().position(|c| c.try_bytes().is_ok_and(|bytes| bytes.get(..bpp) == Some(p0))) { Some(k) => k, None => { self.canonical.push(t.clone()); @@ -169,7 +254,9 @@ impl Surface { let mut out = Vec::new(); out.try_reserve_exact(len).map_err(|_| AllocationError::NotEnoughMemory { bytes })?; out.resize(len, 0.0); + let generation = spill::read_error_generation(); self.read_region_into(r, &mut out); + spill::check_since(generation).map_err(AllocationError::ScratchRead)?; Ok(out) } @@ -189,7 +276,7 @@ impl Surface { match self.tiles.get(&tc) { Some(t) => { let src = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * bpp; - out[dst..dst + span].copy_from_slice(&t.data[src..src + span]); + out[dst..dst + span].copy_from_slice(&t.try_bytes().map_err(AllocationError::ScratchRead)?[src..src + span]); } None => { for px in out[dst..dst + span].chunks_exact_mut(bpp) { @@ -244,6 +331,9 @@ impl Surface { /// Fallible counterpart to [`Surface::tile_mut`]. Pixel storage is reserved before changing /// the surface, and a shared tile is copied only after its replacement has been allocated. pub fn try_tile_mut(&mut self, c: TileCoord) -> Result<&mut Tile, AllocationError> { + if let Some(tile) = self.tiles.get(&c) { + drop(tile.try_bytes().map_err(AllocationError::ScratchRead)?); + } if !self.tiles.contains_key(&c) { let tile = Arc::new(Tile::try_filled(&self.format, &self.default_pixel)?); self.tiles.insert(c, tile); @@ -267,18 +357,41 @@ impl Surface { for tc in r.tiles() { let tr = tc.rect().intersect(&r); let t = self.try_tile_mut(tc)?; + let mut target = t.bytes_mut(); let span = tr.width() as usize * n; for y in tr.y0..tr.y1 { let src = (((y - r.y0) as usize) * r.width() as usize + (tr.x0 - r.x0) as usize) * n; let dst = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; for (i, v) in data[src..src + span].iter().enumerate() { - write_sample(&mut t.data, sample, dst + i, *v); + write_sample(&mut target, sample, dst + i, *v); } } } Ok(()) } + /// Tile rects that differ between `self` and `other`: tiles present in only one, or holding + /// a different (copied-on-write) tile. Compares pointers, never pixels, so it is cheap and + /// never reads spilled tiles back. `None` when the format or default pixel differ (every + /// pixel may read differently). + pub fn changed_rect(&self, other: &Surface) -> Option { + if self.format != other.format || self.default_pixel != other.default_pixel { + return None; + } + let mut r = Rect::EMPTY; + for (c, t) in &self.tiles { + if other.tiles.get(c).is_none_or(|o| !Arc::ptr_eq(t, o)) { + r = r.union(&c.rect()); + } + } + for c in other.tiles.keys() { + if !self.tiles.contains_key(c) { + r = r.union(&c.rect()); + } + } + Some(r) + } + /// Coarse bounds: union of allocated tile rects. pub fn tile_bounds(&self) -> Rect { self.tiles.keys().fold(Rect::EMPTY, |r, c| r.union(&c.rect())) @@ -315,7 +428,7 @@ impl Surface { pub fn prune(&mut self) { let dp = self.default_pixel.clone(); let bpp = dp.len(); - self.tiles.retain(|_, t| t.data.chunks_exact(bpp).any(|px| px != &*dp)); + self.tiles.retain(|_, t| t.bytes().chunks_exact(bpp).any(|px| px != &*dp)); } #[inline] @@ -338,8 +451,9 @@ impl Surface { let n = self.channels(); match self.tiles.get(&c) { Some(t) => { + let data = t.bytes(); for (i, o) in out.iter_mut().enumerate().take(n) { - *o = read_sample(&t.data, self.format.sample, base + i); + *o = read_sample(&data, self.format.sample, base + i); } } None => { @@ -354,9 +468,9 @@ impl Surface { let (c, base) = self.locate(x, y); let n = self.channels(); let sample = self.format.sample; - let t = self.tile_mut(c); + let mut t = self.tile_mut(c).bytes_mut(); for (i, v) in px.iter().enumerate().take(n) { - write_sample(&mut t.data, sample, base + i, *v); + write_sample(&mut t, sample, base + i, *v); } } @@ -365,7 +479,7 @@ impl Surface { pub fn sample_channel(&self, x: i32, y: i32, c: usize) -> f32 { let (tc, base) = self.locate(x, y); match self.tiles.get(&tc) { - Some(t) => read_sample(&t.data, self.format.sample, base + c), + Some(t) => read_sample(&t.bytes(), self.format.sample, base + c), None => read_sample(&self.default_pixel, self.format.sample, c), } } @@ -389,9 +503,10 @@ impl Surface { match self.tiles.get(&TileCoord { tx, ty }) { None => out[i..end].fill(dp), Some(t) => { + let data = t.bytes(); for (k, o) in out[i..end].iter_mut().enumerate() { let lx = (x + k as i32 * step - tx * TILE_SIZE) as usize; - *o = read_sample(&t.data, self.format.sample, (ly * TILE_SIZE as usize + lx) * n + c); + *o = read_sample(&data, self.format.sample, (ly * TILE_SIZE as usize + lx) * n + c); } } } @@ -408,7 +523,8 @@ impl Surface { let dp = self.default_pixel(); for tc in r.tiles() { let tr = tc.rect().intersect(&r); - let tile = self.tiles.get(&tc); + let guard = self.tiles.get(&tc).map(|t| t.bytes()); + let tile = guard.as_deref(); for y in tr.y0..tr.y1 { let o = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * n; let span = tr.width() as usize * n; @@ -417,7 +533,7 @@ impl Surface { Some(t) => { let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; for (i, d) in dst.iter_mut().enumerate() { - *d = read_sample(&t.data, self.format.sample, base + i); + *d = read_sample(t, self.format.sample, base + i); } } None => { @@ -442,7 +558,8 @@ impl Surface { let dp = to_rgba(&fmt, &self.default_pixel()); for tc in r.tiles() { let tr = tc.rect().intersect(&r); - let tile = self.tiles.get(&tc); + let guard = self.tiles.get(&tc).map(|t| t.bytes()); + let tile = guard.as_deref(); for y in tr.y0..tr.y1 { let o = ((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize; let dst = &mut out[o..o + tr.width() as usize]; @@ -453,13 +570,13 @@ impl Surface { let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; match (fmt.mode, fmt.sample, fmt.alpha) { (ColorMode::Rgb, SampleType::U8, true) => { - let src = &t.data[base..base + dst.len() * 4]; + let src = &t[base..base + dst.len() * 4]; for (d, s) in dst.iter_mut().zip(src.as_chunks::<4>().0) { *d = [s[0] as f32 / 255.0, s[1] as f32 / 255.0, s[2] as f32 / 255.0, s[3] as f32 / 255.0]; } } (ColorMode::Grayscale, SampleType::U8, true) => { - let src = &t.data[base..base + dst.len() * 2]; + let src = &t[base..base + dst.len() * 2]; for (d, s) in dst.iter_mut().zip(src.as_chunks::<2>().0) { let g = s[0] as f32 / 255.0; *d = [g, g, g, s[1] as f32 / 255.0]; @@ -468,7 +585,7 @@ impl Surface { (ColorMode::Cmyk, SampleType::U8, _) => { // Identical ink bytes share the exact ICC result; alpha is independent. let mut previous: Option<([u8; 4], [f32; 3])> = None; - let src = &t.data[base..base + dst.len() * n]; + let src = &t[base..base + dst.len() * n]; for (d, s) in dst.iter_mut().zip(src.chunks_exact(n)) { let ink = [s[0], s[1], s[2], s[3]]; let rgb = match previous { @@ -486,7 +603,7 @@ impl Surface { let mut px = [0.0f32; 8]; for (i, d) in dst.iter_mut().enumerate() { for (c, v) in px.iter_mut().enumerate().take(n) { - *v = read_sample(&t.data, fmt.sample, base + i * n + c); + *v = read_sample(t, fmt.sample, base + i * n + c); } *d = to_rgba(&fmt, &px[..n]); } @@ -497,7 +614,7 @@ impl Surface { } /// Reads `r` as straight 8-bit RGBA into `out` (`w*h` entries). RGBA8 surfaces copy tile bytes - /// directly; other formats convert through [`Surface::read_rgba_into`] one tile row at a time. + /// directly; other formats convert while holding the same tile read guard. pub fn read_rgba8_into(&self, r: Rect, out: &mut [[u8; 4]]) { let w = r.width() as usize; debug_assert_eq!(out.len(), w * r.height() as usize); @@ -506,10 +623,11 @@ impl Surface { let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; let dp = to_rgba(&fmt, &self.default_pixel()); let dp8 = [q(dp[0]), q(dp[1]), q(dp[2]), q(dp[3])]; - let mut row = Vec::new(); + let mut px = [0.0f32; 8]; for tc in r.tiles() { let tr = tc.rect().intersect(&r); - let tile = self.tiles.get(&tc); + let guard = self.tiles.get(&tc).map(|t| t.bytes()); + let tile = guard.as_deref(); for y in tr.y0..tr.y1 { let o = ((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize; let dst = &mut out[o..o + tr.width() as usize]; @@ -518,14 +636,19 @@ impl Surface { Some(t) if rgba8 => { let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * 4; let len = dst.len(); - for (d, s) in dst.iter_mut().zip(t.data[base..base + len * 4].as_chunks::<4>().0) { + for (d, s) in dst.iter_mut().zip(t[base..base + len * 4].as_chunks::<4>().0) { *d = [s[0], s[1], s[2], s[3]]; } } - Some(_) => { - row.resize(dst.len(), [0.0f32; 4]); - self.read_rgba_into(Rect::new(tr.x0, y, tr.x1, y + 1), &mut row); - for (d, p) in dst.iter_mut().zip(&row) { + Some(t) => { + // A second read lock could deadlock behind an eviction writer. + let n = fmt.channels(); + let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; + for (i, d) in dst.iter_mut().enumerate() { + for (c, v) in px.iter_mut().enumerate().take(n) { + *v = read_sample(t, fmt.sample, base + i * n + c); + } + let p = to_rgba(&fmt, &px[..n]); *d = [q(p[0]), q(p[1]), q(p[2]), q(p[3])]; } } @@ -548,7 +671,8 @@ impl Surface { let dp = self.default_pixel(); for tc in r.tiles() { let tr = tc.rect().intersect(&r); - let tile = self.tiles.get(&tc); + let guard = self.tiles.get(&tc).map(|t| t.bytes()); + let tile = guard.as_deref(); for y in tr.y0..tr.y1 { for x in tr.x0..tr.x1 { let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; @@ -556,7 +680,7 @@ impl Surface { Some(t) => { let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; for i in 0..n { - out[o + i] = read_sample(&t.data, self.format.sample, base + i); + out[o + i] = read_sample(t, self.format.sample, base + i); } } None => out[o..o + n].copy_from_slice(&dp), @@ -576,6 +700,7 @@ impl Surface { for tc in r.tiles() { let tr = tc.rect().intersect(&r); let t = self.tile_mut(tc); + let mut target = t.bytes_mut(); // Convert contiguous channel samples a row at a time. Dispatching on depth here // removes the per-pixel channel loop and lets the compiler vectorise conversion. let span = tr.width() as usize * n; @@ -584,7 +709,7 @@ impl Surface { let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * n; let src = &data[o..o + span]; let bytes = sample.bytes(); - let dst = &mut t.data[base * bytes..(base + span) * bytes]; + let dst = &mut target[base * bytes..(base + span) * bytes]; match sample { SampleType::U8 => { for (d, v) in dst.iter_mut().zip(src) { @@ -681,12 +806,12 @@ impl Surface { self.tiles.insert(tc, t.clone()); continue; } - let t = self.tile_mut(tc); + let mut t = self.tile_mut(tc).bytes_mut(); for y in tr.y0..tr.y1 { let ly = (y - tc.ty * TILE_SIZE) as usize; let lx0 = (tr.x0 - tc.tx * TILE_SIZE) as usize; let lx1 = (tr.x1 - tc.tx * TILE_SIZE) as usize; - let row = &mut t.data[(ly * TILE_SIZE as usize + lx0) * bpp..(ly * TILE_SIZE as usize + lx1) * bpp]; + let row = &mut t[(ly * TILE_SIZE as usize + lx0) * bpp..(ly * TILE_SIZE as usize + lx1) * bpp]; for p in row.chunks_exact_mut(bpp) { p.copy_from_slice(&enc); } @@ -708,12 +833,12 @@ impl Surface { assert_eq!(bytes.len(), w * r.height() as usize * bpp, "interleaved length mismatch"); for tc in r.tiles() { let tr = tc.rect().intersect(&r); - let t = self.tile_mut(tc); + let mut t = self.tile_mut(tc).bytes_mut(); let span = tr.width() as usize * bpp; for y in tr.y0..tr.y1 { let src = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * bpp; let dst = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * bpp; - t.data[dst..dst + span].copy_from_slice(&bytes[src..src + span]); + t[dst..dst + span].copy_from_slice(&bytes[src..src + span]); } } } @@ -728,10 +853,10 @@ impl Surface { let span = tr.width() as usize * bpp; for y in tr.y0..tr.y1 { let dst = (((y - r.y0) as usize) * w + (tr.x0 - r.x0) as usize) * bpp; - match self.tiles.get(&tc) { + match self.tiles.get(&tc).map(|t| t.bytes()) { Some(t) => { let src = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (tr.x0 - tc.tx * TILE_SIZE) as usize) * bpp; - out[dst..dst + span].copy_from_slice(&t.data[src..src + span]); + out[dst..dst + span].copy_from_slice(&t[src..src + span]); } None => { for p in out[dst..dst + span].chunks_exact_mut(bpp) { @@ -778,32 +903,36 @@ impl Surface { && sr.tiles().all(|sc| self.tiles.contains_key(&sc)); if covered && let Some(shared) = uniform.window(self, sr) { // A tile of only the default pixel is left out, as `prune` would. - if shared.data.get(..bpp) != Some(&*self.default_pixel) { + if shared.bytes().get(..bpp) != Some(&*self.default_pixel) { out.tiles.insert(dc, shared); } continue; } // A covered target is overwritten whole, so skip filling it with the default pixel. let mut tile = Tile::filled(&self.format, if covered { &zero } else { &self.default_pixel }); + let mut target = tile.bytes_mut(); for sc in sr.intersect(&content).tiles() { let Some(st) = self.tiles.get(&sc) else { continue }; + let source = st.bytes(); let part = sc.rect().intersect(&sr); let span = part.width() as usize * bpp; // Offsets inside the tiles (the target's computed wide: an offset near the i32 // limits saturates `translate`, and such rows are skipped rather than misplaced). - let at = |x: i64, y: i64| usize::try_from(y * i64::from(TILE_SIZE) + x).ok().map(|i| i * bpp); + let at = |x: i64, y: i64| usize::try_from(y * i64::from(TILE_SIZE) + x).ok().and_then(|i| i.checked_mul(bpp)); for y in part.y0..part.y1 { let src = at(i64::from(part.x0 - sc.tx * TILE_SIZE), i64::from(y - sc.ty * TILE_SIZE)); let dst = at(i64::from(part.x0) + i64::from(dx) - i64::from(dr.x0), i64::from(y) + i64::from(dy) - i64::from(dr.y0)); let (Some(src), Some(dst)) = (src, dst) else { continue }; - if let (Some(d), Some(s)) = (tile.data.get_mut(dst..dst + span), st.data.get(src..src + span)) { + if let (Some(d), Some(s)) = (target.get_mut(dst..dst.saturating_add(span)), source.get(src..src.saturating_add(span))) { d.copy_from_slice(s); } } } // A target that got only default pixels isn't stored, as `prune` would drop it. Checked // after the copy, a row at a time: a tile with content stops at its first such row. - if tile.data.chunks(default_row.len()).any(|row| row != default_row) { + let has_content = target.chunks(default_row.len()).any(|row| row != default_row); + drop(target); + if has_content { out.tiles.insert(dc, Arc::new(tile)); } } @@ -834,13 +963,15 @@ impl Surface { continue; } let tile = self.tile_mut(c); + let mut bytes = tile.bytes_mut(); for i in 0..px_count { for k in 0..color { let at = i * n + k; - let v = read_sample(&tile.data, format.sample, at); - write_sample(&mut tile.data, format.sample, at, f(v)); + let v = read_sample(&bytes, format.sample, at); + write_sample(&mut bytes, format.sample, at, f(v)); } } + drop(bytes); if let Some(mapped) = self.tiles.get(&c) { done.insert(key, mapped.clone()); } @@ -859,17 +990,19 @@ impl Surface { out.tiles.insert(*c, converted.clone()); continue; } - let dst = out.tile_mut(*c); + let source = t.bytes(); + let mut dst = out.tile_mut(*c).bytes_mut(); let px_count = (TILE_SIZE * TILE_SIZE) as usize; for i in 0..px_count { for (k, v) in src.iter_mut().enumerate() { - *v = read_sample(&t.data, self.format.sample, i * from_n + k); + *v = read_sample(&source, self.format.sample, i * from_n + k); } let px = convert_pixel(&self.format, &to, &src); for (k, v) in px.iter().enumerate() { - write_sample(&mut dst.data, to.sample, i * to.channels() + k, *v); + write_sample(&mut dst, to.sample, i * to.channels() + k, *v); } } + drop(dst); if let Some(converted) = out.tiles.get(c) { done.insert(Arc::as_ptr(t), converted.clone()); } @@ -891,16 +1024,19 @@ impl Surface { continue; } let dst = out.try_tile_mut(*c)?; + let source_bytes = t.try_bytes().map_err(AllocationError::ScratchRead)?; + let mut dest_bytes = dst.bytes_mut(); let px_count = (TILE_SIZE * TILE_SIZE) as usize; for i in 0..px_count { for (k, v) in src.iter_mut().enumerate() { - *v = read_sample(&t.data, self.format.sample, i * from_n + k); + *v = read_sample(&source_bytes, self.format.sample, i * from_n + k); } let px = convert_pixel(&self.format, &to, &src); for (k, v) in px.iter().enumerate() { - write_sample(&mut dst.data, to.sample, i * to.channels() + k, *v); + write_sample(&mut dest_bytes, to.sample, i * to.channels() + k, *v); } } + drop(dest_bytes); if let Some(converted) = out.tiles.get(c) { done.insert(Arc::as_ptr(t), converted.clone()); } @@ -1072,12 +1208,13 @@ mod tests { for tc in r.tiles() { let tr = tc.rect().intersect(&r); let t = surface.tile_mut(tc); + let mut target = t.bytes_mut(); for y in tr.y0..tr.y1 { for x in tr.x0..tr.x1 { let o = (((y - r.y0) as usize) * w + (x - r.x0) as usize) * n; let base = (((y - tc.ty * TILE_SIZE) as usize) * TILE_SIZE as usize + (x - tc.tx * TILE_SIZE) as usize) * n; for i in 0..n { - write_sample(&mut t.data, sample, base + i, data[o + i]); + write_sample(&mut target, sample, base + i, data[o + i]); } } } diff --git a/crates/raster/src/memory.rs b/crates/raster/src/memory.rs new file mode 100644 index 0000000000..069f8c0af0 --- /dev/null +++ b/crates/raster/src/memory.rs @@ -0,0 +1,181 @@ +//! Process-wide memory admission and adaptive tile residency. Native measurements are safe +//! `sysinfo` calls; web clients retain their explicit MB limit without filesystem assumptions. + +#[cfg(not(target_arch = "wasm32"))] +use std::sync::OnceLock; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, PoisonError}; + +const MIB: u64 = 1 << 20; + +#[derive(Clone, Copy, Debug, Default, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Snapshot { + pub total_bytes: u64, + pub available_bytes: u64, + pub process_resident_bytes: u64, + /// Address-space/virtual usage; this is not a portable measure of committed memory. + pub process_virtual_bytes: u64, +} + +#[derive(Clone, Copy, Debug)] +pub struct Policy { + /// None keeps the pre-streaming absolute MB setting. + pub percent: Option, + pub absolute_bytes: u64, +} + +impl Default for Policy { + fn default() -> Self { + Self { percent: None, absolute_bytes: 8 << 30 } + } +} + +#[derive(Clone, Copy, Debug, Default, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Budgets { + pub process_ceiling_bytes: u64, + pub effective_process_bytes: u64, + pub tile_bytes: u64, + pub transient_bytes: u64, +} + +/// Other applications and untiled buffers count against the same ceiling. Keep both system +/// headroom and a working reserve; virtual address-space size is deliberately not treated as RSS. +pub fn budgets(policy: Policy, sample: Snapshot, resident_tiles: u64) -> Budgets { + let ceiling = match (policy.percent, sample.total_bytes) { + (Some(p), total) if total > 0 => total / 100 * u64::from(p.clamp(1, 95)), + _ => policy.absolute_bytes, + } + .max(MIB); + let headroom = (sample.total_bytes / 20).max(256 * MIB); + let effective = if sample.total_bytes == 0 { + ceiling + } else { + ceiling.min(sample.process_resident_bytes.saturating_add(sample.available_bytes).saturating_sub(headroom)) + } + .max(MIB); + let transient = (effective / 8).clamp(MIB, 2 << 30); + let other = sample.process_resident_bytes.saturating_sub(resident_tiles); + let tiles = effective.saturating_sub(other).saturating_sub(transient).max(MIB); + Budgets { process_ceiling_bytes: ceiling, effective_process_bytes: effective, tile_bytes: tiles, transient_bytes: transient } +} + +static POLICY: Mutex = Mutex::new(Policy { percent: None, absolute_bytes: 8 << 30 }); +static CURRENT: Mutex<(Snapshot, Budgets)> = Mutex::new(( + Snapshot { total_bytes: 0, available_bytes: 0, process_resident_bytes: 0, process_virtual_bytes: 0 }, + Budgets { process_ceiling_bytes: 8 << 30, effective_process_bytes: 8 << 30, tile_bytes: 7 << 30, transient_bytes: 1 << 30 }, +)); +static RESERVED: AtomicU64 = AtomicU64::new(0); +static CONFIGURATION: AtomicU64 = AtomicU64::new(0); + +pub fn configuration_generation() -> u64 { + CONFIGURATION.load(Ordering::Relaxed) +} + +#[cfg(not(target_arch = "wasm32"))] +pub fn measure() -> Snapshot { + use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System}; + static SYSTEM: OnceLock> = OnceLock::new(); + let mut s = SYSTEM.get_or_init(|| Mutex::new(System::new())).lock().unwrap_or_else(PoisonError::into_inner); + s.refresh_memory(); + let pid = Pid::from_u32(std::process::id()); + s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), true, ProcessRefreshKind::nothing().with_memory()); + Snapshot { + total_bytes: s.total_memory(), + available_bytes: s.available_memory(), + process_resident_bytes: s.process(pid).map_or(0, |p| p.memory()), + process_virtual_bytes: s.process(pid).map_or(0, |p| p.virtual_memory()), + } +} + +#[cfg(target_arch = "wasm32")] +pub fn measure() -> Snapshot { + Snapshot::default() +} + +pub fn refresh() -> Budgets { + let policy = *POLICY.lock().unwrap_or_else(PoisonError::into_inner); + let sample = measure(); + let b = budgets(policy, sample, crate::spill::stats().resident_bytes as u64); + *CURRENT.lock().unwrap_or_else(PoisonError::into_inner) = (sample, b); + // The test override remains fixed even when process pressure changes. + let tiles = std::env::var("PHOTOCRAFT_TILE_BUDGET_MB").ok().and_then(|s| s.parse::().ok()).map_or(b.tile_bytes, |mb| mb.saturating_mul(MIB)); + crate::spill::set_budget(usize::try_from(tiles).unwrap_or(usize::MAX)); + b +} + +pub fn configure(policy: Policy) -> Budgets { + *POLICY.lock().unwrap_or_else(PoisonError::into_inner) = policy; + CONFIGURATION.fetch_add(1, Ordering::Relaxed); + refresh() +} + +pub fn stats() -> (Snapshot, Budgets, u64) { + let (s, b) = *CURRENT.lock().unwrap_or_else(PoisonError::into_inner); + (s, b, RESERVED.load(Ordering::Relaxed)) +} + +/// A bounded temporary working set. Callers retain the guard until the allocation is released. +pub struct Reservation(u64); + +pub fn try_reserve(bytes: u64) -> Result { + let (_, b, _) = stats(); + RESERVED + .fetch_update(Ordering::AcqRel, Ordering::Relaxed, |n| n.checked_add(bytes).filter(|next| *next <= b.transient_bytes)) + .map_err(|_| "not enough working memory; reduce the operation or wait for other jobs".to_string())?; + Ok(Reservation(bytes)) +} + +/// Admit a legacy operation that needs a whole buffer, including concurrent working sets and +/// the current process RSS. Streaming workers keep the smaller [`try_reserve`] allowance. +/// This deliberately refuses work before an allocation rather than relying on OS paging. +pub fn try_reserve_operation(bytes: u64) -> Result { + let b = refresh(); + let (sample, _, _) = stats(); + let available = if sample.total_bytes == 0 { b.transient_bytes } else { b.effective_process_bytes.saturating_sub(sample.process_resident_bytes) }; + RESERVED + .fetch_update(Ordering::AcqRel, Ordering::Relaxed, |n| n.checked_add(bytes).filter(|next| *next <= available)) + .map_err(|_| "not enough working memory for this operation; reduce its region or use a streaming format".to_string())?; + Ok(Reservation(bytes)) +} + +impl Drop for Reservation { + fn drop(&mut self) { + RESERVED.fetch_sub(self.0, Ordering::AcqRel); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn ceiling_includes_non_tile_memory_and_other_apps() { + let s = Snapshot { total_bytes: 64 << 30, available_bytes: 10 << 30, process_resident_bytes: 20 << 30, process_virtual_bytes: 100 << 30 }; + let b = budgets(Policy { percent: Some(90), absolute_bytes: 8 << 30 }, s, 15 << 30); + assert!(b.process_ceiling_bytes > 57 << 30); + assert!(b.effective_process_bytes < 30 << 30); + assert!(b.tile_bytes + (5 << 30) + b.transient_bytes <= b.effective_process_bytes); + } + #[test] + fn old_absolute_setting_and_missing_measurements_work() { + let b = budgets(Policy { percent: None, absolute_bytes: 512 * MIB }, Snapshot::default(), 0); + assert_eq!(b.process_ceiling_bytes, 512 * MIB); + assert_eq!(b.tile_bytes + b.transient_bytes, b.effective_process_bytes); + } + #[test] + fn hostile_percent_and_pressure_do_not_overflow() { + let b = budgets(Policy { percent: Some(255), absolute_bytes: u64::MAX }, Snapshot { total_bytes: u64::MAX, ..Snapshot::default() }, u64::MAX); + assert!(b.process_ceiling_bytes < u64::MAX); + assert_eq!(b.tile_bytes, MIB); + } + #[test] + fn reservations_are_bounded_and_returned() { + let before = stats().2; + let r = try_reserve(1024).unwrap(); + assert_eq!(stats().2, before + 1024); + assert!(try_reserve(u64::MAX).is_err()); + drop(r); + assert_eq!(stats().2, before); + } +} diff --git a/crates/raster/src/scratch_file.rs b/crates/raster/src/scratch_file.rs new file mode 100644 index 0000000000..f597fd4bba --- /dev/null +++ b/crates/raster/src/scratch_file.rs @@ -0,0 +1,430 @@ +//! The scratch file: where cold tiles go when pixel memory is over budget. +//! +//! - One file per configured directory. Windows deletes it even after a crash; Unix uses private +//! permissions and reaps files of dead processes when the directory is next configured. +//! - Space is handed out in 4 KiB-aligned extents from a free list (best fit, coalescing), else +//! appended at the end. +//! - All I/O is positioned: no shared cursor, no lock held during I/O. The allocator lock only +//! guards the free list. +//! - Reads go through one handle per thread (the file opened again by path): Windows serialises +//! I/O on one synchronous handle, so parallel readers sharing it would run one at a time. +//! +//! Ported from Fotox's `fx-tiles` scratch file (same author), minus its `unsafe` `ReOpenFile`. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::File; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, PoisonError}; + +const ALIGN: u64 = 4096; + +/// A region of the scratch file holding one compressed tile. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Extent { + pub offset: u64, + /// Exact length of the data. + pub len: u32, + /// Allocated length (multiple of 4 KiB, ≥ `len`). + pub alloc: u64, + /// CRC-32 of the stored bytes, checked on every read. + pub crc32: u32, +} + +/// Free-list allocator. Pure bookkeeping, no I/O. +#[derive(Debug, Default)] +pub(crate) struct Allocator { + by_offset: BTreeMap, + by_size: BTreeSet<(u64, u64)>, + end: u64, +} + +impl Allocator { + /// Bytes currently allocated (end of file minus free space). + pub fn used(&self) -> u64 { + self.end - self.by_offset.values().sum::() + } + + pub fn alloc(&mut self, len: u32) -> Extent { + let size = u64::from(len).div_ceil(ALIGN).max(1) * ALIGN; + if let Some(&(free_size, offset)) = self.by_size.range((size, 0)..).next() { + self.remove_free(offset, free_size); + if free_size > size { + self.insert_free(offset + size, free_size - size); + } + return Extent { offset, len, alloc: size, crc32: 0 }; + } + let offset = self.end; + self.end += size; + Extent { offset, len, alloc: size, crc32: 0 } + } + + pub fn free(&mut self, extent: Extent) { + let mut offset = extent.offset; + let mut size = extent.alloc; + if let Some((&prev_off, &prev_size)) = self.by_offset.range(..offset).next_back() + && prev_off + prev_size == offset + { + self.remove_free(prev_off, prev_size); + offset = prev_off; + size += prev_size; + } + if let Some(&next_size) = self.by_offset.get(&(offset + size)) { + self.remove_free(offset + size, next_size); + size += next_size; + } + if offset + size == self.end { + // Free space at the end of the file just shrinks the used range. + self.end = offset; + } else { + self.insert_free(offset, size); + } + } + + fn insert_free(&mut self, offset: u64, size: u64) { + self.by_offset.insert(offset, size); + self.by_size.insert((size, offset)); + } + + fn remove_free(&mut self, offset: u64, size: u64) { + self.by_offset.remove(&offset); + self.by_size.remove(&(size, offset)); + } +} + +pub(crate) struct ScratchFile { + main: File, + readers: OnceLock>, + path: PathBuf, + allocator: Mutex, +} + +impl std::fmt::Debug for ScratchFile { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ScratchFile").field("path", &self.path).finish() + } +} + +impl ScratchFile { + pub fn create(dir: &Path) -> std::io::Result { + std::fs::create_dir_all(dir)?; + static COUNTER: AtomicUsize = AtomicUsize::new(0); + // A reused process id must not collide with an abandoned file from an older launch. + let n = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + .saturating_add(COUNTER.fetch_add(1, Ordering::Relaxed) as u128); + let path = dir.join(format!("photocraft-{}-{n}.scratch", std::process::id())); + let mut options = std::fs::OpenOptions::new(); + options.read(true).write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + #[cfg(windows)] + { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_DELETE_ON_CLOSE: u32 = 0x0400_0000; + options.custom_flags(FILE_FLAG_DELETE_ON_CLOSE); + } + let main = options.open(&path)?; + #[cfg(unix)] + reap_abandoned(dir, &main); + Ok(Self { main, readers: OnceLock::new(), path, allocator: Mutex::new(Allocator::default()) }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// Reserve space and write `data` there. + pub fn write(&self, data: &[u8]) -> std::io::Result { + let len = u32::try_from(data.len()).map_err(|_| std::io::Error::other("block larger than 4 GiB"))?; + let mut extent = self.lock().alloc(len); + if let Err(e) = write_all_at(&self.main, data, extent.offset) { + self.free(extent); + return Err(e); + } + extent.crc32 = crc32fast::hash(data); + Ok(extent) + } + + /// Read an extent into `buf` (resized to it) and check its CRC. + pub fn read_into(&self, extent: Extent, buf: &mut Vec) -> std::io::Result<()> { + buf.resize(extent.len as usize, 0); + read_exact_at(self.reader(), buf, extent.offset)?; + if crc32fast::hash(buf) != extent.crc32 { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("scratch CRC mismatch at offset {}", extent.offset))); + } + Ok(()) + } + + pub fn free(&self, extent: Extent) { + let mut allocator = self.lock(); + allocator.free(extent); + if allocator.end == 0 { + // Release the physical disk space after the last document/history tile closes. + // Keep the allocator locked so a new writer cannot reserve an extent before + // this truncation; failures retain excess space, never live tile bytes. + let _ = self.main.set_len(0); + } + } + + pub fn used(&self) -> u64 { + self.lock().used() + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Allocator> { + self.allocator.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// A handle for reading on the calling thread. + fn reader(&self) -> &File { + let extra = self.readers.get_or_init(|| { + // The same file opened again by path: std shares read, write and delete, so this + // works while `main` (opened delete-on-close) is alive. A failure leaves fewer + // handles, never an error. + let count = std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, 16) - 1; + (0..count).map_while(|_| std::fs::OpenOptions::new().read(true).open(&self.path).ok()).collect() + }); + match thread_slot() % (extra.len() + 1) { + 0 => &self.main, + i => extra.get(i - 1).unwrap_or(&self.main), + } + } +} + +/// Accept only the names we generate, never other temporary files or directories. +#[cfg(any(unix, test))] +fn scratch_pid(name: &str) -> Option { + let (pid, nonce) = name.strip_prefix("photocraft-")?.strip_suffix(".scratch")?.split_once('-')?; + if pid.is_empty() || nonce.is_empty() || !pid.bytes().chain(nonce.bytes()).all(|b| b.is_ascii_digit()) { + return None; + } + let pid = pid.parse::().ok()?; + (pid > 0 && nonce.parse::().is_ok()).then_some(pid) +} + +#[cfg(unix)] +fn reap_abandoned(dir: &Path, own: &File) { + use std::os::unix::fs::MetadataExt; + use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System}; + let Ok(metadata) = own.metadata() else { return }; + let mut system = System::new(); + system.refresh_processes_specifics(ProcessesToUpdate::All, true, ProcessRefreshKind::nothing()); + // Fail closed when process enumeration isn't available. Live files are never removed. + if system.process(Pid::from_u32(std::process::id())).is_none() { + return; + } + reap_with(dir, metadata.uid(), |pid| system.process(Pid::from_u32(pid)).is_some()); +} + +#[cfg(unix)] +fn reap_with(dir: &Path, uid: u32, live: impl Fn(u32) -> bool) { + use std::os::unix::fs::MetadataExt; + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(pid) = name.to_str().and_then(scratch_pid) else { continue }; + if pid == std::process::id() || live(pid) { + continue; + } + let path = entry.path(); + let Ok(meta) = std::fs::symlink_metadata(&path) else { continue }; + // Shared /tmp: do not remove other users' files or follow symlinks. + if meta.file_type().is_file() && meta.uid() == uid { + let _ = std::fs::remove_file(path); + } + } +} + +impl Drop for ScratchFile { + fn drop(&mut self) { + // On Windows the file is already gone (delete-on-close); elsewhere remove it. + if !cfg!(windows) { + let _ = std::fs::remove_file(&self.path); + } + } +} + +/// A stable small number per thread, handed out in turn, so the worker threads of a pool land +/// on different handles. +fn thread_slot() -> usize { + static NEXT: AtomicUsize = AtomicUsize::new(0); + thread_local! { + static SLOT: usize = NEXT.fetch_add(1, Ordering::Relaxed); + } + SLOT.with(|slot| *slot) +} + +#[cfg(unix)] +fn write_all_at(file: &File, data: &[u8], offset: u64) -> std::io::Result<()> { + std::os::unix::fs::FileExt::write_all_at(file, data, offset) +} + +#[cfg(unix)] +fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> std::io::Result<()> { + std::os::unix::fs::FileExt::read_exact_at(file, buf, offset) +} + +#[cfg(windows)] +fn write_all_at(file: &File, mut data: &[u8], mut offset: u64) -> std::io::Result<()> { + use std::os::windows::fs::FileExt; + while !data.is_empty() { + let n = file.seek_write(data, offset)?; + if n == 0 { + return Err(std::io::ErrorKind::WriteZero.into()); + } + data = data.get(n..).unwrap_or_default(); + offset += n as u64; + } + Ok(()) +} + +#[cfg(windows)] +fn read_exact_at(file: &File, mut buf: &mut [u8], mut offset: u64) -> std::io::Result<()> { + use std::os::windows::fs::FileExt; + while !buf.is_empty() { + let n = file.seek_read(buf, offset)?; + if n == 0 { + return Err(std::io::ErrorKind::UnexpectedEof.into()); + } + buf = buf.get_mut(n..).unwrap_or_default(); + offset += n as u64; + } + Ok(()) +} + +#[cfg(not(any(unix, windows)))] +fn write_all_at(_file: &File, _data: &[u8], _offset: u64) -> std::io::Result<()> { + Err(std::io::ErrorKind::Unsupported.into()) +} + +#[cfg(not(any(unix, windows)))] +fn read_exact_at(_file: &File, _buf: &mut [u8], _offset: u64) -> std::io::Result<()> { + Err(std::io::ErrorKind::Unsupported.into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cleanup_names_are_strict() { + assert_eq!(scratch_pid("photocraft-123-987.scratch"), Some(123)); + for name in [ + "photocraft-0-1.scratch", + "photocraft-1-.scratch", + "photocraft-1-../notes.scratch", + "photocraft-1-2.scratch.bak", + "other-1-2.scratch", + "photocraft-4294967296-2.scratch", + ] { + assert_eq!(scratch_pid(name), None, "{name}"); + } + } + + #[cfg(any(unix, windows))] + #[test] + fn abrupt_exit_does_not_leave_permanent_scratch_files() { + const CHILD_DIR: &str = "PHOTOCRAFT_SCRATCH_EXIT_TEST_DIR"; + if let Some(dir) = std::env::var_os(CHILD_DIR) { + let file = ScratchFile::create(Path::new(&dir)).unwrap(); + file.write(b"unreleased pixels").unwrap(); + // No Rust destructors run: this exercises the lifetime of the static manager. + std::process::exit(0); + } + let dir = std::env::temp_dir().join(format!("pc-abrupt-exit-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let result = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "scratch_file::tests::abrupt_exit_does_not_leave_permanent_scratch_files", "--nocapture"]) + .env(CHILD_DIR, &dir) + .status() + .unwrap(); + assert!(result.success()); + #[cfg(windows)] + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "delete-on-close survives exit without Drop"); + let next = ScratchFile::create(&dir).unwrap(); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "a new launch reaps the dead process's files"); + drop(next); + std::fs::remove_dir(dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn unix_files_are_private_and_reaping_preserves_live_and_unrelated_files() { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let dir = std::env::temp_dir().join(format!("pc-reap-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let own = ScratchFile::create(&dir).unwrap(); + let meta = own.main.metadata().unwrap(); + assert_eq!(meta.permissions().mode() & 0o777, 0o600); + let stale = dir.join("photocraft-123-1.scratch"); + let live = dir.join("photocraft-124-1.scratch"); + let unrelated = dir.join("notes.scratch"); + let link = dir.join("photocraft-125-1.scratch"); + for p in [&stale, &live, &unrelated] { + std::fs::write(p, b"test").unwrap(); + } + std::os::unix::fs::symlink(&unrelated, &link).unwrap(); + reap_with(&dir, meta.uid().wrapping_add(1), |_| false); + assert!(stale.exists(), "another owner's files remain"); + reap_with(&dir, meta.uid(), |pid| pid == 124); + assert!(!stale.exists()); + assert!(live.exists() && unrelated.exists() && link.exists() && own.path.exists()); + drop(own); + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn alloc_reuses_and_coalesces() { + let mut a = Allocator::default(); + let x = a.alloc(100); + let y = a.alloc(5000); + let z = a.alloc(4096); + assert_eq!((x.offset, y.offset, z.offset), (0, 4096, 12288)); + assert_eq!(a.used(), 16384); + a.free(x); + a.free(y); // coalesces with x: one free extent of 12 KiB at 0 + let w = a.alloc(12000); + assert_eq!(w.offset, 0, "coalesced hole is reused"); + a.free(z); // tail extent: the file end shrinks + assert_eq!(a.used(), 12288); + a.free(w); + assert_eq!(a.used(), 0); + assert_eq!(a.end, 0, "everything freed collapses the file"); + } + + #[test] + fn best_fit_splits_larger_holes() { + let mut a = Allocator::default(); + let big = a.alloc(40000); + let _tail = a.alloc(1); + a.free(big); + assert_eq!(a.alloc(10).offset, 0); + assert_eq!(a.alloc(10).offset, 4096, "remainder of the split hole is used next"); + } + + #[test] + fn file_roundtrip_and_crc() { + let dir = std::env::temp_dir().join("photocraft-scratch-test"); + let scratch = ScratchFile::create(&dir).unwrap(); + let a = scratch.write(b"hello tiles").unwrap(); + let b = scratch.write(&[7u8; 9000]).unwrap(); + let mut buf = Vec::new(); + scratch.read_into(a, &mut buf).unwrap(); + assert_eq!(buf, b"hello tiles"); + scratch.read_into(b, &mut buf).unwrap(); + assert_eq!(buf, vec![7u8; 9000]); + let bad = Extent { crc32: a.crc32 ^ 1, ..a }; + assert!(scratch.read_into(bad, &mut buf).is_err(), "a CRC mismatch is an error, not garbage"); + scratch.free(a); + scratch.free(b); + assert_eq!(scratch.main.metadata().unwrap().len(), 0, "closing the last tile releases physical disk space"); + let path = scratch.path().to_path_buf(); + drop(scratch); + assert!(!path.exists(), "scratch file is removed on drop"); + } +} diff --git a/crates/raster/src/spill.rs b/crates/raster/src/spill.rs new file mode 100644 index 0000000000..6b6ba3c00c --- /dev/null +++ b/crates/raster/src/spill.rs @@ -0,0 +1,563 @@ +//! Scratch disk: tile pixels beyond a memory budget move to a file and come back on access. +//! +//! Every [`Tile`](crate::Tile) keeps its bytes in a [`Cell`]: resident (`Some`) or on disk +//! (`None`, with its [`Extent`] in the scratch file). Readers take the cell's read lock, so a +//! tile in use is never evicted; a spilled tile is read back (LZ4 + CRC-checked) by whoever +//! touches it first. +//! +//! - **Accounting.** [`stats`] counts the bytes of every live tile that is resident, whether or +//! not a scratch disk is configured. +//! - **Eviction** is the clock ("second chance") algorithm over a registry of weak cell +//! pointers: a tile touched since the hand last passed keeps its place once. A background +//! thread evicts down to 90 % of the budget; a thread that pushes memory past 125 % helps. +//! - **Clean tiles are free to drop.** A tile written once and not changed since keeps its +//! extent, so evicting it again only frees memory; changing it frees the extent. +//! - **Off by default.** Until [`configure`] sets a directory and a budget nothing is evicted +//! (tests, the web build). +//! +//! Failures never panic: a scratch write that fails keeps the tile in memory and turns spilling +//! off (reported in [`SpillStats::last_error`]). A failed read retains its disk extent and +//! poisons the tile: edits and saves must check [`check_integrity`] before committing. The +//! infallible display API uses a temporary placeholder, never replacement pixel storage. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard, Weak}; + +use crate::scratch_file::{Extent, ScratchFile}; + +/// One tile's bytes and where they live. +pub(crate) struct Cell { + data: RwLock>>, + /// Byte length of the tile (fixed for its lifetime). + len: usize, + error: Mutex>, + /// A copy on disk that matches `data` (kept while the tile is unchanged). + slot: Mutex, Extent)>>, + /// Touched since the clock hand last passed. + referenced: AtomicBool, +} + +impl Cell { + pub(crate) fn new(bytes: Vec) -> Arc { + let len = bytes.len(); + let cell = Arc::new(Cell { data: RwLock::new(Some(bytes)), len, error: Mutex::new(None), slot: Mutex::new(None), referenced: AtomicBool::new(true) }); + M.live.fetch_add(1, Ordering::Relaxed); + M.resident.fetch_add(len, Ordering::Relaxed); + M.register(&cell); + maybe_evict(); + cell + } + + pub(crate) fn len(&self) -> usize { + self.len + } + + pub(crate) fn read_error(&self) -> Option { + self.error.lock().unwrap_or_else(PoisonError::into_inner).clone() + } + + fn set_error(&self, error: Option) { + let mut old = self.error.lock().unwrap_or_else(PoisonError::into_inner); + match (old.is_some(), error.is_some()) { + (false, true) => { + M.failed.fetch_add(1, Ordering::Release); + M.read_errors.fetch_add(1, Ordering::Release); + } + (true, false) => { + // Invalidate computations that started while pixels were unreadable too. + // Publish this before reporting the tile healthy to commit guards. + M.read_errors.fetch_add(1, Ordering::Release); + M.failed.fetch_sub(1, Ordering::Release); + } + _ => {} + } + *old = error; + } + + #[inline] + fn touch(&self) { + if !self.referenced.load(Ordering::Relaxed) { + self.referenced.store(true, Ordering::Relaxed); + } + } + + /// Read access; reads the tile back from the scratch disk if it was evicted. + pub(crate) fn read(&self) -> RwLockReadGuard<'_, Option>> { + let mut loaded_pixels = false; + loop { + self.touch(); + let g = self.data.read().unwrap_or_else(PoisonError::into_inner); + if g.is_some() { + if loaded_pixels { + // Pin the tile before eviction: even a budget smaller than one tile + // must not repeatedly evict the pixels this reader just loaded. + maybe_evict(); + } + return g; + } + drop(g); + let mut w = self.data.write().unwrap_or_else(PoisonError::into_inner); + let loaded = self.load(&mut w).is_ok(); + drop(w); + if !loaded { + return self.data.read().unwrap_or_else(PoisonError::into_inner); + } + loaded_pixels = true; + } + } + + /// Write access: resident, and any disk copy is released (it no longer matches). + pub(crate) fn write(&self) -> RwLockWriteGuard<'_, Option>> { + self.touch(); + let mut w = self.data.write().unwrap_or_else(PoisonError::into_inner); + let loaded = w.is_none(); + if self.load(&mut w).is_err() { + // Keep the only original copy. The write guard's temporary placeholder is + // discarded, and the transaction's integrity check refuses to commit it. + return w; + } + if let Some((file, extent)) = self.slot.lock().unwrap_or_else(PoisonError::into_inner).take() { + file.free(extent); + } + if loaded { + // Evicting here could only pick other tiles (this one is locked), so it is safe, and + // a long run of writes to spilled tiles must not outgrow the budget. + maybe_evict(); + } + w + } + + /// Fill `w` from the scratch disk if it is not resident (`w` is this cell's write guard). + fn load(&self, w: &mut Option>) -> Result<(), String> { + if w.is_some() { + return Ok(()); + } + let slot = self.slot.lock().unwrap_or_else(PoisonError::into_inner).clone(); + let bytes = match slot { + Some((file, extent)) => { + let mut packed = Vec::new(); + match file.read_into(extent, &mut packed).map_err(|e| e.to_string()).and_then(|()| unpack(&packed, self.len)) { + Ok(b) => b, + Err(e) => { + let error = format!("scratch read failed ({e}); editing and saving are blocked until the tile is readable"); + self.set_error(Some(error.clone())); + M.error(error.clone()); + return Err(error); + } + } + } + None => { + let error = "a spilled tile has no scratch copy; editing and saving are blocked".to_string(); + self.set_error(Some(error.clone())); + M.error(error.clone()); + return Err(error); + } + }; + *w = Some(bytes); + self.set_error(None); + M.resident.fetch_add(self.len, Ordering::Relaxed); + M.reloads.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + + /// Move this tile to disk if nobody is using it. Returns the bytes freed. + fn evict(&self, file: &Arc) -> Result { + let Ok(mut w) = self.data.try_write() else { return Ok(0) }; + let Some(bytes) = w.as_ref() else { return Ok(0) }; + let mut slot = self.slot.lock().unwrap_or_else(PoisonError::into_inner); + if slot.is_none() { + let packed = lz4_flex::block::compress(bytes); + let extent = file.write(&packed).map_err(|e| format!("scratch write to {} failed: {e}", file.path().display()))?; + M.written.fetch_add(packed.len() as u64, Ordering::Relaxed); + *slot = Some((file.clone(), extent)); + } + drop(slot); + *w = None; + M.resident.fetch_sub(self.len, Ordering::Relaxed); + M.evictions.fetch_add(1, Ordering::Relaxed); + Ok(self.len) + } +} + +impl Drop for Cell { + fn drop(&mut self) { + if self.error.get_mut().unwrap_or_else(PoisonError::into_inner).is_some() { + M.read_errors.fetch_add(1, Ordering::Release); + M.failed.fetch_sub(1, Ordering::Release); + } + let resident = self.data.get_mut().unwrap_or_else(PoisonError::into_inner).is_some(); + if resident { + M.resident.fetch_sub(self.len, Ordering::Relaxed); + } + if let Some((file, extent)) = self.slot.get_mut().unwrap_or_else(PoisonError::into_inner).take() { + file.free(extent); + } + M.live.fetch_sub(1, Ordering::Relaxed); + } +} + +fn unpack(packed: &[u8], len: usize) -> Result, String> { + let bytes = lz4_flex::block::decompress(packed, len).map_err(|e| e.to_string())?; + if bytes.len() == len { Ok(bytes) } else { Err(format!("tile decoded to {} bytes, expected {len}", bytes.len())) } +} + +/// Process-wide state. Plain statics: everything here is const-constructible. +struct Manager { + failed: AtomicUsize, + read_errors: AtomicU64, + resident: AtomicUsize, + live: AtomicUsize, + /// Pixel bytes to keep resident; 0 = spilling off. + budget: AtomicUsize, + registry: Mutex, + config: Mutex, + evictions: AtomicU64, + reloads: AtomicU64, + written: AtomicU64, +} + +struct Registry { + cells: Vec>, + hand: usize, +} + +struct Config { + dir: Option, + /// Opened at configuration time; startup also reaps abandoned Unix files. + file: Option>, + last_error: Option, +} + +static M: Manager = Manager { + failed: AtomicUsize::new(0), + read_errors: AtomicU64::new(0), + resident: AtomicUsize::new(0), + live: AtomicUsize::new(0), + budget: AtomicUsize::new(0), + registry: Mutex::new(Registry { cells: Vec::new(), hand: 0 }), + config: Mutex::new(Config { dir: None, file: None, last_error: None }), + evictions: AtomicU64::new(0), + reloads: AtomicU64::new(0), + written: AtomicU64::new(0), +}; + +impl Manager { + fn register(&self, cell: &Arc) { + let mut r = self.registry.lock().unwrap_or_else(PoisonError::into_inner); + r.cells.push(Arc::downgrade(cell)); + // Drop the pointers of freed tiles once they outnumber the live ones. + if r.cells.len() > self.live.load(Ordering::Relaxed).saturating_mul(2).saturating_add(4096) { + r.cells.retain(|w| w.strong_count() > 0); + r.hand = 0; + } + } + + fn config(&self) -> std::sync::MutexGuard<'_, Config> { + self.config.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn error(&self, msg: String) { + log_error(&msg); + self.config().last_error = Some(msg); + } + + /// The scratch file, created on first use; `None` (and spilling off) if it can't be. + fn file(&self) -> Option> { + let mut c = self.config(); + if let Some(f) = &c.file { + return Some(f.clone()); + } + let dir = c.dir.clone()?; + match ScratchFile::create(&dir) { + Ok(f) => { + let f = Arc::new(f); + c.file = Some(f.clone()); + Some(f) + } + Err(e) => { + let msg = format!("could not create a scratch file in {}: {e}; spilling is off", dir.display()); + log_error(&msg); + c.last_error = Some(msg); + c.dir = None; + self.budget.store(0, Ordering::Relaxed); + None + } + } + } + + /// Evict until resident memory is at most `target` or `max_scan` cells were looked at. + /// Returns the bytes freed. + fn sweep(&self, target: usize, max_scan: usize) -> usize { + let Some(file) = self.file() else { return 0 }; + let mut freed = 0; + let mut scanned = 0; + while self.resident.load(Ordering::Relaxed) > target && scanned < max_scan { + // Pick victims under the registry lock (cheap), evict them after releasing it. + let mut victims = Vec::with_capacity(64); + { + let mut r = self.registry.lock().unwrap_or_else(PoisonError::into_inner); + let mut i = 0; + while victims.len() < 64 && i < 4096 && !r.cells.is_empty() { + if r.hand >= r.cells.len() { + r.hand = 0; + } + let h = r.hand; + i += 1; + match r.cells.get(h).and_then(Weak::upgrade) { + None => { + r.cells.swap_remove(h); + continue; + } + Some(cell) => { + r.hand += 1; + if cell.referenced.swap(false, Ordering::Relaxed) { + continue; + } + if cell.data.try_read().is_ok_and(|d| d.is_some()) { + victims.push(cell); + } + } + } + } + scanned += i; + if i == 0 { + break; + } + } + for cell in victims { + match cell.evict(&file) { + Ok(n) => freed += n, + Err(e) => { + // Disk full or gone: keep everything in memory from now on. + self.budget.store(0, Ordering::Relaxed); + self.error(format!("{e}; spilling is off")); + return freed; + } + } + } + } + freed + } +} + +/// Called after resident memory grew. +fn maybe_evict() { + let budget = M.budget.load(Ordering::Relaxed); + if budget == 0 { + return; + } + let resident = M.resident.load(Ordering::Relaxed); + if resident <= budget { + return; + } + let worker = MAINTENANCE.load(Ordering::Acquire) > 0; + // Far over budget (or no worker thread): this thread helps. + if !worker || resident > budget.saturating_add(budget / 4) { + M.sweep(low_water(budget), 1 << 16); + } +} + +fn low_water(budget: usize) -> usize { + budget / 10 * 9 +} + +// The engine owns and joins the worker. Standalone raster consumers keep synchronous +// eviction; this crate never starts a background thread or retains its owner. +static MAINTENANCE: AtomicUsize = AtomicUsize::new(0); + +/// Register an externally owned residency worker. Keep this guard until that worker exits. +pub struct Maintenance; + +pub fn background_maintenance() -> Maintenance { + MAINTENANCE.fetch_add(1, Ordering::AcqRel); + Maintenance +} + +impl Drop for Maintenance { + fn drop(&mut self) { + MAINTENANCE.fetch_sub(1, Ordering::AcqRel); + } +} + +/// One bounded clock pass. The caller owns scheduling and shutdown. +pub fn maintain_budget() -> usize { + let budget = M.budget.load(Ordering::Relaxed); + if budget == 0 || M.resident.load(Ordering::Relaxed) <= budget { + return 0; + } + M.sweep(low_water(budget), 4096) +} + +/// Turn the scratch disk on (`dir` and a non-zero `budget_bytes`) or off. Tiles already on disk +/// stay readable either way. Changing the directory starts a new scratch file there; the old one +/// is deleted once its last tile is freed or changed. +pub fn set_budget(budget_bytes: usize) { + if enabled() { + M.budget.store(budget_bytes.max(1), Ordering::Relaxed); + maybe_evict(); + } +} + +pub fn configure(dir: Option<&Path>, budget_bytes: usize) -> Result<(), String> { + let mut c = M.config(); + let dir = dir.filter(|_| budget_bytes > 0).map(Path::to_path_buf); + if let Some(d) = &dir + && let Err(e) = std::fs::create_dir_all(d) + { + let msg = format!("scratch disk {}: {e}; spilling is off", d.display()); + c.dir = None; + c.file = None; + c.last_error = Some(msg.clone()); + M.budget.store(0, Ordering::Relaxed); + return Err(msg); + } + if dir != c.dir || (dir.is_some() && c.file.is_none()) { + c.file = match dir.as_deref().map(ScratchFile::create).transpose() { + Ok(file) => file.map(Arc::new), + Err(e) => { + let msg = format!("scratch disk: {e}; spilling is off"); + c.dir = None; + c.last_error = Some(msg.clone()); + M.budget.store(0, Ordering::Relaxed); + return Err(msg); + } + }; + } + c.dir = dir.clone(); + c.last_error = None; + M.budget.store(if dir.is_some() { budget_bytes } else { 0 }, Ordering::Relaxed); + drop(c); + maybe_evict(); + Ok(()) +} + +/// Where the tile memory stands. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SpillStats { + /// Pixel bytes of live tiles in memory. + pub resident_bytes: usize, + pub live_tiles: usize, + /// 0 = spilling off. + pub budget_bytes: usize, + pub dir: Option, + /// Bytes allocated in the current scratch file. + pub scratch_bytes: u64, + pub evictions: u64, + pub reloads: u64, + /// Compressed bytes written to scratch so far. + pub written_bytes: u64, + pub last_error: Option, +} + +pub fn stats() -> SpillStats { + let c = M.config(); + SpillStats { + resident_bytes: M.resident.load(Ordering::Relaxed), + live_tiles: M.live.load(Ordering::Relaxed), + budget_bytes: M.budget.load(Ordering::Relaxed), + dir: c.dir.clone(), + scratch_bytes: c.file.as_ref().map_or(0, |f| f.used()), + evictions: M.evictions.load(Ordering::Relaxed), + reloads: M.reloads.load(Ordering::Relaxed), + written_bytes: M.written.load(Ordering::Relaxed), + last_error: c.last_error.clone(), + } +} + +/// Last storage error, without scanning the scratch allocator for UI status updates. +pub fn last_error() -> Option { + M.config().last_error.clone() +} + +/// Whether spilling is on (tiles beyond the budget go to disk). +pub fn enabled() -> bool { + M.budget.load(Ordering::Relaxed) > 0 +} + +/// Refuse to publish edited or serialized pixels after a scratch read failure. A failed +/// tile can retry its original extent; changing preferences cannot clear this protection. +pub fn check_integrity() -> Result<(), String> { + if M.failed.load(Ordering::Acquire) == 0 { + Ok(()) + } else { + Err(M.config().last_error.clone().unwrap_or_else(|| "scratch pixels are unreadable; editing and saving are blocked".into())) + } +} + +/// Capture before an edit/import/save or derived cache computation. A failed tile might be dropped or repaired +/// before the operation ends; its placeholder must still never be committed as real pixels. +/// Both failure and recovery change this generation, including computations begun during a failure. +pub fn read_error_generation() -> u64 { + M.read_errors.load(Ordering::Acquire) +} + +pub fn check_since(generation: u64) -> Result<(), String> { + check_integrity()?; + if generation == read_error_generation() { + Ok(()) + } else { + Err(last_error().unwrap_or_else(|| "scratch read failed during this operation; the result was discarded".into())) + } +} + +/// Evict down to the budget now, on this thread (tests, and before a measurement). +pub fn settle() { + let budget = M.budget.load(Ordering::Relaxed); + // Stops when nothing more can be evicted (every remaining tile is in use). + while budget > 0 && M.resident.load(Ordering::Relaxed) > budget { + if M.sweep(budget, usize::MAX) == 0 { + break; + } + } +} + +fn log_error(msg: &str) { + #[cfg(not(target_arch = "wasm32"))] + eprintln!("photocraft: {msg}"); + #[cfg(target_arch = "wasm32")] + let _ = msg; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn failed_read_retains_backing_and_blocks_commit_until_repaired() { + let dir = std::env::temp_dir().join(format!("photocraft-read-failure-{}", std::process::id())); + let file = Arc::new(ScratchFile::create(&dir).unwrap()); + let mut tile = crate::Tile { cell: Cell::new(vec![73; 1024]) }; + let generation = read_error_generation(); + assert_eq!(tile.cell.evict(&file).unwrap(), 1024); + let good = tile.cell.slot.lock().unwrap().as_ref().unwrap().1; + tile.cell.slot.lock().unwrap().as_mut().unwrap().1.crc32 ^= 1; + + assert!(tile.try_bytes().is_err()); + let failed_generation = read_error_generation(); + assert!(tile.cell.data.read().unwrap().is_none(), "placeholder must never become stored pixels"); + assert!(check_integrity().is_err()); + tile.bytes_mut()[0] = 9; + assert!(tile.cell.data.read().unwrap().is_none()); + assert!(tile.cell.slot.lock().unwrap().is_some(), "a failed mutation must preserve the original extent"); + let snapshot = tile.clone(); + assert!(Arc::ptr_eq(&tile.cell, &snapshot.cell)); + configure(None, 0).unwrap(); + assert!(check_integrity().is_err(), "changing preferences must not clear unreadable pixels"); + + tile.cell.slot.lock().unwrap().as_mut().unwrap().1 = good; + assert_eq!(&*tile.try_bytes().unwrap(), &[73; 1024]); + assert!(check_integrity().is_ok()); + assert!(check_since(generation).is_err(), "repairing or dropping a failed tile must not validate an earlier result"); + assert!(check_since(failed_generation).is_err(), "recovery must reject a computation begun during the failure"); + assert_eq!(tile.cell.evict(&file).unwrap(), 1024); + tile.cell.slot.lock().unwrap().as_mut().unwrap().1.crc32 ^= 1; + assert!(tile.try_bytes().is_err()); + let dropped_generation = read_error_generation(); + drop((snapshot, tile, file)); + assert!(check_integrity().is_ok()); + assert!(check_since(dropped_generation).is_err(), "dropping the failed tile must also reject its placeholder result"); + let _ = std::fs::remove_dir(&dir); + } +} diff --git a/crates/raster/tests/scratch_translate.rs b/crates/raster/tests/scratch_translate.rs new file mode 100644 index 0000000000..f3e9741da7 --- /dev/null +++ b/crates/raster/tests/scratch_translate.rs @@ -0,0 +1,44 @@ +//! Upstream's shared fills and pixel translations must also work with paged tile bytes. + +use photocraft_color::{PixelFormat, SampleType}; +use photocraft_geom::{Rect, TILE_SIZE, TileCoord}; +use photocraft_raster::{Surface, spill}; + +#[test] +fn translations_and_shared_fills_preserve_spilled_pixels_at_every_depth() { + let dir = std::env::temp_dir().join(format!("photocraft-translate-spill-{}", std::process::id())); + for depth in [SampleType::U8, SampleType::U16, SampleType::F32] { + let format = PixelFormat::RGBA8.with_sample(depth); + let tile_bytes = (TILE_SIZE * TILE_SIZE) as usize * format.bytes_per_pixel(); + spill::configure(Some(&dir), tile_bytes * 2).unwrap(); + let bounds = Rect::new(-17, -21, 281, 271); + let pixels: Vec = (0..bounds.size().area() as usize).flat_map(|i| [(i % 127) as f32 / 126.0, (i % 59) as f32 / 58.0, 0.75, 1.0]).collect(); + let mut original = Surface::new(format); + original.write_region(bounds, &pixels); + let expected = original.to_interleaved(bounds); + spill::settle(); + assert!(spill::stats().resident_bytes <= tile_bytes * 2); + let reloads = spill::stats().reloads; + for (dx, dy) in [(19, -31), (256, -512)] { + let mut moved = original.translated(dx, dy, original.content_bounds()); + assert_eq!(moved.to_interleaved(bounds.translate(dx, dy)), expected, "{depth:?} ({dx}, {dy})"); + moved.fill_rect(Rect::from_xywh(bounds.x0 + dx, bounds.y0 + dy, 4, 4), &[1.0, 0.0, 0.0, 1.0]); + spill::settle(); + assert_eq!(original.to_interleaved(bounds), expected, "translation edits changed the source"); + } + assert!(spill::stats().reloads > reloads, "translation must read paged pixels"); + let mut fill = Surface::new(format); + fill.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.5, 0.25, 0.75, 1.0]); + assert!(std::sync::Arc::ptr_eq(fill.tile(TileCoord::new(0, 0)).unwrap(), fill.tile(TileCoord::new(3, 3)).unwrap())); + let snapshot = fill.clone(); + let color = snapshot.pixel(10, 10); + spill::settle(); + fill.fill_rect(Rect::from_xywh(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); + assert_eq!(snapshot.pixel(1, 1), color); + assert_eq!(fill.pixel(10, 10), color); + assert_eq!(fill.pixel(1, 1), vec![1.0, 0.0, 0.0, 1.0]); + spill::check_integrity().unwrap(); + } + spill::configure(None, 0).unwrap(); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/raster/tests/spill.rs b/crates/raster/tests/spill.rs new file mode 100644 index 0000000000..078c1c4bf6 --- /dev/null +++ b/crates/raster/tests/spill.rs @@ -0,0 +1,149 @@ +//! Scratch disk: tiles over the budget go to disk and come back unchanged. +//! +//! One test function: the spill manager is process-wide, so its steps must not interleave. + +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_geom::{Rect, TILE_SIZE, TileCoord}; +use photocraft_raster::{Surface, spill}; + +const TILE_BYTES: usize = (TILE_SIZE * TILE_SIZE) as usize * 4; + +fn rgba8() -> PixelFormat { + PixelFormat { mode: ColorMode::Rgb, sample: SampleType::U8, alpha: true } +} + +/// Incompressible bytes, different per tile and per seed. +fn noise(seed: u32, len: usize) -> Vec { + let mut x = seed.wrapping_mul(2_654_435_761).max(1); + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + x as u8 + }) + .collect() +} + +/// A surface of `n × 1` tiles of noise; tile `i` holds `noise(seed + i)`. +fn surface(seed: u32, n: i32) -> Surface { + let mut s = Surface::new(rgba8()); + for i in 0..n { + let r = Rect::from_xywh(i * TILE_SIZE, 0, TILE_SIZE as u32, TILE_SIZE as u32); + s.write_interleaved(r, &noise(seed + i as u32, TILE_BYTES)); + } + s +} + +fn check(s: &Surface, seed: u32, n: i32) { + for i in 0..n { + let t = s.tile(TileCoord { tx: i, ty: 0 }).unwrap(); + assert!(*t.bytes() == *noise(seed + i as u32, TILE_BYTES), "tile {i} of seed {seed} changed"); + } +} + +#[test] +fn tiles_spill_and_come_back() { + let dir = std::env::temp_dir().join(format!("photocraft-spill-test-{}", std::process::id())); + let budget = 8 * TILE_BYTES; + spill::configure(Some(&dir), budget).unwrap(); + assert!(spill::enabled()); + + // 1. Over budget: the oldest tiles go to disk, resident memory drops to the budget. + let a = surface(1, 32); + let b = surface(1000, 32); + spill::settle(); + let st = spill::stats(); + assert!(st.resident_bytes <= budget, "resident {} > budget {budget}", st.resident_bytes); + assert!(st.evictions >= 48, "only {} evictions", st.evictions); + assert!(st.scratch_bytes > 0 && st.last_error.is_none(), "{st:?}"); + + // 2. Every pixel reads back exactly (CRC-checked, LZ4 round trip), through every reader. + check(&a, 1, 32); + check(&b, 1000, 32); + assert!(spill::stats().reloads > 0); + let mut row = vec![[0u8; 4]; TILE_SIZE as usize]; + a.read_rgba8_into(Rect::from_xywh(5 * TILE_SIZE, 7, TILE_SIZE as u32, 1), &mut row); + let want = noise(6, TILE_BYTES); + let off = 7 * TILE_SIZE as usize * 4; + assert!(row.iter().flatten().eq(want[off..off + TILE_SIZE as usize * 4].iter())); + + // Upstream's fallible readers and clones must reload evicted storage too. + spill::settle(); + let rect = Rect::from_xywh(0, 0, TILE_SIZE as u32, TILE_SIZE as u32); + assert_eq!(a.try_to_interleaved(rect).unwrap(), noise(1, TILE_BYTES)); + assert_eq!(a.try_read_region(rect).unwrap(), a.read_region(rect)); + let copied = a.tile(TileCoord::new(0, 0)).unwrap().try_clone().unwrap(); + assert_eq!(&*copied.try_bytes().unwrap(), &noise(1, TILE_BYTES)); + drop(copied); + + // 3. Copy-on-write still works on spilled tiles: the clone changes, the original doesn't. + spill::settle(); + let mut c = a.clone(); + c.fill_rect(Rect::from_xywh(0, 0, 10, 10), &[1.0, 0.0, 0.0, 1.0]); + assert_eq!(c.pixel(3, 3), vec![1.0, 0.0, 0.0, 1.0]); + check(&a, 1, 32); + spill::settle(); + // The edit survives its own eviction (the stale disk copy was released, a new one written). + assert_eq!(c.pixel(3, 3), vec![1.0, 0.0, 0.0, 1.0]); + check(&a, 1, 32); + + // 4. Parallel readers of spilled tiles all see the right bytes. + spill::settle(); + std::thread::scope(|scope| { + for k in 0..8 { + let (a, b) = (&a, &b); + scope.spawn(move || { + for round in 0..4 { + let (s, seed) = if (k + round) % 2 == 0 { (a, 1) } else { (b, 1000) }; + check(s, seed, 32); + } + }); + } + }); + + // 5. Dropping everything frees memory and scratch space. + drop((a, b, c)); + let st = spill::stats(); + assert_eq!(st.scratch_bytes, 0, "scratch extents leaked: {st:?}"); + + // 6. Off: nothing more is evicted, and the budget no longer applies. + spill::configure(None, 0).unwrap(); + assert!(!spill::enabled()); + let before = spill::stats().evictions; + let d = surface(5000, 32); + assert_eq!(spill::stats().evictions, before); + check(&d, 5000, 32); + drop(d); + + // 7. Encoded bytes and COW edits survive eviction at every supported depth. + for sample in [SampleType::U8, SampleType::U16, SampleType::F32] { + let fmt = PixelFormat { mode: ColorMode::Rgb, sample, alpha: true }; + let len = (TILE_SIZE * TILE_SIZE) as usize * fmt.bytes_per_pixel(); + spill::configure(Some(&dir), len * 2).unwrap(); + let mut s = Surface::new(fmt); + for i in 0..12 { + s.tile_mut(TileCoord::new(i, 0)).bytes_mut().copy_from_slice(&noise(8000 + i as u32, len)); + } + let original = s.clone(); + spill::settle(); + assert!(spill::stats().resident_bytes <= len * 2); + s.fill_rect(Rect::from_xywh(0, 0, 4, 4), &[1.0, 0.0, 0.0, 1.0]); + spill::settle(); + assert_eq!(s.pixel(1, 1), vec![1.0, 0.0, 0.0, 1.0]); + for i in 0..12 { + assert_eq!(&*original.tile(TileCoord::new(i, 0)).unwrap().bytes(), &noise(8000 + i as u32, len)); + } + let mut converted = [[0; 4]; 4]; + s.read_rgba8_into(Rect::from_xywh(0, 0, 4, 1), &mut converted); + assert_eq!(converted, [[255, 0, 0, 255]; 4]); + } + // A tiny budget must still allow a pinned reader to finish instead of evicting itself. + spill::configure(Some(&dir), 1).unwrap(); + let tiny = surface(9000, 2); + spill::settle(); + check(&tiny, 9000, 2); + drop(tiny); + spill::configure(None, 0).unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index db0efe31fa..7e07c2dbca 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -1635,13 +1635,13 @@ fn ensure_gpu(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, visible: /// counted once per structural change, not per brush dab) and whenever the preference changes. fn gpu_budget(app: &mut PhotocraftApp, gpu: &crate::gpu_canvas::GpuCanvas, idx: usize, partial: bool, visible: DRect) { gpu.set_focus(Some(visible)); - let allowance = u64::from(app.session.prefs().performance.memory_usage_mb).saturating_mul(1 << 20); + let allowance = u64::from(app.session.prefs().performance.gpu_memory_mb).saturating_mul(1 << 20); if partial && app.perf.gpu_budget_allowance == allowance && gpu.memory_budget().is_some() { return; } - let Some(st) = app.session.documents().get(idx) else { return }; - let pixels = st.history.pixel_bytes(&st.doc) as u64; - let budget = crate::gpu_canvas::memory_budget(allowance, pixels, crate::gpu_canvas::physical_memory()); + let _ = idx; + // Graphics resources have their own cap. Reserve space for visible output pages and staging. + let budget = allowance.saturating_sub((allowance / 4).min(128 << 20)).max(8 << 20); gpu.set_memory_budget(budget); app.perf.gpu_budget_mb = budget >> 20; app.perf.gpu_budget_allowance = allowance; diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index db908d0943..64f9c31556 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1262,6 +1262,8 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value { dialogs.extend(crate::discard_ui::inspect(app)); json!({ "window": {"width": screen.width(), "height": screen.height(), "pixelsPerPoint": ctx.pixels_per_point()}, + "scratch": photocraft_raster::spill::stats(), + "memory": photocraft_raster::memory::stats(), "tool": app.ui.tool, "toolOptions": app.ui.tool_options, "perspectiveCrop": app.ui.perspective_crop, diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 805c20f76a..a95010b405 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3745,3 +3745,5 @@ navigator Zoom Zvětšení @plural {n} action|{n} actions {n} akce|{n} akce|{n} akcí Auto Add/Delete Automaticky přidat/odstranit ICO is limited to 256 × 256 pixels ICO je omezen na 256 × 256 pixelů + GPU memory mb Paměť GPU (MB) + Memory usage percent Využití paměti (%) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 88ef957675..50abfac03e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3135,3 +3135,5 @@ curves Smooth Glätten @plural {n} action|{n} actions {n} Aktion|{n} Aktionen Auto Add/Delete Autom. hinzuf./löschen ICO is limited to 256 × 256 pixels ICO ist auf 256 × 256 Pixel begrenzt + GPU memory mb GPU-Speicher (MB) + Memory usage percent Speichernutzung (%) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index e8889313cb..d2c7c6bb4c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3835,3 +3835,5 @@ curves Smooth Εξομάλυνση @plural {n} action|{n} actions {n} ενέργεια|{n} ενέργειες Auto Add/Delete Αυτόματη προσθήκη/διαγραφή ICO is limited to 256 × 256 pixels Το ICO περιορίζεται σε 256 × 256 εικονοστοιχεία + GPU memory mb Μνήμη GPU (MB) + Memory usage percent Χρήση μνήμης (%) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 37f88f4294..4f7c18f908 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2822,3 +2822,5 @@ curves Smooth Suavizar @plural {n} action|{n} actions {n} acción|{n} acciones Auto Add/Delete Añadir/eliminar automáticamente ICO is limited to 256 × 256 pixels ICO está limitado a 256 × 256 píxeles + GPU memory mb Memoria GPU (MB) + Memory usage percent Uso de memoria (%) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index f7d508fb5c..76064d7541 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3139,3 +3139,5 @@ curves Smooth Lisser @plural {n} action|{n} actions {n} action|{n} actions Auto Add/Delete Ajout/suppr. auto ICO is limited to 256 × 256 pixels Le format ICO est limité à 256 × 256 pixels + GPU memory mb Mémoire GPU (Mo) + Memory usage percent Utilisation de la mémoire (%) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 70c2294205..3b64203ab5 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4058,3 +4058,5 @@ cameraRaw Yellow Sárga Ink Characteristics Festék jellemzői Solidity: Fedőképesség: Redrawing Újrarajzolás + GPU memory mb GPU memória MB + Memory usage percent Memóriahasználat százaléka diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index dcc02ec185..6f79f4f511 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3126,3 +3126,5 @@ curves Smooth Haluskan @plural {n} action|{n} actions {n} tindakan Auto Add/Delete Tambah/Hapus Otomatis ICO is limited to 256 × 256 pixels ICO dibatasi hingga 256 × 256 piksel + GPU memory mb Memori GPU (MB) + Memory usage percent Pemakaian memori (%) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index c077d90aa1..0ad5aa345a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4100,3 +4100,5 @@ navigator Zoom Zoom @plural {n} action|{n} actions {n} azione|{n} azioni Auto Add/Delete Aggiungi/elimina automaticamente ICO is limited to 256 × 256 pixels ICO è limitato a 256 × 256 pixel + GPU memory mb Memoria GPU (MB) + Memory usage percent Uso memoria (%) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9f074e3e30..8495dc71c7 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3815,3 +3815,5 @@ curves Smooth スムーズ Reset All Locked Settings ロックされた設定をすべて初期化 Copy Texture to Other Tools テクスチャを他のツールにコピー ICO is limited to 256 × 256 pixels ICO は 256 × 256 ピクセルまでです + GPU memory mb GPU メモリ (MB) + Memory usage percent メモリ使用率 (%) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index eefa162a65..410ab4c31d 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3312,3 +3312,5 @@ curves Smooth 매끄럽게 @plural {n} action|{n} actions 액션 {n}개 Auto Add/Delete 자동 추가/삭제 ICO is limited to 256 × 256 pixels ICO는 256 × 256픽셀로 제한됩니다 + GPU memory mb GPU 메모리(MB) + Memory usage percent 메모리 사용 비율(%) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 68e98a6fef..961d855004 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3897,3 +3897,5 @@ curves Smooth Vloeiend maken @plural {n} action|{n} actions {n} handeling|{n} handelingen Auto Add/Delete Automatisch toevoegen/verwijderen ICO is limited to 256 × 256 pixels ICO is beperkt tot 256 × 256 pixels + GPU memory mb GPU-geheugen (MB) + Memory usage percent Geheugengebruik (%) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2d76183794..dd34855304 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3735,3 +3735,5 @@ curves Smooth Wygładź @plural {n} action|{n} actions {n} operacja|{n} operacje|{n} operacji Auto Add/Delete Automatyczne dodawanie/usuwanie ICO is limited to 256 × 256 pixels ICO jest ograniczony do 256 × 256 pikseli + GPU memory mb Pamięć GPU (MB) + Memory usage percent Użycie pamięci (%) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 0d48ba9b47..9b49500062 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3927,3 +3927,5 @@ layerLabel No Color Sem cor @plural {n} action|{n} actions {n} ação|{n} ações Auto Add/Delete Adicionar/excluir automaticamente ICO is limited to 256 × 256 pixels ICO é limitado a 256 × 256 pixels + GPU memory mb Memória da GPU (MB) + Memory usage percent Uso de memória (%) diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 11a3cb6b2e..ed611ce8e8 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3103,3 +3103,5 @@ curves Smooth Сгладить Gray Value (Median) Уровень серого (медиана) Integrated Density Интегральная плотность Length Длина + GPU memory mb Память GPU (МБ) + Memory usage percent Использование памяти (%) diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index f47fe20162..648d9ee7fc 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4211,3 +4211,5 @@ shape Appearance Izgled Ink Characteristics Karakteristike mastila Solidity: Punoća: Redrawing Ponovno iscrtavanje + GPU memory mb GPU меморија MB + Memory usage percent Проценат употребе меморије diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 948c967467..73bb2f6a48 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3869,3 +3869,5 @@ cameraData Lens Lens Ink Characteristics Mürekkep Özellikleri Solidity: Doluluk: Redrawing Yeniden çiziliyor + GPU memory mb GPU belleği MB + Memory usage percent Bellek kullanım yüzdesi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 2a72fdaf19..b9dbce3b57 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3836,3 +3836,5 @@ curves Smooth Згладити @plural {n} action|{n} actions {n} операція|{n} операції|{n} операцій Auto Add/Delete Автододавання/видалення ICO is limited to 256 × 256 pixels ICO обмежено розміром 256 × 256 пікселів + GPU memory mb Пам’ять GPU (МБ) + Memory usage percent Використання пам’яті (%) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 88b855a707..63ee112d43 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3624,3 +3624,5 @@ curves Smooth Làm mượt Choose a gradient file (.grd). Chọn tệp chuyển sắc (.grd). Auto Add/Delete Tự động thêm/xóa ICO is limited to 256 × 256 pixels ICO giới hạn ở 256 × 256 pixel + GPU memory mb Bộ nhớ GPU MB + Memory usage percent Tỷ lệ sử dụng bộ nhớ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2842771124..fb2cf4ae92 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2747,3 +2747,5 @@ curves Smooth 平滑 @plural {n} action|{n} actions {n} 个动作 Auto Add/Delete 自动添加/删除 ICO is limited to 256 × 256 pixels ICO 最大为 256 × 256 像素 + GPU memory mb GPU 内存 (MB) + Memory usage percent 内存使用比例 (%) diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d02e06646e..534affa728 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2732,3 +2732,5 @@ curves Smooth 平滑 @plural {n} action|{n} actions {n} 個動作 Auto Add/Delete 自動增加/刪除 ICO is limited to 256 × 256 pixels ICO 最大為 256 × 256 像素 + GPU memory mb GPU 記憶體 (MB) + Memory usage percent 記憶體使用比例 (%) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2cd006087d..04027176b1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1782,6 +1782,14 @@ impl eframe::App for PhotocraftApp { } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { + photocraft_compose::discard_unreadable_pixel_caches(); + if let Err(error) = photocraft_raster::spill::check_integrity() { + self.ui.status = error; + self.ui.status_error = true; + } else if let Some(error) = photocraft_raster::spill::last_error() { + self.ui.status = error; + self.ui.status_error = true; + } let ctx = ui.ctx().clone(); self.hover_layer = None; i18n::set_current(i18n::Lang::from_pref(&self.session.prefs().interface.language)); diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index db908ae23f..c29ff03420 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -218,6 +218,7 @@ pub fn load(app: &mut PhotocraftApp) { let template = "Preferences were reset: {error}"; app.ui.status = crate::i18n::fmt(tl!(template), &[("error", &e)]); } + app.session.apply_prefs(); crate::dock::restore(app); crate::brush_picker::restore(app); crate::last_brush::restore(app); @@ -1477,7 +1478,7 @@ fn field_visible(section: &str, obj: &Map, k: &str, query: &str) (query.is_empty() || preference_matches(section, k, query)) && !drawn_elsewhere && !prefs::is_hidden(&path) - && obj.get(k).is_some_and(|v| !matches!(v, Value::Null | Value::Object(_))) + && obj.get(k).is_some_and(|v| (path == "performance.memoryUsagePercent" && v.is_null()) || !matches!(v, Value::Null | Value::Object(_))) } /// Generic editor for a section's fields: checkboxes, dropdowns for choices, colour swatches, @@ -1513,6 +1514,18 @@ fn field_rows(ui: &mut egui::Ui, section: &str, obj: &mut Map, ke let v = obj.get(&k).cloned().unwrap_or(Value::Null); let human = humanize(&k); let label = tl!(&human).to_string(); + if path == "performance.memoryUsagePercent" { + ui.label(RichText::new(&label).color(t.text_dim)); + let mut enabled = v.is_number(); + let mut percent = v.as_u64().unwrap_or(70) as u32; + ui.horizontal(|ui| { + crate::widgets::checkbox(ui, &mut enabled, ""); + ui.add_enabled(enabled, egui::DragValue::new(&mut percent).range(1..=95).suffix("%")); + }); + obj.insert(k, if enabled { json!(percent) } else { Value::Null }); + ui.end_row(); + continue; + } match &v { Value::Bool(b) => { ui.label(""); @@ -2835,10 +2848,10 @@ mod tests { let values = prefs::Preferences::default().to_json(); assert!(has_visible_fields(&values, "general")); assert!(has_visible_fields(&values, "fileHandling")); + assert!(has_visible_fields(&values, "scratchDisks")); + assert!(!prefs::is_hidden("scratchDisks.disks")); // Every setting of these sections is still unimplemented. - for section in ["integrations", "scratchDisks"] { - assert!(!has_visible_fields(&values, section), "{section}"); - } + assert!(!has_visible_fields(&values, "integrations")); // "Fill new type layers with placeholder text" and "Use Escape to Commit" are live; other Type rows stay hidden. assert!(has_visible_fields(&values, "type")); assert!(!prefs::is_hidden("type.fillNewTypeLayersWithPlaceholder")); diff --git a/docs/development.md b/docs/development.md index 17c7e67dce..fd90a1a633 100644 --- a/docs/development.md +++ b/docs/development.md @@ -95,6 +95,10 @@ If the device is lost while running (#243), every GPU entry point checks the dev ## Logs +Native pixel residency, RAM limits and scratch failure recovery are described in +[`scratch-disks.md`](scratch-disks.md). Control `ui.inspect` includes `scratch` counters and +the `memory` sample, effective allowances and current working reservations. + The desktop app writes its `log` records to standard error and to `logs/photocraft.log` in the settings directory (Linux `~/.config/photocraft/logs/`, macOS `~/Library/Application Support/Photocraft/logs/`, Windows `%APPDATA%\Photocraft\logs\`, or under `PHOTOCRAFT_CONFIG_DIR` / the portable data folder). A start launched from a desktop menu or the Dock has no terminal, so this file is what to attach to a bug report: GPU startup fallbacks, a lost device and the crash guard's panic report all land there. Each launch moves the previous log to `photocraft.1.log` (and that one to `photocraft.2.log`), so the log of a run that crashed survives the next start. The file stops growing at 16 MiB. `--version` and command-line errors write no file. By default PhotoCraft's own crates log at `info` and everything else at `warn`. `RUST_LOG` replaces that with env_logger-style directives, for example `RUST_LOG=debug`, `RUST_LOG=warn,photocraft_gpu=trace` or `RUST_LOG=info,wgpu_core=warn`; a directive ending in `*` covers every target starting with it (`photocraft*=debug`). The logger is `apps/photocraft/src/logging.rs`; the web build logs to the browser console instead. diff --git a/docs/roadmap.md b/docs/roadmap.md index bca91616c7..ccdd5b8291 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -122,3 +122,5 @@ Each milestone has a **definition of done (DoD)** and must leave `main` green on | 2026-10-10 | major | Progress-docs standard: honest assessment and dated measurements moved to `target-app-parity.md`, Affinity notes to `file-format-parity.md`; new Current focus and estimates; `parity.md` renamed `parity-checklist.md` | | 2026-10-08 | minor | Tools, Affinity import and performance measurements added | | 2026-10-05 | major | Honest parity assessment added | + +2026-10-13: native scratch storage pages current and history tiles through compressed, CRC-checked files. Fresh RAM budgets default to 70%; engine-owned memory supervision stops with its last session. Scratch errors block edit/save commits and permit retry. Unix files are private and stale files swept at startup; Windows files use delete-on-close. See [scratch disks](scratch-disks.md). Streaming import and viewport rendering follow separately. diff --git a/docs/scorecard.md b/docs/scorecard.md index 92f9315ebd..3b7b0f40e8 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 17 not run, 5 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 7 | 13 | 7 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 145/256, round trip ≥ 258/256 | | [Tools](#tools) | 28 | 14 | 1 | | -| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 157 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 25 of 159 (target 0) | | [Type](#type) | 4 | 3 | 2 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present | @@ -176,9 +176,9 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t ## Workspace and UI -**Settings that do nothing: 26 of 157** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 25 of 159** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. -Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. +Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `file_handling.save_in_background`, `performance.cache_levels`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`. | Id | Target | Status | Issue | Note | |---|---|---|---|---| @@ -248,7 +248,7 @@ Never-crash attribute on 28 of 28 crate roots. | REL-2 | Every workspace crate carries the never-crash deny(clippy::unwrap_used, ...) attribute | done | | Counted automatically above (crate roots under crates/ and apps/); testkit gained it in #221 | | REL-3 | The app catches escaped panics around command dispatch and import/export | done | | a_panic_in_a_command_... runs the test-only `test.panic` spec through Session::execute and asserts Err plus an unchanged document (engine jobs_tests.rs); the worker guard is covered by a_panic_in_the_worker_...; crash_guard.rs guard_turns_a_panic_into_an_error covers import/export (apps/photocraft) | | REL-4 | Atomic save (temp, fsync, rename) for every document write | done | [#203](https://github.com/storytold/photocraft/issues/203) | photocraft_format::atomic_write (format/src/atomic.rs, #230): same-dir temp, sync_all, rename with Windows PermissionDenied retry, Unix dir fsync; every document write site routes through it and format/src/atomic/tests.rs failure-injects write, rename and read-only-dir errors | -| REL-212-1 | Fallible allocation for paste/erase/fill/transform/save/import, clear out-of-memory error | partial | [#212](https://github.com/storytold/photocraft/issues/212) | Raster region/tile buffers, paste/erase/fill/transform and warp output use fallible reservations; save/import boundaries preserve existing state, but encoder/decoder internals still need a broader fallible-allocation audit | +| REL-212-1 | Fallible allocation for paste/erase/fill/transform/save/import, clear out-of-memory error | partial | [#212](https://github.com/storytold/photocraft/issues/212) | Raster region/tile buffers, paste/erase/fill/transform and warp output use fallible reservations; filter and lens working memory is admitted before edits, and current/history tiles spill to CRC-checked scratch. Save/import boundaries preserve state; remaining encoder/decoder allocations still need broader audit. | | REL-212-2 | Export switches to PSB when the estimated file size exceeds 2 GB | done | [#212](https://github.com/storytold/photocraft/issues/212) | PSD export uses checked size estimates for raster, masks, channels, and retained metadata | | REL-212-3 | Tests: an allocation-limit injection makes each command Err with the document unchanged | partial | [#212](https://github.com/storytold/photocraft/issues/212) | Engine failpoint tests cover paste, erase, fill, transform, import and save transaction boundaries; codec-level allocator failure coverage remains open | diff --git a/docs/scratch-disks.md b/docs/scratch-disks.md new file mode 100644 index 0000000000..a99cc7b30d --- /dev/null +++ b/docs/scratch-disks.md @@ -0,0 +1,39 @@ +# Scratch disks and memory residency + +Native PhotoCraft keeps pixel tiles in RAM and spills cold tiles to a configured scratch +directory. A read or write guard keeps a tile resident while a consumer uses its bytes. Undo +snapshots keep their copy-on-write tiles, including disk-backed tiles, until History States +retires them. Web builds retain their explicit memory limit and do not use a filesystem. + +New preferences use **70% of physical RAM** as the process ceiling. This is configurable from +1–95%; older preferences without `performance.memoryUsagePercent` retain their absolute +`performance.memoryUsageMb` limit. Other applications, non-tile process memory and bounded +working buffers reduce the live tile allowance. The separate `performance.gpuMemoryMb` +setting limits graphics resources. Memory virtual address-space usage is diagnostic data, +not a measurement of committed memory or a substitute for scratch storage. + +Enable a directory in Preferences → Scratch Disks. `(system temp)` selects the operating +system's temporary directory. Only the first enabled, nonempty directory is used. Changing +directories creates a new scratch file; old disk-backed tiles keep their old file alive. +The development override `PHOTOCRAFT_TILE_BUDGET_MB` fixes the tile allowance for stress tests. + +Scratch extents are LZ4 compressed, CRC-checked and reused after a tile is released. Closing +the last tile truncates its file. Windows opens files with delete-on-close so process exit, +including exit without Rust destructors, removes them. Unix creates files with mode `0600` +and sweeps `photocraft--.scratch` when configuring the directory. It preserves +live-process files, other users' files, symlinks and unrelated names; unavailable process +enumeration leaves files untouched. PID reuse conservatively retains a stale file, and a +unique launch nonce avoids a collision. Normal Unix drops remove the file immediately. + +The engine owns a shared, stoppable residency supervisor and joins it when its last session +is dropped. `photocraft-raster` only exposes synchronous measurement and bounded eviction +operations; standalone callers work without a background thread. `sysinfo` is native-only +with its default features disabled and only the `system` feature enabled. + +An unavailable or full scratch disk retains resident pixels and reports the failure. +A failed read retains its backing extent and blocks editing, cache admission and saving +until the tile is readable again. Recovery can retry the original bytes after the storage +becomes available; zeros from a failed display read must never become saved pixels. + +Scratch storage alone does not make every format, filter or renderer streamable. The native +PSD/EXR import and viewport streaming changes build on these guards and memory reservations. diff --git a/scorecard/reliability.toml b/scorecard/reliability.toml index 081af4461f..d5fc1fb5a7 100644 --- a/scorecard/reliability.toml +++ b/scorecard/reliability.toml @@ -35,7 +35,7 @@ id = "REL-212-1" target = "Fallible allocation for paste/erase/fill/transform/save/import, clear out-of-memory error" status = "partial" issue = 212 -note = "Raster region/tile buffers, paste/erase/fill/transform and warp output use fallible reservations; save/import boundaries preserve existing state, but encoder/decoder internals still need a broader fallible-allocation audit" +note = "Raster region/tile buffers, paste/erase/fill/transform and warp output use fallible reservations; filter and lens working memory is admitted before edits, and current/history tiles spill to CRC-checked scratch. Save/import boundaries preserve state; remaining encoder/decoder allocations still need broader audit." [[item]] id = "REL-212-2" From 13271f58fa9dd13c2c88b56bed91fa59dc5def7b Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:16:32 +0100 Subject: [PATCH 2/9] Size filter working sets by area and serialize overlapping operations working_bytes reserved three 256 MiB result groups for every filter, so two concurrent filters on a 24x18 image could exhaust the transient allowance and actions.play reported 'not enough working memory'. Bound the result groups by the area, charge only untiled RSS when resident tiles are evictable, always admit the transient allowance, and let an operation that fits on its own wait (bounded, 30 s, native only) for concurrent reservations instead of failing. Replace the deprecated AtomicU64::fetch_update with try_update (stable since 1.95, the MSRV). --- crates/algo/src/lib.rs | 3 +- crates/algo/src/tests.rs | 3 ++ crates/raster/src/memory.rs | 60 +++++++++++++++++++++++++++++++++---- 3 files changed, 59 insertions(+), 7 deletions(-) diff --git a/crates/algo/src/lib.rs b/crates/algo/src/lib.rs index def8d6b42e..60a3b488e4 100644 --- a/crates/algo/src/lib.rs +++ b/crates/algo/src/lib.rs @@ -1035,7 +1035,8 @@ pub fn working_bytes(params: &FilterParams, area: Rect, bounds: Rect, channels: let threads = 1u64; let tile = auto_tile(params, bounds).max(1) as u64; let floats = (channels as u64).saturating_mul(4); - let base = (RESULT_BUDGET as u64).saturating_mul(3); + // Result groups hold at most RESULT_BUDGET bytes of floats, and never more than the area. + let base = area.size().area().saturating_mul(floats).min(RESULT_BUDGET as u64).saturating_mul(3); match params.halo_for(bounds) { Halo::Bounds => base.saturating_add(bounds.union(&area).size().area().saturating_mul(floats)), Halo::Radius(r) => { diff --git a/crates/algo/src/tests.rs b/crates/algo/src/tests.rs index 1ed8c11403..8a2e6a272d 100644 --- a/crates/algo/src/tests.rs +++ b/crates/algo/src/tests.rs @@ -11,6 +11,9 @@ fn relight_admission_tracks_the_document_dependent_working_set() { let large = Rect::new(0, 0, 86400, 43200); assert!(working_bytes(¶ms, small, small, 4) < working_bytes(¶ms, small, large, 4)); assert_eq!(working_bytes(¶ms, Rect::EMPTY, large, 4), 0); + // A tiny image must not reserve the 256 MiB group budget three times over. + let tiny = Rect::new(0, 0, 24, 18); + assert!(working_bytes(¶ms, tiny, tiny, 4) < 64 << 20, "{}", working_bytes(¶ms, tiny, tiny, 4)); } fn fmt(s: SampleType) -> PixelFormat { diff --git a/crates/raster/src/memory.rs b/crates/raster/src/memory.rs index 069f8c0af0..5ad3df50d0 100644 --- a/crates/raster/src/memory.rs +++ b/crates/raster/src/memory.rs @@ -122,7 +122,7 @@ pub struct Reservation(u64); pub fn try_reserve(bytes: u64) -> Result { let (_, b, _) = stats(); RESERVED - .fetch_update(Ordering::AcqRel, Ordering::Relaxed, |n| n.checked_add(bytes).filter(|next| *next <= b.transient_bytes)) + .try_update(Ordering::AcqRel, Ordering::Relaxed, |n| n.checked_add(bytes).filter(|next| *next <= b.transient_bytes)) .map_err(|_| "not enough working memory; reduce the operation or wait for other jobs".to_string())?; Ok(Reservation(bytes)) } @@ -133,16 +133,51 @@ pub fn try_reserve(bytes: u64) -> Result { pub fn try_reserve_operation(bytes: u64) -> Result { let b = refresh(); let (sample, _, _) = stats(); - let available = if sample.total_bytes == 0 { b.transient_bytes } else { b.effective_process_bytes.saturating_sub(sample.process_resident_bytes) }; - RESERVED - .fetch_update(Ordering::AcqRel, Ordering::Relaxed, |n| n.checked_add(bytes).filter(|next| *next <= available)) - .map_err(|_| "not enough working memory for this operation; reduce its region or use a streaming format".to_string())?; - Ok(Reservation(bytes)) + // Resident tiles are evictable when spilling is on, so only the untiled part of RSS is + // charged. The transient allowance is always admissible: it is what the budget reserves + // for working sets, so normal-sized operations are never refused by a high RSS sample. + let evictable = if crate::spill::enabled() { crate::spill::stats().resident_bytes as u64 } else { 0 }; + let untiled = sample.process_resident_bytes.saturating_sub(evictable); + let available = if sample.total_bytes == 0 { b.transient_bytes } else { b.effective_process_bytes.saturating_sub(untiled).max(b.transient_bytes) }; + let refused = || "not enough working memory for this operation; reduce its region or use a streaming format".to_string(); + if bytes > available { + return Err(refused()); + } + // It fits on its own: wait (bounded) for concurrent operations to return their working + // sets instead of failing an operation that only overlapped another one. + #[cfg(not(target_arch = "wasm32"))] + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + loop { + if RESERVED.try_update(Ordering::AcqRel, Ordering::Relaxed, |n| n.checked_add(bytes).filter(|next| *next <= available)).is_ok() { + return Ok(Reservation(bytes)); + } + #[cfg(target_arch = "wasm32")] + return Err(refused()); + #[cfg(not(target_arch = "wasm32"))] + { + let now = std::time::Instant::now(); + if now >= deadline { + return Err(refused()); + } + let guard = RELEASED.0.lock().unwrap_or_else(PoisonError::into_inner); + // Re-checked after the wake-up; a missed notification costs at most this slice. + let slice = deadline.saturating_duration_since(now).min(std::time::Duration::from_millis(50)); + drop(RELEASED.1.wait_timeout(guard, slice).unwrap_or_else(PoisonError::into_inner)); + } + } } +#[cfg(not(target_arch = "wasm32"))] +static RELEASED: (Mutex<()>, std::sync::Condvar) = (Mutex::new(()), std::sync::Condvar::new()); + impl Drop for Reservation { fn drop(&mut self) { RESERVED.fetch_sub(self.0, Ordering::AcqRel); + #[cfg(not(target_arch = "wasm32"))] + { + let _guard = RELEASED.0.lock().unwrap_or_else(PoisonError::into_inner); + RELEASED.1.notify_all(); + } } } @@ -170,6 +205,19 @@ mod tests { assert_eq!(b.tile_bytes, MIB); } #[test] + fn an_operation_that_fits_alone_waits_for_a_concurrent_one() { + let available = refresh().transient_bytes; + let first = try_reserve_operation(available / 2 + 1).unwrap(); + let releaser = std::thread::spawn(move || { + std::thread::sleep(std::time::Duration::from_millis(100)); + drop(first); + }); + let second = try_reserve_operation(available / 2 + 1); + releaser.join().unwrap(); + assert!(second.is_ok(), "overlapping work is serialized, not refused"); + assert!(try_reserve_operation(u64::MAX).is_err(), "work that can never fit is refused at once"); + } + #[test] fn reservations_are_bounded_and_returned() { let before = stats().2; let r = try_reserve(1024).unwrap(); From 947038d0db52280ad003eb3d55f6f19aa5070f66 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:17:50 +0100 Subject: [PATCH 3/9] Unlink Unix scratch files right after opening The spill manager is process-global and never dropped, so the Unix scratch file was only removed by the next launch's reap. Unlink it immediately after opening and read/write through the one handle with pread/pwrite (readers can no longer reopen it by path). Windows keeps delete-on-close and per-thread readers. The abrupt-exit test now asserts that no file remains on every platform; docs/scratch-disks.md updated. --- crates/compose/src/lib.rs | 4 +- crates/engine/src/color_channels.rs | 3 +- crates/engine/src/filters/tests.rs | 7 +-- crates/raster/src/lib.rs | 14 ++--- crates/raster/src/scratch_file.rs | 79 ++++++++++++++++++++++++----- docs/scratch-disks.md | 12 +++-- 6 files changed, 88 insertions(+), 31 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 37f7974564..9039a2c621 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -68,7 +68,9 @@ pub use extents::{ }; #[cfg(test)] use extents::{mask_k, shapeless_stroke_bounds, trim_to_painted}; -pub use fx_cache::{DEFAULT_FX_CACHE_BUDGET, discard_unreadable_pixel_caches, effect_cache_budget, effect_cache_bytes, purge_effect_cache, set_effect_cache_budget}; +pub use fx_cache::{ + DEFAULT_FX_CACHE_BUDGET, discard_unreadable_pixel_caches, effect_cache_budget, effect_cache_bytes, purge_effect_cache, set_effect_cache_budget, +}; #[cfg(test)] use fx_cache::{effect_maps, effect_region, fx_region_bytes}; pub use reduced::{PROXY_THUMBNAIL_PIXELS, render_reduced, render_reduced_damage, render_reduced_rect, thumbnail, thumbnail_buffer, thumbnail_size}; diff --git a/crates/engine/src/color_channels.rs b/crates/engine/src/color_channels.rs index d538267b98..c19c7e389c 100644 --- a/crates/engine/src/color_channels.rs +++ b/crates/engine/src/color_channels.rs @@ -175,7 +175,8 @@ fn restrict_surface_impl(before: &Surface, after: &mut Surface, colors: ColorCha continue; } let offset = i.saturating_mul(warped.bytes_per_pixel()); - let input = source_bytes.as_deref().and_then(|t| t.get(offset..offset.saturating_add(warped.bytes_per_pixel()))).unwrap_or(after.default_bytes()); + let input = + source_bytes.as_deref().and_then(|t| t.get(offset..offset.saturating_add(warped.bytes_per_pixel()))).unwrap_or(after.default_bytes()); for channel in colors.indices() { let offset = channel.saturating_mul(bytes); let range = offset..offset.saturating_add(bytes); diff --git a/crates/engine/src/filters/tests.rs b/crates/engine/src/filters/tests.rs index 077b7636a8..4d21d2dfdf 100644 --- a/crates/engine/src/filters/tests.rs +++ b/crates/engine/src/filters/tests.rs @@ -84,12 +84,7 @@ fn enormous_global_filter_is_refused_before_allocating_and_preserves_document() let mut s = Session::new(); // A sparse document exercises admission without allocating a giant background first. s.add_document( - photocraft_doc::Document::new( - "large", - photocraft_doc::Size::new(300000, 300000), - photocraft_color::ColorMode::Rgb, - photocraft_color::SampleType::U8, - ), + photocraft_doc::Document::new("large", photocraft_doc::Size::new(300000, 300000), photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8), None, ); s.execute("layer.new.layer", json!({})).unwrap(); diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 2a99549683..4ba7d45ee7 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -223,8 +223,6 @@ impl DerefMut for TileBytesMut<'_> { fn deref_mut(&mut self) -> &mut [u8] { self.0.as_deref_mut().unwrap_or(&mut self.1) } - - } /// Bytes compared at once while looking for a difference in a tile row. @@ -291,11 +289,13 @@ impl UniformTiles { } let bytes = t.try_bytes().ok()?; let mut px = bytes.chunks_exact(bpp); - let k = px.next().filter(|p0| px.all(|p| p == *p0)).map(|p0| match self.canonical.iter().position(|c| c.try_bytes().is_ok_and(|bytes| bytes.get(..bpp) == Some(p0))) { - Some(k) => k, - None => { - self.canonical.push(t.clone()); - self.canonical.len() - 1 + let k = px.next().filter(|p0| px.all(|p| p == *p0)).map(|p0| { + match self.canonical.iter().position(|c| c.try_bytes().is_ok_and(|bytes| bytes.get(..bpp) == Some(p0))) { + Some(k) => k, + None => { + self.canonical.push(t.clone()); + self.canonical.len() - 1 + } } }); self.of.insert(key, k); diff --git a/crates/raster/src/scratch_file.rs b/crates/raster/src/scratch_file.rs index f597fd4bba..2df4d82f33 100644 --- a/crates/raster/src/scratch_file.rs +++ b/crates/raster/src/scratch_file.rs @@ -1,21 +1,28 @@ //! The scratch file: where cold tiles go when pixel memory is over budget. //! -//! - One file per configured directory. Windows deletes it even after a crash; Unix uses private -//! permissions and reaps files of dead processes when the directory is next configured. +//! - One file per configured directory, never visible after the process ends. Unix creates it +//! with private permissions and unlinks it right after opening, so the space is returned when +//! the last handle closes, even on a crash or `exit` without destructors. Windows opens it +//! delete-on-close. Files of dead processes (an older build, or a crash between creating and +//! unlinking) are reaped when the directory is next configured. //! - Space is handed out in 4 KiB-aligned extents from a free list (best fit, coalescing), else //! appended at the end. //! - All I/O is positioned: no shared cursor, no lock held during I/O. The allocator lock only //! guards the free list. -//! - Reads go through one handle per thread (the file opened again by path): Windows serialises -//! I/O on one synchronous handle, so parallel readers sharing it would run one at a time. +//! - Unix reads and writes with `pread`/`pwrite` on the one handle (no reopen by path, which +//! is impossible once unlinked). Windows reads through one handle per thread (the file opened +//! again by path): it serialises I/O on one synchronous handle, so parallel readers sharing it +//! would run one at a time. //! //! Ported from Fotox's `fx-tiles` scratch file (same author), minus its `unsafe` `ReOpenFile`. use std::collections::{BTreeMap, BTreeSet}; use std::fs::File; use std::path::{Path, PathBuf}; +#[cfg(windows)] +use std::sync::OnceLock; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{Mutex, OnceLock, PoisonError}; +use std::sync::{Mutex, PoisonError}; const ALIGN: u64 = 4096; @@ -94,8 +101,12 @@ impl Allocator { pub(crate) struct ScratchFile { main: File, + #[cfg(windows)] readers: OnceLock>, path: PathBuf, + /// The directory entry still exists (Unix unlink failed): remove it on drop. + #[cfg(not(windows))] + linked: bool, allocator: Mutex, } @@ -132,7 +143,19 @@ impl ScratchFile { let main = options.open(&path)?; #[cfg(unix)] reap_abandoned(dir, &main); - Ok(Self { main, readers: OnceLock::new(), path, allocator: Mutex::new(Allocator::default()) }) + // Unix: the open handle keeps the inode; nothing is left behind at any exit. A + // filesystem that refuses the unlink keeps the name until drop or the next reap. + #[cfg(not(windows))] + let linked = std::fs::remove_file(&path).is_err(); + Ok(Self { + main, + #[cfg(windows)] + readers: OnceLock::new(), + path, + #[cfg(not(windows))] + linked, + allocator: Mutex::new(Allocator::default()), + }) } pub fn path(&self) -> &Path { @@ -180,7 +203,14 @@ impl ScratchFile { self.allocator.lock().unwrap_or_else(PoisonError::into_inner) } + /// Positioned reads on one handle run in parallel on Unix. + #[cfg(not(windows))] + fn reader(&self) -> &File { + &self.main + } + /// A handle for reading on the calling thread. + #[cfg(windows)] fn reader(&self) -> &File { let extra = self.readers.get_or_init(|| { // The same file opened again by path: std shares read, write and delete, so this @@ -242,8 +272,9 @@ fn reap_with(dir: &Path, uid: u32, live: impl Fn(u32) -> bool) { impl Drop for ScratchFile { fn drop(&mut self) { - // On Windows the file is already gone (delete-on-close); elsewhere remove it. - if !cfg!(windows) { + // Windows deletes on close and Unix unlinked at creation; only a refused unlink remains. + #[cfg(not(windows))] + if self.linked { let _ = std::fs::remove_file(&self.path); } } @@ -251,6 +282,7 @@ impl Drop for ScratchFile { /// A stable small number per thread, handed out in turn, so the worker threads of a pool land /// on different handles. +#[cfg(windows)] fn thread_slot() -> usize { static NEXT: AtomicUsize = AtomicUsize::new(0); thread_local! { @@ -344,10 +376,11 @@ mod tests { .status() .unwrap(); assert!(result.success()); - #[cfg(windows)] - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "delete-on-close survives exit without Drop"); + // Windows: delete-on-close. Unix: unlinked right after opening. Neither needs Drop. + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "no scratch file outlives an exit without destructors"); let next = ScratchFile::create(&dir).unwrap(); - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "a new launch reaps the dead process's files"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "a live scratch file has no directory entry either"); + next.write(b"still usable").unwrap(); drop(next); std::fs::remove_dir(dir).unwrap(); } @@ -373,11 +406,33 @@ mod tests { assert!(stale.exists(), "another owner's files remain"); reap_with(&dir, meta.uid(), |pid| pid == 124); assert!(!stale.exists()); - assert!(live.exists() && unrelated.exists() && link.exists() && own.path.exists()); + assert!(live.exists() && unrelated.exists() && link.exists()); + assert!(!own.path.exists() && !own.linked, "the open scratch file is already unlinked"); drop(own); std::fs::remove_dir_all(dir).unwrap(); } + #[test] + fn parallel_positioned_reads_share_one_unlinked_file() { + let dir = std::env::temp_dir().join(format!("pc-scratch-parallel-{}", std::process::id())); + let scratch = ScratchFile::create(&dir).unwrap(); + let extents: Vec<_> = (0..32u8).map(|i| scratch.write(&vec![i; 5000 + usize::from(i)]).unwrap()).collect(); + std::thread::scope(|s| { + for t in 0..8 { + let (scratch, extents) = (&scratch, &extents); + s.spawn(move || { + let mut buf = Vec::new(); + for (i, e) in extents.iter().enumerate().skip(t) { + scratch.read_into(*e, &mut buf).unwrap(); + assert_eq!(buf, vec![i as u8; 5000 + i]); + } + }); + } + }); + drop(scratch); + std::fs::remove_dir(dir).unwrap(); + } + #[test] fn alloc_reuses_and_coalesces() { let mut a = Allocator::default(); diff --git a/docs/scratch-disks.md b/docs/scratch-disks.md index a99cc7b30d..22936897e3 100644 --- a/docs/scratch-disks.md +++ b/docs/scratch-disks.md @@ -18,12 +18,16 @@ directories creates a new scratch file; old disk-backed tiles keep their old fil The development override `PHOTOCRAFT_TILE_BUDGET_MB` fixes the tile allowance for stress tests. Scratch extents are LZ4 compressed, CRC-checked and reused after a tile is released. Closing -the last tile truncates its file. Windows opens files with delete-on-close so process exit, -including exit without Rust destructors, removes them. Unix creates files with mode `0600` -and sweeps `photocraft--.scratch` when configuring the directory. It preserves +the last tile truncates its file. No scratch file outlives the process, including a crash or +an exit without Rust destructors: Windows opens it with delete-on-close, and Unix creates it +with mode `0600` and unlinks it immediately after opening, reading and writing through the +one open handle with positioned I/O (`pread`/`pwrite`). The space is returned when the last +handle closes. Configuring a directory also sweeps `photocraft--.scratch` files of +dead processes (older builds, or a crash between creating and unlinking). It preserves live-process files, other users' files, symlinks and unrelated names; unavailable process enumeration leaves files untouched. PID reuse conservatively retains a stale file, and a -unique launch nonce avoids a collision. Normal Unix drops remove the file immediately. +unique launch nonce avoids a collision. A filesystem that refuses the unlink keeps the name +until the file is dropped or the next sweep. The engine owns a shared, stoppable residency supervisor and joins it when its last session is dropped. `photocraft-raster` only exposes synchronous measurement and bounded eviction From 44f13e5498af63a42a3b0f4cba67774bb5b15eab Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:23:42 +0100 Subject: [PATCH 4/9] Scope scratch read failures to the document that holds the tile One unreadable tile used to block editing, saving and exporting every open document (spill::check_integrity was process-global). Add Tile/Surface/Document::scratch_health (free while no tile has failed) and Document::for_each_surface (ops' history walk now delegates to it). edit_with checks the document before and after, jobs the document they captured, import the result, save/export the document written; check_since is now generation-only so a failure or recovery during an operation refuses it once and a retry works. Caches check their own sources and purge once per new failure instead of every frame. Fault-injection tests use a duplicated handle (the Unix file has no name). --- crates/compose/src/bounds.rs | 2 +- crates/compose/src/fx_cache.rs | 18 ++++++--- crates/compose/src/masks.rs | 2 +- crates/compose/src/shape_split.rs | 2 +- crates/compose/tests/scratch_retry.rs | 4 +- crates/doc/src/lib.rs | 52 ++++++++++++++++++++++++++ crates/engine/src/cmd/timeline_cmds.rs | 3 ++ crates/engine/src/jobs.rs | 6 ++- crates/engine/src/session/execute.rs | 7 +++- crates/engine/tests/scratch_disk.rs | 35 +++++++++++++++-- crates/format/src/store.rs | 20 +++++++--- crates/format/tests/scratch_retry.rs | 4 +- crates/io/src/lib.rs | 6 ++- crates/ops/src/tiles.rs | 38 ++----------------- crates/raster/src/lib.rs | 26 +++++++++++++ crates/raster/src/scratch_file.rs | 5 +++ crates/raster/src/spill.rs | 44 +++++++++++++++++----- docs/scratch-disks.md | 12 ++++-- 18 files changed, 214 insertions(+), 72 deletions(-) diff --git a/crates/compose/src/bounds.rs b/crates/compose/src/bounds.rs index dec2d868d9..d6a3a88ef1 100644 --- a/crates/compose/src/bounds.rs +++ b/crates/compose/src/bounds.rs @@ -62,7 +62,7 @@ pub fn content_bounds(s: &Surface) -> Rect { None => { let generation = photocraft_raster::spill::read_error_generation(); let b = t.content_bounds(&dp); - if photocraft_raster::spill::check_since(generation).is_ok() { + if photocraft_raster::spill::check_since(generation).is_ok() && t.scratch_health().is_ok() { c.entries.insert(key, Entry { tile: Arc::downgrade(t), default: dp.clone().into_boxed_slice(), bounds: b }); } b diff --git a/crates/compose/src/fx_cache.rs b/crates/compose/src/fx_cache.rs index 2559e44854..b24aabc29b 100644 --- a/crates/compose/src/fx_cache.rs +++ b/crates/compose/src/fx_cache.rs @@ -122,10 +122,14 @@ pub fn purge_effect_cache() -> usize { freed } -/// Discard derived pixels and their source pins after a scratch read failure. This also lets -/// closing the affected document release its failed tiles instead of keeping them in a cache. +/// Discard derived pixels and their source pins once after each new scratch read failure. +/// This lets closing the affected document release its failed tiles instead of keeping them +/// in a cache. Caches never admit results built from unreadable tiles, so healthy documents' +/// caches are not purged again on every call while one document stays unreadable. pub fn discard_unreadable_pixel_caches() { - if photocraft_raster::spill::check_integrity().is_err() { + static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let generation = photocraft_raster::spill::read_error_generation(); + if SEEN.swap(generation, std::sync::atomic::Ordering::AcqRel) != generation && photocraft_raster::spill::any_failed() { purge_effect_cache(); super::bounds::purge(); super::masks::purge(); @@ -233,11 +237,15 @@ fn build_fx_slot_maps(layer: &Layer, region: Rect, key: u64, cx: &Ctx, slot: &Fx let shape: Vec = if region.is_empty() { Vec::new() } else { effect_shape(layer, region, cx) }; let maps = effects::build_maps_prepared(layer, shape, region, &cx.light, &texture_ctx(layer, region, cx), cx.patterns); let mut pin = Vec::new(); - layer_identity(layer, &mut std::collections::hash_map::DefaultHasher::new(), &mut |t| pin.push(std::sync::Arc::downgrade(t))); + let mut readable = true; + layer_identity(layer, &mut std::collections::hash_map::DefaultHasher::new(), &mut |t| { + readable &= t.scratch_health().is_ok(); + pin.push(std::sync::Arc::downgrade(t)); + }); // The maps, plus what each reserved tile address keeps allocated. let bytes = maps.bytes().saturating_add(pin.len().saturating_mul(std::mem::size_of::() + 2 * std::mem::size_of::())); let maps = std::sync::Arc::new(maps); - if photocraft_raster::spill::check_since(generation).is_err() { + if !readable || photocraft_raster::spill::check_since(generation).is_err() { // Built from a scratch placeholder: use it for this frame, never cache it. return maps; } diff --git a/crates/compose/src/masks.rs b/crates/compose/src/masks.rs index e60e151f50..faf45a19d0 100644 --- a/crates/compose/src/masks.rs +++ b/crates/compose/src/masks.rs @@ -124,7 +124,7 @@ fn finish_mask(c: &Mutex, k: u64, slot: &Arc>, generati // Never hold the global cache mutex while rasterizing or feathering. let read_generation = photocraft_raster::spill::read_error_generation(); let (surface, pixel_input) = build(); - if photocraft_raster::spill::check_since(read_generation).is_err() { + if photocraft_raster::spill::check_since(read_generation).is_err() || pixel_input.as_ref().is_some_and(|p| p.scratch_health().is_err()) { return surface; } let bytes = entry_bytes(&surface, pixel_input.as_ref()); diff --git a/crates/compose/src/shape_split.rs b/crates/compose/src/shape_split.rs index 176d43e3bf..53875d5922 100644 --- a/crates/compose/src/shape_split.rs +++ b/crates/compose/src/shape_split.rs @@ -83,7 +83,7 @@ pub fn split(sh: &ShapeLayer, canvas: Rect, depth: SampleType) -> Option<(Surfac if let Some(cache) = &sh.cache { fit_stroke(&parts.0, &mut parts.1, cache, canvas); } - if photocraft_raster::spill::check_since(generation).is_err() { + if photocraft_raster::spill::check_since(generation).is_err() || sh.cache.as_ref().is_some_and(|c| c.scratch_health().is_err()) { return Some(parts); } let mut c = cache().lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/compose/tests/scratch_retry.rs b/crates/compose/tests/scratch_retry.rs index 051113857c..70fdc41225 100644 --- a/crates/compose/tests/scratch_retry.rs +++ b/crates/compose/tests/scratch_retry.rs @@ -22,8 +22,8 @@ fn failed_effect_build_is_not_reused_after_original_pixels_recover() { photocraft_compose::purge_effect_cache(); spill::settle(); assert_eq!(spill::stats().resident_bytes, 0); - let path = std::fs::read_dir(&dir).unwrap().filter_map(Result::ok).map(|e| e.path()).find(|p| p.extension().is_some_and(|e| e == "scratch")).unwrap(); - let mut file = std::fs::OpenOptions::new().read(true).write(true).open(path).unwrap(); + let mut file = spill::scratch_handle_for_tests().unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); let mut good = Vec::new(); file.read_to_end(&mut good).unwrap(); file.seek(SeekFrom::Start(0)).unwrap(); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index ab13697e73..915ddca7da 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -1064,6 +1064,58 @@ impl Document { max } + /// Every pixel surface the document holds: layer pixels and caches, masks, smart filter + /// masks, video frames (including the originals), channels, the quick mask, patterns and + /// the selection. History snapshots and saves cover exactly these tiles. + pub fn for_each_surface(&self, mut visit: impl FnMut(&Surface)) { + for (_, _, layer) in self.walk() { + if let Some(surface) = layer.surface() { + visit(surface); + } + if let Some(mask) = &layer.mask { + visit(&mask.surface); + } + if let Some(cache) = &layer.fill_cache { + visit(&cache.surface); + } + if let LayerContent::Smart(smart) = &layer.content + && let Some(mask) = &smart.filter_mask + { + visit(&mask.surface); + } + if let Some(video) = &layer.video { + for frame in video.frames.iter().chain(video.original_frames.iter().flatten()) { + visit(frame); + } + } + } + for channel in self.channels.iter().chain(&self.quick_mask) { + visit(&channel.surface); + } + for pattern in &self.patterns { + visit(&pattern.surface); + } + if let Some(selection) = &self.selection { + visit(selection); + } + } + + /// `Err` if any of this document's tiles is unreadable on the scratch disk. Edits, saves + /// and exports of this document check it; other documents are unaffected. Free when no + /// tile in the process has failed. + pub fn scratch_health(&self) -> Result<(), String> { + if !photocraft_raster::spill::any_failed() { + return Ok(()); + } + let mut health = Ok(()); + self.for_each_surface(|surface| { + if health.is_ok() { + health = surface.scratch_health(); + } + }); + health + } + /// Depth-first walk yielding `(path, depth, layer)` bottom-to-top. pub fn walk(&self) -> Vec<(LayerPath, usize, &Layer)> { fn rec<'a>(layers: &'a [Layer], prefix: &mut LayerPath, out: &mut Vec<(LayerPath, usize, &'a Layer)>) { diff --git a/crates/engine/src/cmd/timeline_cmds.rs b/crates/engine/src/cmd/timeline_cmds.rs index 7893ac8d8f..9b6e0623cc 100644 --- a/crates/engine/src/cmd/timeline_cmds.rs +++ b/crates/engine/src/cmd/timeline_cmds.rs @@ -31,6 +31,7 @@ fn has_timeline(s: &Session) -> std::result::Result<(), String> { /// Mutate the document timeline without a history step (navigation / metadata). fn with_timeline(s: &mut Session, f: impl FnOnce(&mut Option)) -> Result { let st = s.active_mut().ok_or(EngineError::NoDocument)?; + let generation = photocraft_raster::spill::read_error_generation(); let mut doc = (*st.doc).clone(); crate::video_cmds::store(&mut doc); f(&mut doc.timeline); @@ -38,6 +39,8 @@ fn with_timeline(s: &mut Session, f: impl FnOnce(&mut Option)) -> Resu t.clamp(); } crate::video_cmds::sync(&mut doc); + // Storing and syncing video frames bypasses edit_with: apply the same scratch guard. + photocraft_raster::spill::check_since(generation).and_then(|()| doc.scratch_health()).map_err(EngineError::Other)?; st.doc = Arc::new(doc); st.revision += 1; info(s) diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 78fcea4956..dfc7fd39f8 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -377,12 +377,16 @@ pub fn run( work: impl FnOnce(&JobCtx) -> Result + Send + 'static, apply: impl FnOnce(&mut Session, T) -> Result + Send + 'static, ) -> Result { + // The job reads the active document it captured; only that document's pixels gate it. + let source = s.active().map(|d| d.doc.clone()); let work = move |ctx: &JobCtx| -> Result { photocraft_compose::discard_unreadable_pixel_caches(); - photocraft_raster::spill::check_integrity().map_err(EngineError::Other)?; + let health = || source.as_deref().map_or(Ok(()), photocraft_doc::Document::scratch_health).map_err(EngineError::Other); + health()?; let generation = photocraft_raster::spill::read_error_generation(); let value = work(ctx)?; photocraft_raster::spill::check_since(generation).map_err(EngineError::Other)?; + health()?; Ok(value) }; let authorization = s.authorize.or_else(|| RENDER_AUTHORIZATION.with(std::cell::Cell::get)); diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 76d33ecfd0..1a16f6d192 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -208,7 +208,6 @@ impl Session { let _authorization = crate::jobs::render_authorization_scope(self.authorize); let _document = crate::doc_path::scope(self.active().and_then(|d| d.path.as_deref()).map(std::path::Path::new)); photocraft_compose::discard_unreadable_pixel_caches(); - photocraft_raster::spill::check_integrity().map_err(EngineError::Other)?; let scratch_generation = photocraft_raster::spill::read_error_generation(); let restrict = self.color_restrict; let filter_mask_layer = self.filter_mask_layer; @@ -216,6 +215,9 @@ impl Session { let symmetry_map = self.symmetry_map.take(); let st = self.active_mut().ok_or(EngineError::NoDocument)?; let before = st.doc.clone(); + // Only this document's pixels gate its edits: an unreadable tile elsewhere (another + // open document) does not block it. + before.scratch_health().map_err(EngineError::Other)?; // Selecting layers is not a step, so the state this edit leaves behind targets what was // selected just before it (#1356): undoing a stroke keeps the painted layer active. let prior = st.layer_target(); @@ -229,7 +231,8 @@ impl Session { if let Some(id) = filter_mask_layer { smart_cmds::refresh_after_filter_mask_edit(&mut doc, id)?; } - if let Err(error) = photocraft_raster::spill::check_since(scratch_generation) { + if let Err(error) = photocraft_raster::spill::check_since(scratch_generation).and_then(|()| before.scratch_health()).and_then(|()| doc.scratch_health()) + { st.active_layer = previous_active_layer; return Err(EngineError::Other(error)); } diff --git a/crates/engine/tests/scratch_disk.rs b/crates/engine/tests/scratch_disk.rs index 6a323c7389..55a361133e 100644 --- a/crates/engine/tests/scratch_disk.rs +++ b/crates/engine/tests/scratch_disk.rs @@ -48,8 +48,8 @@ fn scratch_pixels_history_and_failed_save_are_transactional() { spill::settle(); assert_eq!(spill::stats().resident_bytes, 0); // Damage only this test's scratch file; retain its exact contents to restore the backing. - let path = std::fs::read_dir(&dir).unwrap().filter_map(Result::ok).map(|e| e.path()).find(|p| p.extension().is_some_and(|e| e == "scratch")).unwrap(); - let mut file = std::fs::OpenOptions::new().read(true).write(true).open(path).unwrap(); + let mut file = spill::scratch_handle_for_tests().unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); let mut good = Vec::new(); file.read_to_end(&mut good).unwrap(); file.seek(SeekFrom::Start(0)).unwrap(); @@ -71,6 +71,35 @@ fn scratch_pixels_history_and_failed_save_are_transactional() { let mut writer = photocraft_format::PcraftWriter::new(); assert!(writer.save_zip(&retained, &Default::default()).is_err()); assert!(photocraft_io::export(&retained, "png", &Default::default()).is_err()); + // No failure or recovery happens during a retry, so only the document's own health + // refuses it. + let generation = spill::read_error_generation(); + assert!(session.edit("Retry paint", |_, _| Ok(())).is_err()); + assert_eq!(spill::read_error_generation(), generation, "an already-failed tile does not change the generation"); + assert!(Arc::ptr_eq(&session.active().unwrap().doc, &retained)); + + // Another document is unaffected: it edits, saves and exports while this one is unreadable. + assert!(spill::check_integrity().is_err(), "the process-wide status still reports the failure"); + let mut other = Document::new("Healthy", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); + let mut pixels = Layer::raster("Other", PixelFormat::RGBA8); + let other_id = pixels.id; + pixels.surface_mut().unwrap().fill_rect(Rect::from_xywh(0, 0, 512, 256), &[0.0, 0.0, 1.0, 1.0]); + other.layers.push(pixels); + session.add_document(other, None); + session.select_layer(other_id).unwrap(); + session + .edit("Paint other", |d, _| { + d.layer_mut(other_id).unwrap().surface_mut().unwrap().fill_rect(Rect::from_xywh(0, 0, 8, 8), &[1.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + spill::settle(); + let healthy = session.active().unwrap().doc.clone(); + assert!(healthy.scratch_health().is_ok()); + let (saved, _) = photocraft_format::PcraftWriter::new().save_zip(&healthy, &Default::default()).unwrap(); + assert_eq!(photocraft_format::load_from_bytes(&saved).unwrap().layers, healthy.layers); + assert!(photocraft_io::export(&healthy, "png", &Default::default()).is_ok()); + assert!(retained.scratch_health().is_err()); file.seek(SeekFrom::Start(0)).unwrap(); file.write_all(&good).unwrap(); @@ -84,7 +113,7 @@ fn scratch_pixels_history_and_failed_save_are_transactional() { let (bytes, _) = writer.save_zip(&retained, &Default::default()).unwrap(); let loaded = photocraft_format::load_from_bytes(&bytes).unwrap(); assert_eq!(loaded.layers, retained.layers); - drop((session, before, retained, loaded, writer, file)); + drop((session, before, retained, healthy, loaded, writer, file)); spill::configure(None, 0).unwrap(); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs index 8b08ef7cfa..f221af9f57 100644 --- a/crates/format/src/store.rs +++ b/crates/format/src/store.rs @@ -579,6 +579,14 @@ struct Prepared { stats: SaveStats, } +/// Refuse to write pixels of `doc` that are unreadable now, or that may have been read as a +/// placeholder because some tile failed or recovered since `generation` (the save's start). +/// Other documents' scratch failures do not block this save. +fn scratch_ok(doc: &Document, generation: u64) -> Result<()> { + doc.scratch_health().map_err(FormatError::corrupt)?; + photocraft_raster::spill::check_since(generation).map_err(FormatError::corrupt) +} + enum Object { Tile(Arc, SampleType), Blob(Arc>), @@ -973,7 +981,7 @@ impl PcraftWriter { } fn prepare(&mut self, doc: &Document, opts: &SaveOptions) -> Result { - photocraft_raster::spill::check_integrity().map_err(FormatError::corrupt)?; + doc.scratch_health().map_err(FormatError::corrupt)?; let generation = photocraft_raster::spill::read_error_generation(); let prepared = self.prepare_inner(doc, opts); if let Err(error) = photocraft_raster::spill::check_since(generation) { @@ -1012,12 +1020,13 @@ impl PcraftWriter { for (h, b) in c.blobs { objects.insert(blob_path(&h).ok_or_else(|| invalid(&h))?, Object::Blob(b)); } - photocraft_raster::spill::check_integrity().map_err(FormatError::corrupt)?; + doc.scratch_health().map_err(FormatError::corrupt)?; Ok(Prepared { manifest, objects, stats }) } /// Save as a ZIP bundle in memory. pub fn save_zip(&mut self, doc: &Document, opts: &SaveOptions) -> Result<(Vec, SaveStats)> { + let generation = photocraft_raster::spill::read_error_generation(); // Another thread encodes the previews while the document is collected and its new // objects are compressed on all cores (zstd dominates a full save). let (previews, prepared) = beside( @@ -1070,7 +1079,7 @@ impl PcraftWriter { next.insert(key.unwrap_or_else(|| path.clone()), data); } } - photocraft_raster::spill::check_integrity().map_err(FormatError::corrupt)?; + scratch_ok(doc, generation)?; self.compressed = next; Ok((z.finish()?, stats)) } @@ -1085,6 +1094,7 @@ impl PcraftWriter { /// The same save path with an injectable publication barrier, for failure/GC ordering tests. fn save_dir_with(&mut self, doc: &Document, dir: &Path, opts: &SaveOptions, fs: &dyn crate::atomic::AtomicFs) -> Result { + let scratch_generation = photocraft_raster::spill::read_error_generation(); let canonical_dir = bundle_root(dir)?; let dir = canonical_dir.as_path(); // Held until the end of the save: listing, writing, publishing and cleanup (#4957). @@ -1145,7 +1155,7 @@ impl PcraftWriter { Object::Blob(_) => stats.blobs_written += 1, } let compressed = obj.compressed(compressor.get_or_insert_with(Compressor::new)); - photocraft_raster::spill::check_integrity().map_err(FormatError::corrupt)?; + scratch_ok(doc, scratch_generation)?; write_bundle_file(dir, &object_path, &compressed, fs)?; let written = path_signature(&object_path)?; if let Some(cache) = &mut self.verified_directory { @@ -1182,7 +1192,7 @@ impl PcraftWriter { confirm_flushed(&folder, &folder)?; } } - photocraft_raster::spill::check_integrity().map_err(FormatError::corrupt)?; + scratch_ok(doc, scratch_generation)?; write_bundle_file(dir, &dir.join(MANIFEST), &p.manifest, fs)?; // Omitted previews belong to the previous manifest until the new one commits. // After commit, a locked leftover is only housekeeping, just like unused objects. diff --git a/crates/format/tests/scratch_retry.rs b/crates/format/tests/scratch_retry.rs index 1bb06110ec..3d8a32f540 100644 --- a/crates/format/tests/scratch_retry.rs +++ b/crates/format/tests/scratch_retry.rs @@ -21,8 +21,8 @@ fn retry_after_failed_hashing_never_reuses_placeholder_hashes() { doc.layers.push(layer); spill::settle(); assert_eq!(spill::stats().resident_bytes, 0); - let path = std::fs::read_dir(&dir).unwrap().filter_map(Result::ok).map(|e| e.path()).find(|p| p.extension().is_some_and(|e| e == "scratch")).unwrap(); - let mut file = std::fs::OpenOptions::new().read(true).write(true).open(path).unwrap(); + let mut file = spill::scratch_handle_for_tests().unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); let mut good = Vec::new(); file.read_to_end(&mut good).unwrap(); file.seek(SeekFrom::Start(0)).unwrap(); diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 33b0ec7502..6303ebf0b7 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -388,14 +388,15 @@ pub fn import_for_open(name: &str, bytes: &[u8], opts: &ImportOptions) -> Result /// [`import_for_open`] with cancellation and progress, shared with [`import_with_options_and_interrupt`]. pub fn import_for_open_with(name: &str, bytes: &[u8], opts: &ImportOptions, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> { photocraft_compose::discard_unreadable_pixel_caches(); - photocraft_raster::spill::check_integrity().map_err(IoError::Unsupported)?; let scratch_generation = photocraft_raster::spill::read_error_generation(); ctl.check().map_err(|_| IoError::Cancelled)?; let mut damaged = false; let result = import_stages(name, bytes, ctl, opts, &mut damaged)?; ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(1.0); + // The imported document's own tiles, and anything that failed or recovered meanwhile. photocraft_raster::spill::check_since(scratch_generation).map_err(IoError::Unsupported)?; + result.document.scratch_health().map_err(IoError::Unsupported)?; Ok((result, damaged)) } @@ -603,10 +604,11 @@ pub fn export(doc: &Document, name_or_ext: &str, opts: &ExportOptions) -> Result pub fn export_with(doc: &Document, name_or_ext: &str, opts: &ExportOptions, ctl: &photocraft_raster::Interrupt) -> Result { ctl.check().map_err(|_| IoError::Cancelled)?; photocraft_compose::discard_unreadable_pixel_caches(); - photocraft_raster::spill::check_integrity().map_err(IoError::Unsupported)?; + doc.scratch_health().map_err(IoError::Unsupported)?; let scratch_generation = photocraft_raster::spill::read_error_generation(); let r = export_stages(doc, name_or_ext, opts, ctl)?; photocraft_raster::spill::check_since(scratch_generation).map_err(IoError::Unsupported)?; + doc.scratch_health().map_err(IoError::Unsupported)?; ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(1.0); Ok(r) diff --git a/crates/ops/src/tiles.rs b/crates/ops/src/tiles.rs index dd813a897d..64da14929e 100644 --- a/crates/ops/src/tiles.rs +++ b/crates/ops/src/tiles.rs @@ -11,40 +11,10 @@ pub(crate) struct Tiles { bytes: u128, } -pub(crate) fn surfaces(doc: &Document, mut visit: impl FnMut(&Surface)) { - for (_, _, layer) in doc.walk() { - if let Some(surface) = layer.surface() { - visit(surface); - } - if let Some(mask) = &layer.mask { - visit(&mask.surface); - } - if let Some(cache) = &layer.fill_cache { - visit(&cache.surface); - } - if let LayerContent::Smart(smart) = &layer.content - && let Some(mask) = &smart.filter_mask - { - visit(&mask.surface); - } - if let Some(video) = &layer.video { - // Undo retains the whole clip, not only the displayed frame. Visit aliases too: - // Tiles tracks every owner and counts their shared allocations only once. - for frame in video.frames.iter().chain(video.original_frames.iter().flatten()) { - visit(frame); - } - } - } - for channel in doc.channels.iter().chain(&doc.quick_mask) { - visit(&channel.surface); - } - // A pattern fill or layer style copies its pattern into the document. - for pattern in &doc.patterns { - visit(&pattern.surface); - } - if let Some(selection) = &doc.selection { - visit(selection); - } +pub(crate) fn surfaces(doc: &Document, visit: impl FnMut(&Surface)) { + // Undo retains the whole clip, not only the displayed frame. Video aliases are visited + // too: Tiles tracks every owner and counts their shared allocations only once. + doc.for_each_surface(visit); } /// Every shared allocation `doc` holds that history can retain, as `visit(address, length)`: diff --git a/crates/raster/src/lib.rs b/crates/raster/src/lib.rs index 4ba7d45ee7..994c02c57c 100644 --- a/crates/raster/src/lib.rs +++ b/crates/raster/src/lib.rs @@ -129,6 +129,14 @@ impl Tile { let placeholder = if guard.is_none() { vec![0; self.len()] } else { Vec::new() }; TileBytesMut(guard, placeholder) } + /// `Err` while this tile's scratch copy is unreadable (its bytes read as a placeholder). + /// Free when no tile in the process has failed. + pub fn scratch_health(&self) -> Result<(), String> { + if !spill::any_failed() { + return Ok(()); + } + self.cell.read_error().map_or(Ok(()), Err) + } /// Fallible pixel access for callers that can propagate a scratch read failure. pub fn try_bytes(&self) -> Result, String> { let bytes = self.bytes(); @@ -451,9 +459,27 @@ impl Surface { let generation = spill::read_error_generation(); self.read_region_into(r, &mut out); spill::check_since(generation).map_err(AllocationError::ScratchRead)?; + self.region_health(r).map_err(AllocationError::ScratchRead)?; Ok(out) } + /// `Err` if any stored tile of this surface is unreadable. Free when no tile in the + /// process has failed. + pub fn scratch_health(&self) -> Result<(), String> { + if !spill::any_failed() { + return Ok(()); + } + self.tiles.values().try_for_each(|t| t.scratch_health()) + } + + /// [`Surface::scratch_health`] for the tiles overlapping `r` only. + pub fn region_health(&self, r: Rect) -> Result<(), String> { + if !spill::any_failed() { + return Ok(()); + } + r.tiles().filter_map(|c| self.tiles.get(&c)).try_for_each(|t| t.scratch_health()) + } + /// Reads a region as encoded interleaved bytes with fallible allocation. pub fn try_to_interleaved(&self, r: Rect) -> Result, AllocationError> { let bpp = self.format.bytes_per_pixel(); diff --git a/crates/raster/src/scratch_file.rs b/crates/raster/src/scratch_file.rs index 2df4d82f33..2a4d4d1302 100644 --- a/crates/raster/src/scratch_file.rs +++ b/crates/raster/src/scratch_file.rs @@ -158,6 +158,11 @@ impl ScratchFile { }) } + /// Another handle to the open file (the Unix one has no name), for fault-injection tests. + pub(crate) fn duplicate_handle(&self) -> std::io::Result { + self.main.try_clone() + } + pub fn path(&self) -> &Path { &self.path } diff --git a/crates/raster/src/spill.rs b/crates/raster/src/spill.rs index 7bd09c7f58..efdccb5c1c 100644 --- a/crates/raster/src/spill.rs +++ b/crates/raster/src/spill.rs @@ -17,7 +17,8 @@ //! //! Failures never panic: a scratch write that fails keeps the tile in memory and turns spilling //! off (reported in [`SpillStats::last_error`]). A failed read retains its disk extent and -//! poisons the tile: edits and saves must check [`check_integrity`] before committing. The +//! poisons the tile: edits and saves check the health of the document they publish, plus +//! [`check_since`] for failures that came and went during the operation. The //! infallible display API uses a temporary placeholder, never replacement pixel storage. use std::path::{Path, PathBuf}; @@ -487,25 +488,35 @@ pub fn enabled() -> bool { M.budget.load(Ordering::Relaxed) > 0 } -/// Refuse to publish edited or serialized pixels after a scratch read failure. A failed -/// tile can retry its original extent; changing preferences cannot clear this protection. +/// Whether any live tile in the process is currently unreadable (cheap; the fast path of +/// every per-document health check). +pub fn any_failed() -> bool { + M.failed.load(Ordering::Acquire) > 0 +} + +/// Process-wide status for the UI: some live tile, in any document, is unreadable. Commit +/// guards check only the pixels they publish ([`Tile::scratch_health`](crate::Tile::scratch_health) +/// and the document's health) so one document's failure does not block the others. pub fn check_integrity() -> Result<(), String> { - if M.failed.load(Ordering::Acquire) == 0 { - Ok(()) - } else { + if any_failed() { Err(M.config().last_error.clone().unwrap_or_else(|| "scratch pixels are unreadable; editing and saving are blocked".into())) + } else { + Ok(()) } } -/// Capture before an edit/import/save or derived cache computation. A failed tile might be dropped or repaired -/// before the operation ends; its placeholder must still never be committed as real pixels. -/// Both failure and recovery change this generation, including computations begun during a failure. +/// Capture before an edit/import/save or derived cache computation. A tile that fails or +/// recovers while the operation runs might have fed it placeholder pixels and then been +/// dropped or repaired; its result must still never be committed as real pixels. Both failure +/// and recovery change this generation. Tiles that were already unreadable when the operation +/// began do not change it: callers also check the health of the pixels they read. pub fn read_error_generation() -> u64 { M.read_errors.load(Ordering::Acquire) } +/// Refuse a result if any tile failed or recovered since `generation` was captured. A retry +/// (capturing a new generation) succeeds once the transition is over. pub fn check_since(generation: u64) -> Result<(), String> { - check_integrity()?; if generation == read_error_generation() { Ok(()) } else { @@ -513,6 +524,14 @@ pub fn check_since(generation: u64) -> Result<(), String> { } } +/// A second handle to the current scratch file, for tests that damage or restore its bytes. +/// The Unix file is unlinked, so it cannot be reopened by path. All scratch I/O is positioned, +/// so the shared file offset of a duplicated handle does not affect it. +#[doc(hidden)] +pub fn scratch_handle_for_tests() -> Option { + M.config().file.as_ref().and_then(|f| f.duplicate_handle().ok()) +} + /// Evict down to the budget now, on this thread (tests, and before a measurement). pub fn settle() { let budget = M.budget.load(Ordering::Relaxed); @@ -549,6 +568,10 @@ mod tests { let failed_generation = read_error_generation(); assert!(tile.cell.data.read().unwrap().is_none(), "placeholder must never become stored pixels"); assert!(check_integrity().is_err()); + assert!(tile.scratch_health().is_err(), "the tile reports its own failure"); + assert!(crate::Tile::from_vec(vec![1; 16]).scratch_health().is_ok(), "other tiles stay healthy"); + assert!(tile.try_bytes().is_err()); + assert!(check_since(failed_generation).is_ok(), "re-reading a tile that already failed is not a new transition"); tile.bytes_mut()[0] = 9; assert!(tile.cell.data.read().unwrap().is_none()); assert!(tile.cell.slot.lock().unwrap().is_some(), "a failed mutation must preserve the original extent"); @@ -560,6 +583,7 @@ mod tests { tile.cell.slot.lock().unwrap().as_mut().unwrap().1 = good; assert_eq!(&*tile.try_bytes().unwrap(), &[73; 1024]); assert!(check_integrity().is_ok()); + assert!(tile.scratch_health().is_ok()); assert!(check_since(generation).is_err(), "repairing or dropping a failed tile must not validate an earlier result"); assert!(check_since(failed_generation).is_err(), "recovery must reject a computation begun during the failure"); assert_eq!(tile.cell.evict(&file).unwrap(), 1024); diff --git a/docs/scratch-disks.md b/docs/scratch-disks.md index 22936897e3..6f888ddf4a 100644 --- a/docs/scratch-disks.md +++ b/docs/scratch-disks.md @@ -35,9 +35,15 @@ operations; standalone callers work without a background thread. `sysinfo` is na with its default features disabled and only the `system` feature enabled. An unavailable or full scratch disk retains resident pixels and reports the failure. -A failed read retains its backing extent and blocks editing, cache admission and saving -until the tile is readable again. Recovery can retry the original bytes after the storage -becomes available; zeros from a failed display read must never become saved pixels. +A failed read retains its backing extent and blocks editing, saving and exporting of the +document that holds the tile until it is readable again; other open documents keep working. +Each commit checks the health of its own document (before and after an edit, the document a +job captured, the imported result, the document being saved or exported) and refuses a result +if any tile failed or recovered while it ran; the retry succeeds. Derived-pixel caches never +admit results built from unreadable tiles and are purged once per new failure. Recovery can +retry the original bytes after the storage becomes available; zeros from a failed display +read must never become saved pixels. Limitation: a tile that was already unreadable and is +read from outside the edited document (for example a clipboard copy) is not detected. Scratch storage alone does not make every format, filter or renderer streamable. The native PSD/EXR import and viewport streaming changes build on these guards and memory reservations. From 9eddf1d8cace75e5359c186f4632c99e3746cf6f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 2 Nov 2026 22:31:56 +0100 Subject: [PATCH 5/9] Pause and retry a failed or full scratch disk instead of turning spilling off A scratch write or create failure, or a volume about to drop below max(1 GiB, 5%) free space, now pauses spilling with exponential backoff (1 s doubling to 60 s) instead of disabling it for the session. Tiles stay resident, set_budget keeps the latest budget for the resume, preference changes retry at once, and spill::epoch lets the engine re-apply History's byte limit while paused. spill::set_size_cap adds an explicit size limit; free space comes from sysinfo's disk feature. --- crates/engine/src/jobs.rs | 1 + crates/engine/src/lib.rs | 3 + crates/engine/src/prefs.rs | 20 ++ crates/engine/src/scratch.rs | 3 +- crates/engine/tests/scratch_pause.rs | 54 ++++ crates/raster/Cargo.toml | 4 +- crates/raster/src/spill.rs | 312 ++++++++++++++++++++---- crates/raster/tests/scratch_recovery.rs | 117 +++++++++ docs/scratch-disks.md | 12 +- 9 files changed, 468 insertions(+), 58 deletions(-) create mode 100644 crates/engine/tests/scratch_pause.rs create mode 100644 crates/raster/tests/scratch_recovery.rs diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index dfc7fd39f8..7c64b74fa5 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -825,6 +825,7 @@ impl Session { // The offer belongs to this one dispatch. Early errors drop it locally, including // authorization, validation, floating-selection and admission failures. let live_commit = self.live_commit.take(); + self.sync_scratch_state(); let spec = crate::commands::find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; // Params are named fields: anything but an object (or null, meaning none) is a caller // mistake, not "use every default". diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a228864591..1b370ace46 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -285,6 +285,9 @@ pub struct Session { next_held_open: u64, /// Shared native memory supervision, owned and stopped by the last session using it. scratch_runtime: Option, + /// [`photocraft_raster::spill::epoch`] when History's byte limits were last applied: a + /// scratch disk that pauses or resumes changes the limit ([`Session::sync_scratch_state`]). + scratch_epoch: u64, /// The document before the latest [`Session::edit`] of the running command, which /// [`Session::hint_damage`] checks a hint against. Set by `edit`, taken by `hint_damage`, /// dropped when the command ends. Debug and test builds only. diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 9317c31c30..891f9585c9 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -1351,6 +1351,7 @@ impl Session { pub fn apply_prefs(&mut self) { self.scratch_runtime.get_or_insert_with(crate::scratch::Runtime::default); crate::scratch::configure(self.prefs()); + self.scratch_epoch = photocraft_raster::spill::epoch(); let n = self.prefs().performance.history_states.max(1) as usize; let bytes = self.prefs().performance.history_cap_bytes(); let budget = self.prefs().performance.effect_cache_mb as usize; @@ -1368,6 +1369,25 @@ impl Session { crate::plugin_cmds::sync_prefs(self); } + /// Re-apply History's byte limit after the scratch disk paused (a write, create or + /// free-space failure) or resumed since it was last applied: while spilling is paused, + /// History again bounds the pixel memory it holds, as with no scratch disk. Runs before + /// every command; a single atomic load when nothing changed. + pub(crate) fn sync_scratch_state(&mut self) { + let epoch = photocraft_raster::spill::epoch(); + if self.scratch_epoch == epoch { + return; + } + self.scratch_epoch = epoch; + let bytes = self.prefs().performance.history_cap_bytes(); + for st in &mut self.docs { + if st.history.max_bytes != bytes { + st.history.max_bytes = bytes; + st.trim_history(); + } + } + } + /// Everything persisted as one JSON document: the preferences plus `colorSettings`. pub fn prefs_to_json(&self) -> String { serde_json::to_string_pretty(&self.prefs_value()).unwrap_or_default() diff --git a/crates/engine/src/scratch.rs b/crates/engine/src/scratch.rs index 79d67ab0db..486efbe9b3 100644 --- a/crates/engine/src/scratch.rs +++ b/crates/engine/src/scratch.rs @@ -128,7 +128,8 @@ pub(crate) fn configure(prefs: &Preferences) { .iter() .find(|d| d.enabled && !d.path.trim().is_empty()) .map(|d| if d.path.trim() == "(system temp)" { std::env::temp_dir() } else { std::path::PathBuf::from(d.path.trim()) }); - // An unusable directory disables eviction without dropping resident pixels. + // An unusable or full directory pauses eviction without dropping resident pixels and + // is retried with backoff; History's byte limit applies meanwhile (sync_scratch_state). // The reason is exposed in ui.inspect and the application's status bar. let tiles = if std::env::var_os("PHOTOCRAFT_TILE_BUDGET_MB").is_some() { prefs.performance.tile_budget_bytes() diff --git a/crates/engine/tests/scratch_pause.rs b/crates/engine/tests/scratch_pause.rs new file mode 100644 index 0000000000..d8990d504c --- /dev/null +++ b/crates/engine/tests/scratch_pause.rs @@ -0,0 +1,54 @@ +//! A scratch disk that fills up pauses spilling; History's byte limit applies again until it +//! resumes, so undo states cannot pile up in memory unbounded meanwhile. +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_doc::{Document, Layer}; +use photocraft_engine::Session; +use photocraft_geom::{Size, TileCoord}; +use photocraft_raster::spill; +use serde_json::json; + +#[test] +fn paused_scratch_disk_restores_the_history_limit() { + let dir = std::env::temp_dir().join(format!("photocraft-engine-scratch-pause-{}", std::process::id())); + let mut session = Session::new(); + session.edit_prefs(|p| { + p.scratch_disks.disks = vec![photocraft_engine::prefs::ScratchDisk { path: dir.to_string_lossy().into(), enabled: true }]; + p.performance.memory_usage_mb = 64; + }); + assert!(spill::enabled()); + let mut doc = Document::new("Pause fixture", Size::new(1024, 256), ColorMode::Rgb, SampleType::U8); + let mut layer = Layer::raster("Pixels", PixelFormat::RGBA8); + let id = layer.id; + for i in 0..4 { + for (j, b) in layer.surface_mut().unwrap().tile_mut(TileCoord::new(i, 0)).bytes_mut().iter_mut().enumerate() { + *b = (j as u32).wrapping_mul(31).wrapping_add(i as u32 * 7) as u8; + } + } + doc.layers.push(layer); + session.add_document(doc, None); + session.select_layer(id).unwrap(); + assert_eq!(session.active().unwrap().history.max_bytes, 0, "spilling: only History States bound History"); + + // The disk "fills up": a size limit below what eviction needs pauses spilling. + spill::set_size_cap(Some(1)); + spill::configure(Some(&dir), 1).unwrap_or_default(); + spill::settle(); + assert!(spill::paused() && !spill::enabled(), "{:?}", spill::stats()); + let limit = session.prefs().performance.history_budget_bytes(); + assert!(limit > 0); + session.execute("edit.fill", json!({"color": "#204060"})).unwrap(); + assert_eq!(session.active().unwrap().history.max_bytes, limit, "a paused disk must restore History's byte limit"); + assert!(session.active().unwrap().memory_bytes() <= limit); + + // Room again: spilling resumes and the next command lifts the limit again. + spill::set_size_cap(None); + assert!(spill::enabled() && !spill::paused(), "{:?}", spill::stats()); + session.execute("edit.fill", json!({"color": "#406080"})).unwrap(); + assert_eq!(session.active().unwrap().history.max_bytes, 0); + assert!(session.undo()); + assert!(session.undo()); + + drop(session); + spill::configure(None, 0).unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml index e84d963978..e7f5af6420 100644 --- a/crates/raster/Cargo.toml +++ b/crates/raster/Cargo.toml @@ -15,10 +15,10 @@ crc32fast = "1" lz4_flex = { version = "0.11", default-features = false, features = ["std", "safe-encode", "safe-decode"] } # Native only: converting a region's tiles is independent per tile, so it runs on all cores; -# sysinfo reads the physical RAM size for the memory limit. +# sysinfo reads the physical RAM size for the memory limit and the scratch volume's free space. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rayon = { workspace = true } -sysinfo = { version = "0.37", default-features = false, features = ["system"] } +sysinfo = { version = "0.37", default-features = false, features = ["system", "disk"] } [dev-dependencies] proptest = { workspace = true } diff --git a/crates/raster/src/spill.rs b/crates/raster/src/spill.rs index efdccb5c1c..ae0b56f3a0 100644 --- a/crates/raster/src/spill.rs +++ b/crates/raster/src/spill.rs @@ -15,8 +15,10 @@ //! - **Off by default.** Until [`configure`] sets a directory and a budget nothing is evicted //! (tests, the web build). //! -//! Failures never panic: a scratch write that fails keeps the tile in memory and turns spilling -//! off (reported in [`SpillStats::last_error`]). A failed read retains its disk extent and +//! Failures never panic: a scratch write or file creation that fails, or a volume running low +//! on free space, keeps the tile in memory and pauses spilling (reported in +//! [`SpillStats::last_error`]); it is retried with exponential backoff and resumes on its own. +//! [`epoch`] tells owners of memory caps (history) to re-apply them meanwhile. A failed read retains its disk extent and //! poisons the tile: edits and saves check the health of the document they publish, plus //! [`check_since`] for failures that came and went during the operation. The //! infallible display API uses a temporary placeholder, never replacement pixel storage. @@ -24,6 +26,7 @@ use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard, Weak}; +use std::time::{Duration, Instant}; use crate::scratch_file::{Extent, ScratchFile}; @@ -220,8 +223,18 @@ struct Manager { read_errors: AtomicU64, resident: AtomicUsize, live: AtomicUsize, - /// Pixel bytes to keep resident; 0 = spilling off. + /// Pixel bytes to keep resident; 0 = spilling off or paused. budget: AtomicUsize, + /// Spilling is paused after a write, create or free-space failure ([`Config::paused`]). + paused: AtomicBool, + /// Changes whenever spilling turns on or off, so owners of memory caps re-apply them. + epoch: AtomicU64, + /// Scratch bytes allowed before the volume would run low or the size cap is reached. + space_limit: AtomicU64, + /// Re-read the volume's free space once the scratch file grows past this. + next_space_check: AtomicU64, + /// A sweep wrote successfully since the last resume: reset the retry backoff. + recovering: AtomicBool, registry: Mutex, config: Mutex, evictions: AtomicU64, @@ -239,16 +252,40 @@ struct Config { /// Opened at configuration time; startup also reaps abandoned Unix files. file: Option>, last_error: Option, + /// The budget [`configure`] / [`set_budget`] asked for; restored when a pause ends. + budget: usize, + paused: Option, + /// Delay before the next retry; doubles per failed retry up to [`RETRY_MAX`]. + backoff: Duration, + /// Explicit scratch size limit ([`set_size_cap`]); the free-space reserve always applies. + size_cap: Option, } +struct Pause { + message: String, + retry_at: Instant, +} + +const RETRY_FIRST: Duration = Duration::from_secs(1); +const RETRY_MAX: Duration = Duration::from_secs(60); +/// Re-check free space after this much scratch growth. +const SPACE_CHECK_EVERY: u64 = 64 << 20; +/// Leave at least max(1 GiB, 5 % of the volume) free for the system and other programs. +const RESERVE_MIN: u64 = 1 << 30; + static M: Manager = Manager { failed: AtomicUsize::new(0), read_errors: AtomicU64::new(0), resident: AtomicUsize::new(0), live: AtomicUsize::new(0), budget: AtomicUsize::new(0), + paused: AtomicBool::new(false), + epoch: AtomicU64::new(0), + space_limit: AtomicU64::new(u64::MAX), + next_space_check: AtomicU64::new(0), + recovering: AtomicBool::new(false), registry: Mutex::new(Registry { cells: Vec::new(), hand: 0 }), - config: Mutex::new(Config { dir: None, file: None, last_error: None }), + config: Mutex::new(Config { dir: None, file: None, last_error: None, budget: 0, paused: None, backoff: RETRY_FIRST, size_cap: None }), evictions: AtomicU64::new(0), reloads: AtomicU64::new(0), written: AtomicU64::new(0), @@ -274,28 +311,118 @@ impl Manager { self.config().last_error = Some(msg); } - /// The scratch file, created on first use; `None` (and spilling off) if it can't be. + /// Set the active budget, bumping [`epoch`] when spilling turns on or off. + fn set_active(&self, budget: usize) { + let old = self.budget.swap(budget, Ordering::AcqRel); + if (old > 0) != (budget > 0) { + self.epoch.fetch_add(1, Ordering::AcqRel); + } + } + + /// Pause spilling after a failure: every tile stays in memory (owners re-apply their + /// memory caps through [`epoch`]) and a retry is scheduled with exponential backoff. + fn pause(&self, c: &mut Config, reason: &str) { + let wait = c.backoff; + c.backoff = c.backoff.saturating_mul(2).min(RETRY_MAX); + let message = format!("{reason}; spilling is paused (tiles stay in memory), retrying in {} s", wait.as_secs()); + log_error(&message); + c.last_error = Some(message.clone()); + c.paused = Some(Pause { message, retry_at: Instant::now().checked_add(wait).unwrap_or_else(Instant::now) }); + self.recovering.store(false, Ordering::Relaxed); + self.paused.store(true, Ordering::Release); + self.set_active(0); + } + + /// End a pause: the directory is usable and has room again. + fn resume(&self, c: &mut Config) { + if let Some(p) = c.paused.take() + && c.last_error.as_deref() == Some(p.message.as_str()) + { + c.last_error = None; + } + self.paused.store(false, Ordering::Release); + self.recovering.store(true, Ordering::Relaxed); + self.set_active(c.budget); + } + + /// Open the scratch file and check its volume's room; pause (and say why) if either fails. + /// The caller holds the config lock. Returns whether spilling can go ahead. + fn prepare(&self, c: &mut Config) -> bool { + let Some(dir) = c.dir.clone() else { return false }; + if c.file.is_none() { + match std::fs::create_dir_all(&dir).and_then(|()| ScratchFile::create(&dir)) { + Ok(f) => c.file = Some(Arc::new(f)), + Err(e) => { + self.pause(c, &format!("could not create a scratch file in {}: {e}", dir.display())); + return false; + } + } + } + let used = c.file.as_ref().map_or(0, |f| f.used()); + refresh_space(c, &dir, used); + if used >= self.space_limit.load(Ordering::Relaxed) { + let msg = no_room(&dir, c.size_cap); + self.pause(c, &msg); + return false; + } + true + } + + /// Retry a paused scratch disk once its backoff has elapsed. Cheap when not paused. + fn retry(&self) { + if !self.paused.load(Ordering::Acquire) { + return; + } + let mut c = match self.config.try_lock() { + Ok(c) => c, + Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(), + // Someone else is configuring or retrying. + Err(std::sync::TryLockError::WouldBlock) => return, + }; + let due = c.paused.as_ref().is_some_and(|p| Instant::now() >= p.retry_at); + if !due { + return; + } + if c.dir.is_none() || c.budget == 0 { + c.paused = None; + self.paused.store(false, Ordering::Release); + return; + } + if self.prepare(&mut c) { + self.resume(&mut c); + } + } + + /// The scratch file, if spilling is on and the volume still has room. fn file(&self) -> Option> { let mut c = self.config(); - if let Some(f) = &c.file { - return Some(f.clone()); + if self.budget.load(Ordering::Relaxed) == 0 { + return None; } - let dir = c.dir.clone()?; - match ScratchFile::create(&dir) { - Ok(f) => { - let f = Arc::new(f); - c.file = Some(f.clone()); - Some(f) - } - Err(e) => { - let msg = format!("could not create a scratch file in {}: {e}; spilling is off", dir.display()); - log_error(&msg); - c.last_error = Some(msg); - c.dir = None; - self.budget.store(0, Ordering::Relaxed); - None - } + if c.file.is_none() && !self.prepare(&mut c) { + return None; } + c.file.clone() + } + + /// Whether the scratch file may grow further; re-reads free space every + /// [`SPACE_CHECK_EVERY`] bytes and pauses spilling when the volume runs low. + fn has_room(&self, file: &ScratchFile) -> bool { + let used = file.used(); + if used < self.next_space_check.load(Ordering::Relaxed) && used < self.space_limit.load(Ordering::Relaxed) { + return true; + } + let mut c = self.config(); + let Some(dir) = c.dir.clone() else { return false }; + refresh_space(&c, &dir, used); + if used < self.space_limit.load(Ordering::Relaxed) { + return true; + } + if c.paused.is_none() { + let msg = no_room(&dir, c.size_cap); + self.pause(&mut c, &msg); + } + false } /// Evict until resident memory is at most `target` or `max_scan` cells were looked at. @@ -338,25 +465,68 @@ impl Manager { } } for cell in victims { + if !self.has_room(&file) { + return freed; + } match cell.evict(&file) { Ok(n) => freed += n, Err(e) => { - // Disk full or gone: keep everything in memory from now on. - self.budget.store(0, Ordering::Relaxed); - self.error(format!("{e}; spilling is off")); + // Disk full or gone: keep tiles in memory until a retry succeeds. + let mut c = self.config(); + if c.paused.is_none() { + self.pause(&mut c, &e); + } return freed; } } } } + if freed > 0 && self.recovering.swap(false, Ordering::Relaxed) { + self.config().backoff = RETRY_FIRST; + } freed } } +/// Free space on the volume holding `dir`, minus the reserve, sets how far the file may grow. +fn refresh_space(c: &Config, dir: &Path, used: u64) { + let room = free_space(dir).map_or(u64::MAX, |(available, total)| used.saturating_add(available.saturating_sub(RESERVE_MIN.max(total / 20)))); + let limit = c.size_cap.map_or(room, |cap| cap.min(room)); + M.space_limit.store(limit, Ordering::Relaxed); + M.next_space_check.store(used.saturating_add(SPACE_CHECK_EVERY), Ordering::Relaxed); +} + +fn no_room(dir: &Path, cap: Option) -> String { + match cap { + Some(cap) => format!("scratch disk {} reached its size limit ({} MB) or is low on free space", dir.display(), cap >> 20), + None => format!("scratch disk {} is low on free space", dir.display()), + } +} + +/// (available, total) bytes of the volume holding `dir`: the mount point that is its longest +/// prefix. `None` if unknown, which disables only the free-space check, not spilling. +#[cfg(not(target_arch = "wasm32"))] +fn free_space(dir: &Path) -> Option<(u64, u64)> { + let dir = std::fs::canonicalize(dir).ok()?; + let disks = sysinfo::Disks::new_with_refreshed_list_specifics(sysinfo::DiskRefreshKind::nothing().with_storage()); + disks + .list() + .iter() + .filter(|d| dir.starts_with(d.mount_point())) + .max_by_key(|d| d.mount_point().as_os_str().len()) + .map(|d| (d.available_space(), d.total_space())) +} + +#[cfg(target_arch = "wasm32")] +fn free_space(_dir: &Path) -> Option<(u64, u64)> { + None +} + /// Called after resident memory grew. fn maybe_evict() { let budget = M.budget.load(Ordering::Relaxed); if budget == 0 { + M.retry(); return; } let resident = M.resident.load(Ordering::Relaxed); @@ -392,8 +562,10 @@ impl Drop for Maintenance { } } -/// One bounded clock pass. The caller owns scheduling and shutdown. +/// One bounded clock pass, plus a due retry of a paused scratch disk. The caller owns +/// scheduling and shutdown. pub fn maintain_budget() -> usize { + M.retry(); let budget = M.budget.load(Ordering::Relaxed); if budget == 0 || M.resident.load(Ordering::Relaxed) <= budget { return 0; @@ -401,49 +573,80 @@ pub fn maintain_budget() -> usize { M.sweep(low_water(budget), 4096) } -/// Turn the scratch disk on (`dir` and a non-zero `budget_bytes`) or off. Tiles already on disk -/// stay readable either way. Changing the directory starts a new scratch file there; the old one -/// is deleted once its last tile is freed or changed. +/// Change the memory budget of a configured scratch disk (the memory limit moved). A paused +/// disk keeps its pause and resumes with this budget. pub fn set_budget(budget_bytes: usize) { - if enabled() { - M.budget.store(budget_bytes.max(1), Ordering::Relaxed); - maybe_evict(); + let mut c = M.config(); + if c.dir.is_none() || c.budget == 0 { + return; } + c.budget = budget_bytes.max(1); + if c.paused.is_none() { + M.set_active(c.budget); + } + drop(c); + maybe_evict(); } +/// Limit how large the scratch file may grow (`None`: only the free-space reserve applies). +/// Reaching the limit pauses spilling like a full disk; changing it retries a paused disk now. +pub fn set_size_cap(cap: Option) { + let mut c = M.config(); + c.size_cap = cap; + M.next_space_check.store(0, Ordering::Relaxed); + if let Some(p) = &mut c.paused { + p.retry_at = Instant::now(); + c.backoff = RETRY_FIRST; + } + drop(c); + M.retry(); +} + +/// Turn the scratch disk on (`dir` and a non-zero `budget_bytes`) or off. Tiles already on disk +/// stay readable either way. Changing the directory starts a new scratch file there; the old one +/// is deleted once its last tile is freed or changed. A directory that can't be used is kept and +/// retried with backoff (spilling stays paused meanwhile); the error is returned and reported. pub fn configure(dir: Option<&Path>, budget_bytes: usize) -> Result<(), String> { let mut c = M.config(); let dir = dir.filter(|_| budget_bytes > 0).map(Path::to_path_buf); - if let Some(d) = &dir - && let Err(e) = std::fs::create_dir_all(d) - { - let msg = format!("scratch disk {}: {e}; spilling is off", d.display()); - c.dir = None; + if dir != c.dir { c.file = None; - c.last_error = Some(msg.clone()); - M.budget.store(0, Ordering::Relaxed); - return Err(msg); - } - if dir != c.dir || (dir.is_some() && c.file.is_none()) { - c.file = match dir.as_deref().map(ScratchFile::create).transpose() { - Ok(file) => file.map(Arc::new), - Err(e) => { - let msg = format!("scratch disk: {e}; spilling is off"); - c.dir = None; - c.last_error = Some(msg.clone()); - M.budget.store(0, Ordering::Relaxed); - return Err(msg); - } - }; } c.dir = dir.clone(); + c.budget = if dir.is_some() { budget_bytes } else { 0 }; + c.backoff = RETRY_FIRST; + c.paused = None; c.last_error = None; - M.budget.store(if dir.is_some() { budget_bytes } else { 0 }, Ordering::Relaxed); + M.paused.store(false, Ordering::Release); + M.next_space_check.store(0, Ordering::Relaxed); + if dir.is_some() && !M.prepare(&mut c) { + return Err(c.last_error.clone().unwrap_or_default()); + } + M.set_active(c.budget); drop(c); maybe_evict(); Ok(()) } +/// Changes whenever spilling turns on or off, including a pause after a disk error and the +/// resume after it. Owners of memory caps that depend on [`enabled`] re-apply them on a change. +pub fn epoch() -> u64 { + M.epoch.load(Ordering::Acquire) +} + +/// Whether spilling is paused after a scratch disk failure (it retries on its own). +pub fn paused() -> bool { + M.paused.load(Ordering::Acquire) +} + +/// Retry a paused scratch disk on the next maintenance pass instead of after its backoff. +#[doc(hidden)] +pub fn retry_now_for_tests() { + if let Some(p) = &mut M.config().paused { + p.retry_at = Instant::now(); + } +} + /// Where the tile memory stands. #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] #[serde(rename_all = "camelCase")] @@ -461,6 +664,8 @@ pub struct SpillStats { /// Compressed bytes written to scratch so far. pub written_bytes: u64, pub last_error: Option, + /// Spilling is paused after a scratch disk failure and will be retried. + pub paused: bool, } pub fn stats() -> SpillStats { @@ -475,6 +680,7 @@ pub fn stats() -> SpillStats { reloads: M.reloads.load(Ordering::Relaxed), written_bytes: M.written.load(Ordering::Relaxed), last_error: c.last_error.clone(), + paused: c.paused.is_some(), } } diff --git a/crates/raster/tests/scratch_recovery.rs b/crates/raster/tests/scratch_recovery.rs new file mode 100644 index 0000000000..fc4e91bfc7 --- /dev/null +++ b/crates/raster/tests/scratch_recovery.rs @@ -0,0 +1,117 @@ +//! Scratch disk failures pause spilling instead of turning it off for the session: tiles stay +//! in memory, the pause is retried with backoff and spilling resumes once the disk has room. +//! +//! One test function: the spill manager is process-wide, so its steps must not interleave. + +use photocraft_color::{ColorMode, PixelFormat, SampleType}; +use photocraft_geom::{Rect, TILE_SIZE, TileCoord}; +use photocraft_raster::{Surface, spill}; + +const TILE_BYTES: usize = (TILE_SIZE * TILE_SIZE) as usize * 4; + +fn rgba8() -> PixelFormat { + PixelFormat { mode: ColorMode::Rgb, sample: SampleType::U8, alpha: true } +} + +/// Incompressible bytes, different per seed. +fn noise(seed: u32, len: usize) -> Vec { + let mut x = seed.wrapping_mul(2_654_435_761).max(1); + (0..len) + .map(|_| { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + x as u8 + }) + .collect() +} + +fn surface(seed: u32, n: i32) -> Surface { + let mut s = Surface::new(rgba8()); + for i in 0..n { + let r = Rect::from_xywh(i * TILE_SIZE, 0, TILE_SIZE as u32, TILE_SIZE as u32); + s.write_interleaved(r, &noise(seed + i as u32, TILE_BYTES)); + } + s +} + +fn check(s: &Surface, seed: u32, n: i32) { + for i in 0..n { + let t = s.tile(TileCoord { tx: i, ty: 0 }).unwrap(); + assert!(*t.bytes() == *noise(seed + i as u32, TILE_BYTES), "tile {i} of seed {seed} changed"); + } +} + +#[test] +fn full_or_missing_scratch_disk_pauses_and_recovers() { + let root = std::env::temp_dir().join(format!("photocraft-scratch-recovery-{}", std::process::id())); + let dir = root.join("scratch"); + let budget = 8 * TILE_BYTES; + spill::configure(Some(&dir), budget).unwrap(); + assert!(spill::enabled() && !spill::paused()); + + // 1. "Disk full": the scratch file reaches its size limit. Spilling pauses, every tile stays + // in memory and readable, and owners of memory caps see the change. + let cap = 16 * TILE_BYTES as u64; + spill::set_size_cap(Some(cap)); + let epoch = spill::epoch(); + let a = surface(1, 64); + spill::settle(); + let st = spill::stats(); + assert!(st.paused && !spill::enabled(), "{st:?}"); + assert_ne!(spill::epoch(), epoch, "pausing must tell owners to re-apply their caps"); + assert!(st.resident_bytes > budget, "tiles must stay in memory while paused: {st:?}"); + assert!(st.scratch_bytes < cap + 2 * TILE_BYTES as u64, "the file grew past its limit: {st:?}"); + assert!(st.last_error.as_deref().is_some_and(|e| e.contains("paused") && e.contains("retrying in 1 s")), "{st:?}"); + check(&a, 1, 64); + + // 2. A retry while the disk is still full pauses again, with a longer backoff; a budget + // change (the memory limit moved) does not end the pause. + spill::retry_now_for_tests(); + spill::maintain_budget(); + let st = spill::stats(); + assert!(st.paused && !spill::enabled(), "{st:?}"); + assert!(st.last_error.as_deref().is_some_and(|e| e.contains("retrying in 2 s")), "{st:?}"); + spill::set_budget(budget); + assert!(!spill::enabled(), "set_budget must not bypass the pause"); + + // 3. Room again: the next retry resumes spilling with the latest budget and clears the error. + let epoch = spill::epoch(); + spill::set_size_cap(None); + spill::maintain_budget(); + let st = spill::stats(); + assert!(!st.paused && spill::enabled() && st.budget_bytes == budget && st.last_error.is_none(), "{st:?}"); + assert_ne!(spill::epoch(), epoch); + spill::settle(); + assert!(spill::stats().resident_bytes <= budget, "{:?}", spill::stats()); + check(&a, 1, 64); + drop(a); + + // 4. "Disk gone": the directory can't be created (a file is in the way). Configuring reports + // it and pauses; the directory is kept and retried, and spilling resumes once it works. + let blocked = root.join("blocked"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(&blocked, b"not a directory").unwrap(); + assert!(spill::configure(Some(&blocked), budget).is_err()); + let st = spill::stats(); + assert!(st.paused && !spill::enabled() && st.dir.as_deref() == Some(blocked.as_path()), "{st:?}"); + let b = surface(500, 32); + spill::settle(); + check(&b, 500, 32); + std::fs::remove_file(&blocked).unwrap(); + spill::retry_now_for_tests(); + spill::maintain_budget(); + assert!(spill::enabled() && !spill::paused(), "{:?}", spill::stats()); + spill::settle(); + assert!(spill::stats().resident_bytes <= budget); + check(&b, 500, 32); + + // 5. Cleanup: once spilling is off and the tiles are freed, no scratch file is left behind. + drop(b); + spill::configure(None, 0).unwrap(); + for d in [&dir, &blocked] { + let left: Vec<_> = std::fs::read_dir(d).map(|r| r.flatten().map(|e| e.path()).collect()).unwrap_or_default(); + assert!(left.is_empty(), "scratch files left in {}: {left:?}", d.display()); + } + let _ = std::fs::remove_dir_all(&root); +} diff --git a/docs/scratch-disks.md b/docs/scratch-disks.md index 6f888ddf4a..0ffbcf2a11 100644 --- a/docs/scratch-disks.md +++ b/docs/scratch-disks.md @@ -32,9 +32,17 @@ until the file is dropped or the next sweep. The engine owns a shared, stoppable residency supervisor and joins it when its last session is dropped. `photocraft-raster` only exposes synchronous measurement and bounded eviction operations; standalone callers work without a background thread. `sysinfo` is native-only -with its default features disabled and only the `system` feature enabled. +with its default features disabled and only the `system` (RAM) and `disk` (free space) +features enabled. -An unavailable or full scratch disk retains resident pixels and reports the failure. +An unavailable or full scratch disk never loses pixels or turns spilling off for the session. +A failed scratch write or file creation, or a volume about to run low (free space is checked +when configuring, every 64 MB of scratch growth and on each retry; spilling stops while less +than max(1 GiB, 5% of the volume) would stay free), pauses spilling: tiles stay in memory, +the status bar shows the reason, and History's Memory Usage byte limit applies again from the +next command, as without a scratch disk. The pause is retried after 1 s, doubling up to 60 s; +spilling resumes on its own once the directory is usable and has room, and changing +preferences retries at once. `spill::set_size_cap` adds an explicit scratch size limit. A failed read retains its backing extent and blocks editing, saving and exporting of the document that holds the tile until it is readable again; other open documents keep working. Each commit checks the health of its own document (before and after an edit, the document a From 51e9bed8b7d4c41d813ed2628ced381f9646ef99 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:13:34 +0100 Subject: [PATCH 6/9] Borrow guarded tile bytes in the profile dither from main Main's new profile dither (8a0f959d2) matched on the tile bytes by value inside the per-pixel loop. On this branch Tile::bytes returns a TileBytes guard rather than a slice, so borrow it for the loop instead, and compare the test's tiles as owned bytes since the guard has no Debug or PartialEq. --- crates/engine/src/cmd/color_cmds/profile_dither.rs | 2 +- crates/engine/tests/convert_profile_dither.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/color_cmds/profile_dither.rs b/crates/engine/src/cmd/color_cmds/profile_dither.rs index 8f99f49dbe..4bc5854ac0 100644 --- a/crates/engine/src/cmd/color_cmds/profile_dither.rs +++ b/crates/engine/src/cmd/color_cmds/profile_dither.rs @@ -122,7 +122,7 @@ fn dither_tile(s: &Surface, out: &Surface, t: &Transform, bounds: Rect, c: TileC for (index, dp) in dest.bytes_mut().chunks_exact_mut(ds).enumerate() { let x = x0 + (index % TILE_SIZE as usize) as i32; let y = y0 + (index / TILE_SIZE as usize) as i32; - let sp = match source { + let sp = match &source { Some(bytes) => bytes.get(index * ss..index * ss + ss).ok_or_else(|| bad("a stored tile has invalid sample storage"))?, None => default, }; diff --git a/crates/engine/tests/convert_profile_dither.rs b/crates/engine/tests/convert_profile_dither.rs index 6a78b83956..a8c92e2e5b 100644 --- a/crates/engine/tests/convert_profile_dither.rs +++ b/crates/engine/tests/convert_profile_dither.rs @@ -104,7 +104,7 @@ fn shared_tiles_and_distant_nondefault_pixels_use_actual_coordinates() { let a = converted(document(size, source, SampleType::U8), params(json!(true))); let b = converted(document(size, independent, SampleType::U8), params(json!(true))); assert_eq!(pixels(&a).read_region(a.bounds()), pixels(&b).read_region(b.bounds())); - assert_ne!(pixels(&a).tile(TileCoord::new(0, 0)).unwrap().bytes(), pixels(&a).tile(TileCoord::new(1, 0)).unwrap().bytes()); + assert_ne!(pixels(&a).tile(TileCoord::new(0, 0)).unwrap().bytes().to_vec(), pixels(&a).tile(TileCoord::new(1, 0)).unwrap().bytes().to_vec()); for (x, y) in [(-512, 0), (256_000_003, 256_000_007)] { let px = pixels(&a).pixel(x, y); assert!([55.0, 56.0].contains(&(px[0] * 255.0).round())); From c9478d0501ba6097074e121d8659a376cfee194c Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:54:09 +0100 Subject: [PATCH 7/9] Expect the Windows scratch entry until its delete-on-close handle closes Windows keeps delete-on-close (unlinking an open file is not portable there), so a live scratch file still has a directory entry. Only Unix unlinks it right after opening. Check that the directory is empty once the file is closed on both. --- crates/raster/src/scratch_file.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/raster/src/scratch_file.rs b/crates/raster/src/scratch_file.rs index 2a4d4d1302..bcb46c3d0f 100644 --- a/crates/raster/src/scratch_file.rs +++ b/crates/raster/src/scratch_file.rs @@ -384,9 +384,12 @@ mod tests { // Windows: delete-on-close. Unix: unlinked right after opening. Neither needs Drop. assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "no scratch file outlives an exit without destructors"); let next = ScratchFile::create(&dir).unwrap(); - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "a live scratch file has no directory entry either"); + // Unix unlinks the open file; Windows keeps the entry until the delete-on-close handle closes. + let live_entries = if cfg!(unix) { 0 } else { 1 }; + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), live_entries, "a live scratch file is unlinked on Unix only"); next.write(b"still usable").unwrap(); drop(next); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0, "closing the last scratch file leaves the directory empty"); std::fs::remove_dir(dir).unwrap(); } From ed681787c3a5909d8e55dd7b1ce34b8958d3544f Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 3 Nov 2026 01:16:52 +0100 Subject: [PATCH 8/9] Add a Scratch Size Limit preference and honour the web memory cap in the memory policy --- crates/engine/src/prefs.rs | 6 +++++- crates/engine/src/scratch.rs | 5 ++++- crates/engine/tests/scratch_pause.rs | 6 ++++++ crates/raster/src/spill.rs | 6 ++++++ crates/ui-egui/src/i18n/ar.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nb.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sr.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/prefs/prefs_ui/fields.rs | 4 ++++ docs/scorecard.md | 4 ++-- docs/scratch-disks.md | 7 +++++-- 32 files changed, 57 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 891f9585c9..64cfe59c1e 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -698,11 +698,15 @@ pub struct ScratchDisk { pub struct ScratchDisks { /// Disks for spilling tiles once the memory budget is reached (in priority order). pub disks: Vec, + /// Largest the scratch file may grow, in MB; 0 = no limit. Reaching it pauses spilling + /// like a full disk (History's byte limit applies again). At least max(1 GB, 5 % of the + /// volume) is always left free, whatever this is set to. + pub size_limit_mb: u32, } impl Default for ScratchDisks { fn default() -> Self { - Self { disks: vec![ScratchDisk { path: "(system temp)".into(), enabled: true }] } + Self { disks: vec![ScratchDisk { path: "(system temp)".into(), enabled: true }], size_limit_mb: 0 } } } diff --git a/crates/engine/src/scratch.rs b/crates/engine/src/scratch.rs index 486efbe9b3..6e21d9c1d7 100644 --- a/crates/engine/src/scratch.rs +++ b/crates/engine/src/scratch.rs @@ -118,7 +118,8 @@ mod native { pub(crate) fn configure(prefs: &Preferences) { let budget = photocraft_raster::memory::configure(photocraft_raster::memory::Policy { percent: prefs.performance.memory_usage_percent, - absolute_bytes: u64::from(prefs.performance.memory_usage_mb).saturating_mul(1 << 20), + // The web build's cap applies here too (effective_memory_usage_mb). + absolute_bytes: u64::from(prefs.performance.effective_memory_usage_mb()).saturating_mul(1 << 20), }); #[cfg(not(target_arch = "wasm32"))] { @@ -136,6 +137,8 @@ pub(crate) fn configure(prefs: &Preferences) { } else { usize::try_from(budget.tile_bytes).unwrap_or(usize::MAX) }; + let limit = prefs.scratch_disks.size_limit_mb; + photocraft_raster::spill::set_size_cap((limit > 0).then(|| u64::from(limit).saturating_mul(1 << 20))); let _ = photocraft_raster::spill::configure(dir.as_deref(), tiles); } #[cfg(target_arch = "wasm32")] diff --git a/crates/engine/tests/scratch_pause.rs b/crates/engine/tests/scratch_pause.rs index d8990d504c..3b694f2da2 100644 --- a/crates/engine/tests/scratch_pause.rs +++ b/crates/engine/tests/scratch_pause.rs @@ -16,6 +16,12 @@ fn paused_scratch_disk_restores_the_history_limit() { p.performance.memory_usage_mb = 64; }); assert!(spill::enabled()); + assert_eq!(spill::stats().size_cap_bytes, None, "0 MB = no scratch size limit"); + // Preferences › Scratch Disks › Scratch Size Limit becomes the scratch file's cap. + session.edit_prefs(|p| p.scratch_disks.size_limit_mb = 4096); + assert_eq!(spill::stats().size_cap_bytes, Some(4096 << 20)); + session.edit_prefs(|p| p.scratch_disks.size_limit_mb = 0); + assert_eq!(spill::stats().size_cap_bytes, None); let mut doc = Document::new("Pause fixture", Size::new(1024, 256), ColorMode::Rgb, SampleType::U8); let mut layer = Layer::raster("Pixels", PixelFormat::RGBA8); let id = layer.id; diff --git a/crates/raster/src/spill.rs b/crates/raster/src/spill.rs index ae0b56f3a0..26e06785b7 100644 --- a/crates/raster/src/spill.rs +++ b/crates/raster/src/spill.rs @@ -592,6 +592,9 @@ pub fn set_budget(budget_bytes: usize) { /// Reaching the limit pauses spilling like a full disk; changing it retries a paused disk now. pub fn set_size_cap(cap: Option) { let mut c = M.config(); + if c.size_cap == cap { + return; + } c.size_cap = cap; M.next_space_check.store(0, Ordering::Relaxed); if let Some(p) = &mut c.paused { @@ -666,6 +669,8 @@ pub struct SpillStats { pub last_error: Option, /// Spilling is paused after a scratch disk failure and will be retried. pub paused: bool, + /// Scratch file size limit ([`set_size_cap`]); `None` = only the free-space reserve. + pub size_cap_bytes: Option, } pub fn stats() -> SpillStats { @@ -681,6 +686,7 @@ pub fn stats() -> SpillStats { written_bytes: M.written.load(Ordering::Relaxed), last_error: c.last_error.clone(), paused: c.paused.is_some(), + size_cap_bytes: c.size_cap, } } diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 0b09aae6e1..0c67a91ec6 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -3424,6 +3424,7 @@ curves Smooth تنعيم This document's layers: {needed} of {budget} for layers طبقات هذا المستند: {needed} من {budget} للطبقات This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU تحتاج طبقات هذا المستند إلى {needed} لكنها تستوعب {budget}: تستخدم إعادة رسم المستند بالكامل وحدة المعالجة المركزية GPU Memory (MB, 0 = Automatic) ذاكرة GPU (ميغابايت، 0 = تلقائي) + Scratch Size Limit (MB, 0 = No Limit) حد حجم ملف التسويد (ميغابايت، 0 = بلا حد) {path}: the path is not valid Unicode; save under another name. {path}: المسار ليس Unicode صالحًا؛ احفظ باسم آخر. {name} was changed by another app after it was opened or saved here. تم تغيير {name} بواسطة تطبيق آخر بعد فتحه أو حفظه هنا. Replace it with this document, or cancel and use File › Save As to keep both. استبدله بهذا المستند، أو ألغِ واستخدم ملف › حفظ باسم للاحتفاظ بكليهما. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 460a30973c..530359b4eb 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4023,6 +4023,7 @@ navigator Zoom Zvětšení This document's layers: {needed} of {budget} for layers Vrstvy tohoto dokumentu: {needed} z {budget} pro vrstvy This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Vrstvy tohoto dokumentu potřebují {needed}, ale mohou zabrat {budget}: překreslení celého dokumentu probíhá na CPU GPU Memory (MB, 0 = Automatic) Paměť GPU (MB, 0 = Automaticky) + Scratch Size Limit (MB, 0 = No Limit) Limit velikosti odkládacího disku (MB, 0 = bez limitu) {path}: the path is not valid Unicode; save under another name. {path}: cesta není platný Unicode; uložte soubor pod jiným názvem. {name} was changed by another app after it was opened or saved here. Soubor {name} změnila jiná aplikace poté, co byl zde otevřen nebo uložen. Replace it with this document, or cancel and use File › Save As to keep both. Nahraďte ho tímto dokumentem, nebo zrušte a použijte Soubor › Uložit jako, abyste zachovali obojí. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 00cfb09d84..46e71ed2cf 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -3361,6 +3361,7 @@ curves Smooth Udjævn This document's layers: {needed} of {budget} for layers Dette dokuments lag: {needed} af {budget} til lag This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Dette dokuments lag kræver {needed}, men kan rumme {budget}: gentegninger af hele dokumentet bruger CPU'en GPU Memory (MB, 0 = Automatic) GPU-hukommelse (MB, 0 = automatisk) + Scratch Size Limit (MB, 0 = No Limit) Størrelsesgrænse for arbejdsdisk (MB, 0 = ingen grænse) {path}: the path is not valid Unicode; save under another name. {path}: stien er ikke gyldig Unicode; gem under et andet navn. Replace Erstat {name} was changed by another app after it was opened or saved here. {name} blev ændret af et andet program, efter at den blev åbnet eller gemt her. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 2565608d7a..a56ef68064 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3424,6 +3424,7 @@ curves Smooth Glätten This document's layers: {needed} of {budget} for layers Ebenen dieses Dokuments: {needed} von {budget} für Ebenen This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Die Ebenen dieses Dokuments brauchen {needed}, dürfen aber {budget} belegen: Das ganze Dokument wird auf der CPU neu gezeichnet GPU Memory (MB, 0 = Automatic) GPU-Speicher (MB, 0 = Automatisch) + Scratch Size Limit (MB, 0 = No Limit) Größenlimit für Arbeitsvolume (MB, 0 = kein Limit) {path}: the path is not valid Unicode; save under another name. {path}: Der Dateipfad enthält ungültige Zeichen. Speichere unter einem anderen Namen. {name} was changed by another app after it was opened or saved here. {name} wurde von einer anderen App geändert, nachdem es hier geöffnet oder gespeichert wurde. Replace it with this document, or cancel and use File › Save As to keep both. Ersetze die Datei durch dieses Dokument oder brich ab und nutze Datei › Speichern unter, um beide zu behalten. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bb89361d76..e1deee2890 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4106,6 +4106,7 @@ curves Smooth Εξομάλυνση This document's layers: {needed} of {budget} for layers Επίπεδα αυτού του εγγράφου: {needed} από {budget} για επίπεδα This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Τα επίπεδα αυτού του εγγράφου χρειάζονται {needed} αλλά μπορούν να καταλάβουν {budget}: η επανασχεδίαση όλου του εγγράφου γίνεται στη CPU GPU Memory (MB, 0 = Automatic) Μνήμη GPU (MB, 0 = Αυτόματο) + Scratch Size Limit (MB, 0 = No Limit) Όριο μεγέθους δίσκου προσωρινής αποθήκευσης (MB, 0 = χωρίς όριο) {path}: the path is not valid Unicode; save under another name. {path}: η διαδρομή δεν είναι έγκυρο Unicode· αποθηκεύστε με άλλο όνομα. {name} was changed by another app after it was opened or saved here. Το {name} άλλαξε από άλλη εφαρμογή αφού ανοίχτηκε ή αποθηκεύτηκε εδώ. Replace it with this document, or cancel and use File › Save As to keep both. Αντικαταστήστε το με αυτό το έγγραφο ή ακυρώστε και χρησιμοποιήστε Αρχείο › Αποθήκευση ως για να κρατήσετε και τα δύο. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9daaf9934f..ef0171fe33 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4318,6 +4318,7 @@ navigator Zoom Zoom This document's layers: {needed} of {budget} for layers Capas de este documento: {needed} de {budget} para capas This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Las capas de este documento necesitan {needed} pero pueden ocupar {budget}: los redibujados de todo el documento usan la CPU GPU Memory (MB, 0 = Automatic) Memoria de GPU (MB, 0 = Automático) + Scratch Size Limit (MB, 0 = No Limit) Límite de tamaño del disco de memoria virtual (MB, 0 = sin límite) {path}: the path is not valid Unicode; save under another name. {path}: la ruta no es Unicode válido; guarde con otro nombre. {name} was changed by another app after it was opened or saved here. Otra aplicación cambió {name} después de abrirlo o guardarlo aquí. Replace it with this document, or cancel and use File › Save As to keep both. Reemplázalo con este documento, o cancela y usa Archivo › Guardar como para conservar ambos. diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1cacf9ffea..b08a224b27 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3362,6 +3362,7 @@ curves Smooth Tasoita This document's layers: {needed} of {budget} for layers Tämän asiakirjan tasot: {needed} / {budget} tasoille This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Tämän asiakirjan tasot tarvitsevat {needed}, mutta saavat käyttää {budget}: koko asiakirjan uudelleenpiirrot käyttävät suoritinta GPU Memory (MB, 0 = Automatic) GPU-muisti (Mt, 0 = automaattinen) + Scratch Size Limit (MB, 0 = No Limit) Työlevyn kokoraja (Mt, 0 = ei rajaa) {path}: the path is not valid Unicode; save under another name. {path}: polku ei ole kelvollista Unicodea; tallenna toisella nimellä. Replace Korvaa {name} was changed by another app after it was opened or saved here. Toinen ohjelma on muuttanut tiedostoa {name} sen jälkeen, kun se avattiin tai tallennettiin täällä. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 68cc2853a1..2e07d2fe6a 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3414,6 +3414,7 @@ curves Smooth Lisser This document's layers: {needed} of {budget} for layers Calques de ce document : {needed} sur {budget} pour les calques This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Les calques de ce document ont besoin de {needed} mais peuvent occuper {budget} : le document entier se redessine sur le CPU GPU Memory (MB, 0 = Automatic) Mémoire GPU (Mo, 0 = Automatique) + Scratch Size Limit (MB, 0 = No Limit) Limite de taille du disque de travail (Mo, 0 = aucune limite) {path}: the path is not valid Unicode; save under another name. {path} : le chemin n’est pas un Unicode valide ; enregistrez sous un autre nom. Replace Remplacer {name} was changed by another app after it was opened or saved here. {name} a été modifié par une autre application après avoir été ouvert ou enregistré ici. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 420dc7b850..e9471dc61a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4320,6 +4320,7 @@ cameraRaw Yellow Sárga This document's layers: {needed} of {budget} for layers A dokumentum rétegei: {needed} / {budget} a rétegeknek This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU A dokumentum rétegeinek {needed} kell, de {budget} foglalhatnak: a teljes dokumentum újrarajzolása a CPU-n fut GPU Memory (MB, 0 = Automatic) GPU-memória (MB, 0 = Automatikus) + Scratch Size Limit (MB, 0 = No Limit) Lapozólemez méretkorlátja (MB, 0 = nincs korlát) {path}: the path is not valid Unicode; save under another name. {path}: az elérési út nem érvényes Unicode-szöveg. Mentsd más néven. {name} was changed by another app after it was opened or saved here. A(z) {name} fájlt egy másik alkalmazás módosította, miután itt megnyitották vagy mentették. Replace it with this document, or cancel and use File › Save As to keep both. Cserélje le erre a dokumentumra, vagy válassza a Mégse gombot, és a Fájl › Mentés másként paranccsal tartsa meg mindkettőt. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ea9f0d02be..e47e213b74 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3419,6 +3419,7 @@ curves Smooth Haluskan This document's layers: {needed} of {budget} for layers Layer dokumen ini: {needed} dari {budget} untuk layer This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Layer dokumen ini membutuhkan {needed} tetapi boleh memakai {budget}: penggambaran ulang seluruh dokumen memakai CPU GPU Memory (MB, 0 = Automatic) Memori GPU (MB, 0 = Otomatis) + Scratch Size Limit (MB, 0 = No Limit) Batas ukuran disk scratch (MB, 0 = Tanpa batas) {path}: the path is not valid Unicode; save under another name. {path}: jalur bukan Unicode yang valid; simpan dengan nama lain. Replace Ganti {name} was changed by another app after it was opened or saved here. {name} diubah oleh aplikasi lain setelah dibuka atau disimpan di sini. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 98071d223f..ea03b3c894 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4529,6 +4529,7 @@ shape Appearance Aspetto This document's layers: {needed} of {budget} for layers Livelli di questo documento: {needed} su {budget} per i livelli This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU I livelli di questo documento richiedono {needed} ma possono occupare {budget}: i ridisegni dell'intero documento usano la CPU GPU Memory (MB, 0 = Automatic) Memoria GPU (MB, 0 = Automatico) + Scratch Size Limit (MB, 0 = No Limit) Limite dimensioni disco di memoria virtuale (MB, 0 = nessun limite) {path}: the path is not valid Unicode; save under another name. {path}: il percorso non è Unicode valido; salva con un altro nome. {name} was changed by another app after it was opened or saved here. {name} è stato modificato da un'altra app dopo essere stato aperto o salvato qui. Replace it with this document, or cancel and use File › Save As to keep both. Sostituiscilo con questo documento, oppure annulla e usa File › Salva con nome per tenerli entrambi. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 48f98c0c40..e21697ca86 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4080,6 +4080,7 @@ curves Smooth スムーズ This document's layers: {needed} of {budget} for layers このドキュメントのレイヤー: レイヤー用 {budget} のうち {needed} This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU このドキュメントのレイヤーには {needed} が必要ですが、使えるのは {budget} です: ドキュメント全体の再描画は CPU で行われます GPU Memory (MB, 0 = Automatic) GPU メモリ(MB、0 = 自動) + Scratch Size Limit (MB, 0 = No Limit) 仮想記憶ディスクのサイズ上限(MB、0 = 上限なし) {path}: the path is not valid Unicode; save under another name. {path}: パスが有効な Unicode ではありません。別の名前で保存してください。 Replace 置き換え {name} was changed by another app after it was opened or saved here. {name} は、ここで開くか保存した後に別のアプリで変更されました。 diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 782eef9caa..80c2b28d7c 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3615,6 +3615,7 @@ curves Smooth 매끄럽게 This document's layers: {needed} of {budget} for layers 이 문서의 레이어: 레이어용 {budget} 중 {needed} This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU 이 문서의 레이어에 {needed}가 필요하지만 {budget}만 사용할 수 있습니다: 문서 전체 다시 그리기는 CPU를 사용합니다 GPU Memory (MB, 0 = Automatic) GPU 메모리(MB, 0 = 자동) + Scratch Size Limit (MB, 0 = No Limit) 임시 디스크 크기 제한(MB, 0 = 제한 없음) {path}: the path is not valid Unicode; save under another name. {path}: 경로가 올바른 유니코드가 아닙니다. 다른 이름으로 저장하세요. Replace 대치 {name} was changed by another app after it was opened or saved here. {name}이(가) 여기서 열거나 저장한 뒤 다른 앱에서 변경되었습니다. diff --git a/crates/ui-egui/src/i18n/nb.tsv b/crates/ui-egui/src/i18n/nb.tsv index 85f9a0441a..d7232004b6 100644 --- a/crates/ui-egui/src/i18n/nb.tsv +++ b/crates/ui-egui/src/i18n/nb.tsv @@ -3361,6 +3361,7 @@ curves Smooth Jevn ut This document's layers: {needed} of {budget} for layers Dette dokumentets lag: {needed} av {budget} for lag This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Dette dokumentets lag trenger {needed}, men kan holde {budget}: gjentegning av hele dokumentet bruker CPU-en GPU Memory (MB, 0 = Automatic) GPU-minne (MB, 0 = automatisk) + Scratch Size Limit (MB, 0 = No Limit) Størrelsesgrense for arbeidsdisk (MB, 0 = ingen grense) {path}: the path is not valid Unicode; save under another name. {path}: banen er ikke gyldig Unicode. Lagre under et annet navn. Replace Erstatt {name} was changed by another app after it was opened or saved here. {name} ble endret av et annet program etter at den ble åpnet eller lagret her. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b63cdcdc40..21ef79fdf4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4164,6 +4164,7 @@ curves Smooth Vloeiend maken This document's layers: {needed} of {budget} for layers Lagen van dit document: {needed} van {budget} voor lagen This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU De lagen van dit document hebben {needed} nodig maar mogen {budget} gebruiken: het hele document wordt op de CPU opnieuw getekend GPU Memory (MB, 0 = Automatic) GPU-geheugen (MB, 0 = Automatisch) + Scratch Size Limit (MB, 0 = No Limit) Groottelimiet voor werkschijf (MB, 0 = geen limiet) {path}: the path is not valid Unicode; save under another name. {path}: het pad is geen geldige Unicode; sla op onder een andere naam. {name} was changed by another app after it was opened or saved here. {name} is door een andere app gewijzigd nadat het hier is geopend of bewaard. Replace it with this document, or cancel and use File › Save As to keep both. Vervang het door dit document, of annuleer en gebruik Bestand › Opslaan als om beide te houden. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 98e7dae10f..a470bf1087 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4021,6 +4021,7 @@ curves Smooth Wygładź This document's layers: {needed} of {budget} for layers Warstwy tego dokumentu: {needed} z {budget} na warstwy This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Warstwy tego dokumentu potrzebują {needed}, ale mogą zająć {budget}: odświeżanie całego dokumentu używa CPU GPU Memory (MB, 0 = Automatic) Pamięć GPU (MB, 0 = Automatycznie) + Scratch Size Limit (MB, 0 = No Limit) Limit rozmiaru dysku roboczego (MB, 0 = bez limitu) {path}: the path is not valid Unicode; save under another name. {path}: ścieżka nie jest prawidłowym Unicode; zapisz pod inną nazwą. Replace Zastąp {name} was changed by another app after it was opened or saved here. Plik {name} został zmieniony przez inną aplikację po otwarciu lub zapisaniu go tutaj. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 2ab4bbd172..5f16eea094 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -4204,6 +4204,7 @@ layerLabel No Color Sem cor This document's layers: {needed} of {budget} for layers Camadas deste documento: {needed} de {budget} para camadas This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU As camadas deste documento precisam de {needed} mas podem ocupar {budget}: o documento inteiro é redesenhado na CPU GPU Memory (MB, 0 = Automatic) Memória da GPU (MB, 0 = Automático) + Scratch Size Limit (MB, 0 = No Limit) Limite de tamanho do disco de rascunho (MB, 0 = sem limite) {path}: the path is not valid Unicode; save under another name. {path}: o caminho não é Unicode válido; salve com outro nome. {name} was changed by another app after it was opened or saved here. {name} foi alterado por outro app depois de ser aberto ou salvo aqui. Replace it with this document, or cancel and use File › Save As to keep both. Substitua-o por este documento, ou cancele e use Arquivo › Salvar como para manter os dois. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 2c5ca8e6eb..6ff24a98a5 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3388,6 +3388,7 @@ curves Smooth Сгладить This document's layers: {needed} of {budget} for layers Слои этого документа: {needed} из {budget} для слоёв This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Слоям этого документа нужно {needed}, но занимать они могут {budget}: весь документ перерисовывается на CPU GPU Memory (MB, 0 = Automatic) Память GPU (МБ, 0 = автоматически) + Scratch Size Limit (MB, 0 = No Limit) Предел размера рабочего диска (МБ, 0 = без ограничения) {path}: the path is not valid Unicode; save under another name. {path}: путь не является допустимым Unicode; сохраните под другим именем. Replace Заменить {name} was changed by another app after it was opened or saved here. Файл {name} был изменён другим приложением после того, как его открыли или сохранили здесь. diff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsv index cebead75fb..7354c5cf40 100644 --- a/crates/ui-egui/src/i18n/sr.tsv +++ b/crates/ui-egui/src/i18n/sr.tsv @@ -4473,6 +4473,7 @@ shape Appearance Izgled This document's layers: {needed} of {budget} for layers Slojevi ovog dokumenta: {needed} od {budget} za slojeve This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Slojevima ovog dokumenta treba {needed}, a smeju da zauzmu {budget}: ceo dokument se ponovo iscrtava na CPU-u GPU Memory (MB, 0 = Automatic) GPU memorija (MB, 0 = Automatski) + Scratch Size Limit (MB, 0 = No Limit) Ograničenje veličine radnog diska (MB, 0 = bez ograničenja) {path}: the path is not valid Unicode; save under another name. {path}: putanja nije ispravan Unicode; sačuvajte pod drugim imenom. {name} was changed by another app after it was opened or saved here. Datoteku {name} je izmenila druga aplikacija nakon što je ovde otvorena ili sačuvana. Replace it with this document, or cancel and use File › Save As to keep both. Zameni je ovim dokumentom ili otkaži i koristi Datoteka › Sačuvaj kao da zadržiš obe. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 64191012c4..b9c3721765 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3359,6 +3359,7 @@ curves Smooth Jämna ut This document's layers: {needed} of {budget} for layers Lagren i det här dokumentet: {needed} av {budget} för lager This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Lagren i det här dokumentet behöver {needed} men får använda {budget}: omritningar av hela dokumentet använder CPU:n GPU Memory (MB, 0 = Automatic) GPU-minne (MB, 0 = automatisk) + Scratch Size Limit (MB, 0 = No Limit) Storleksgräns för arbetsdisk (MB, 0 = ingen gräns) {path}: the path is not valid Unicode; save under another name. {path}: sökvägen är inte giltig Unicode; spara under ett annat namn. Replace Ersätt {name} was changed by another app after it was opened or saved here. {name} har ändrats av en annan app efter att den öppnades eller sparades här. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 1a3eab8bf2..e03cd01c77 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4127,6 +4127,7 @@ cameraData Lens Lens This document's layers: {needed} of {budget} for layers Bu belgenin katmanları: katmanlar için {budget} içinden {needed} This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Bu belgenin katmanlarının {needed} belleğe ihtiyacı var ama en fazla {budget} kullanabilirler: tüm belgenin yeniden çizimi CPU'yu kullanır GPU Memory (MB, 0 = Automatic) GPU Belleği (MB, 0 = Otomatik) + Scratch Size Limit (MB, 0 = No Limit) Geçici disk boyut sınırı (MB, 0 = Sınırsız) {path}: the path is not valid Unicode; save under another name. {path}: yol geçerli bir Unicode değil; başka bir adla kaydedin. {name} was changed by another app after it was opened or saved here. {name}, burada açıldıktan veya kaydedildikten sonra başka bir uygulama tarafından değiştirildi. Replace it with this document, or cancel and use File › Save As to keep both. Bu belgeyle değiştirin ya da iptal edip ikisini de korumak için Dosya › Farklı Kaydet'i kullanın. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index eb8ad312ae..b0a6c75041 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4107,6 +4107,7 @@ curves Smooth Згладити This document's layers: {needed} of {budget} for layers Шари цього документа: {needed} з {budget} для шарів This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Шарам цього документа потрібно {needed}, але займати вони можуть {budget}: увесь документ перемальовується на CPU GPU Memory (MB, 0 = Automatic) Пам'ять GPU (МБ, 0 = автоматично) + Scratch Size Limit (MB, 0 = No Limit) Обмеження розміру робочого диска (МБ, 0 = без обмеження) {path}: the path is not valid Unicode; save under another name. {path}: шлях не є коректним Unicode; збережіть під іншою назвою. Replace Замінити {name} was changed by another app after it was opened or saved here. Файл {name} змінила інша програма після того, як його тут відкрили або зберегли. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8ddd03bf99..7d5f39e280 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3898,6 +3898,7 @@ curves Smooth Làm mượt This document's layers: {needed} of {budget} for layers Các lớp của tài liệu này: {needed} trên {budget} dành cho lớp This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU Các lớp của tài liệu này cần {needed} nhưng chỉ được dùng {budget}: vẽ lại toàn bộ tài liệu dùng CPU GPU Memory (MB, 0 = Automatic) Bộ nhớ GPU (MB, 0 = Tự động) + Scratch Size Limit (MB, 0 = No Limit) Giới hạn dung lượng đĩa tạm (MB, 0 = Không giới hạn) {path}: the path is not valid Unicode; save under another name. {path}: đường dẫn không phải Unicode hợp lệ; hãy lưu với tên khác. Replace Thay thế {name} was changed by another app after it was opened or saved here. {name} đã bị một ứng dụng khác thay đổi sau khi được mở hoặc lưu ở đây. diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c7b11fc593..953566b08a 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3069,6 +3069,7 @@ curves Smooth 平滑 This document's layers: {needed} of {budget} for layers 此文档的图层:图层可用 {budget} 中的 {needed} This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU 此文档的图层需要 {needed},但只能占用 {budget}:整个文档的重绘使用 CPU GPU Memory (MB, 0 = Automatic) GPU 内存(MB,0 = 自动) + Scratch Size Limit (MB, 0 = No Limit) 暂存盘大小上限(MB,0 = 无限制) {path}: the path is not valid Unicode; save under another name. {path}:路径不是有效的 Unicode;请以其他名称存储。 Replace 替换 {name} was changed by another app after it was opened or saved here. {name} 在此处打开或存储后已被其他应用更改。 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index a8de12a6d1..06440368af 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3030,6 +3030,7 @@ curves Smooth 平滑 This document's layers: {needed} of {budget} for layers 此文件的圖層:圖層可用 {budget} 中的 {needed} This document's layers need {needed} but may hold {budget}: whole-document redraws use the CPU 此文件的圖層需要 {needed},但只能佔用 {budget}:整份文件的重繪使用 CPU GPU Memory (MB, 0 = Automatic) GPU 記憶體(MB,0 = 自動) + Scratch Size Limit (MB, 0 = No Limit) 暫存磁碟大小上限(MB,0 = 無限制) {path}: the path is not valid Unicode; save under another name. {path}:路徑不是有效的 Unicode;請以其他名稱儲存。 Replace 取代 {name} was changed by another app after it was opened or saved here. {name} 在此處開啟或儲存後已被其他 App 更改。 diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index b79867bf6b..0c15f630a6 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -71,6 +71,10 @@ pub(super) fn humanize(key: &str) -> String { return "Low-Latency Drawing (vsync off, applies at next launch)".into(); } // Performance: the canvas compositor's GPU memory, 0 for the automatic budget (L3). + // Scratch Disks: how large the scratch file may grow; the free-space reserve always applies. + if key == "sizeLimitMb" { + return "Scratch Size Limit (MB, 0 = No Limit)".into(); + } if key == "gpuMemoryMb" { return "GPU Memory (MB, 0 = Automatic)".into(); } diff --git a/docs/scorecard.md b/docs/scorecard.md index 34778e7bb3..4b3f1299c6 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js | [Performance](#performance) | 3 | 22 | 45 | 79 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 41 not run, 4 not measurable yet (baseline 2026-10-05) | | [File compatibility](#file-compatibility) | 11 | 14 | 2 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 | | [Tools](#tools) | 36 | 9 | 0 | | -| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 184 (target 0) | +| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 10 of 185 (target 0) | | [Type](#type) | 5 | 5 | 0 | | | [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) | | [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present | @@ -203,7 +203,7 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu ## Workspace and UI -**Settings that do nothing: 10 of 184** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. +**Settings that do nothing: 10 of 185** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't. Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.legacy_compositing`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`. diff --git a/docs/scratch-disks.md b/docs/scratch-disks.md index 0ffbcf2a11..93f314a426 100644 --- a/docs/scratch-disks.md +++ b/docs/scratch-disks.md @@ -3,7 +3,8 @@ Native PhotoCraft keeps pixel tiles in RAM and spills cold tiles to a configured scratch directory. A read or write guard keeps a tile resident while a consumer uses its bytes. Undo snapshots keep their copy-on-write tiles, including disk-backed tiles, until History States -retires them. Web builds retain their explicit memory limit and do not use a filesystem. +retires them. Web builds retain their explicit memory limit (capped like Memory Usage) and do not use a +filesystem. New preferences use **70% of physical RAM** as the process ceiling. This is configurable from 1–95%; older preferences without `performance.memoryUsagePercent` retain their absolute @@ -42,7 +43,9 @@ than max(1 GiB, 5% of the volume) would stay free), pauses spilling: tiles stay the status bar shows the reason, and History's Memory Usage byte limit applies again from the next command, as without a scratch disk. The pause is retried after 1 s, doubling up to 60 s; spilling resumes on its own once the directory is usable and has room, and changing -preferences retries at once. `spill::set_size_cap` adds an explicit scratch size limit. +preferences retries at once. Preferences → Scratch Disks → Scratch Size Limit +(`scratchDisks.sizeLimitMb`, 0 = no limit; `spill::set_size_cap`) caps the scratch file: +reaching it pauses spilling the same way, and the free-space reserve applies regardless. A failed read retains its backing extent and blocks editing, saving and exporting of the document that holds the tile until it is readable again; other open documents keep working. Each commit checks the health of its own document (before and after an edit, the document a From f4d8886f6ea5b44802c980fc5a5402815872e93e Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 3 Nov 2026 07:19:16 +0100 Subject: [PATCH 9/9] Refuse scripted .pcraft saves whose previews read unreadable scratch The automation .pcraft save renders the previews and main's optional full-size composite before the bundle writer takes its scratch snapshot, so a tile that failed and recovered in between could be saved as placeholder pixels. Check the document's scratch health and the read-error generation around that render, as io's export path already does. --- Cargo.lock | 1 + crates/automation/Cargo.toml | 1 + crates/automation/src/files.rs | 16 ++++--- crates/automation/tests/scratch_save.rs | 55 +++++++++++++++++++++++++ 4 files changed, 68 insertions(+), 5 deletions(-) create mode 100644 crates/automation/tests/scratch_save.rs diff --git a/Cargo.lock b/Cargo.lock index 8c27a0d101..ed5486be6a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5080,6 +5080,7 @@ dependencies = [ "photocraft-doc", "photocraft-engine", "photocraft-format", + "photocraft-geom", "photocraft-io", "photocraft-raster", "photocraft-raw", diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index ba073af2ff..e72b38f760 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -29,6 +29,7 @@ cap-std = "4" clap = { workspace = true } [dev-dependencies] +photocraft-geom = { workspace = true } # Synthetic camera raws (#7789). photocraft-raw = { workspace = true, features = ["testgen"] } rmcp = { version = "3.5", default-features = false, features = ["client", "server", "macros", "transport-io"] } diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index a74af99241..fddd15ca96 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -58,14 +58,20 @@ pub fn previews(doc: &Document) -> SaveOptions { } /// [`previews`], plus the full-size composite when `opts` asks for it and it can be rendered -/// ([`ExportOptions::pcraft_full_composite`]). -fn native_options(doc: &Document, opts: &ExportOptions) -> SaveOptions { +/// ([`ExportOptions::pcraft_full_composite`]). Fails when a scratch tile of `doc` could not be +/// read while they were rendered: the previews may then hold placeholder pixels, and the +/// bundle's own scratch checks only cover reads made after it starts. +fn native_options(doc: &Document, opts: &ExportOptions) -> Result { + doc.scratch_health().map_err(AutomationError::Io)?; + let generation = photocraft_raster::spill::read_error_generation(); let mut out = previews(doc); if opts.pcraft_full_composite { out.full_composite = photocraft_io::pcraft_full_composite(doc); out.full_composite_icc = out.full_composite.as_ref().map(|_| photocraft_io::pcraft_full_composite_icc(doc)); } - out + photocraft_raster::spill::check_since(generation).map_err(AutomationError::Io)?; + doc.scratch_health().map_err(AutomationError::Io)?; + Ok(out) } /// Encode the name the saved native bundle will report on reopening. Save As updates @@ -97,7 +103,7 @@ pub fn save( let named = named_for_output(doc, &path.to_string_lossy()); let mut local = PcraftWriter::new(); let w = writer.unwrap_or(&mut local); - w.save_path(&named, path, &native_options(&named, opts))?; + w.save_path(&named, path, &native_options(&named, opts)?)?; return Ok(Vec::new()); } let r = photocraft_io::export(doc, &ext, opts)?; @@ -115,7 +121,7 @@ pub fn save_bytes(doc: &Document, name: &str, format_override: Option<&str>, opt .ok_or_else(|| AutomationError::BadRequest(format!("cannot tell the format of `{name}`; pass a format")))?; if ext == photocraft_format::EXTENSION { let named = named_for_output(doc, name); - return Ok((photocraft_format::save_to_bytes(&named, &native_options(&named, opts))?, Vec::new())); + return Ok((photocraft_format::save_to_bytes(&named, &native_options(&named, opts)?)?, Vec::new())); } let result = photocraft_io::export(doc, &ext, opts)?; Ok((result.bytes, result.warnings)) diff --git a/crates/automation/tests/scratch_save.rs b/crates/automation/tests/scratch_save.rs new file mode 100644 index 0000000000..e61c607e8f --- /dev/null +++ b/crates/automation/tests/scratch_save.rs @@ -0,0 +1,55 @@ +//! A scripted `.pcraft` save refuses to write previews or a full-size composite rendered from +//! scratch tiles that could not be read. Its own test binary: the scratch store is per process. +#![cfg(not(target_arch = "wasm32"))] + +use photocraft_automation::{AutomationError, files}; +use photocraft_doc::{ColorMode, Document, Layer, PixelFormat, SampleType, Size}; +use photocraft_geom::TileCoord; +use photocraft_raster::spill; +use std::io::{Read, Seek, SeekFrom, Write}; + +#[test] +fn native_save_refuses_previews_rendered_from_unreadable_scratch() { + let dir = std::env::temp_dir().join(format!("photocraft-automation-scratch-save-{}", std::process::id())); + spill::configure(Some(&dir), 1).unwrap(); + let mut doc = Document::new("Scratch", Size::new(512, 256), ColorMode::Rgb, SampleType::U8); + let mut layer = Layer::raster("Pixels", PixelFormat::RGBA8); + for i in 0..2 { + let mut bytes = layer.surface_mut().unwrap().tile_mut(TileCoord::new(i, 0)).bytes_mut(); + for (j, byte) in bytes.iter_mut().enumerate() { + *byte = (j as u8).wrapping_mul(29).wrapping_add((i * 7) as u8 + 1); + } + } + doc.layers.push(layer); + spill::settle(); + assert_eq!(spill::stats().resident_bytes, 0); + let mut file = spill::scratch_handle_for_tests().unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + let mut good = Vec::new(); + file.read_to_end(&mut good).unwrap(); + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&vec![0; good.len()]).unwrap(); + file.sync_all().unwrap(); + + let on = photocraft_io::ExportOptions { pcraft_full_composite: true, ..Default::default() }; + // Refused while rendering the previews, before the bundle is assembled. + let err = files::save_bytes(&doc, "Scratch.pcraft", None, &on).unwrap_err(); + assert!(matches!(err, AutomationError::Io(_)), "{err:?}"); + let path = dir.join("Scratch.pcraft"); + let err = files::save(&doc, &path, None, &on, None).unwrap_err(); + assert!(matches!(err, AutomationError::Io(_)), "{err:?}"); + assert!(!path.exists()); + + file.seek(SeekFrom::Start(0)).unwrap(); + file.write_all(&good).unwrap(); + file.sync_all().unwrap(); + for (_, tile) in doc.layers[0].surface().unwrap().tiles() { + tile.try_bytes().unwrap(); + } + assert!(spill::check_integrity().is_ok()); + let (bytes, _) = files::save_bytes(&doc, "Scratch.pcraft", None, &on).unwrap(); + assert_eq!(photocraft_format::load_from_bytes(&bytes).unwrap().layers, doc.layers); + drop((doc, file)); + spill::configure(None, 0).unwrap(); + let _ = std::fs::remove_dir_all(dir); +}