From 2f451dedac104ed1e72ac34d8301a23701f091c1 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Wed, 18 Nov 2026 23:06:46 +1000 Subject: [PATCH 1/2] PERF-979: a large library opens in seconds: edited photos are found in the background Opening a library spent most of a minute (300,000 photos) in keep_edited_previews_last, which asked every photo's camera defaults, and with them its camera's lookups by name in the profile and camera tables, on the opening thread to find the edited photos whose previews a full cache keeps last. The thumbnail cache's files were never read (attaching it costs 0.2 ms), which is why clearing it changed nothing. - library: the search runs on a thread of its own with a cancellable "Finding edited photos" row, stopped when the library closes; up to 2,000 photos it is done inline (under 10 ms). Each camera is looked up once per pass (Photo::relative_wb_key, camera_defaults_as, looks_as_shot_given): 300,000 photos take about 1 s instead of 60-74 s. - preview: a full cache prunes nothing while the set is pending, and keep_last adds to the set. - the open log splits the stage into thumbnail cache / edited previews / thumbnail cache tidy. - open_bench: realistic raws, an optional thumbnail cache of N KB per photo, background time. 300,000 photos with a 16.5 GB cache: opened in 65.4 / 70.5 s, now 3.8 / 4.0 s. Refs #979 Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/model.rs | 11 +- crates/engine/examples/open_bench.rs | 67 +++++++++++- crates/engine/src/import.rs | 14 ++- crates/engine/src/library.rs | 93 ++++++++++++++-- crates/engine/src/tests_library.rs | 103 ++++++++++++++++++ crates/preview/src/disk.rs | 36 +++++- crates/preview/src/tests.rs | 72 ++++++++++++ crates/ui-egui/locales/fork/cs.json | 1 + crates/ui-egui/locales/fork/de.json | 1 + crates/ui-egui/locales/fork/es.json | 1 + crates/ui-egui/locales/fork/fi.json | 1 + crates/ui-egui/locales/fork/fr.json | 1 + crates/ui-egui/locales/fork/id.json | 1 + crates/ui-egui/locales/fork/it.json | 1 + crates/ui-egui/locales/fork/ja.json | 1 + crates/ui-egui/locales/fork/ka.json | 1 + crates/ui-egui/locales/fork/pl.json | 1 + crates/ui-egui/locales/fork/pt-br.json | 1 + crates/ui-egui/locales/fork/ru.json | 1 + crates/ui-egui/locales/fork/sv.json | 1 + crates/ui-egui/locales/fork/uk.json | 1 + crates/ui-egui/locales/fork/vi.json | 1 + crates/ui-egui/locales/fork/zh-hans.json | 1 + crates/ui-egui/locales/fork/zh-hant.json | 1 + .../2026-11-18-faster-large-library-open.md | 3 + .../2026-11-18-faster-large-library-open.md | 2 + 26 files changed, 395 insertions(+), 23 deletions(-) create mode 100644 docs/changelog/unreleased/2026-11-18-faster-large-library-open.md create mode 100644 docs/whats-new/2026-11-18-faster-large-library-open.md diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 6ae7dca8f2..f5ff39414a 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -692,6 +692,10 @@ impl Photo { pub fn relative_wb(&self) -> bool { self.develops_raw() && relative_wb_camera_as(&self.format, &self.meta.camera, &self.develop.profile.camera) } + /// What [`Self::relative_wb`] depends on: photos with equal keys have the same answer. + pub fn relative_wb_key(&self) -> (bool, &str, &str, &str) { + (self.develops_raw(), &self.format, &self.meta.camera, &self.develop.profile.camera) + } /// The settings the Before view starts from: the one set by the user, else the photo as it /// came into the library (its import state), else its import defaults. pub fn before_base(&self) -> DevelopSettings { @@ -717,7 +721,12 @@ impl Photo { /// process a photo renders with is not an edit, so comparisons with its defaults (edited? /// still as imported?) don't change when a newer process exists. A new photo has the latest. pub fn camera_defaults(&self) -> DevelopSettings { - let relative = self.relative_wb(); + self.camera_defaults_as(self.relative_wb()) + } + /// [`Self::camera_defaults`] of a photo whose [`Self::relative_wb`] is `relative`: that looks the + /// camera up by name in the camera tables and profiles, so a pass over many photos asks it once + /// per camera ([`Self::relative_wb_key`]) instead of once per photo (issue #979). + pub fn camera_defaults_as(&self, relative: bool) -> DevelopSettings { let wb = if relative { Some((6500.0, 0.0)) } else { self.as_shot_wb }; let mut d = match wb { Some((t, tint)) => DevelopSettings::for_raw(t, tint), diff --git a/crates/engine/examples/open_bench.rs b/crates/engine/examples/open_bench.rs index b9386d4734..d8e76a8e0e 100644 --- a/crates/engine/examples/open_bench.rs +++ b/crates/engine/examples/open_bench.rs @@ -1,19 +1,28 @@ //! How long opening a large library takes, stage by stage (issue #979). Makes a library of N //! photos in `` (when it has none), then opens it twice and prints the stages. //! -//! `_PROFILE=1 cargo run --release -p lcc-engine --example open_bench -- [photos]` +//! `_PROFILE=1 cargo run --release -p lcc-engine --example open_bench -- [photos] [thumb KB]` +//! +//! The photos are raws of a few camera bodies with an as-shot white balance, a third of them +//! edited, like a library brought over from another program. With `thumb KB` above 0 the +//! library also gets a thumbnail cache of one file of that size per photo (a reporter's +//! 328 000-photo library had 18 GB of them, some 55 KB each), so a stage that reads the cache +//! shows. use std::time::Instant; -use lcc_catalog::{Op, Photo, Source}; +use lcc_catalog::{MediaKind, Op, Photo, Source}; use lcc_engine::Session; +const BODIES: [(&str, &str); 4] = [("Canon EOS R5", "CR3"), ("SONY ILCE-7M4", "ARW"), ("NIKON CORPORATION NIKON Z 6_2", "NEF"), ("FUJIFILM X-T4", "RAF")]; + fn main() { let _ = env_logger_lite(); let Some(dir) = std::env::args().nth(1) else { - eprintln!("usage: open_bench [photos]"); + eprintln!("usage: open_bench [photos] [thumb KB]"); return; }; let n: u32 = std::env::args().nth(2).and_then(|a| a.parse().ok()).unwrap_or(300_000); + let thumb_kb: usize = std::env::args().nth(3).and_then(|a| a.parse().ok()).unwrap_or(0); if !lcc_engine::library::is_library(std::path::Path::new(&dir)) { let mut s = Session::new().with_fs(); if let Err(e) = s.open_library(&dir, false) { @@ -22,19 +31,35 @@ fn main() { } for i in 0..n { let id = s.catalog.alloc_photo_id(); - let path = format!("/photos/{}/{}/IMG_{i:06}.CR2", 2000 + i % 25, i % 365); - let mut p = Photo::new(id, Source::File { path }, &format!("IMG_{i:06}.CR2"), "CR2", 6000, 4000, "2026-01-01T00:00:00"); + let (camera, ext) = BODIES[i as usize % BODIES.len()]; + let path = format!("/photos/{}/{}/IMG_{i:06}.{ext}", 2000 + i % 25, i % 365); + let mut p = Photo::new(id, Source::File { path }, &format!("IMG_{i:06}.{ext}"), ext, 6000, 4000, "2026-01-01T00:00:00"); + p.kind = MediaKind::Raw; + p.meta.camera = camera.into(); + p.as_shot_wb = Some((5000.0 + f64::from(i % 1500), f64::from(i % 7))); + p.develop = std::sync::Arc::new(p.camera_defaults()); + p.file_size = 30_000_000 + u64::from(i); p.captured = Some(format!("{}-{:02}-{:02}T10:00:00", 2000 + i % 25, 1 + i % 12, 1 + i % 28)); p.meta.keywords = vec![format!("kw{}", i % 500), format!("place{}", i % 50)]; p.rating = (i % 6) as u8; if i % 3 == 0 { p.edited = Some("2026-01-02T00:00:00".into()); + let mut d = (*p.develop).clone(); + d.light.exposure = 0.3; + p.develop = std::sync::Arc::new(d); } let _ = s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }); } let t = Instant::now(); let _ = s.close_library(); println!("made {n} photos, closed in {:.1} s", t.elapsed().as_secs_f64()); + if thumb_kb > 0 { + let t = Instant::now(); + match write_thumbs(&std::path::Path::new(&dir).join("thumbs"), n as usize, thumb_kb << 10) { + Ok(()) => println!("wrote {n} thumbnails of {thumb_kb} KB in {:.1} s", t.elapsed().as_secs_f64()), + Err(e) => eprintln!("thumbnails: {e}"), + } + } } for run in 0..2 { let mut s = Session::new().with_fs(); @@ -46,9 +71,41 @@ fn main() { let t = Instant::now(); let _ = s.visible(); println!("run {run}: first visible list {:.1} ms", t.elapsed().as_secs_f64() * 1000.0); + // the edited photos' previews are found in the background after a large library opens + let t = Instant::now(); + while s.media.rendered.disk().is_some_and(|d| d.is_keep_last_pending()) && t.elapsed().as_secs() < 600 { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + println!("run {run}: edited photos found in the background {:.1} ms later", t.elapsed().as_secs_f64() * 1000.0); } } +/// `count` cache files of `bytes` each under `dir`, in the cache's own layout +/// (`<2 hex>/<32 hex>.lcthumb`), written on all cores. +fn write_thumbs(dir: &std::path::Path, count: usize, bytes: usize) -> std::io::Result<()> { + let threads = std::thread::available_parallelism().map_or(4, |n| n.get()); + let body = vec![0x5au8; bytes]; + std::thread::scope(|sc| { + let jobs: Vec<_> = (0..threads) + .map(|t| { + let body = &body; + sc.spawn(move || -> std::io::Result<()> { + for i in (t..count).step_by(threads) { + // (a key spread over all 256 shards like the cache's hashes) + let key = (i as u128).wrapping_mul(0x9e37_79b9_7f4a_7c15_f39c_c060_5ced_c835); + let hex = format!("{key:032x}"); + let shard = dir.join(hex.get(..2).unwrap_or("00")); + std::fs::create_dir_all(&shard)?; + std::fs::write(shard.join(format!("{hex}.lcthumb")), body)?; + } + Ok(()) + }) + }) + .collect(); + jobs.into_iter().try_for_each(|j| j.join().unwrap_or_else(|_| Err(std::io::Error::other("writer panicked")))) + }) +} + /// Print `log` records to stderr (the stage timings are logged). fn env_logger_lite() -> Result<(), log::SetLoggerError> { struct L; diff --git a/crates/engine/src/import.rs b/crates/engine/src/import.rs index 0ce9896de5..a1bd23a18b 100644 --- a/crates/engine/src/import.rs +++ b/crates/engine/src/import.rs @@ -351,16 +351,22 @@ pub fn has_import_look(p: &Photo) -> bool { /// the photo as framed and exposed, a fair stand-in until the render arrives (labelled "Camera /// preview" in the loupe). Any other edit is never shown as the camera JPEG. pub fn looks_as_shot(p: &Photo) -> bool { - if has_import_look(p) { - return true; - } + looks_as_shot_given(p, p.camera_defaults()) +} + +/// [`looks_as_shot`] of a photo whose camera defaults ([`Photo::camera_defaults`]) are `defaults`. +pub fn looks_as_shot_given(p: &Photo, defaults: lcc_develop::DevelopSettings) -> bool { let neutral = |d: &lcc_develop::DevelopSettings| { let mut d = d.clone(); d.profile.camera.clear(); d.profile.id = lcc_develop::Profile::default().id; d }; - neutral(&p.develop) == neutral(&p.camera_defaults()) + // (has_import_look) + if p.develop_matches(defaults.clone()) { + return true; + } + neutral(&p.develop) == neutral(&defaults) } /// The name `library.setImportDefault` saves its preset under when the caller doesn't name one diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 81c0fd59a8..8918abd72f 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -551,6 +551,45 @@ impl SettingsLoad { } } +/// The activity-stack row of [`Session::keep_edited_previews_last`]'s work. +pub const EDITED_PREVIEWS_LABEL: &str = "Finding edited photos"; + +/// Most photos [`Session::keep_edited_previews_last`] looks through as the library opens (some +/// 3 µs each, so under 10 ms; issue #979); a larger library is looked through in the background. +pub const INLINE_EDITED_PHOTOS: usize = 2_000; + +#[cfg(test)] +thread_local! { + /// Photos [`edited_preview_keys`] looked at on this thread (tests: opening a library looks at + /// none on the thread that opens it). + pub(crate) static EDITED_LOOKED_AT: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The latest-preview keys of the edited photos among `photos` ([`Session::keep_edited_previews_last`]): +/// `None` when `stop` said so. `stop` is asked, and `progress` told (done, of), every few thousand photos. +fn edited_preview_keys(photos: &[std::sync::Arc], stop: &dyn Fn() -> bool, progress: &dyn Fn(usize, usize)) -> Option> { + const STEP: usize = 4096; + let mut keys = Vec::new(); + // (a camera is looked up by name once, not once per photo: most of the time this took) + let mut relative: std::collections::HashMap<(bool, &str, &str, &str), bool> = std::collections::HashMap::new(); + for (i, p) in photos.iter().enumerate() { + if i % STEP == 0 { + if stop() { + return None; + } + progress(i, photos.len()); + } + #[cfg(test)] + EDITED_LOOKED_AT.with(|n| n.set(n.get().saturating_add(1))); + let rel = *relative.entry(p.relative_wb_key()).or_insert_with(|| p.relative_wb()); + if !crate::import::looks_as_shot_given(p, p.camera_defaults_as(rel)) { + keys.extend([crate::media::latest_view_key(p, true), crate::media::latest_thumb_key(p)]); + } + } + progress(photos.len(), photos.len()); + Some(keys) +} + /// How long each stage of opening a library took: logged when the whole took a while (issue /// #979: a large catalog spent a minute between being read and the library opening, with no /// timings for that part), and always with `_PROFILE` set. @@ -900,10 +939,12 @@ impl Session { self.media.clear_sources(); if on_disk { self.media.attach_disk_cache(&dir.join("thumbs"), self.cache_bytes_in(&dir.join("thumbs"))); + stages.mark("thumbnail cache"); self.keep_edited_previews_last(); + stages.mark("edited previews"); self.tidy_thumbnail_cache(); } - stages.mark("thumbnail cache"); + stages.mark("thumbnail cache tidy"); let view_written = self.view_json(); let store_with_library = prefs.store_with_library; let own_store = store_with_library || self.app_store.is_none(); @@ -1369,22 +1410,54 @@ impl Session { out } - /// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default, which - /// grows with the library: [`crate::media::default_disk_cache_bytes`]). /// The edited photos' latest previews (their last loupe view and grid thumbnail) are the last /// pictures a full disk cache lets go: the only pictures of their edits (a photo as shot has its /// camera JPEG). A full cache otherwise lost every rendered edit, and the loupe had nothing but /// the unedited camera JPEG. + /// + /// Telling which photos are edited asks each photo's camera defaults, which look its camera up + /// by name in the camera tables and profiles: most of a minute for 300 000 photos, which every + /// opening of the library waited for (issue #979). It is worked out on a thread of its own with + /// a row in the activity stack that can stop it; the cache prunes nothing until it is known. + /// A library of up to [`INLINE_EDITED_PHOTOS`] photos is looked through at once (a moment). pub fn keep_edited_previews_last(&self) { - let Some(d) = self.media.rendered.disk() else { return }; - let keys = self - .catalog - .photos() - .filter(|p| !crate::import::looks_as_shot(p)) - .flat_map(|p| [crate::media::latest_view_key(p, true), crate::media::latest_thumb_key(p)]); - d.keep_last(keys); + let cache = self.media.rendered.clone(); + let Some(d) = cache.disk() else { return }; + // (shared, not copied: the photos are reference-counted) + let photos: Vec> = self.catalog.photos().cloned().collect(); + if cfg!(target_arch = "wasm32") || photos.len() <= INLINE_EDITED_PHOTOS { + d.keep_last(edited_preview_keys(&photos, &|| false, &|_, _| ()).unwrap_or_default()); + return; + } + d.keep_last_pending(); + #[cfg(not(target_arch = "wasm32"))] + { + use std::sync::atomic::{AtomicBool, Ordering}; + let stop = std::sync::Arc::new(AtomicBool::new(false)); + let task = self.activity.start("cache", EDITED_PREVIEWS_LABEL, crate::activity::Cancel::Flag(stop.clone())); + let worker = cache.clone(); + let spawned = std::thread::Builder::new().name("lc-keep-edited".into()).spawn(move || { + // the row stays while this runs (it is dropped with the closure, however that ends) + let row = task; + // (also given up when the library is closed or another is opened: the cache is retired then) + let stopped = || stop.load(Ordering::Relaxed) || worker.generation() == u64::MAX; + let Some(d) = worker.disk() else { return }; + match edited_preview_keys(&photos, &stopped, &|done, of| row.progress(done as u64, of as u64)) { + Some(keys) => d.keep_last(keys), + None => d.keep_last_unknown(), + } + }); + // (not started: worked out here, as before) + if let Err(e) = spawned { + log::warn!("thumbnail cache: edited photos looked through on this thread: {e}"); + let photos: Vec> = self.catalog.photos().cloned().collect(); + d.keep_last(edited_preview_keys(&photos, &|| false, &|_, _| ()).unwrap_or_default()); + } + } } + /// The thumbnail disk cache budget in bytes ([`Session::cache_mb`], else the default, which + /// grows with the library: [`crate::media::default_disk_cache_bytes`]). pub fn cache_bytes(&self) -> u64 { match (self.cache_mb, self.media.rendered.disk()) { (0, Some(d)) => self.cache_bytes_in(d.dir()), diff --git a/crates/engine/src/tests_library.rs b/crates/engine/src/tests_library.rs index 666e94984b..a36dcf15ca 100644 --- a/crates/engine/src/tests_library.rs +++ b/crates/engine/src/tests_library.rs @@ -1028,3 +1028,106 @@ fn a_selection_restored_from_view_json_names_each_photo_once() { assert_eq!(s.selection.active, Some(ids[1])); let _ = std::fs::remove_dir_all(&dir); } + +/// A library of `n` raws on disk in `dir`, the `edited`-th of them edited: its id and that of an unedited one. +fn large_library(dir: &std::path::Path, n: usize, edited: usize) -> (lcc_catalog::PhotoId, lcc_catalog::PhotoId) { + let mut s = Session::new().with_fs(); + s.open_library(dir, false).unwrap(); + let mut ids = Vec::new(); + for i in 0..n { + let id = s.catalog.alloc_photo_id(); + let path = format!("/photos/IMG_{i:05}.CR3"); + let mut p = lcc_catalog::Photo::new(id, lcc_catalog::Source::File { path }, &format!("IMG_{i:05}.CR3"), "CR3", 6000, 4000, "2026-01-01T00:00:00"); + p.kind = lcc_catalog::MediaKind::Raw; + p.meta.camera = "Canon EOS R5".into(); + p.as_shot_wb = Some((5200.0, 3.0)); + let mut d = p.camera_defaults(); + if i == edited { + d.light.exposure = 0.7; + } + p.develop = std::sync::Arc::new(d); + s.catalog.apply(lcc_catalog::Op::AddPhoto { photo: Box::new(p) }).unwrap(); + ids.push(id); + } + s.close_library().unwrap(); + (ids[edited], ids[(edited + 1) % n]) +} + +/// Issue #979: opening a large library looked at every photo's camera defaults on the thread that +/// opens it, to find the edited photos whose previews a full cache lets go last (most of a minute +/// for 300 000 photos). Given a library over the inline limit, when it opens, then the opening +/// thread looks at no photo, and the edited photo's latest previews are still kept last once the +/// background work ends (the cache pruned nothing meanwhile). +#[test] +fn opening_a_large_library_finds_its_edited_photos_off_the_opening_thread() { + use crate::library::EDITED_LOOKED_AT; + let dir = temp_dir("edited-bg"); + let (edited, plain) = large_library(&dir, crate::library::INLINE_EDITED_PHOTOS + 500, 7); + let before = EDITED_LOOKED_AT.with(std::cell::Cell::get); + let mut s = Session::new().with_fs(); + s.open_library(&dir, false).unwrap(); + assert_eq!(EDITED_LOOKED_AT.with(std::cell::Cell::get) - before, 0, "no photo looked at while opening"); + let d = s.media.rendered.disk().unwrap(); + // (a machine busy with other tests can take a while) + let t0 = std::time::Instant::now(); + while d.is_keep_last_pending() && t0.elapsed() < std::time::Duration::from_secs(120) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!d.is_keep_last_pending(), "the background work ended"); + let p = s.catalog.photo(edited).unwrap(); + assert!(d.is_kept_last(crate::media::latest_thumb_key(p)) && d.is_kept_last(crate::media::latest_view_key(p, true))); + assert!(!d.is_kept_last(crate::media::latest_thumb_key(s.catalog.photo(plain).unwrap())), "a photo as shot has its camera JPEG"); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A small library still works it out as it opens (a moment), with no row in the activity stack. +#[test] +fn opening_a_small_library_finds_its_edited_photos_at_once() { + use crate::library::EDITED_LOOKED_AT; + let dir = temp_dir("edited-inline"); + let (edited, _) = large_library(&dir, 20, 3); + let before = EDITED_LOOKED_AT.with(std::cell::Cell::get); + let mut s = Session::new().with_fs(); + s.open_library(&dir, false).unwrap(); + assert_eq!(EDITED_LOOKED_AT.with(std::cell::Cell::get) - before, 20); + assert!(s.activity.list().is_empty()); + let d = s.media.rendered.disk().unwrap(); + assert!(!d.is_keep_last_pending() && d.is_kept_last(crate::media::latest_thumb_key(s.catalog.photo(edited).unwrap()))); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A thumbnail cache left damaged (files cut short or emptied, a file where a shard folder goes, +/// stray names) never stops a library from opening: the damaged thumbnails are misses that go. +#[test] +fn a_damaged_thumbnail_cache_opens_and_its_bad_files_go() { + let dir = temp_dir("bad-thumbs"); + let (edited, _) = large_library(&dir, 20, 3); + let thumbs = dir.join("thumbs"); + std::fs::create_dir_all(&thumbs).unwrap(); + std::fs::write(thumbs.join("ab"), b"a file where a shard folder goes").unwrap(); + std::fs::create_dir_all(thumbs.join("zz")).unwrap(); + std::fs::write(thumbs.join("zz").join("not-a-key.lcthumb"), b"x").unwrap(); + let img = lcc_raster::Rgba8 { width: 32, height: 20, data: vec![[90, 120, 150, 255]; 640] }; + let jpeg = lcc_preview::encode_jpeg(&img).unwrap(); + let keys: Vec = (0..4u8).map(|i| lcc_preview::hash_bytes(&[i, 42])).collect(); + for (k, bytes) in keys.iter().zip([&jpeg[..jpeg.len() / 3], &[][..], &[0xff, 0xd8][..], &jpeg[..]]) { + let hex = k.to_string(); + std::fs::create_dir_all(thumbs.join(&hex[..2])).unwrap(); + std::fs::write(thumbs.join(&hex[..2]).join(format!("{hex}.lcthumb")), bytes).unwrap(); + } + let mut s = Session::new().with_fs(); + s.open_library(&dir, false).unwrap(); + assert!(s.catalog.photo(edited).is_some()); + let d = s.media.rendered.disk().unwrap(); + for k in &keys[1..3] { + assert!(d.get(*k).is_none()); + } + assert!(d.get(keys[3]).is_some(), "a whole thumbnail is read"); + // (a JPEG cut short may decode with its end grey or be refused: either way no panic) + let _ = d.get(keys[0]); + assert!(d.size() > 0); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/preview/src/disk.rs b/crates/preview/src/disk.rs index d3d8fe4818..94744994fb 100644 --- a/crates/preview/src/disk.rs +++ b/crates/preview/src/disk.rs @@ -128,6 +128,9 @@ pub struct DiskCache { /// Pictures a full cache lets go only after everything else ([`Self::keep_last`]): the edited /// photos' latest previews, the only pictures of their edits (a photo as shot has its camera JPEG). last: Mutex>, + /// The set of [`Self::keep_last`] is being worked out (in the background, issue #979): a full + /// cache prunes nothing meanwhile, so the pictures to keep last are not let go before they are known. + last_pending: std::sync::atomic::AtomicBool, } impl DiskCache { @@ -143,14 +146,40 @@ impl DiskCache { writes: AtomicU64::new(0), read: Mutex::new(Default::default()), last: Mutex::new(Default::default()), + last_pending: Default::default(), } } /// Let the pictures under `keys` go last when the cache is full (after the ones read in this /// session too): the edited photos' latest previews (a full cache pruned the rendered edits and - /// the loupe had nothing but the unedited camera JPEG). Replaces the set. + /// the loupe had nothing but the unedited camera JPEG). Added to the set (keys added one by one + /// with [`Self::keep_last_one`] meanwhile stay), and the set is known from now on + /// ([`Self::keep_last_pending`]). pub fn keep_last(&self, keys: impl IntoIterator) { - *self.last.lock().unwrap_or_else(|e| e.into_inner()) = keys.into_iter().map(|k| k.0).collect(); + self.last.lock().unwrap_or_else(|e| e.into_inner()).extend(keys.into_iter().map(|k| k.0)); + self.last_pending.store(false, Ordering::Release); + } + + /// Say that [`Self::keep_last`]'s set is being worked out: until it is given (or + /// [`Self::keep_last_unknown`] says it won't be), a full cache prunes nothing. + pub fn keep_last_pending(&self) { + self.last_pending.store(true, Ordering::Release); + } + + /// The set [`Self::keep_last_pending`] waited for won't come (the work was stopped): the cache + /// prunes again as it fills, with the keys it has. + pub fn keep_last_unknown(&self) { + self.last_pending.store(false, Ordering::Release); + } + + /// Whether [`Self::keep_last`]'s set is still being worked out. + pub fn is_keep_last_pending(&self) -> bool { + self.last_pending.load(Ordering::Acquire) + } + + /// Whether `key` is among the pictures a full cache lets go last ([`Self::keep_last`]). + pub fn is_kept_last(&self, key: Hash128) -> bool { + self.last.lock().unwrap_or_else(|e| e.into_inner()).contains(&key.0) } /// Add one key to [`Self::keep_last`]'s set. @@ -336,7 +365,8 @@ impl DiskCache { self.known.store(*used, Ordering::Relaxed); let over = *used > self.budget(); drop(total); - if over { + // (not while the pictures to keep last are being worked out: the first write after prunes) + if over && !self.is_keep_last_pending() { self.prune(); } } diff --git a/crates/preview/src/tests.rs b/crates/preview/src/tests.rs index 952dfe8847..d6d6a42f98 100644 --- a/crates/preview/src/tests.rs +++ b/crates/preview/src/tests.rs @@ -1216,3 +1216,75 @@ fn disk_cache_entry_that_is_not_a_regular_file_is_a_miss() { assert!(d.get_data(key).is_none()); let _ = std::fs::remove_dir_all(&dir); } + +/// While the pictures to keep last are still being worked out (in the background as a large +/// library opens, issue #979), a full cache lets nothing go; once they are known, the next write +/// prunes and keeps them. Keys added one by one meanwhile stay in the set. +#[test] +fn a_full_cache_waits_for_the_pictures_to_keep_last() { + let dir = temp_dir("keep-last-pending"); + let disk = DiskCache::new(&dir, 1 << 30); + disk.keep_last_pending(); + let keys: Vec = (0..10u8).map(|i| hash_bytes(&[i, 7])).collect(); + disk.put(keys[0], &gradient(32, 32, 0)); + let one = disk.size(); + disk.set_budget(one * 4); + for (i, k) in keys.iter().enumerate().skip(1) { + disk.put(*k, &gradient(32, 32, i as u8)); + } + assert_eq!(keys.iter().filter(|k| disk.modified(**k).is_some()).count(), 10, "nothing let go while the set is unknown"); + disk.keep_last_one(keys[9]); + disk.keep_last([keys[0]]); + assert!(!disk.is_keep_last_pending()); + assert!(disk.is_kept_last(keys[0]) && disk.is_kept_last(keys[9]), "the key added meanwhile stays in the set"); + disk.put(hash_bytes(b"one more"), &gradient(32, 32, 11)); + assert!(disk.modified(keys[0]).is_some() && disk.modified(keys[9]).is_some(), "the pictures to keep last stay"); + assert!(keys.iter().filter(|k| disk.modified(**k).is_some()).count() <= 4, "the next write pruned"); + let _ = std::fs::remove_dir_all(dir); +} + +/// A stopped search for the pictures to keep last lets the cache prune again as it fills. +#[test] +fn a_cache_whose_keep_last_search_stopped_prunes_again() { + let dir = temp_dir("keep-last-unknown"); + let disk = DiskCache::new(&dir, 1 << 30); + disk.keep_last_pending(); + disk.keep_last_unknown(); + let keys: Vec = (0..10u8).map(|i| hash_bytes(&[i, 8])).collect(); + disk.put(keys[0], &gradient(32, 32, 0)); + disk.set_budget(disk.size() * 4); + for (i, k) in keys.iter().enumerate().skip(1) { + disk.put(*k, &gradient(32, 32, i as u8)); + } + assert!(keys.iter().filter(|k| disk.modified(**k).is_some()).count() <= 4); + let _ = std::fs::remove_dir_all(dir); +} + +/// Cache files cut short or emptied (a disk that filled, a crash mid-copy) are misses that go, +/// never a panic: an empty file, a file holding only a JPEG's first marker, a JPEG cut before its +/// frame header. One cut in its picture data decodes with its end grey, or is a miss. +#[test] +fn truncated_cache_files_are_misses_that_go() { + let dir = temp_dir("truncated"); + let d = DiskCache::new(&dir, 1 << 30); + let img = gradient(160, 100, 3); + let full = encode_jpeg(&img).unwrap(); + let k = hash_bytes(b"cut in its data"); + d.put(k, &img); + let hex = k.to_string(); + std::fs::write(dir.join(&hex[..2]).join(format!("{hex}.lcthumb")), full.get(..full.len() / 2).unwrap()).unwrap(); + if let Some(back) = d.get(k) { + assert_eq!((back.width, back.height), (160, 100)); + } + for (i, bytes) in [&[][..], &[0xff, 0xd8][..], full.get(..20).unwrap()].into_iter().enumerate() { + let k = hash_bytes(&[i as u8, 9]); + d.put(k, &img); + let hex = k.to_string(); + let p = dir.join(&hex[..2]).join(format!("{hex}.lcthumb")); + std::fs::write(&p, bytes).unwrap(); + assert!(d.get(k).is_none(), "case {i}"); + assert!(!p.exists(), "case {i}: dropped, to be rendered again"); + assert!(d.dims(k).is_none()); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/locales/fork/cs.json b/crates/ui-egui/locales/fork/cs.json index 48432f953e..60b92a8e76 100644 --- a/crates/ui-egui/locales/fork/cs.json +++ b/crates/ui-egui/locales/fork/cs.json @@ -1006,6 +1006,7 @@ "Find Skin": "Najít pleť", "Find items that have associated all these words:": "Najít položky spojené se všemi těmito slovy:", "Finding blemishes…": "Hledání nedokonalostí…", + "Finding edited photos": "Hledání upravených fotografií", "Finding eyes…": "Hledání očí…", "Finding faces…": "Hledání obličejů…", "Finding teeth…": "Hledání zubů…", diff --git a/crates/ui-egui/locales/fork/de.json b/crates/ui-egui/locales/fork/de.json index 51dec7869e..99f0430ada 100644 --- a/crates/ui-egui/locales/fork/de.json +++ b/crates/ui-egui/locales/fork/de.json @@ -975,6 +975,7 @@ "Find Skin": "Haut suchen", "Find items that have associated all these words:": "Elemente finden, die mit all diesen Wörtern versehen sind:", "Finding blemishes…": "Hautunreinheiten werden gesucht …", + "Finding edited photos": "Bearbeitete Fotos werden gesucht", "Finding eyes…": "Augen werden gesucht…", "Finding faces…": "Gesichter werden gesucht…", "Finding teeth…": "Zähne werden gesucht…", diff --git a/crates/ui-egui/locales/fork/es.json b/crates/ui-egui/locales/fork/es.json index 876c19c9e9..f9d1c20682 100644 --- a/crates/ui-egui/locales/fork/es.json +++ b/crates/ui-egui/locales/fork/es.json @@ -1071,6 +1071,7 @@ "Find Skin": "Buscar la piel", "Find items that have associated all these words:": "Buscar elementos que tengan asociadas todas estas palabras:", "Finding blemishes…": "Buscando imperfecciones…", + "Finding edited photos": "Buscando fotos editadas", "Finding eyes…": "Buscando ojos…", "Finding faces…": "Buscando caras…", "Finding teeth…": "Buscando los dientes…", diff --git a/crates/ui-egui/locales/fork/fi.json b/crates/ui-egui/locales/fork/fi.json index 896426b599..4239c2eecb 100644 --- a/crates/ui-egui/locales/fork/fi.json +++ b/crates/ui-egui/locales/fork/fi.json @@ -1060,6 +1060,7 @@ "Find Skin": "Etsi iho", "Find items that have associated all these words:": "Etsi kohteet, joihin liittyy kaikki nämä sanat:", "Finding blemishes…": "Etsitään ihovirheitä…", + "Finding edited photos": "Etsitään muokattuja kuvia", "Finding eyes…": "Etsitään silmiä…", "Finding faces…": "Etsitään kasvoja…", "Finding skin and faces to retouch": "Etsitään retusoitavaa ihoa ja kasvoja", diff --git a/crates/ui-egui/locales/fork/fr.json b/crates/ui-egui/locales/fork/fr.json index eb8101f228..d6e2750590 100644 --- a/crates/ui-egui/locales/fork/fr.json +++ b/crates/ui-egui/locales/fork/fr.json @@ -967,6 +967,7 @@ "Find Skin": "Trouver la peau", "Find items that have associated all these words:": "Trouver les éléments associés à tous ces mots :", "Finding blemishes…": "Recherche des imperfections…", + "Finding edited photos": "Recherche des photos retouchées", "Finding eyes…": "Recherche des yeux…", "Finding faces…": "Recherche des visages…", "Finding teeth…": "Recherche des dents…", diff --git a/crates/ui-egui/locales/fork/id.json b/crates/ui-egui/locales/fork/id.json index e7e83f812d..378b21398d 100644 --- a/crates/ui-egui/locales/fork/id.json +++ b/crates/ui-egui/locales/fork/id.json @@ -1058,6 +1058,7 @@ "Find Skin": "Cari kulit", "Find items that have associated all these words:": "Cari item yang terkait dengan semua kata ini:", "Finding blemishes…": "Mencari noda…", + "Finding edited photos": "Mencari foto yang diedit", "Finding eyes…": "Mencari mata…", "Finding faces…": "Mencari wajah…", "Finding skin and faces to retouch": "Mencari kulit dan wajah untuk di-retouch", diff --git a/crates/ui-egui/locales/fork/it.json b/crates/ui-egui/locales/fork/it.json index 7c35519782..6687b870dc 100644 --- a/crates/ui-egui/locales/fork/it.json +++ b/crates/ui-egui/locales/fork/it.json @@ -1004,6 +1004,7 @@ "Find Skin": "Trova pelle", "Find items that have associated all these words:": "Trova gli elementi associati a tutte queste parole:", "Finding blemishes…": "Ricerca delle imperfezioni…", + "Finding edited photos": "Ricerca delle foto modificate", "Finding eyes…": "Ricerca degli occhi…", "Finding faces…": "Ricerca dei volti…", "Finding teeth…": "Ricerca dei denti…", diff --git a/crates/ui-egui/locales/fork/ja.json b/crates/ui-egui/locales/fork/ja.json index 9aa24b414a..423c1e215e 100644 --- a/crates/ui-egui/locales/fork/ja.json +++ b/crates/ui-egui/locales/fork/ja.json @@ -1074,6 +1074,7 @@ "Find Skin": "肌を検出", "Find items that have associated all these words:": "次のすべての言葉が関連付けられた項目を検索:", "Finding blemishes…": "シミを検出しています…", + "Finding edited photos": "編集済みの写真を探しています", "Finding eyes…": "目を検出中…", "Finding faces…": "顔を検出中…", "Finding teeth…": "歯を検出中…", diff --git a/crates/ui-egui/locales/fork/ka.json b/crates/ui-egui/locales/fork/ka.json index 4839a14332..8bf494bf0c 100644 --- a/crates/ui-egui/locales/fork/ka.json +++ b/crates/ui-egui/locales/fork/ka.json @@ -1139,6 +1139,7 @@ "Find Skin": "კანის მოძებნა", "Find items that have associated all these words:": "იპოვეთ ელემენტები, რომლებსაც აქვთ ეს ყველა სიტყვა:", "Finding blemishes…": "ლაქები იძებნება…", + "Finding edited photos": "რედაქტირებული ფოტოების ძიება", "Finding eyes…": "თვალები იძებნება…", "Finding faces…": "სახეები იძებნება…", "Finding teeth…": "კბილები იძებნება…", diff --git a/crates/ui-egui/locales/fork/pl.json b/crates/ui-egui/locales/fork/pl.json index fe506eca33..22dd36b503 100644 --- a/crates/ui-egui/locales/fork/pl.json +++ b/crates/ui-egui/locales/fork/pl.json @@ -1096,6 +1096,7 @@ "Find Skin": "Znajdź skórę", "Find items that have associated all these words:": "Znajdź elementy powiązane ze wszystkimi tymi słowami:", "Finding blemishes…": "Wyszukiwanie skaz…", + "Finding edited photos": "Wyszukiwanie edytowanych zdjęć", "Finding eyes…": "Wyszukiwanie oczu…", "Finding faces…": "Wyszukiwanie twarzy…", "Finding teeth…": "Wyszukiwanie zębów…", diff --git a/crates/ui-egui/locales/fork/pt-br.json b/crates/ui-egui/locales/fork/pt-br.json index 6a9f0b3f12..2fc03d8b9e 100644 --- a/crates/ui-egui/locales/fork/pt-br.json +++ b/crates/ui-egui/locales/fork/pt-br.json @@ -1074,6 +1074,7 @@ "Find Skin": "Encontrar a pele", "Find items that have associated all these words:": "Encontrar itens que tenham associadas todas estas palavras:", "Finding blemishes…": "Procurando imperfeições…", + "Finding edited photos": "Procurando fotos editadas", "Finding eyes…": "Procurando olhos…", "Finding faces…": "Procurando rostos…", "Finding teeth…": "Procurando os dentes…", diff --git a/crates/ui-egui/locales/fork/ru.json b/crates/ui-egui/locales/fork/ru.json index 47f203228e..c7f99ae29e 100644 --- a/crates/ui-egui/locales/fork/ru.json +++ b/crates/ui-egui/locales/fork/ru.json @@ -1068,6 +1068,7 @@ "Find Skin": "Найти кожу", "Find items that have associated all these words:": "Найти объекты, связанные со всеми этими словами:", "Finding blemishes…": "Поиск дефектов кожи…", + "Finding edited photos": "Поиск отредактированных фотографий", "Finding eyes…": "Поиск глаз…", "Finding faces…": "Поиск лиц…", "Finding teeth…": "Поиск зубов…", diff --git a/crates/ui-egui/locales/fork/sv.json b/crates/ui-egui/locales/fork/sv.json index 04bb0f15ae..97d9c3295d 100644 --- a/crates/ui-egui/locales/fork/sv.json +++ b/crates/ui-egui/locales/fork/sv.json @@ -1087,6 +1087,7 @@ "Find Skin": "Hitta hud", "Find items that have associated all these words:": "Hitta objekt som har alla dessa ord kopplade till sig:", "Finding blemishes…": "Söker efter fläckar…", + "Finding edited photos": "Söker redigerade foton", "Finding eyes…": "Söker efter ögon…", "Finding faces…": "Söker efter ansikten…", "Finding skin and faces to retouch": "Söker efter hud och ansikten att retuschera", diff --git a/crates/ui-egui/locales/fork/uk.json b/crates/ui-egui/locales/fork/uk.json index 8b9f12cc41..2523aba545 100644 --- a/crates/ui-egui/locales/fork/uk.json +++ b/crates/ui-egui/locales/fork/uk.json @@ -1003,6 +1003,7 @@ "Find Skin": "Знайти шкіру", "Find items that have associated all these words:": "Знайти об'єкти, пов'язані з усіма цими словами:", "Finding blemishes…": "Пошук вад шкіри…", + "Finding edited photos": "Пошук відредагованих фотографій", "Finding eyes…": "Пошук очей…", "Finding faces…": "Пошук облич…", "Finding teeth…": "Пошук зубів…", diff --git a/crates/ui-egui/locales/fork/vi.json b/crates/ui-egui/locales/fork/vi.json index 5fc9700121..a3e3ed4fec 100644 --- a/crates/ui-egui/locales/fork/vi.json +++ b/crates/ui-egui/locales/fork/vi.json @@ -1153,6 +1153,7 @@ "Find Skin": "Tìm da", "Find items that have associated all these words:": "Tìm các mục có liên kết với tất cả những từ này:", "Finding blemishes…": "Đang tìm khuyết điểm…", + "Finding edited photos": "Đang tìm ảnh đã chỉnh sửa", "Finding eyes…": "Đang tìm mắt…", "Finding faces…": "Đang tìm khuôn mặt…", "Finding skin and faces to retouch": "Đang tìm da và khuôn mặt để chỉnh sửa", diff --git a/crates/ui-egui/locales/fork/zh-hans.json b/crates/ui-egui/locales/fork/zh-hans.json index 183f3603ce..24768fec6f 100644 --- a/crates/ui-egui/locales/fork/zh-hans.json +++ b/crates/ui-egui/locales/fork/zh-hans.json @@ -1049,6 +1049,7 @@ "Find Skin": "查找皮肤", "Find items that have associated all these words:": "查找关联了以下所有词的项目:", "Finding blemishes…": "正在查找瑕疵…", + "Finding edited photos": "正在查找已编辑的照片", "Finding eyes…": "正在查找眼睛…", "Finding faces…": "正在查找面部…", "Finding teeth…": "正在查找牙齿…", diff --git a/crates/ui-egui/locales/fork/zh-hant.json b/crates/ui-egui/locales/fork/zh-hant.json index 374058fe63..96fcd8b15a 100644 --- a/crates/ui-egui/locales/fork/zh-hant.json +++ b/crates/ui-egui/locales/fork/zh-hant.json @@ -1074,6 +1074,7 @@ "Find Skin": "尋找皮膚", "Find items that have associated all these words:": "尋找關聯了以下所有詞彙的項目:", "Finding blemishes…": "正在尋找瑕疵…", + "Finding edited photos": "正在尋找已編輯的照片", "Finding eyes…": "正在尋找眼睛…", "Finding faces…": "正在尋找臉部…", "Finding teeth…": "正在尋找牙齒…", diff --git a/docs/changelog/unreleased/2026-11-18-faster-large-library-open.md b/docs/changelog/unreleased/2026-11-18-faster-large-library-open.md new file mode 100644 index 0000000000..545961abdc --- /dev/null +++ b/docs/changelog/unreleased/2026-11-18-faster-large-library-open.md @@ -0,0 +1,3 @@ +## Performance + +- **Large libraries open in seconds:** the search for edited photos (whose previews a full thumbnail cache keeps longest) now runs in the background after the library opens, as **Finding edited photos** in the activity stack, and looks each camera up once instead of once per photo. A synthetic 300,000-photo library with a 16.5 GB thumbnail cache opened in 65–70 s and now opens in about 4 s. Issue #979. diff --git a/docs/whats-new/2026-11-18-faster-large-library-open.md b/docs/whats-new/2026-11-18-faster-large-library-open.md new file mode 100644 index 0000000000..f4bd236a60 --- /dev/null +++ b/docs/whats-new/2026-11-18-faster-large-library-open.md @@ -0,0 +1,2 @@ +### Large libraries open in seconds +- A library of hundreds of thousands of photos opens in a few seconds (it took about a minute): the search for edited photos, whose previews the thumbnail cache keeps longest, runs in the background as **Finding edited photos** in the activity stack (issue #979). From eee28cd05430180c860cc43c78c9d44ab841d911 Mon Sep 17 00:00:00 2001 From: OneSlips Date: Wed, 18 Nov 2026 23:10:54 +1000 Subject: [PATCH 2/2] PERF-979: rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/engine/examples/open_bench.rs | 3 ++- crates/engine/src/library.rs | 6 +++++- crates/engine/src/tests_library.rs | 3 ++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/crates/engine/examples/open_bench.rs b/crates/engine/examples/open_bench.rs index d8e76a8e0e..cd09d5f6b2 100644 --- a/crates/engine/examples/open_bench.rs +++ b/crates/engine/examples/open_bench.rs @@ -13,7 +13,8 @@ use std::time::Instant; use lcc_catalog::{MediaKind, Op, Photo, Source}; use lcc_engine::Session; -const BODIES: [(&str, &str); 4] = [("Canon EOS R5", "CR3"), ("SONY ILCE-7M4", "ARW"), ("NIKON CORPORATION NIKON Z 6_2", "NEF"), ("FUJIFILM X-T4", "RAF")]; +const BODIES: [(&str, &str); 4] = + [("Canon EOS R5", "CR3"), ("SONY ILCE-7M4", "ARW"), ("NIKON CORPORATION NIKON Z 6_2", "NEF"), ("FUJIFILM X-T4", "RAF")]; fn main() { let _ = env_logger_lite(); diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 8918abd72f..c55e9f59ce 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -567,7 +567,11 @@ thread_local! { /// The latest-preview keys of the edited photos among `photos` ([`Session::keep_edited_previews_last`]): /// `None` when `stop` said so. `stop` is asked, and `progress` told (done, of), every few thousand photos. -fn edited_preview_keys(photos: &[std::sync::Arc], stop: &dyn Fn() -> bool, progress: &dyn Fn(usize, usize)) -> Option> { +fn edited_preview_keys( + photos: &[std::sync::Arc], + stop: &dyn Fn() -> bool, + progress: &dyn Fn(usize, usize), +) -> Option> { const STEP: usize = 4096; let mut keys = Vec::new(); // (a camera is looked up by name once, not once per photo: most of the time this took) diff --git a/crates/engine/src/tests_library.rs b/crates/engine/src/tests_library.rs index a36dcf15ca..ef2881f24e 100644 --- a/crates/engine/src/tests_library.rs +++ b/crates/engine/src/tests_library.rs @@ -1037,7 +1037,8 @@ fn large_library(dir: &std::path::Path, n: usize, edited: usize) -> (lcc_catalog for i in 0..n { let id = s.catalog.alloc_photo_id(); let path = format!("/photos/IMG_{i:05}.CR3"); - let mut p = lcc_catalog::Photo::new(id, lcc_catalog::Source::File { path }, &format!("IMG_{i:05}.CR3"), "CR3", 6000, 4000, "2026-01-01T00:00:00"); + let mut p = + lcc_catalog::Photo::new(id, lcc_catalog::Source::File { path }, &format!("IMG_{i:05}.CR3"), "CR3", 6000, 4000, "2026-01-01T00:00:00"); p.kind = lcc_catalog::MediaKind::Raw; p.meta.camera = "Canon EOS R5".into(); p.as_shot_wb = Some((5200.0, 3.0));