From 4564884ae597ed35dfd7b1fb10163d987f4ae9d6 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 19 Nov 2026 15:09:31 +0100 Subject: [PATCH 01/42] LR-LIB-VIRTUALCOPY: Share source reads across Reload and Recheck Group source reads by family and path and retain every explicitly selected metadata target. Reuse the same freshness tickets for Reload and Recheck, invalidate superseded reads during Relink and history, and report recovery only for accepted probes. --- Cargo.lock | 1 + assets/ATTRIBUTION.md | 1 + crates/engine/src/cmd/convert.rs | 54 ++-- crates/engine/src/cmd/recheck.rs | 65 ++--- crates/engine/src/cmd/reload.rs | 159 +++++++++--- crates/engine/src/files/tests.rs | 15 ++ crates/engine/src/lib.rs | 14 +- crates/engine/src/tests.rs | 24 ++ crates/engine/src/tests/import.rs | 304 +++++++++++++++++++++++ crates/engine/src/tests/recheck.rs | 299 +++++++++++++++++++++- crates/engine/tests/it/orf_withdrawal.rs | 10 +- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/recheck.rs | 2 +- crates/ui-egui/src/reload.rs | 23 +- crates/ui-egui/src/tests/recheck.rs | 108 +++++++- docs/gaps.md | 3 + docs/parity-checklist.md | 3 +- 17 files changed, 943 insertions(+), 143 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2bad8366a63..1cb259e8604 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6170,6 +6170,7 @@ dependencies = [ "lightcraft-pipeline", "lightcraft-preview", "lightcraft-raster", + "lightcraft-raw", "lightcraft-slideshow", "lightcraft-testkit", "log", diff --git a/assets/ATTRIBUTION.md b/assets/ATTRIBUTION.md index 7ac5695d7a8..15c2ded7367 100644 --- a/assets/ATTRIBUTION.md +++ b/assets/ATTRIBUTION.md @@ -28,6 +28,7 @@ covers a whole directory), or if a licence file referenced in the Licence column | `crates/raw/src/chart_table.rs` | Chart-measured camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D50) for the Canon EOS D60 | LightCraft contributors; ColorChecker photographs taken by Robert Woldberg on the maintainer's EOS D60 | original work: fitted to our own CRWs of a ColorChecker Classic (post-November-2014 formulation) under a ~2,900 K tungsten bulb (11 frames) and direct sun (~4,850 K, 20 frames); reference colours: X-Rite's published L*a*b* (D50) for the chart, as packaged by [colour-science](https://github.com/colour-science/colour) (BSD-3-Clause), used for fitting only and not shipped; method in `clean-room/crw/10-chart-calibration.md` | MIT OR Apache-2.0 | 2026-10-25 | kept by hand: a 3×3 matrix per illuminant fitted on chromaticity with neutral held at D50; no Adobe or third-party camera matrix, no number from a GPL raw decoder | | `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none | | `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a | +| `crates/ui-egui/src/tests/recheck.rs`, `crates/engine/src/{files/tests.rs,tests/{recheck,import}.rs}` (runtime fixtures) | Generated source and Reload fixtures | LightCraft contributors | original work: procedural RGB pixels, a linear DNG generated by LightCraft and a synthetic uncompressed ORF | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-11-25 | generated at runtime, no binary fixture committed | | `crates/ui-egui/src/icons.rs` | UI icons drawn as vector paths in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-09-30 | n/a | | `crates/ui-egui/src/panels/person.rs` | Up arrow on the People page bulk-confirm control, drawn in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-10-13 | n/a | | `docs/images/*-tetons.jpg`, `docs/images/grid-pd.jpg` (screenshots containing it) | "The Tetons and the Snake River" | Ansel Adams (1942), U.S. National Archives | https://commons.wikimedia.org/wiki/File:Adams_The_Tetons_and_the_Snake_River.jpg | Public domain (U.S. federal government work) | 2026-09-30 | developed in LightCraft; shown inside app screenshots | diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index cf0991f4e3d..f66a724f52b 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -224,7 +224,7 @@ pub(crate) fn content_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalo } /// Ops that fill a photo's empty camera fields (camera, lens, exposure, GPS, capture time) from a fresh probe. -fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo) -> Vec { +pub(crate) fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo) -> Vec { let (mut m, src) = (ph.meta.clone(), &info.meta); let before = m.clone(); if m.camera.is_empty() { @@ -315,7 +315,7 @@ pub(crate) fn as_shot_wb_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_cat (ph.develops_raw() && !ph.relative_wb() && ph.as_shot_wb != Some(read)).then_some(Op::SetAsShotWb { id, wb: Some(read) }) } -/// The ops that bring photo `id` and its virtual copies up to date with what their file is now +/// The ops that bring photo `id` and its same-file family up to date with what their file is now /// (`info`, a fresh probe), appended to `ops`; the photos they change are appended to `changed`. /// Reload and the preview-only recheck (`library.recheckPreviewOnly`) share it. pub(crate) fn reload_ops( @@ -324,36 +324,35 @@ pub(crate) fn reload_ops( info: &crate::media::ProbeInfo, ops: &mut Vec, changed: &mut Vec, + targets: impl IntoIterator, + metadata_target: impl Fn(lightcraft_catalog::PhotoId) -> bool, ) { let Some(ph) = cat.photo(id) else { return }; - // camera fields the catalog lacks (e.g. a raw imported before its format was read) are filled in; - // nothing already set is overwritten - let meta_ops = fill_missing_meta(id, ph, info); - let mut mine: Vec = - content_op(id, ph, info.clone()).into_iter().chain(meta_ops).chain(lens_ops(id, ph, info)).chain(as_shot_wb_op(id, ph, info)).collect(); - if !mine.is_empty() { - ops.append(&mut mine); - changed.push(id); - } - // virtual copies share the file - for c in cat.photos().filter(|c| c.copy_of == Some(id)) { - let mut meta = c.meta.clone(); - // Copies share the source file but may have independently edited metadata. Repair only - // recognizable legacy shutter values, not every missing field on the copy. - let shutter_op = repair_legacy_shutter(&mut meta, &info.meta).then(|| Op::SetMeta { id: c.id, meta: Box::new(meta) }); - let theirs: Vec = content_op(c.id, c, info.clone()) - .into_iter() - .chain(shutter_op) - .chain(lens_ops(c.id, c, info)) - .chain(as_shot_wb_op(c.id, c, info)) - .collect(); - if !theirs.is_empty() { - ops.extend(theirs); + // Only same-file family members share a probe; independently relinked copies keep their facts. + for c in targets.into_iter().filter_map(|id| cat.photo(id)).filter(|c| !c.deleted && shares_reload_source(c, ph)) { + let metadata = if metadata_target(c.id) { + fill_missing_meta(c.id, c, info) + } else { + // A fallback representative is still implicit: only repair recognizable legacy + // shutter values, without filling independent metadata from the shared file. + let mut meta = c.meta.clone(); + repair_legacy_shutter(&mut meta, &info.meta).then(|| Op::SetMeta { id: c.id, meta: Box::new(meta) }).into_iter().collect() + }; + let wb = as_shot_wb_op(c.id, c, info); + let before = ops.len(); + ops.extend(content_op(c.id, c, info.clone()).into_iter().chain(metadata).chain(lens_ops(c.id, c, info)).chain(wb)); + if ops.len() != before { changed.push(c.id); } } } +/// Copies share probe results only while both the family and the actual file agree. +pub(crate) fn shares_reload_source(a: &lightcraft_catalog::Photo, b: &lightcraft_catalog::Photo) -> bool { + a.copy_of.unwrap_or(a.id) == b.copy_of.unwrap_or(b.id) + && matches!((&a.source, &b.source), (Source::File { path: a }, Source::File { path: b }) if a == b) +} + /// Re-read photos whose files changed on disk (an external editor saved them): new size, /// dimensions and content hash, cached sources dropped. The app runs the same steps /// ([`crate::cmd::reload`]) with the files read on a worker thread. → {reloaded: [ids]} @@ -362,8 +361,7 @@ fn reload(s: &mut Session, p: &Value) -> Result { let items = r::plan(s, p)?; let probe = r::file_probe(s); let results = r::probe(probe.as_ref(), &items, &std::sync::atomic::AtomicBool::new(false), &|_| {}); - let reloaded = r::apply(s, items, results)?; - Ok(r::to_json(&reloaded)) + Ok(r::apply(s, items, results)?.to_json()) } /// Duplicate: copy the file next to itself (`-copy`, never overwriting) and add it with the @@ -526,7 +524,7 @@ mod tests { info.meta.title = "File title".into(); let mut ops = Vec::new(); let mut changed = Vec::new(); - reload_ops(&cat, source.id, &info, &mut ops, &mut changed); + reload_ops(&cat, source.id, &info, &mut ops, &mut changed, (1..=5).map(PhotoId), |id| id == source.id); for op in ops { cat.apply(op).unwrap(); } diff --git a/crates/engine/src/cmd/recheck.rs b/crates/engine/src/cmd/recheck.rs index 359f588ae54..f99279a1677 100644 --- a/crates/engine/src/cmd/recheck.rs +++ b/crates/engine/src/cmd/recheck.rs @@ -1,7 +1,7 @@ //! Preview-only raws rechecked after an update (issue #662): a raw imported while its format or -//! variant couldn't be decoded keeps [`Photo::preview_only`] until something re-reads its file. -//! Each flag is stamped with the app version that set it ([`Photo::preview_checked`]); when a -//! library opens in another version, its stale preview-only photos are probed again and get +//! variant couldn't be decoded keeps [`lightcraft_catalog::Photo::preview_only`] until something re-reads its file. +//! Each flag is stamped with the app version that set it ([`lightcraft_catalog::Photo::preview_checked`]); +//! when a library opens with another version, its stale preview-only photos are probed again and get //! exactly what Reload from Disk would give them: a file that decodes now loses the flag, one that //! still doesn't gets the new reason and a fresh stamp, so it isn't probed again. //! ORF records are rechecked even when previously sensor-decodable: compressed sensor support @@ -12,42 +12,28 @@ //! results as LightCraft's own bookkeeping (journaled, not an undo step). Agents and tests use //! `library.recheckPreviewOnly`, which does all three at once. -use lightcraft_catalog::{Catalog, Op, Photo, PhotoId}; +use lightcraft_catalog::{Op, PhotoId}; use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd}; use crate::media::{FileProbe, ProbeInfo}; use crate::{Result, Session}; -/// A photo to probe, and what the library knew about it when it was listed (so a -/// result for a photo that changed meanwhile is dropped). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Stale { - pub id: PhotoId, - pub path: String, - preview_only: Option, - preview_checked: String, -} - -impl Stale { - fn of(p: &Photo, path: &str) -> Stale { - Stale { id: p.id, path: path.to_string(), preview_only: p.preview_only.clone(), preview_checked: p.preview_checked.clone() } - } - - /// The photo is still as it was listed: same file, flag and stamp. - fn current(&self, p: &Photo) -> bool { - p.library_file() == Some(self.path.as_str()) && p.preview_only == self.preview_only && p.preview_checked == self.preview_checked - } -} +/// A grouped source read, with Reload's membership and freshness checks. +pub use super::reload::Item as Stale; /// The library's preview-only photos and ORFs whose support another app version checked (or -/// every such photo, with `all`): library photos with a file, not virtual copies (they follow -/// the photo they were copied from). No file-system calls. -pub fn stale(cat: &Catalog, all: bool) -> Vec { - cat.photos() - .filter(|p| p.copy_of.is_none() && (p.preview_only_stale() || (all && (p.preview_only.is_some() || p.format.eq_ignore_ascii_case("orf"))))) - .filter_map(|p| p.library_file().map(|path| Stale::of(p, path))) - .collect() +/// every such photo, with `all`), grouped by family and path under a new source-read ticket. Every +/// same-file member retains its ticket so a copy can use the result if its representative relinks. +/// Local browsing records are included. No file-system calls. +pub fn stale(s: &mut Session, all: bool) -> Vec { + let ids = s + .catalog + .photos() + .filter(|p| p.preview_only_stale() || (all && (p.preview_only.is_some() || p.format.eq_ignore_ascii_case("orf")))) + .map(|p| p.id) + .collect(); + super::reload::plan_ids(s, ids) } /// The session's file probe, to [`probe`] with on a worker thread; `None` when the session has no @@ -79,18 +65,16 @@ impl Rechecked { /// Apply [`probe`]'s results: each photo gets the ops Reload would give it, all in one batch that is /// journaled but isn't an undo step. A file that can't be read (missing, offline) changes nothing, -/// so it is tried again next time; a photo that changed since it was listed (relinked, reloaded, -/// removed) is skipped. +/// so it is tried again next time. Relink, removal and source history invalidate pending reads; +/// a completed older read leaves newer pending reads usable. pub fn apply(s: &mut Session, results: Vec<(Stale, std::result::Result)>) -> Result { let mut ops = Vec::new(); let mut out = Rechecked::default(); - for (item, info) in results { + for (mut item, info) in results { let Ok(info) = info else { continue }; - if !s.catalog.photo(item.id).is_some_and(|p| item.current(p)) { - continue; - } + let Some(id) = item.accept(s) else { continue }; let first = out.updated.len(); - crate::cmd::convert::reload_ops(&s.catalog, item.id, &info, &mut ops, &mut out.updated); + crate::cmd::convert::reload_ops(&s.catalog, id, &info, &mut ops, &mut out.updated, item.source_targets, |id| id == item.id); if info.preview_only.is_none() { out.cleared.extend(out.updated[first..].iter().copied().filter(|id| s.catalog.photo(*id).is_some_and(|p| p.preview_only.is_some()))); } @@ -98,6 +82,7 @@ pub fn apply(s: &mut Session, results: Vec<(Stale, std::result::Result Result { let all = p.get("all").and_then(Value::as_bool).unwrap_or(false); // without file access every probe "succeeds" with nothing known, which would clear every flag let fp = file_probe(s).ok_or_else(|| bad(C, "this session has no file access"))?; - let listed = stale(&s.catalog, all); + let listed = stale(s, all); let n = listed.len(); let mut r = apply(s, probe(&fp, listed))?.to_json(); r["checked"] = json!(n); @@ -122,7 +107,7 @@ pub fn specs() -> Vec { "Recheck Preview-Only Raws", [], None, - "{all?: bool} — probe again preview-only raws and ORFs whose support another LightCraft version checked (the app does this in the background when a library opens; `all` rechecks every preview-only raw and ORF, e.g. when testing a decoder build of the same version), and bring each up to date as Reload from Disk would; not an undo step, develop settings and history are kept; files that can't be read are left for next time → {checked, updated: [ids], cleared: [ids] (develop from their raw data now)}", + "{all?: bool} — probe again preview-only raws and ORFs whose support another app version checked (the app does this in the background when a library opens; `all` rechecks every preview-only raw and ORF), and bring each up to date as Reload from Disk would; not an undo step, develop settings and history are kept; files that can't be read are left for next time → {checked, updated: [ids], cleared: [ids] (develop from their raw data now)}", always, recheck )] diff --git a/crates/engine/src/cmd/reload.rs b/crates/engine/src/cmd/reload.rs index 0c1cb964cda..cd9a2c510e0 100644 --- a/crates/engine/src/cmd/reload.rs +++ b/crates/engine/src/cmd/reload.rs @@ -8,6 +8,7 @@ //! each [`plan`] takes a ticket and [`apply`] drops a photo's result when a reload planned later //! has already been applied to it: an older read never replaces a newer one. +use std::collections::HashSet; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use lightcraft_catalog::{Op, PhotoId, Source}; @@ -16,37 +17,111 @@ use serde_json::{Value, json}; use crate::media::{FileProbe, ProbeInfo}; use crate::{Result, Session}; -/// A photo to re-read: its id and the file it had when it was listed (a photo relinked meanwhile -/// is skipped by [`apply`]). +/// One family’s file to re-read, retaining every explicitly selected metadata target. +/// [`apply`] skips targets removed or relinked meanwhile. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Item { pub id: PhotoId, pub path: String, + /// Explicitly selected photos sharing this probe; each may gain missing metadata. + pub metadata_targets: Vec, + /// Same-file family members present at planning time, including implicit fallback targets. + pub(crate) source_targets: Vec, + family: PhotoId, /// The [`plan`] it came from, in the order reloads were started (see [`Tickets`]). pub ticket: u64, } -/// Which reload each photo last took its file information from, so a reload started earlier but -/// finishing later doesn't put back what its file was before (session memory, not saved). +impl Item { + /// Accept a successful read for the still-current members, returning its representative. + pub(crate) fn accept(&mut self, s: &mut Session) -> Option { + self.source_targets.retain(|id| { + s.reload_tickets.valid(*id, self.ticket) + && s.catalog.photo(*id).is_some_and(|p| { + !p.deleted && p.copy_of.unwrap_or(p.id) == self.family && matches!(&p.source, Source::File { path } if *path == self.path) + }) + }); + let id = *self.source_targets.first()?; + s.reload_tickets.accept(self.family, self.path.clone(), self.ticket).then_some(id) + } +} + +/// Which Reload or recheck each same-file family last took its file information from, so an older read +/// cannot replace a newer one. A relink must not carry freshness to another file (session memory). #[derive(Debug, Default)] pub struct Tickets { last: u64, - applied: std::collections::BTreeMap, + applied: std::collections::BTreeMap<(PhotoId, String), u64>, + invalidated: std::collections::BTreeMap, +} + +impl Tickets { + /// Planning order shared by Reload and automatic raw rechecks. + pub(crate) fn next(&mut self) -> u64 { + self.last = self.last.saturating_add(1); + self.last + } + + /// A catalog source change supersedes reads already planned for this photo. + pub(crate) fn invalidate(&mut self, id: PhotoId) { + self.invalidated.insert(id, self.last); + } + + /// Keep changed file facts without cancelling an untouched sibling's pending read. + pub(crate) fn valid(&self, id: PhotoId, ticket: u64) -> bool { + self.invalidated.get(&id).is_none_or(|cutoff| *cutoff < ticket) + } + + /// Only a newer completed read of this family's file supersedes its result. + pub(crate) fn accept(&mut self, family: PhotoId, path: String, ticket: u64) -> bool { + let key = (family, path); + if self.applied.get(&key).is_some_and(|latest| *latest > ticket) { + return false; + } + self.applied.insert(key, ticket); + true + } } -/// The photos `p` targets (`ids`, else the selection) that have a file, under a new ticket. No -/// file-system calls. +/// The files `p` targets (`ids`, else the selection), grouped by family and path under a new +/// ticket. No file-system calls. pub fn plan(s: &mut Session, p: &Value) -> Result> { let ids = s.targets(p)?; - s.reload_tickets.last = s.reload_tickets.last.saturating_add(1); - let ticket = s.reload_tickets.last; - Ok(ids - .into_iter() - .filter_map(|id| match s.catalog.photo(id).map(|ph| &ph.source) { - Some(Source::File { path }) => Some(Item { id, path: path.clone(), ticket }), - _ => None, - }) - .collect()) + Ok(plan_ids(s, ids)) +} + +/// Group explicit targets and index their same-file siblings once, also for automatic rechecks. +pub(crate) fn plan_ids(s: &mut Session, ids: Vec) -> Vec { + let mut groups = std::collections::HashMap::<(PhotoId, &str), usize>::new(); + let mut items: Vec = Vec::new(); + let mut seen = HashSet::new(); + let ticket = s.reload_tickets.next(); + for id in ids.into_iter().filter(|id| seen.insert(*id)) { + let Some(ph) = s.catalog.photo(id) else { continue }; + if ph.deleted { + continue; + } + let Source::File { path } = &ph.source else { continue }; + let family = ph.copy_of.unwrap_or(ph.id); + let key = (family, path.as_str()); + // Sharing a probe must not drop any explicitly selected metadata target. + if let Some(item) = groups.get(&key).and_then(|index| items.get_mut(*index)) { + item.metadata_targets.push(id); + } else { + groups.insert(key, items.len()); + items.push(Item { id, path: path.clone(), metadata_targets: vec![id], source_targets: vec![id], family, ticket }); + } + } + for ph in s.catalog.photos().filter(|p| !p.deleted) { + if let Source::File { path } = &ph.source + && let Some(index) = groups.get(&(ph.copy_of.unwrap_or(ph.id), path.as_str())) + && let Some(item) = items.get_mut(*index) + && ph.id != item.id + { + item.source_targets.push(ph.id); + } + } + items } /// The session's file probe, to [`probe`] with on a worker thread (`None` in a session without file @@ -82,33 +157,39 @@ pub fn probe( r } -/// Commit [`probe`]'s results as one undo step ("Reload Changed Files"): each photo and its virtual -/// copies get what their file is now. A file that couldn't be read changes nothing; a photo removed +/// What Reload checked successfully and what it changed. +#[derive(Debug, Default)] +pub struct Reloaded { + pub reloaded: Vec, + /// Current targets whose probes succeeded, including photos whose facts were unchanged. + pub checked: Vec, +} + +impl Reloaded { + /// `{reloaded: [ids]}`; accepted probes are internal notification bookkeeping. + pub fn to_json(&self) -> Value { + json!({"reloaded": self.reloaded.iter().map(|i| i.0).collect::>()}) + } +} + +/// Commit [`probe`]'s results as one undo step ("Reload Changed Files"): each selected photo and +/// its same-file family get what their file is now. A file that couldn't be read changes nothing; a photo removed /// or relinked since it was listed, or already given a newer reload's result, is skipped. Returns -/// the photos that changed. -pub fn apply(s: &mut Session, items: Vec, results: Vec>) -> Result> { +/// both the accepted probes and the photos that changed. +pub fn apply(s: &mut Session, items: Vec, results: Vec>) -> Result { let mut ops = Vec::new(); - let mut reloaded = Vec::new(); - for (item, info) in items.into_iter().zip(results) { + let mut out = Reloaded::default(); + for (mut item, info) in items.into_iter().zip(results) { let Ok(info) = info else { continue }; - let current = s.catalog.photo(item.id).is_some_and(|ph| matches!(&ph.source, Source::File { path } if *path == item.path)); - let superseded = s.reload_tickets.applied.get(&item.id).is_some_and(|t| *t > item.ticket); - if !current || superseded { - continue; - } - s.reload_tickets.applied.insert(item.id, item.ticket); - crate::cmd::convert::reload_ops(&s.catalog, item.id, &info, &mut ops, &mut reloaded); - } - for id in &reloaded { - s.media.forget(*id); + let Some(id) = item.accept(s) else { continue }; + let selected: HashSet<_> = item.metadata_targets.into_iter().collect(); + crate::cmd::convert::reload_ops(&s.catalog, id, &info, &mut ops, &mut out.reloaded, item.source_targets.iter().copied(), |id| { + selected.contains(&id) + }); + out.checked.extend(item.source_targets); } if !ops.is_empty() { - s.commit("Reload Changed Files", Op::Batch { ops })?; + s.commit_with_read_invalidation("Reload Changed Files", Op::Batch { ops }, false)?; } - Ok(reloaded) -} - -/// `{reloaded: [ids]}`. -pub fn to_json(reloaded: &[PhotoId]) -> Value { - json!({"reloaded": reloaded.iter().map(|i| i.0).collect::>()}) + Ok(out) } diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index 1f724fdd1c0..b77982255a3 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -44,6 +44,21 @@ fn psd_probe_reads_embedded_capture_time_gps_and_title() { use super::*; use lightcraft_codecs::{ChromaSubsampling, EncodeImage, EncodeMeta, Samples, encode_jpeg}; +pub(crate) fn sensor_orf() -> Vec { + use craft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags as t}; + let mut raw = IfdBuilder::new(); + raw.set(t::IMAGE_WIDTH, Value::Long(vec![8])); + raw.set(t::IMAGE_LENGTH, Value::Long(vec![8])); + raw.set(t::BITS_PER_SAMPLE, Value::Short(vec![16])); + raw.set(t::COMPRESSION, Value::Short(vec![1])); + raw.set(t::PHOTOMETRIC, Value::Short(vec![1])); + raw.set(t::MAKE, Value::Ascii("OLYMPUS IMAGING CORP.".into())); + raw.set_image(ImageData::Strips { rows_per_strip: 8, strips: vec![vec![17; 8 * 8 * 2]] }); + let mut sensor = TiffWriter::default().write(&[raw]).unwrap(); + sensor[..4].copy_from_slice(b"IIRO"); + sensor +} + #[test] fn crw_probes_name_their_camera_from_the_ciff_records() { // no Exif in a CRW: the camera and capture time come from the decoder's records, and the catalog's camera diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 04be5d669a0..82bf86d060e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -747,8 +747,13 @@ impl Session { /// it is journaled all the same (replaying it leaves the same changes), and what is left of its rollback is the /// undo step: undoing it finishes the rollback. The error still reaches the caller. pub fn commit(&mut self, label: &str, op: Op) -> Result<()> { + self.commit_with_read_invalidation(label, op, true) + } + + /// A completed source read must leave newer pending reads usable. + pub(crate) fn commit_with_read_invalidation(&mut self, label: &str, op: Op, invalidate_reads: bool) -> Result<()> { let fwd = op.clone(); - let (inv, failure) = match self.apply_through(op, Catalog::apply_new) { + let (inv, failure) = match self.apply_through(op, Catalog::apply_new, invalidate_reads) { Ok(inv) => (inv, None), Err(EngineError::Catalog(CatalogError::PartlyApplied { cause, remaining })) => { let remaining = *remaining; @@ -782,12 +787,12 @@ impl Session { /// [`Catalog::apply`] for what brings back what was (an undo or a redo). fn apply_catalog(&mut self, op: Op) -> Result { - self.apply_through(op, Catalog::apply) + self.apply_through(op, Catalog::apply, true) } /// Apply `op` with `apply` (the catalog's way in for a new edit or for bringing back what /// was), then forget what the session cached of the photos it replaced. - fn apply_through(&mut self, op: Op, apply: fn(&mut Catalog, Op) -> std::result::Result) -> Result { + fn apply_through(&mut self, op: Op, apply: fn(&mut Catalog, Op) -> std::result::Result, invalidate_reads: bool) -> Result { // Retain only cache IDs while the catalog consumes the operation. Cloning an import // batch here also cloned every photo, although commit already keeps the journal copy. let mut invalidated = Vec::new(); @@ -821,6 +826,9 @@ impl Session { self.denoise_photo_changed(id); } for id in invalidated { + if invalidate_reads { + self.reload_tickets.invalidate(id); + } self.media.forget(id); } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 9e4013ffdf7..ac2e591bcb4 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -69,6 +69,30 @@ mod task_queue; mod view_follow; pub(super) mod xmp; +pub(crate) struct TestDir(std::path::PathBuf); + +impl TestDir { + pub(crate) fn new(tag: &str) -> Self { + let dir = Self(std::env::temp_dir().join(format!("lc-{tag}-{}", std::process::id()))); + let _ = std::fs::remove_dir_all(&dir.0); + std::fs::create_dir_all(&dir.0).unwrap(); + dir + } +} + +impl std::ops::Deref for TestDir { + type Target = std::path::Path; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + fn demo() -> Session { Session::with_demo() } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 3b65dbae9a3..ce649275376 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -4800,3 +4800,307 @@ fn a_broken_link_before_dotdot_is_an_error() { assert_eq!(crate::import::browse_spelling(&link.join("..")).unwrap(), dir); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn reload_relinked_virtual_copy_reads_its_own_file() { + reload_relinked_virtual_copy(true); +} + +#[test] +fn reload_original_leaves_relinked_virtual_copy_unchanged() { + reload_relinked_virtual_copy(false); +} + +#[test] +fn reload_copy_refreshes_family_and_keeps_the_metadata_target() { + reload_copy_family_metadata(false); +} + +#[test] +fn reload_selected_copies_fill_metadata_after_deduplication() { + reload_copy_family_metadata(true); +} + +fn reload_copy_family_metadata(select_sibling: bool) { + use crate::cmd::reload; + let dir = super::TestDir::new(&format!("reload-copy-family-{select_sibling}")); + let path = dir.join("original.png"); + write_png(&path, 10); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap(); + let original = s.active().unwrap(); + let r = s.execute("photo.virtualCopy", &json!({"ids": [original.0]})).unwrap(); + let copy = PhotoId(r["ids"][0].as_u64().unwrap()); + let r = s.execute("photo.virtualCopy", &json!({"ids": [original.0]})).unwrap(); + let sibling = PhotoId(r["ids"][0].as_u64().unwrap()); + s.execute("develop.set", &json!({"ids": [copy.0], "control": "light.exposure", "value": 0.7})).unwrap(); + let before: Vec<_> = [original, copy, sibling].map(|id| s.catalog.photo(id).unwrap().clone()).into(); + let old_items = reload::plan(&mut s, &json!({"ids": [original.0]})).unwrap(); + let old_info = reload::file_probe(&s).unwrap()(&path.to_string_lossy()).unwrap(); + write_png(&path, 200); + let targets = if select_sibling { vec![copy.0, sibling.0, copy.0, sibling.0] } else { vec![copy.0, copy.0] }; + let items = reload::plan(&mut s, &json!({"ids": targets})).unwrap(); + assert_eq!(items.len(), 1, "one probe per shared file"); + assert_eq!(items[0].id, copy, "keep the explicit metadata target"); + assert_eq!(items[0].metadata_targets.len(), if select_sibling { 2 } else { 1 }, "each selected photo counts once"); + let mut info = reload::file_probe(&s).unwrap()(&path.to_string_lossy()).unwrap(); + info.meta.camera = "new camera metadata".into(); + let changed = reload::apply(&mut s, items, vec![Ok(info)]).unwrap().reloaded; + assert_eq!(changed.len(), 3); + for old in &before { + let new = s.catalog.photo(old.id).unwrap(); + assert_ne!(new.content_hash, old.content_hash); + assert_eq!(new.develop, old.develop); + assert_eq!(new.meta.camera, if old.id == copy || (select_sibling && old.id == sibling) { "new camera metadata" } else { "" }); + } + assert!( + reload::apply(&mut s, old_items, vec![Ok(old_info)]).unwrap().reloaded.is_empty(), + "the newer copy reload supersedes its original's old result" + ); + s.execute("edit.undo", &json!({})).unwrap(); + for old in &before { + assert_eq!(s.catalog.photo(old.id).unwrap(), old); + } + s.execute("edit.redo", &json!({})).unwrap(); + for old in &before { + assert_ne!(s.catalog.photo(old.id).unwrap().content_hash, old.content_hash); + } +} + +fn reload_relinked_virtual_copy(from_copy: bool) { + let dir = super::TestDir::new(&format!("reload-relinked-copy-{from_copy}")); + let original_path = dir.join("original.png"); + let copy_path = dir.join("other.png"); + write_png(&original_path, 10); + write_png(©_path, 20); + let mut s = Session::new().with_fs(); + let r = s.execute("library.import", &json!({"paths": [original_path.to_string_lossy()]})).unwrap(); + let original = PhotoId(r["imported"][0].as_u64().unwrap()); + let mut copies = Vec::new(); + for _ in 0..2 { + let r = s.execute("photo.virtualCopy", &json!({"ids": [original.0]})).unwrap(); + copies.push(PhotoId(r["ids"][0].as_u64().unwrap())); + } + let (copy, sibling) = (copies[0], copies[1]); + s.execute("photo.relink", &json!({"id": copy.0, "path": copy_path.to_string_lossy()})).unwrap(); + assert_eq!(s.catalog.photo(copy).unwrap().copy_of, Some(original)); + let before: Vec<_> = [original, sibling, copy].into_iter().map(|id| s.catalog.photo(id).unwrap().clone()).collect(); + write_png(&original_path, 100); + write_png(©_path, 200); + + if from_copy { + // A relinked copy keeps its own probe; same-file siblings still share one original probe. + let items = crate::cmd::reload::plan(&mut s, &json!({"ids": [copy.0, original.0, sibling.0]})).unwrap(); + assert_eq!(items.iter().map(|item| item.id).collect::>(), vec![copy, original]); + assert_eq!(items[0].path, copy_path.to_string_lossy()); + assert_eq!(items[1].path, original_path.to_string_lossy()); + } + let target = if from_copy { copy } else { original }; + let changed = if from_copy { vec![copy] } else { vec![original, sibling] }; + let r = s.execute("photo.reload", &json!({"ids": [target.0]})).unwrap(); + assert_eq!(r["reloaded"], json!(changed.iter().map(|id| id.0).collect::>())); + for old in &before { + let new = s.catalog.photo(old.id).unwrap(); + if changed.contains(&old.id) { + assert_ne!(new.content_hash, old.content_hash); + assert_eq!(new.develop, old.develop); + } else { + assert_eq!(new, old, "a photo using another file stays unchanged"); + } + } + s.execute("edit.undo", &json!({})).unwrap(); + for old in &before { + assert_eq!(s.catalog.photo(old.id).unwrap(), old, "reload remains one undo step"); + } +} + +#[test] +fn reload_ticket_stays_with_its_file_after_a_copy_is_relinked() { + use crate::cmd::reload; + let dir = super::TestDir::new("reload-relinked-ticket"); + let original_path = dir.join("original.png"); + let other_path = dir.join("other.png"); + write_png(&original_path, 10); + write_png(&other_path, 20); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [original_path.to_string_lossy()]})).unwrap(); + let original = s.active().unwrap(); + let r = s.execute("photo.virtualCopy", &json!({"ids": [original.0]})).unwrap(); + let copy = PhotoId(r["ids"][0].as_u64().unwrap()); + s.execute("photo.relink", &json!({"id": copy.0, "path": other_path.to_string_lossy()})).unwrap(); + write_png(&original_path, 100); + let original_items = reload::plan(&mut s, &json!({"ids": [original.0]})).unwrap(); + let original_info = reload::file_probe(&s).unwrap()(&original_path.to_string_lossy()).unwrap(); + let expected = original_info.content_hash.clone(); + let copy_items = reload::plan(&mut s, &json!({"ids": [copy.0]})).unwrap(); + let copy_info = reload::file_probe(&s).unwrap()(&other_path.to_string_lossy()).unwrap(); + reload::apply(&mut s, copy_items, vec![Ok(copy_info)]).unwrap(); + s.execute("photo.relink", &json!({"id": copy.0, "path": original_path.to_string_lossy()})).unwrap(); + + let changed = reload::apply(&mut s, original_items, vec![Ok(original_info)]).unwrap().reloaded; + assert!(changed.contains(&original), "a newer read of another file must not supersede this result"); + assert_eq!(s.catalog.photo(original).unwrap().content_hash, expected); + assert_eq!(s.catalog.photo(copy).unwrap().content_hash, expected); +} + +#[test] +fn reload_keeps_selected_targets_when_the_probe_representative_relinks() { + use crate::cmd::reload; + let dir = super::TestDir::new("reload-relinked-representative"); + let original_path = dir.join("original.png"); + let other_path = dir.join("other.png"); + write_png(&original_path, 10); + write_png(&other_path, 20); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [original_path.to_string_lossy()]})).unwrap(); + let original = s.active().unwrap(); + let r = s.execute("photo.virtualCopy", &json!({"ids": [original.0]})).unwrap(); + let copy = PhotoId(r["ids"][0].as_u64().unwrap()); + let items = reload::plan(&mut s, &json!({"ids": [copy.0, original.0]})).unwrap(); + assert_eq!(items.len(), 1); + assert_eq!(items[0].id, copy); + write_png(&original_path, 100); + let mut info = reload::file_probe(&s).unwrap()(&original_path.to_string_lossy()).unwrap(); + let expected = info.content_hash.clone(); + info.meta.camera = "fresh metadata".into(); + s.execute("photo.relink", &json!({"id": copy.0, "path": other_path.to_string_lossy()})).unwrap(); + let relinked = s.catalog.photo(copy).unwrap().clone(); + + assert_eq!(reload::apply(&mut s, items, vec![Ok(info)]).unwrap().reloaded, vec![original]); + let parent = s.catalog.photo(original).unwrap(); + assert_eq!(parent.content_hash, expected); + assert_eq!(parent.meta.camera, "fresh metadata"); + assert_eq!(s.catalog.photo(copy).unwrap(), &relinked); +} + +#[test] +fn review_relink_rejects_old_reload_facts_only_for_the_changed_photo() { + use crate::cmd::reload; + let dir = super::TestDir::new("reload-relink-aba"); + let a = dir.join("a.png"); + let b = dir.join("b.png"); + write_png(&a, 10); + write_png(&b, 20); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + let copy = PhotoId(s.execute("photo.virtualCopy", &json!({"ids": [id.0]})).unwrap()["ids"][0].as_u64().unwrap()); + s.execute("photo.relink", &json!({"id": copy.0, "path": a.to_string_lossy()})).unwrap(); + let items = reload::plan(&mut s, &json!({"ids": [id.0, copy.0]})).unwrap(); + let mut old = reload::file_probe(&s).unwrap()(&a.to_string_lossy()).unwrap(); + old.meta.camera = "old probe metadata".into(); + s.execute("photo.relink", &json!({"id": id.0, "path": b.to_string_lossy()})).unwrap(); + write_png(&a, 200); + s.execute("photo.relink", &json!({"id": id.0, "path": a.to_string_lossy()})).unwrap(); + let current = s.catalog.photo(id).unwrap().clone(); + let changed = reload::apply(&mut s, items, vec![Ok(old)]).unwrap().reloaded; + assert!(!changed.contains(&id)); + assert_eq!(s.catalog.photo(id).unwrap(), ¤t, "the replaced A keeps its current facts"); + assert_eq!(s.catalog.photo(copy).unwrap().meta.camera, "old probe metadata", "the untouched sibling keeps its pending reload"); + write_png(&a, 201); + let fresh = s.execute("photo.reload", &json!({"ids": [id.0]})).unwrap(); + assert!(fresh["reloaded"].as_array().unwrap().contains(&json!(id.0)), "a newly planned reload is accepted"); +} + +#[test] +fn source_history_rejects_pending_reload_without_cancelling_untouched_siblings() { + use crate::cmd::reload; + for redo in [false, true] { + let dir = super::TestDir::new(&format!("reload-history-{redo}")); + let path = dir.join("original.png"); + write_png(&path, 10); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [path.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + let copy = PhotoId(s.execute("photo.virtualCopy", &json!({"id": id.0})).unwrap()["ids"][0].as_u64().unwrap()); + write_png(&path, 20); + s.execute("photo.relink", &json!({"id": id.0, "path": path.to_string_lossy()})).unwrap(); + if redo { + s.execute("edit.undo", &json!({})).unwrap(); + } + let items = reload::plan(&mut s, &json!({"ids": [id.0, copy.0]})).unwrap(); + write_png(&path, 30); + let old = reload::file_probe(&s).unwrap()(&path.to_string_lossy()).unwrap(); + s.execute(if redo { "edit.redo" } else { "edit.undo" }, &json!({})).unwrap(); + let current = s.catalog.photo(id).unwrap().clone(); + let changed = reload::apply(&mut s, items, vec![Ok(old)]).unwrap().reloaded; + assert_eq!(s.catalog.photo(id).unwrap(), ¤t, "history protects the restored source facts"); + assert_eq!(changed, [copy], "history leaves an untouched sibling's pending read usable"); + assert_eq!(s.execute("photo.reload", &json!({"id": id.0})).unwrap()["reloaded"], json!([id.0])); + } +} + +#[test] +fn review_relinked_reload_keeps_an_implicit_same_file_copy() { + use crate::cmd::reload; + use lightcraft_catalog::Op; + let dir = super::TestDir::new("reload-relink-implicit-copy"); + let a = dir.join("a.png"); + let b = dir.join("b.png"); + write_png(&a, 10); + write_png(&b, 20); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + let copy = PhotoId(s.execute("photo.virtualCopy", &json!({"ids": [id.0]})).unwrap()["ids"][0].as_u64().unwrap()); + let p = s.catalog.photo(copy).unwrap().clone(); + let mut metadata = p.meta.clone(); + metadata.shutter = "1/2".into(); + s.catalog.apply(Op::SetMeta { id: copy, meta: Box::new(metadata) }).unwrap(); + s.catalog + .apply(Op::SetContent { + id: copy, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + preview_only: Some("old unsupported source".into()), + preview_checked: "old".into(), + }) + .unwrap(); + let items = reload::plan(&mut s, &json!({"ids": [id.0]})).unwrap(); + let mut old = reload::file_probe(&s).unwrap()(&a.to_string_lossy()).unwrap(); + old.meta.camera = "must not fill the unselected copy".into(); + old.meta.lens = "must not fill the unselected copy".into(); + old.meta.shutter = "0.4".into(); + old.meta.exposure_time = Some(0.4); + s.execute("photo.relink", &json!({"id": id.0, "path": b.to_string_lossy()})).unwrap(); + write_png(&a, 200); + s.execute("photo.relink", &json!({"id": id.0, "path": a.to_string_lossy()})).unwrap(); + let current = s.catalog.photo(id).unwrap().clone(); + let changed = reload::apply(&mut s, items, vec![Ok(old)]).unwrap().reloaded; + assert!(!changed.contains(&id) && changed.contains(©)); + assert_eq!(s.catalog.photo(id).unwrap(), ¤t); + let sibling = s.catalog.photo(copy).unwrap(); + assert!(sibling.preview_only.is_none()); + assert!(sibling.meta.camera.is_empty() && sibling.meta.lens.is_empty()); + assert_eq!((sibling.meta.shutter.as_str(), sibling.meta.exposure_time), ("0.4", Some(0.4))); +} + +#[test] +fn review_reload_keeps_an_implicit_copy_when_its_selected_parent_moves() { + use crate::cmd::reload; + let dir = super::TestDir::new("reload-parent-moves"); + let a = dir.join("a.png"); + let b = dir.join("b.png"); + write_png(&a, 10); + write_png(&b, 20); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [a.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + let copy = PhotoId(s.execute("photo.virtualCopy", &json!({"ids": [id.0]})).unwrap()["ids"][0].as_u64().unwrap()); + let items = reload::plan(&mut s, &json!({"ids": [id.0]})).unwrap(); + write_png(&a, 200); + let mut info = reload::file_probe(&s).unwrap()(&a.to_string_lossy()).unwrap(); + let hash = info.content_hash.clone(); + info.meta.camera = "must not fill implicit metadata".into(); + s.execute("photo.relink", &json!({"id": id.0, "path": b.to_string_lossy()})).unwrap(); + let parent = s.catalog.photo(id).unwrap().clone(); + let before = s.catalog.photo(copy).unwrap().clone(); + assert_eq!(reload::apply(&mut s, items, vec![Ok(info)]).unwrap().reloaded, vec![copy]); + let photo = s.catalog.photo(copy).unwrap(); + assert_eq!(photo.content_hash, hash); + assert_ne!(photo.content_hash, before.content_hash); + assert_eq!(photo.meta.camera, before.meta.camera); + assert_eq!(s.catalog.photo(id).unwrap(), &parent); +} diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index 9f7dab984f9..b3513017d00 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -1,4 +1,4 @@ -//! Issue #662: preview-only raws are rechecked when a library opens in another app version. +//! Issue #662: preview-only raws are rechecked when a library opens with another app version. use std::path::PathBuf; @@ -14,23 +14,16 @@ const OTHER: &str = "0.5.0"; struct Lib { s: Session, - dir: PathBuf, + dir: super::TestDir, lib: PathBuf, file: PathBuf, id: PhotoId, } -impl Drop for Lib { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.dir); - } -} - /// A library with one preview-only CR3, its flag stamped by [`OTHER`] as a library saved by /// another version would be. fn library(name: &str) -> Lib { - let dir = std::env::temp_dir().join(format!("lc-recheck-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let dir = super::TestDir::new(&format!("recheck-{name}")); let (lib, files) = (dir.join("lib"), dir.join("files")); std::fs::create_dir_all(&files).unwrap(); let file = files.join("IMG_0001.cr3"); @@ -118,7 +111,7 @@ fn missing_file_keeps_its_flag_and_stamp_and_is_retried() { #[test] fn photo_changed_while_probing_is_skipped() { let mut x = library("changed"); - let listed = recheck::stale(&x.s.catalog, false); + let listed = recheck::stale(&mut x.s, false); assert_eq!(listed.iter().map(|i| i.id).collect::>(), vec![x.id]); let probed = recheck::probe(&recheck::file_probe(&x.s).unwrap(), listed); decodable_now(&x); @@ -137,7 +130,7 @@ fn virtual_copies_follow_their_photo() { let r = x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap(); let copy = PhotoId(r["ids"][0].as_u64().unwrap()); assert!(x.s.catalog.photo(copy).unwrap().preview_only.is_some()); - assert_eq!(recheck::stale(&x.s.catalog, true).len(), 1, "copies aren't probed on their own"); + assert_eq!(recheck::stale(&mut x.s, true).len(), 1, "copies aren't probed on their own"); decodable_now(&x); let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); assert_eq!(r["cleared"], json!([x.id.0, copy.0])); @@ -153,3 +146,285 @@ fn session_without_file_access_refuses() { assert!(e.contains("no file access"), "{e}"); assert!(x.s.catalog.photo(x.id).unwrap().preview_only.is_some()); } + +/// Relinked copies must be checked independently, and must not receive their parent's file facts. +#[test] +fn relinked_copy_rechecks_its_own_file() { + let mut x = library("relinked-copy"); + let r = x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap(); + let copy = PhotoId(r["ids"][0].as_u64().unwrap()); + let other = x.dir.join("files/other.cr3"); + std::fs::write(&other, cr3_with_preview(120, 80)).unwrap(); + x.s.execute("photo.relink", &json!({"id": copy.0, "path": other.to_string_lossy()})).unwrap(); + let p = x.s.catalog.photo(copy).unwrap(); + x.s.apply_system(Op::SetContent { + id: copy, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + preview_only: p.preview_only.clone(), + preview_checked: OTHER.into(), + }) + .unwrap(); + let listed = recheck::stale(&mut x.s, false); + assert_eq!(listed.iter().map(|p| p.id).collect::>(), vec![x.id, copy]); + let original = x.s.catalog.photo(x.id).unwrap().clone(); + std::fs::write(&other, crate::tests_xmp::synthetic_dng_with(None, lightcraft_meta::Metadata::default())).unwrap(); + let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert_eq!(r["checked"], 2); + assert_eq!(r["cleared"], json!([copy.0])); + let parent = x.s.catalog.photo(x.id).unwrap(); + assert_eq!(parent.content_hash, original.content_hash); + assert_eq!(parent.preview_only, original.preview_only); + assert_eq!(parent.preview_checked, APP_VERSION); + assert!(x.s.catalog.photo(copy).unwrap().develops_raw()); +} + +/// A same-file copy still needs its own probe when its parent's stamp is already current. +#[test] +fn stale_copy_is_checked_when_its_parent_is_current() { + let mut x = library("copy-only-stale"); + let r = x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap(); + let copy = PhotoId(r["ids"][0].as_u64().unwrap()); + let p = x.s.catalog.photo(x.id).unwrap(); + x.s.apply_system(Op::SetContent { + id: x.id, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + preview_only: p.preview_only.clone(), + preview_checked: APP_VERSION.into(), + }) + .unwrap(); + assert_eq!(recheck::stale(&mut x.s, false).iter().map(|p| p.id).collect::>(), vec![copy]); + assert_eq!(recheck::stale(&mut x.s, true).iter().map(|p| p.id).collect::>(), vec![x.id]); + decodable_now(&x); + let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert_eq!(r["checked"], 1); + assert_eq!(r["cleared"], json!([copy.0, x.id.0])); + assert!(x.s.catalog.photo(copy).unwrap().develops_raw()); + assert!(x.s.catalog.photo(x.id).unwrap().develops_raw()); +} + +#[test] +fn review_stale_copies_share_one_probe_when_the_parent_is_current() { + let mut x = library("stale-siblings"); + let mut copies = Vec::new(); + for _ in 0..2 { + copies.push(PhotoId(x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap()["ids"][0].as_u64().unwrap())); + } + let p = x.s.catalog.photo(x.id).unwrap(); + x.s.apply_system(Op::SetContent { + id: x.id, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + preview_only: p.preview_only.clone(), + preview_checked: APP_VERSION.into(), + }) + .unwrap(); + decodable_now(&x); + let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert_eq!(r["checked"], 1, "same-file siblings share a probe even without an eligible parent"); + let mut expected = vec![x.id.0]; + expected.extend(copies.iter().map(|id| id.0)); + for field in ["updated", "cleared"] { + let mut ids: Vec<_> = r[field].as_array().unwrap().iter().map(|id| id.as_u64().unwrap()).collect(); + ids.sort(); + assert_eq!(ids, expected, "{field} reports each recovered photo once"); + } +} + +#[test] +fn review_recheck_keeps_a_listed_copy_after_its_parent_moves() { + for relink_copy in [false, true] { + let mut x = library(&format!("parent-moves-{relink_copy}")); + let copy = PhotoId(x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap()["ids"][0].as_u64().unwrap()); + let listed = recheck::stale(&mut x.s, false); + assert_eq!(listed.len(), 1); + decodable_now(&x); + let mut info = recheck::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + info.meta.camera = "must not fill implicit metadata".into(); + let other = x.dir.join("other.cr3"); + std::fs::write(&other, cr3_with_preview(120, 80)).unwrap(); + x.s.execute("photo.relink", &json!({"id": x.id.0, "path": other.to_string_lossy()})).unwrap(); + if relink_copy { + x.s.execute("photo.relink", &json!({"id": copy.0, "path": x.file.to_string_lossy()})).unwrap(); + } + let parent = x.s.catalog.photo(x.id).unwrap().clone(); + let before = x.s.catalog.photo(copy).unwrap().clone(); + let out = recheck::apply(&mut x.s, listed.into_iter().map(|item| (item, Ok(info.clone()))).collect()).unwrap(); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), &parent); + if relink_copy { + assert!(out.updated.is_empty()); + assert_eq!(x.s.catalog.photo(copy).unwrap(), &before); + } else { + assert_eq!(out.cleared, vec![copy]); + let photo = x.s.catalog.photo(copy).unwrap(); + assert!(photo.develops_raw()); + assert_eq!(photo.meta.camera, before.meta.camera); + } + } +} + +#[test] +fn review_same_path_relink_invalidates_older_reads_even_when_facts_match() { + let mut x = checked_orf("same-path"); + let listed = recheck::stale(&mut x.s, true); + let current = x.s.catalog.photo(x.id).unwrap().clone(); + replace_checked_orf(&x.file); + let old = recheck::probe(&recheck::file_probe(&x.s).unwrap(), listed); + std::fs::write(&x.file, crate::files::tests::sensor_orf()).unwrap(); + x.s.execute("photo.relink", &json!({"id": x.id.0, "path": x.file.to_string_lossy()})).unwrap(); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), ¤t, "relink confirmed exactly the same facts"); + assert!(recheck::apply(&mut x.s, old).unwrap().updated.is_empty()); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), ¤t); + replace_checked_orf(&x.file); + assert_eq!(x.s.execute("library.recheckPreviewOnly", &json!({"all": true})).unwrap()["updated"], json!([x.id.0])); +} + +#[test] +fn recheck_does_not_overwrite_copies_created_after_its_listing() { + let mut x = checked_orf("late-copy"); + let copy = PhotoId(x.s.execute("photo.virtualCopy", &json!({"id": x.id.0})).unwrap()["ids"][0].as_u64().unwrap()); + let listed = recheck::stale(&mut x.s, true); + replace_checked_orf(&x.file); + let old = recheck::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + replace_checked_orf(&x.file); + x.s.execute("photo.relink", &json!({"id": x.id.0, "path": x.file.to_string_lossy()})).unwrap(); + let late = PhotoId(x.s.execute("photo.virtualCopy", &json!({"id": x.id.0})).unwrap()["ids"][0].as_u64().unwrap()); + let current = x.s.catalog.photo(late).unwrap().clone(); + let out = recheck::apply(&mut x.s, listed.into_iter().map(|item| (item, Ok(old.clone()))).collect()).unwrap(); + assert_eq!(x.s.catalog.photo(late).unwrap(), ¤t, "a copy inheriting newer facts keeps them"); + assert_eq!(out.updated, [copy], "the untouched listed sibling still accepts its pending result"); + assert_eq!(x.s.catalog.photo(copy).unwrap().file_size, old.file_size); +} + +fn checked_orf(name: &str) -> Lib { + let dir = super::TestDir::new(&format!("recheck-checked-{name}")); + let file = dir.join("original.orf"); + let mut x = Lib { s: Session::new().with_fs(), lib: dir.join("lib"), dir, file, id: PhotoId(0) }; + std::fs::write(&x.file, crate::files::tests::sensor_orf()).unwrap(); + let r = x.s.execute("library.import", &json!({"paths": [x.file.to_string_lossy()]})).unwrap(); + x.id = PhotoId(r["imported"][0].as_u64().unwrap()); + let photo = x.s.catalog.photo(x.id).unwrap(); + assert!(photo.preview_only.is_none() && !photo.preview_only_stale() && photo.format == "ORF"); + x +} + +#[test] +fn review_recheck_after_relink_keeps_fresh_facts_and_the_untouched_copy() { + let mut x = checked_orf("aba"); + let copy = PhotoId(x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap()["ids"][0].as_u64().unwrap()); + let p = x.s.catalog.photo(copy).unwrap(); + x.s.catalog + .apply(Op::SetContent { + id: copy, + width: p.width, + height: p.height, + file_size: 0, + content_hash: p.content_hash.clone(), + preview_only: None, + preview_checked: p.preview_checked.clone(), + }) + .unwrap(); + let listed = recheck::stale(&mut x.s, true); + assert_eq!(listed.len(), 1, "the eligible parent owns one grouped probe"); + let mut old = recheck::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + old.meta.lens = "must not fill the unselected copy".into(); + let old_size = old.file_size; + let other = x.dir.join("other.orf"); + std::fs::copy(&x.file, &other).unwrap(); + x.s.execute("photo.relink", &json!({"id": x.id.0, "path": other.to_string_lossy()})).unwrap(); + replace_checked_orf(&x.file); + x.s.execute("photo.relink", &json!({"id": x.id.0, "path": x.file.to_string_lossy()})).unwrap(); + let current = x.s.catalog.photo(x.id).unwrap().clone(); + let out = recheck::apply(&mut x.s, listed.into_iter().map(|item| (item, Ok(old.clone()))).collect()).unwrap(); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), ¤t); + assert!(!out.updated.contains(&x.id) && out.updated.contains(©)); + let sibling = x.s.catalog.photo(copy).unwrap(); + assert_eq!(sibling.file_size, old_size); + assert!(sibling.meta.lens.is_empty(), "automatic grouping does not select a copy's metadata"); +} + +#[test] +fn review_a_new_reload_supersedes_an_older_recheck() { + overlapping_source_checks(true); +} + +#[test] +fn an_older_reload_finishing_first_keeps_a_newer_pending_read() { + use crate::cmd::reload; + let mut x = checked_orf("older-first"); + let older = reload::plan(&mut x.s, &json!({"id": x.id.0})).unwrap(); + replace_checked_orf(&x.file); + let old = reload::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + let newer = reload::plan(&mut x.s, &json!({"id": x.id.0})).unwrap(); + replace_checked_orf(&x.file); + let new = reload::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + let expected = new.content_hash.clone(); + assert_eq!(reload::apply(&mut x.s, older, vec![Ok(old)]).unwrap().reloaded, [x.id]); + assert_eq!(reload::apply(&mut x.s, newer, vec![Ok(new)]).unwrap().reloaded, [x.id]); + assert_eq!(x.s.catalog.photo(x.id).unwrap().content_hash, expected); +} + +#[test] +fn an_older_source_read_refreshing_the_stamp_keeps_a_newer_recheck() { + use crate::cmd::reload; + for older_reload in [false, true] { + let mut x = library(&format!("older-stamp-{older_reload}")); + let reloading = older_reload.then(|| reload::plan(&mut x.s, &json!({"id": x.id.0})).unwrap()); + let checking = (!older_reload).then(|| recheck::stale(&mut x.s, false)); + let probe = recheck::file_probe(&x.s).unwrap(); + let old = probe(&x.file.to_string_lossy()).unwrap(); + let newer = recheck::stale(&mut x.s, false); + decodable_now(&x); + let newer = recheck::probe(&probe, newer); + if let Some(items) = reloading { + reload::apply(&mut x.s, items, vec![Ok(old)]).unwrap(); + } else { + recheck::apply(&mut x.s, checking.unwrap().into_iter().map(|item| (item, Ok(old.clone()))).collect()).unwrap(); + } + assert!(!x.s.catalog.photo(x.id).unwrap().preview_only_stale(), "the older read refreshed the stamp"); + assert_eq!(recheck::apply(&mut x.s, newer).unwrap().cleared, [x.id]); + assert!(x.s.catalog.photo(x.id).unwrap().develops_raw()); + } +} + +#[test] +fn review_a_new_recheck_supersedes_an_older_reload() { + overlapping_source_checks(false); +} + +fn replace_checked_orf(file: &std::path::Path) { + let mut bytes = std::fs::read(file).unwrap(); + bytes.push(42); + std::fs::write(file, bytes).unwrap(); +} + +fn overlapping_source_checks(older_recheck: bool) { + let mut x = checked_orf(if older_recheck { "old-recheck" } else { "old-reload" }); + let checking = older_recheck.then(|| recheck::stale(&mut x.s, true)); + let reloading = (!older_recheck).then(|| crate::cmd::reload::plan(&mut x.s, &json!({"ids": [x.id.0]})).unwrap()); + let old = recheck::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + replace_checked_orf(&x.file); + let replacement = Some(lightcraft_preview::hash_bytes(&std::fs::read(&x.file).unwrap()).to_string()); + assert_ne!(replacement, old.content_hash); + let command = if older_recheck { "photo.reload" } else { "library.recheckPreviewOnly" }; + let result = x.s.execute(command, &json!({"ids": [x.id.0], "all": true})).unwrap(); + assert_eq!(result[if older_recheck { "reloaded" } else { "updated" }], json!([x.id.0])); + let current = x.s.catalog.photo(x.id).unwrap().clone(); + assert_eq!(current.content_hash, replacement, "the newer check applied the replacement bytes"); + assert!(current.format == "ORF" && !current.preview_only_stale(), "current decoder facts still require ticket ordering"); + let updated = if let Some(items) = checking { + recheck::apply(&mut x.s, items.into_iter().map(|item| (item, Ok(old.clone()))).collect()).unwrap().updated + } else { + crate::cmd::reload::apply(&mut x.s, reloading.unwrap(), vec![Ok(old)]).unwrap().reloaded + }; + assert!(updated.is_empty()); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), ¤t); + assert_eq!(x.s.catalog.photo(x.id).unwrap().content_hash, replacement); +} diff --git a/crates/engine/tests/it/orf_withdrawal.rs b/crates/engine/tests/it/orf_withdrawal.rs index a29c8d06fc8..d1fbcfe5883 100644 --- a/crates/engine/tests/it/orf_withdrawal.rs +++ b/crates/engine/tests/it/orf_withdrawal.rs @@ -173,7 +173,7 @@ fn legacy_compressed_orf_and_copies_become_preview_only_without_losing_edits() { x.s = Session::new(); x.s.open_library(&x.lib, false).unwrap(); assert!(x.s.catalog.photo(x.id).unwrap().preview_only.is_some()); - assert!(recheck::stale(&x.s.catalog, false).is_empty()); + assert!(recheck::stale(&mut x.s, false).is_empty()); } /// Supported uncompressed ORF is checked once and never reported as newly recovered sensor support. @@ -185,12 +185,12 @@ fn legacy_uncompressed_orf_is_stamped_once_without_a_false_recovery_notice() { let p = x.s.catalog.photo(x.id).unwrap(); assert!(p.develops_raw()); assert_eq!(p.preview_checked, APP_VERSION); - assert!(recheck::stale(&x.s.catalog, false).is_empty()); - assert_eq!(recheck::stale(&x.s.catalog, true).len(), 1); + assert!(recheck::stale(&mut x.s, false).is_empty()); + assert_eq!(recheck::stale(&mut x.s, true).len(), 1); x.s.persist().unwrap(); x.s = Session::new(); x.s.open_library(&x.lib, false).unwrap(); - assert!(recheck::stale(&x.s.catalog, false).is_empty()); + assert!(recheck::stale(&mut x.s, false).is_empty()); assert!(x.s.catalog.photo(x.id).unwrap().develops_raw()); } @@ -203,5 +203,5 @@ fn unavailable_legacy_orf_is_unchanged_and_retried() { let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); assert_eq!(r, json!({"checked": 1, "updated": [], "cleared": []})); assert_eq!(x.s.catalog.photo(x.id).unwrap(), &before); - assert_eq!(recheck::stale(&x.s.catalog, false).len(), 1); + assert_eq!(recheck::stale(&mut x.s, false).len(), 1); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index dd3e9100efb..19d4cfb34a2 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -34,6 +34,7 @@ log = { workspace = true } craft = { workspace = true, features = ["screen-testing"] } # tests record why they skip (`cargo xtask ci` lists the skips) lightcraft-testkit = { workspace = true } +lightcraft-raw = { workspace = true } # The model-setup tests install and resume a real denoise model. Without this the engine's # `default_loader` is the "this build cannot run denoise models" stub when the package is tested # on its own (`cargo test -p lightcraft-ui-egui`); a workspace test only passed by feature diff --git a/crates/ui-egui/src/recheck.rs b/crates/ui-egui/src/recheck.rs index 9a53c5a063b..779981c6c4d 100644 --- a/crates/ui-egui/src/recheck.rs +++ b/crates/ui-egui/src/recheck.rs @@ -19,7 +19,7 @@ pub fn tick(app: &mut LightcraftApp) { app.ui.rechecked_library = Some(library); // a demo or browser session has no files to read let Some(probe) = recheck::file_probe(&app.session) else { return }; - let stale = recheck::stale(&app.session.catalog, false); + let stale = recheck::stale(&mut app.session, false); if stale.is_empty() { return; } diff --git a/crates/ui-egui/src/reload.rs b/crates/ui-egui/src/reload.rs index 8748bfd6553..ae394824d90 100644 --- a/crates/ui-egui/src/reload.rs +++ b/crates/ui-egui/src/reload.rs @@ -36,9 +36,6 @@ pub fn command(app: &mut LightcraftApp, p: &Value) -> Option = - items.iter().filter(|i| app.session.catalog.photo(i.id).is_some_and(|ph| ph.preview_only.is_some())).map(|i| i.id).collect(); let library = app.session.library_generation(); let probe = reload::file_probe(&app.session); let cancel = Arc::new(AtomicBool::new(false)); @@ -50,15 +47,27 @@ pub fn command(app: &mut LightcraftApp, p: &Value) -> Option, _)| { if app.session.library_generation() != library { return; } + let preview_only: std::collections::HashSet<_> = items + .iter() + .flat_map(|i| i.metadata_targets.iter().copied()) + .filter(|id| app.session.catalog.photo(*id).is_some_and(|ph| ph.preview_only.is_some())) + .collect(); + let mut cleared = 0; + let mut still_preview_only = false; // as the command: one undo step, the durable save and the automatic XMP sidecar write - if let Err(e) = app.session.execute_fn("photo.reload", |s| reload::apply(s, items, results).map(|ids| reload::to_json(&ids))) { + if let Err(e) = app.session.execute_fn("photo.reload", |s| { + let out = reload::apply(s, items, results)?; + cleared = out.reloaded.iter().filter(|id| preview_only.contains(id) && s.catalog.photo(**id).is_some_and(|ph| ph.develops_raw())).count(); + still_preview_only = + out.checked.iter().any(|id| preview_only.contains(id) && s.catalog.photo(*id).is_some_and(|ph| ph.preview_only.is_some())); + Ok(out.to_json()) + }) { return app.toast_error(ctx, e.to_string()); } - let cleared = preview_only.iter().filter(|id| app.session.catalog.photo(**id).is_some_and(|ph| ph.preview_only.is_none())).count(); // stopped before the files were read: they weren't tried again, so say nothing about them // (a raw that did decode before the stop is still reported) if stopped.load(std::sync::atomic::Ordering::Relaxed) && cleared == 0 { @@ -66,7 +75,7 @@ pub fn command(app: &mut LightcraftApp, p: &Value) -> Option crate::i18n::tr("This raw is now developed from its raw data").to_string(), - (1, 1, _) => crate::i18n::tr("This raw variant still can't be decoded").to_string(), + (1, 1, _) if still_preview_only => crate::i18n::tr("This raw variant still can't be decoded").to_string(), (_, _, 0) => return, (_, _, 1) => crate::i18n::tr("1 raw can now be developed from its raw data").to_string(), (_, _, n) => crate::i18n::tr_format!("{n} raws can now be developed from their raw data", n = n), diff --git a/crates/ui-egui/src/tests/recheck.rs b/crates/ui-egui/src/tests/recheck.rs index 4d808f736e2..b7ed3203e16 100644 --- a/crates/ui-egui/src/tests/recheck.rs +++ b/crates/ui-egui/src/tests/recheck.rs @@ -17,14 +17,28 @@ impl Drop for Dir { } /// An app on a library at `dir/lib` with one photo whose preview-only flag an older version set. -/// Its file (a PNG) reads fine, as a raw a newer decoder handles would. fn app_with_stale_photo(dir: &Path) -> (LightcraftApp, PhotoId) { + app_with_stale_file(dir, false) +} + +fn app_with_stale_raw(dir: &Path) -> (LightcraftApp, PhotoId) { + app_with_stale_file(dir, true) +} + +fn app_with_stale_file(dir: &Path, raw: bool) -> (LightcraftApp, PhotoId) { let _ = std::fs::remove_dir_all(dir); std::fs::create_dir_all(dir.join("files")).unwrap(); let img = lightcraft_raster::Rgba8::from_fn(16, 12, |x, y| [(x * 9) as u8, (y * 11) as u8, 50, 255]); let o = lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() }; - let file = dir.join("files/one.png"); - std::fs::write(&file, lightcraft_engine::export::encode_image(&img, &o).unwrap()).unwrap(); + let file = dir.join(if raw { "files/one.dng" } else { "files/one.png" }); + let bytes = if raw { + // Our procedural pixels, written as a real, developable linear DNG. + let rgb: Vec<_> = img.data.iter().flat_map(|pixel| pixel[..3].iter().map(|v| f32::from(*v) / 255.0)).collect(); + lightcraft_raw::write_rendered_dng(16, 12, &rgb, &lightcraft_color::SRGB, &Default::default(), None).unwrap() + } else { + lightcraft_engine::export::encode_image(&img, &o).unwrap() + }; + std::fs::write(&file, bytes).unwrap(); let mut session = lightcraft_engine::Session::new().with_fs(); session.open_library(dir.join("lib"), false).unwrap(); let r = session.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); @@ -48,7 +62,7 @@ fn app_with_stale_photo(dir: &Path) -> (LightcraftApp, PhotoId) { #[test] fn opening_a_library_rechecks_stale_preview_only_raws_in_the_background() { let dir = Dir(std::env::temp_dir().join(format!("lc-ui-recheck-{}", std::process::id()))); - let (mut app, id) = app_with_stale_photo(&dir.0); + let (mut app, id) = app_with_stale_raw(&dir.0); let ctx = egui::Context::default(); crate::recheck::tick(&mut app); // it shows in the activity stack while it runs @@ -58,6 +72,7 @@ fn opening_a_library_rechecks_stale_preview_only_raws_in_the_background() { assert!(app.session.activity.list().iter().all(|r| r.kind != "recheck"), "the row goes with the task"); let p = app.session.catalog.photo(id).unwrap(); assert_eq!(p.preview_only, None); + assert!(p.develops_raw()); assert!(app.ui.toast.as_ref().is_some_and(|(t, _, _)| t == "1 raw can now be developed from its raw data"), "{:?}", app.ui.toast); // once per opened library app.ui.toast = None; @@ -83,7 +98,7 @@ fn recheck_result_is_dropped_after_switching_libraries() { #[test] fn notice_reload_button_rereads_the_file() { let dir = Dir(std::env::temp_dir().join(format!("lc-ui-recheck-reload-{}", std::process::id()))); - let (mut app, id) = app_with_stale_photo(&dir.0); + let (mut app, id) = app_with_stale_raw(&dir.0); let ctx = egui::Context::default(); crate::panels::edit::reload_preview_only(&mut app, &ctx, id); let rows = app.session.activity.list(); @@ -93,11 +108,89 @@ fn notice_reload_button_rereads_the_file() { assert!(crate::tasks::wait(&mut app, &ctx, Duration::from_secs(10))); assert!(app.session.activity.list().iter().all(|r| r.kind != "reload"), "the row goes with the task"); assert_eq!(app.session.catalog.photo(id).unwrap().preview_only, None); + assert!(app.session.catalog.photo(id).unwrap().develops_raw()); assert!(app.ui.toast.as_ref().is_some_and(|(t, _, _)| t == "This raw is now developed from its raw data"), "{:?}", app.ui.toast); // one undo step assert_eq!(app.session.undo.last().map(|u| u.label.as_str()), Some("Reload Changed Files")); } +#[test] +fn review_grouped_reload_reports_a_cleared_preview_only_copy() { + for relink in [false, true] { + let dir = Dir(std::env::temp_dir().join(format!("lc-ui-reload-grouped-{relink}-{}", std::process::id()))); + let (mut app, id) = app_with_stale_raw(&dir.0); + let r = app.session.execute("photo.virtualCopy", &json!({"ids": [id.0]})).unwrap(); + let copy = PhotoId(r["ids"][0].as_u64().unwrap()); + let p = app.session.catalog.photo(id).unwrap().clone(); + app.session + .catalog + .apply(Op::SetContent { + id, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + preview_only: None, + preview_checked: String::new(), + }) + .unwrap(); + let ctx = egui::Context::default(); + assert_eq!(app.run("photo.reload", json!({"ids": [id.0, copy.0]})).unwrap()["count"], 1); + if relink { + let lightcraft_catalog::Source::File { path } = app.session.catalog.photo(copy).unwrap().source.clone() else { panic!("file photo") }; + app.session.execute("photo.relink", &json!({"id": copy.0, "path": path})).unwrap(); + } + assert!(crate::tasks::wait(&mut app, &ctx, Duration::from_secs(10))); + assert!(app.session.catalog.photo(copy).unwrap().preview_only.is_none()); + assert!(app.session.catalog.photo(copy).unwrap().develops_raw()); + if relink { + assert!(app.ui.toast.is_none(), "Reload must not claim a recovery performed by Relink: {:?}", app.ui.toast); + } else { + assert!(app.ui.toast.as_ref().is_some_and(|(t, _, _)| t == "This raw is now developed from its raw data"), "{:?}", app.ui.toast); + } + } +} + +#[test] +fn a_negative_reload_notice_requires_an_accepted_probe_even_when_unchanged() { + for case in ["unchanged", "relinked", "unreadable"] { + let dir = Dir(std::env::temp_dir().join(format!("lc-ui-reload-negative-{case}-{}", std::process::id()))); + let (mut app, id) = app_with_stale_raw(&dir.0); + let file = dir.0.join("files/preview.dng"); + std::fs::copy(dir.0.join("files/one.dng"), &file).unwrap(); + let native = app.session.media.file_probe.clone().unwrap(); + app.session.media.file_probe = Some(std::sync::Arc::new(move |path| { + let mut info = native(path)?; + // Simulate a decoder that can only use this raw's embedded preview. + if path.ends_with("preview.dng") { + info.preview_only = Some("unsupported raw variant".into()); + } + Ok(info) + })); + let relink = json!({"id": id.0, "path": file.to_string_lossy()}); + if case != "relinked" { + app.session.execute("photo.relink", &relink).unwrap(); + } + if case == "unreadable" { + std::fs::remove_file(&file).unwrap(); + } + app.run("photo.reload", json!({"ids": [id.0]})).unwrap(); + if case == "relinked" { + app.session.execute("photo.relink", &relink).unwrap(); + } + let before = app.session.catalog.photo(id).unwrap().clone(); + let undo = app.session.undo.len(); + assert!(crate::tasks::wait(&mut app, &egui::Context::default(), Duration::from_secs(10))); + assert_eq!(app.session.catalog.photo(id).unwrap(), &before); + assert_eq!(app.session.undo.len(), undo, "none of these Reloads changes the catalog"); + assert_eq!( + app.ui.toast.as_ref().map(|(text, _, _)| text.as_str()), + (case == "unchanged").then_some("This raw variant still can't be decoded"), + "{case}" + ); + } +} + /// Reload from Disk on a selection returns at once and reads the files on a worker thread; `wait` /// runs it in place; a cancelled reload changes nothing it didn't read. #[test] @@ -136,7 +229,7 @@ fn reload_of_a_selection_runs_in_the_background() { let probe = lightcraft_engine::cmd::reload::file_probe(&app.session); let cancelled = std::sync::atomic::AtomicBool::new(true); let results = lightcraft_engine::cmd::reload::probe(probe.as_ref(), &items, &cancelled, &|_| {}); - assert!(lightcraft_engine::cmd::reload::apply(&mut app.session, items, results).unwrap().is_empty()); + assert!(lightcraft_engine::cmd::reload::apply(&mut app.session, items, results).unwrap().reloaded.is_empty()); assert!(app.session.catalog.photo(id).unwrap().preview_only.is_some()); } @@ -247,7 +340,7 @@ fn reload_with_bad_ids_names_the_command() { fn a_cancelled_reload_reports_only_what_it_did() { use std::sync::{Arc, Condvar, Mutex}; let dir = Dir(std::env::temp_dir().join(format!("lc-ui-reload-cancel-{}", std::process::id()))); - let (mut app, id) = app_with_stale_photo(&dir.0); + let (mut app, id) = app_with_stale_raw(&dir.0); let ctx = egui::Context::default(); let native = app.session.media.file_probe.clone().unwrap(); for read in [false, true] { @@ -275,6 +368,7 @@ fn a_cancelled_reload_reports_only_what_it_did() { assert!(crate::tasks::wait(&mut app, &ctx, Duration::from_secs(10))); if read { assert_eq!(app.session.catalog.photo(id).unwrap().preview_only, None); + assert!(app.session.catalog.photo(id).unwrap().develops_raw()); assert!(app.ui.toast.as_ref().is_some_and(|(t, _, _)| t == "This raw is now developed from its raw data"), "{:?}", app.ui.toast); } else { assert!(app.session.catalog.photo(id).unwrap().preview_only.is_some()); diff --git a/docs/gaps.md b/docs/gaps.md index b0ae8d980f3..3716e5ec09a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -63,6 +63,8 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w ## Closed recently (kept for calibration) +- 2026-11-19: Reload refreshes same-file originals and copies together with one probe, keeps all selected metadata targets, and leaves independently relinked copies on their own file. Reload freshness follows the family and file; preview rechecks also cover copies whose parent uses another file or is already current. Edits, legacy shutter repair and one-step Undo are preserved. Existing feature hardened; no ranked gap or readiness estimate changes. + - 2026-10-29: the import review has a remembered 80–320 pt thumbnail-size slider, density-aware previews and bounded visible retention (#2237, part of #2056). Small sources do not reconstruct the same preview job every frame. The pre-import loupe and keyboard culling remain open in #2056; no ranked gap or headline feature count closes. - 2026-10-22: saving XMP preserves foreign namespaces even when they use `lc:` or `xmp:` prefixes; importing them no longer interprets their properties as native settings or ratings. Parser, merge and save-command regressions cover the correction; no ranked gap or readiness estimate changes. @@ -97,6 +99,7 @@ Beta-blocking gaps (B) total **~230–430 h**; with the stability and platform w | Date | Change | Summary | |---|---|---| | 2026-11-26 | minor | Gap 31 added: sidebar multi-selection — the batch album, keyword and library-folder commands (#2757) have no sidebar caller yet | +| 2026-11-19 | patch | Reload and preview rechecks respect virtual copies’ actual source files, retain selected metadata targets and scope overlapping reads to the family and file; edits and legacy shutter repair are preserved. No ranked gap or headline number changes. | | 2026-11-01 | minor | Gap 13: Lightroom catalog backup zips import directly, and a backup of an imported catalog adds no collection twice (#2592); the gap stays open | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-23 | minor | Gap 3: process V13 eases global Shadows off at large amounts, and negative Texture and the Global grading wheel act less, fitted to 56 Lightroom exports of real Canon edits (mean ΔE 9.5 → 9.0, #523); the gap stays open and hours are unchanged | diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 02c309546c7..be43dc18228 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -123,7 +123,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `cmd:photo.moveToBurst`, `cmd:panel.bursts`, `crates/pipeline/src/cull.rs`, `crates/ui-egui/src/panels/bursts.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; bursts put right by hand in Window ▸ Bursts (drag a photo within its burst — first place is the pick, and the Pick flag culling set, Best of Similar Shots and a stacked burst's top follow — into another burst, a new one or none; drag a burst onto another to merge; kept when culling runs again unless *Regroup bursts I arranged by hand*); classical measures — no eyes-closed / expression detection | | LR-LIB-ACTIVITY | Comments & likes | OOS | 🚫 | | | | LR-LIB-QUICKCOLL | Quick collection [Classic] | P2 | ✅ | `cmd:album.toggleTarget`, `cmd:album.clearQuick` | B in the grids | -| LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs`, `crates/ui-egui/src/thumb.rs` | “Copy N” tag on the grid and on the filmstrip (widgets `copy:`, `film:copy:`; on a narrow thumbnail it drops its name and then hides rather than meet the stack badge), stacked with the original, same albums, no XMP writes; default numbers are checked across the batch before copies are created, while explicit names bypass the counter; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” | +| LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs`, `crates/ui-egui/src/thumb.rs` | “Copy N” tag on the grid and on the filmstrip (widgets `copy:`, `film:copy:`; on a narrow thumbnail it drops its name and then hides rather than meet the stack badge), stacked with the original, same albums, no XMP writes; default numbers are checked across the batch before copies are created, while explicit names bypass the counter; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” |. Reload shares one probe and file facts within a same-file family, retains every selected metadata target and scopes overlapping reads to that family and file; independently relinked copies keep their own facts and preview rechecks, as do stale copies whose parent is already current. Edits, legacy shutter repair and one-step Undo are preserved. | ## C. Views & navigation (VIEW) @@ -816,6 +816,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-29 | minor | MENU-EDIT-SELECTBY: Edit → Select by lists each rating on its own (★ only … ★★★★★ only, `library.selectBy` with `ratingOp: eq`) after the "and higher" rows, beside Unrated (#3311); status unchanged (✅) | | 2026-11-15 | patch | LR-PRE-AMOUNT: Amount blends tone curves, fades in the strength of a profile/LUT or switched-on group a preset changes, and takes white balance on another scale whole (#2669); the step at half amount for switches and choices stays (#2207); status unchanged (✅) | | 2026-11-09 | minor | LR-PREF-LOCALSTORAGE: the low-disk notice warns under 20 GB free, no longer under 10 % of the drive (76 GB free of a 926 GB drive warned, #4013); status unchanged | +| 2026-11-19 | patch | LR-LIB-VIRTUALCOPY: Reload and preview rechecks respect actual source files, retain selected metadata targets and scope overlapping reads to the family and file; edits and legacy shutter repair are preserved. Status and headline numbers unchanged. | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-23 | minor | LR-BEHAV-RENDER-FIDELITY, LR-EDIT-LIGHT-SHADOWS, LR-EDIT-EFFECTS-TEXTURE, LR-EDIT-COLOR-GRADING, LRC-DEV-PROCESS: process V13 eases global Shadows off at large amounts, negative Texture and the Global grading wheel act less, fitted to Lightroom exports of real edits (#523); statuses and counts unchanged | | 2026-11-24 | minor | LR-REM-HEAL, LR-REM-CLONE, LRC-DEV-PROCESS: process V14 pins Heal and Remove spots to the photo on the spot's edge (membrane fill of the log ratio), matches the source's grain to its surroundings and reads every spot's source at whole pixels; statuses and counts unchanged | From b7fdf1cf87742718ba53da01544dc35b9eefeecd Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 01:24:28 +0100 Subject: [PATCH 02/42] LR-LIB-VIRTUALCOPY: keep Recheck metadata and Reload previews current --- crates/engine/src/cmd/convert.rs | 37 +++++++++++++++++++++++++++ crates/engine/src/cmd/recheck.rs | 3 ++- crates/engine/src/lib.rs | 15 +++++------ crates/engine/src/media/quick.rs | 40 ++++++++++++++++-------------- crates/engine/src/media/session.rs | 28 ++++++++++----------- crates/engine/src/tests/recheck.rs | 31 ++++++++++++++++++++--- 6 files changed, 108 insertions(+), 46 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index f66a724f52b..d8d653fa2e6 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -628,6 +628,43 @@ mod tests { assert!(lens_ops(ph.id, &ph, &info).is_empty()); } + #[test] + fn reload_with_new_source_metadata_leaves_the_old_render_and_source_behind() { + use crate::SourceLevel; + use std::sync::Arc; + + let mut s = Session::new(); + let id = PhotoId(1); + let mut ph = Photo::new(id, Source::File { path: "/x.arw".into() }, "x.arw", "ARW", 64, 64, "2026-10-06T00:00:00"); + ph.kind = lightcraft_catalog::MediaKind::Raw; + ph.meta.camera = "SONY ILCE-7M3".into(); + ph.as_shot_wb = Some((6500.0, 0.0)); + assert!(!ph.relative_wb()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(ph) }).unwrap(); + s.selection.ids = vec![id]; + s.selection.active = Some(id); + let before = s.catalog.photo(id).unwrap().clone(); + let render_key = s.loupe_job(id, 64, 64, true).unwrap().key; + let quick_key = s.quick_view_job(id, 64, true).unwrap().key; + let view_key = s.view_key(&before, true); + s.media.rendered.put(view_key, Arc::new(lightcraft_raster::Rgba8::new(64, 64))); + s.media.insert(id, SourceLevel::Thumb, Arc::new(lightcraft_raster::Rgb32f::new(64, 64))); + + let info = crate::media::ProbeInfo { width: before.width, height: before.height, as_shot_wb: Some((4986.0, -2.0)), ..Default::default() }; + s.media.file_probe = Some(Arc::new(move |_| Ok(info.clone()))); + assert_eq!(s.execute("photo.reload", &json!({"ids": [id.0]})).unwrap()["reloaded"], json!([id.0])); + let after = s.catalog.photo(id).unwrap(); + assert_eq!(after.content_hash, before.content_hash); + assert_eq!(after.as_shot_wb, Some((4986.0, -2.0))); + assert!(s.media.rendered.get(s.view_key(after, true)).is_none(), "the old view render no longer matches"); + assert_ne!(s.loupe_job(id, 64, 64, true).unwrap().key, render_key); + assert_ne!(s.quick_view_job(id, 64, true).unwrap().key, quick_key); + assert!(!s.media.has_source(id, SourceLevel::Thumb), "Reload discards the old decoded source"); + + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.view_key(s.catalog.photo(id).unwrap(), true), view_key); + } + /// End to end on a public Panasonic raw (skipped without the corpus): a catalog from before the lens data was read /// gets it on Reload, the render changes to the corrected one, and Undo takes it all back. #[test] diff --git a/crates/engine/src/cmd/recheck.rs b/crates/engine/src/cmd/recheck.rs index f99279a1677..cd5a7564ab8 100644 --- a/crates/engine/src/cmd/recheck.rs +++ b/crates/engine/src/cmd/recheck.rs @@ -74,7 +74,8 @@ pub fn apply(s: &mut Session, results: Vec<(Stale, std::result::Result = item.metadata_targets.into_iter().collect(); + crate::cmd::convert::reload_ops(&s.catalog, id, &info, &mut ops, &mut out.updated, item.source_targets, |id| selected.contains(&id)); if info.preview_only.is_none() { out.cleared.extend(out.updated[first..].iter().copied().filter(|id| s.catalog.photo(*id).is_some_and(|p| p.preview_only.is_some()))); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 82bf86d060e..b364620c2f7 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -793,8 +793,8 @@ impl Session { /// Apply `op` with `apply` (the catalog's way in for a new edit or for bringing back what /// was), then forget what the session cached of the photos it replaced. fn apply_through(&mut self, op: Op, apply: fn(&mut Catalog, Op) -> std::result::Result, invalidate_reads: bool) -> Result { - // Retain only cache IDs while the catalog consumes the operation. Cloning an import - // batch here also cloned every photo, although commit already keeps the journal copy. + // Retain only the affected IDs while the catalog consumes the operation. Cloning an + // import batch here would clone every photo, although commit already keeps the journal copy. let mut invalidated = Vec::new(); let mut denoise_changed = Vec::new(); // photos whose file was replaced: the faces made from the old pixels go too (issue #1524) @@ -803,7 +803,7 @@ impl Session { while let Some(op) = pending.pop() { match op { Op::SetContent { id, .. } => { - invalidated.push(*id); + invalidated.push((*id, true)); replaced.push(*id); } Op::SetDevelop { id, settings, .. } @@ -811,8 +811,9 @@ impl Session { { denoise_changed.push(*id); } - Op::SetFile { id, .. } | Op::Relink { id, .. } | Op::RemovePhoto { id } => invalidated.push(*id), - Op::AddPhoto { photo } => invalidated.push(photo.id), + Op::SetFile { id, .. } | Op::Relink { id, .. } | Op::RemovePhoto { id } => invalidated.push((*id, true)), + Op::AddPhoto { photo } => invalidated.push((photo.id, true)), + Op::SetAsShotWb { id, .. } | Op::SetEmbeddedLens { id, .. } => invalidated.push((*id, false)), Op::Batch { ops } => pending.extend(ops), _ => {} } @@ -825,8 +826,8 @@ impl Session { for id in denoise_changed { self.denoise_photo_changed(id); } - for id in invalidated { - if invalidate_reads { + for (id, source_changed) in invalidated { + if source_changed && invalidate_reads { self.reload_tickets.invalidate(id); } self.media.forget(id); diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 3bc6c163e9b..9fd2bd9a6de 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -147,10 +147,9 @@ pub(super) fn decoder_key(p: &Photo) -> u64 { ((h.0 as u64) ^ ((h.0 >> 64) as u64)) | 1 } -/// Which decode of a photo a loaded source is: its file's content, decoder identity and database lens profile -/// ([`lens_key`]; the decode fits the starting colour through it). A job's source is kept only when this still -/// matches when the job finishes ([`super::Session::accept`]), so a decode started before a profile change never -/// returns to the cache after `cmd::lens_refresh` has dropped the photo's sources. +/// Which decode of a photo a loaded source is: its file's content, decoder and source metadata. +/// A result is kept only while these still match, so a decode started before a metadata refresh +/// cannot repopulate the cache with the old source. pub fn source_identity(p: &Photo) -> Hash128 { let mut k = Hasher128::new(); k.str(&content_key(p)); @@ -158,9 +157,9 @@ pub fn source_identity(p: &Photo) -> Hash128 { if decoder != 0 { k.str("decoder").u64(decoder); } - let lens = lens_key(p); - if lens != 0 { - k.u64(lens); + let metadata = source_metadata_key(p); + if metadata != 0 { + k.u64(metadata); } k.finish() } @@ -173,19 +172,22 @@ pub fn content_key(p: &Photo) -> String { } } -/// What a photo's lens profile adds to its render and thumbnail keys: a database profile (0 without one), with the -/// correction on or off: a raw's starting colour is fitted through the profile's vignetting either way -/// (`camera_preview::starting_colour`), so the decoded picture depends on it. When a database update gives the -/// photo another profile, its cached renders and thumbnails no longer match. (The file's own correction changes only with the file, which the content -/// key covers, so it adds nothing and existing thumbnails stay valid.) -pub fn lens_key(p: &Photo) -> u64 { - match &p.embedded_lens { - Some(l) if l.source == lightcraft_develop::LensSource::Database => { - let k = Hasher128::new().str("lens").str(&format!("{l:?}")).finish(); - (k.0 as u64) ^ ((k.0 >> 64) as u64) | 1 - } - _ => 0, +/// Source facts that affect pixels and can change when the source bytes stay the same. +/// Include lens data even with the correction off: fitting a raw's starting colour uses the profile. +pub(super) fn source_metadata_key(p: &Photo) -> u64 { + let wb = p.as_shot_wb.filter(|_| p.develops_raw() && !p.relative_wb()); + if p.embedded_lens.is_none() && wb.is_none() { + return 0; + } + let mut key = Hasher128::new(); + if let Some(lens) = &p.embedded_lens { + key.str("lens").str(&format!("{lens:?}")); + } + if let Some((temp, tint)) = wb { + key.str("as-shot-wb").u64(temp.to_bits()).u64(tint.to_bits()); } + let k = key.finish(); + (k.0 as u64) ^ ((k.0 >> 64) as u64) | 1 } pub fn source_info(p: &Photo) -> SourceInfo { diff --git a/crates/engine/src/media/session.rs b/crates/engine/src/media/session.rs index 7c69f949aed..998b75d6954 100644 --- a/crates/engine/src/media/session.rs +++ b/crates/engine/src/media/session.rs @@ -81,7 +81,7 @@ impl crate::Session { let ai_defringe = if before { None } else { self.aidefringe_for_render(&p, &settings, false).ok().flatten() }; let salt = denoise_salt ^ ai_defringe.as_ref().map_or(0, |a| a.key().rotate_left(11)); let profile_salt = self.media.camera_profile_salt(&settings.profile.id); - let lens = super::quick::lens_key(&p); + let metadata = super::quick::source_metadata_key(&p); let key = settings_hash ^ ((max_w as u64) << 40) ^ ((max_h as u64) << 20) @@ -92,7 +92,7 @@ impl crate::Session { ^ salt ^ self.denoise.texture_epoch(denoise_salt) ^ profile_salt.rotate_left(29) - ^ lens.rotate_left(37) + ^ metadata.rotate_left(37) ^ decoder.rotate_left(43); let cache = thumb_bucket.map(|b| { let mut k = Hasher128::new(); @@ -106,9 +106,8 @@ impl crate::Session { if profile_salt != 0 { k.str("dcp").u64(profile_salt); } - // (likewise a database lens profile: thumbnails of every other photo keep their keys) - if lens != 0 { - k.u64(lens); + if metadata != 0 { + k.u64(metadata); } if decoder != 0 { k.str("decoder").u64(decoder); @@ -154,8 +153,7 @@ impl crate::Session { // (the imported camera profile's file is in the key, as in `render_job`'s: a profile file replaced under the // same id is a new picture) let profile_salt = self.media.camera_profile_salt(&settings.profile.id); - // (the photo's database lens profile stays part of it: a profile looked up again renders afresh) - let lens = self.catalog.photo(id).map_or(0, |p| super::quick::lens_key(p)); + let metadata = super::quick::source_metadata_key(&p); let decoder = super::quick::decoder_key(&p); job.key = settings.hash64() ^ denoise_salt @@ -166,7 +164,7 @@ impl crate::Session { ^ (apply_crop as u64) ^ (job.level as u64) << 60 ^ profile_salt.rotate_left(29) - ^ lens.rotate_left(37) + ^ metadata.rotate_left(37) ^ decoder.rotate_left(43) ^ job.ai_defringe.as_ref().map_or(0, |a| a.key().rotate_left(11)); Some(job) @@ -198,9 +196,9 @@ impl crate::Session { if profile_salt != 0 { k.str("dcp").u64(profile_salt); } - let lens = super::quick::lens_key(p); - if lens != 0 { - k.u64(lens); + let metadata = super::quick::source_metadata_key(p); + if metadata != 0 { + k.u64(metadata); } let decoder = super::quick::decoder_key(p); if decoder != 0 { @@ -355,9 +353,9 @@ impl crate::Session { if profile_salt != 0 { k.str("dcp").u64(profile_salt); } - let lens = super::quick::lens_key(p); - if lens != 0 { - k.u64(lens); + let metadata = super::quick::source_metadata_key(p); + if metadata != 0 { + k.u64(metadata); } let decoder = super::quick::decoder_key(p); if decoder != 0 { @@ -491,7 +489,7 @@ impl crate::Session { .u64(id.0) .u64(profile_salt) .finish(); - let key = h.0 as u64 ^ super::quick::decoder_key(&p).rotate_left(43); + let key = h.0 as u64 ^ super::quick::source_metadata_key(&p).rotate_left(37) ^ super::quick::decoder_key(&p).rotate_left(43); let embedded = self.embedded_of(&p).map(|(path, l)| (path, l, max_edge.clamp(1, SourceLevel::Preview.max_edge()))); let embedded_cache = embedded.as_ref().map(|(_, _, edge)| { let cache = self.media.rendered.clone(); diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index b3513017d00..98f26b8266d 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -227,8 +227,18 @@ fn review_stale_copies_share_one_probe_when_the_parent_is_current() { }) .unwrap(); decodable_now(&x); + let file_probe = recheck::file_probe(&x.s).unwrap(); + x.s.media.file_probe = Some(std::sync::Arc::new(move |path| { + let mut info = file_probe(path)?; + info.meta.camera = "Camera from shared source".into(); + Ok(info) + })); let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); assert_eq!(r["checked"], 1, "same-file siblings share a probe even without an eligible parent"); + for id in &copies { + assert_eq!(x.s.catalog.photo(*id).unwrap().meta.camera, "Camera from shared source"); + } + assert!(x.s.catalog.photo(x.id).unwrap().meta.camera.is_empty(), "the current parent was only an implicit target"); let mut expected = vec![x.id.0]; expected.extend(copies.iter().map(|id| id.0)); for field in ["updated", "cleared"] { @@ -247,7 +257,7 @@ fn review_recheck_keeps_a_listed_copy_after_its_parent_moves() { assert_eq!(listed.len(), 1); decodable_now(&x); let mut info = recheck::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); - info.meta.camera = "must not fill implicit metadata".into(); + info.meta.camera = "Camera from the listed copy’s source".into(); let other = x.dir.join("other.cr3"); std::fs::write(&other, cr3_with_preview(120, 80)).unwrap(); x.s.execute("photo.relink", &json!({"id": x.id.0, "path": other.to_string_lossy()})).unwrap(); @@ -265,7 +275,7 @@ fn review_recheck_keeps_a_listed_copy_after_its_parent_moves() { assert_eq!(out.cleared, vec![copy]); let photo = x.s.catalog.photo(copy).unwrap(); assert!(photo.develops_raw()); - assert_eq!(photo.meta.camera, before.meta.camera); + assert_eq!(photo.meta.camera, "Camera from the listed copy’s source"); } } } @@ -331,8 +341,21 @@ fn review_recheck_after_relink_keeps_fresh_facts_and_the_untouched_copy() { preview_checked: p.preview_checked.clone(), }) .unwrap(); - let listed = recheck::stale(&mut x.s, true); - assert_eq!(listed.len(), 1, "the eligible parent owns one grouped probe"); + let p = x.s.catalog.photo(x.id).unwrap(); + x.s.catalog + .apply(Op::SetContent { + id: x.id, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + preview_only: None, + preview_checked: OTHER.into(), + }) + .unwrap(); + let listed = recheck::stale(&mut x.s, false); + assert_eq!(listed.len(), 1, "only the stale parent requests a probe"); + assert_eq!(listed[0].metadata_targets, [x.id]); let mut old = recheck::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); old.meta.lens = "must not fill the unselected copy".into(); let old_size = old.file_size; From 04b731d483d36a98bdf0f3bcf3e5f9175fa89ef9 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 18:32:21 +0100 Subject: [PATCH 03/42] Reload: skip the catalog membership scan for empty plans --- crates/engine/src/cmd/reload.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/engine/src/cmd/reload.rs b/crates/engine/src/cmd/reload.rs index cd9a2c510e0..df9f96bae77 100644 --- a/crates/engine/src/cmd/reload.rs +++ b/crates/engine/src/cmd/reload.rs @@ -112,6 +112,9 @@ pub(crate) fn plan_ids(s: &mut Session, ids: Vec) -> Vec { items.push(Item { id, path: path.clone(), metadata_targets: vec![id], source_targets: vec![id], family, ticket }); } } + if groups.is_empty() { + return items; + } for ph in s.catalog.photos().filter(|p| !p.deleted) { if let Source::File { path } = &ph.source && let Some(index) = groups.get(&(ph.copy_of.unwrap_or(ph.id), path.as_str())) From a4d25c5147405c575ac8371ea13929571f027d20 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:04:59 +0100 Subject: [PATCH 04/42] Reload and Recheck: refresh copies created while a probe runs --- crates/engine/src/cmd/organize.rs | 1 + crates/engine/src/cmd/recheck.rs | 3 ++- crates/engine/src/cmd/reload.rs | 37 +++++++++++++++++++++--------- crates/engine/src/tests.rs | 15 ++++++++---- crates/engine/src/tests/import.rs | 20 ++++++++++++++++ crates/engine/src/tests/recheck.rs | 13 +++++++++++ docs/parity-checklist.md | 2 +- 7 files changed, 74 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/organize.rs b/crates/engine/src/cmd/organize.rs index 84d82c7c9cc..603fea47903 100644 --- a/crates/engine/src/cmd/organize.rs +++ b/crates/engine/src/cmd/organize.rs @@ -134,6 +134,7 @@ fn virtual_copy(s: &mut Session, src: PhotoId, name: &str) -> Result)>) -> Result { let mut ops = Vec::new(); let mut out = Rechecked::default(); + let mut results: Vec<_> = results.into_iter().filter_map(|(item, info)| info.ok().map(|info| (item, info))).collect(); + super::reload::include_same_file_copies(&s.catalog, results.iter_mut().map(|(item, _)| item)); for (mut item, info) in results { - let Ok(info) = info else { continue }; let Some(id) = item.accept(s) else { continue }; let first = out.updated.len(); let selected: std::collections::HashSet<_> = item.metadata_targets.into_iter().collect(); diff --git a/crates/engine/src/cmd/reload.rs b/crates/engine/src/cmd/reload.rs index df9f96bae77..e00d9d41c54 100644 --- a/crates/engine/src/cmd/reload.rs +++ b/crates/engine/src/cmd/reload.rs @@ -25,7 +25,7 @@ pub struct Item { pub path: String, /// Explicitly selected photos sharing this probe; each may gain missing metadata. pub metadata_targets: Vec, - /// Same-file family members present at planning time, including implicit fallback targets. + /// Same-file family members, including implicit fallback targets. pub(crate) source_targets: Vec, family: PhotoId, /// The [`plan`] it came from, in the order reloads were started (see [`Tickets`]). @@ -67,6 +67,15 @@ impl Tickets { self.invalidated.insert(id, self.last); } + /// A new virtual copy shares the source's facts and their freshness. + pub(crate) fn inherit_copy(&mut self, copy: PhotoId, source: PhotoId) { + if let Some(cutoff) = self.invalidated.get(&source).copied() { + self.invalidated.insert(copy, cutoff); + } else { + self.invalidated.remove(©); + } + } + /// Keep changed file facts without cancelling an untouched sibling's pending read. pub(crate) fn valid(&self, id: PhotoId, ticket: u64) -> bool { self.invalidated.get(&id).is_none_or(|cutoff| *cutoff < ticket) @@ -90,7 +99,7 @@ pub fn plan(s: &mut Session, p: &Value) -> Result> { Ok(plan_ids(s, ids)) } -/// Group explicit targets and index their same-file siblings once, also for automatic rechecks. +/// Group explicit targets for Reload and automatic rechecks. pub(crate) fn plan_ids(s: &mut Session, ids: Vec) -> Vec { let mut groups = std::collections::HashMap::<(PhotoId, &str), usize>::new(); let mut items: Vec = Vec::new(); @@ -112,19 +121,24 @@ pub(crate) fn plan_ids(s: &mut Session, ids: Vec) -> Vec { items.push(Item { id, path: path.clone(), metadata_targets: vec![id], source_targets: vec![id], family, ticket }); } } + items +} + +/// Index same-file siblings in one pass at completion, including copies created during the probe. +pub(crate) fn include_same_file_copies<'a>(catalog: &lightcraft_catalog::Catalog, items: impl Iterator) { + let mut groups: std::collections::HashMap<_, _> = + items.map(|item| ((item.family, item.path.as_str()), (item.id, &mut item.source_targets))).collect(); if groups.is_empty() { - return items; + return; } - for ph in s.catalog.photos().filter(|p| !p.deleted) { + for ph in catalog.photos().filter(|p| !p.deleted) { if let Source::File { path } = &ph.source - && let Some(index) = groups.get(&(ph.copy_of.unwrap_or(ph.id), path.as_str())) - && let Some(item) = items.get_mut(*index) - && ph.id != item.id + && let Some((id, targets)) = groups.get_mut(&(ph.copy_of.unwrap_or(ph.id), path.as_str())) + && ph.id != *id { - item.source_targets.push(ph.id); + targets.push(ph.id); } } - items } /// The session's file probe, to [`probe`] with on a worker thread (`None` in a session without file @@ -182,8 +196,9 @@ impl Reloaded { pub fn apply(s: &mut Session, items: Vec, results: Vec>) -> Result { let mut ops = Vec::new(); let mut out = Reloaded::default(); - for (mut item, info) in items.into_iter().zip(results) { - let Ok(info) = info else { continue }; + let mut results: Vec<_> = items.into_iter().zip(results).filter_map(|(item, info)| info.ok().map(|info| (item, info))).collect(); + include_same_file_copies(&s.catalog, results.iter_mut().map(|(item, _)| item)); + for (mut item, info) in results { let Some(id) = item.accept(s) else { continue }; let selected: HashSet<_> = item.metadata_targets.into_iter().collect(); crate::cmd::convert::reload_ops(&s.catalog, id, &info, &mut ops, &mut out.reloaded, item.source_targets.iter().copied(), |id| { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ac2e591bcb4..cbade11502c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -73,10 +73,17 @@ pub(crate) struct TestDir(std::path::PathBuf); impl TestDir { pub(crate) fn new(tag: &str) -> Self { - let dir = Self(std::env::temp_dir().join(format!("lc-{tag}-{}", std::process::id()))); - let _ = std::fs::remove_dir_all(&dir.0); - std::fs::create_dir_all(&dir.0).unwrap(); - dir + use std::sync::atomic::{AtomicUsize, Ordering}; + static NEXT: AtomicUsize = AtomicUsize::new(0); + loop { + let serial = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("lc-{tag}-{}-{serial}", std::process::id())); + match std::fs::create_dir(&dir) { + Ok(()) => return Self(dir), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => panic!("could not create test directory {}: {e}", dir.display()), + } + } } } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index ce649275376..3a2b46ea95b 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5104,3 +5104,23 @@ fn review_reload_keeps_an_implicit_copy_when_its_selected_parent_moves() { assert_eq!(photo.meta.camera, before.meta.camera); assert_eq!(s.catalog.photo(id).unwrap(), &parent); } + +#[test] +fn reload_refreshes_a_copy_created_during_the_probe() { + use crate::cmd::reload; + let dir = super::TestDir::new("reload-late-copy"); + let file = dir.join("a.png"); + write_png(&file, 10); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + let items = reload::plan(&mut s, &json!({"id": id.0})).unwrap(); + write_png(&file, 200); + let info = reload::file_probe(&s).unwrap()(&file.to_string_lossy()).unwrap(); + let copy = PhotoId(s.execute("photo.virtualCopy", &json!({"id": id.0})).unwrap()["ids"][0].as_u64().unwrap()); + assert_ne!(s.catalog.photo(copy).unwrap().content_hash, info.content_hash); + let hash = info.content_hash.clone(); + let out = reload::apply(&mut s, items, vec![Ok(info)]).unwrap(); + assert!(out.reloaded.contains(©)); + assert_eq!(s.catalog.photo(copy).unwrap().content_hash, hash); +} diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index 98f26b8266d..06a201e5343 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -296,6 +296,19 @@ fn review_same_path_relink_invalidates_older_reads_even_when_facts_match() { assert_eq!(x.s.execute("library.recheckPreviewOnly", &json!({"all": true})).unwrap()["updated"], json!([x.id.0])); } +#[test] +fn recheck_refreshes_a_copy_created_during_the_probe() { + let mut x = checked_orf("new-copy"); + let listed = recheck::stale(&mut x.s, true); + replace_checked_orf(&x.file); + let info = recheck::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + let copy = PhotoId(x.s.execute("photo.virtualCopy", &json!({"id": x.id.0})).unwrap()["ids"][0].as_u64().unwrap()); + assert_ne!(x.s.catalog.photo(copy).unwrap().content_hash, info.content_hash); + let out = recheck::apply(&mut x.s, listed.into_iter().map(|item| (item, Ok(info.clone()))).collect()).unwrap(); + assert!(out.updated.contains(©)); + assert_eq!(x.s.catalog.photo(copy).unwrap().content_hash, info.content_hash); +} + #[test] fn recheck_does_not_overwrite_copies_created_after_its_listing() { let mut x = checked_orf("late-copy"); diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index be43dc18228..0f7abefffb7 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -123,7 +123,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-CULL | Assisted culling | P2 | 🟡 | `cmd:photo.analyze`, `cmd:dialog.cull`, `cmd:photo.moveToBurst`, `cmd:panel.bursts`, `crates/pipeline/src/cull.rs`, `crates/ui-egui/src/panels/bursts.rs` | Photo ▸ Assisted Culling…: focus score (0–100), clipping, burst grouping (look-alike shots within 10 s, both limits adjustable in the dialog and as `burstGap` / `similarity`, #2275) with the sharpest marked, optionally stacked collapsed with the best photo on top (`stackGroups`, #2277; photos already stacked are left alone); reject below a focus score, pick each burst's best; bursts put right by hand in Window ▸ Bursts (drag a photo within its burst — first place is the pick, and the Pick flag culling set, Best of Similar Shots and a stacked burst's top follow — into another burst, a new one or none; drag a burst onto another to merge; kept when culling runs again unless *Regroup bursts I arranged by hand*); classical measures — no eyes-closed / expression detection | | LR-LIB-ACTIVITY | Comments & likes | OOS | 🚫 | | | | LR-LIB-QUICKCOLL | Quick collection [Classic] | P2 | ✅ | `cmd:album.toggleTarget`, `cmd:album.clearQuick` | B in the grids | -| LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs`, `crates/ui-egui/src/thumb.rs` | “Copy N” tag on the grid and on the filmstrip (widgets `copy:`, `film:copy:`; on a narrow thumbnail it drops its name and then hides rather than meet the stack badge), stacked with the original, same albums, no XMP writes; default numbers are checked across the batch before copies are created, while explicit names bypass the counter; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master” |. Reload shares one probe and file facts within a same-file family, retains every selected metadata target and scopes overlapping reads to that family and file; independently relinked copies keep their own facts and preview rechecks, as do stale copies whose parent is already current. Edits, legacy shutter repair and one-step Undo are preserved. | +| LR-LIB-VIRTUALCOPY | Virtual copies [Classic] | P1 | ✅ | `cmd:photo.virtualCopy`, `cmd:photo.delete`, `crates/engine/src/cmd/organize.rs`, `crates/ui-egui/src/thumb.rs` | “Copy N” tag on the grid and on the filmstrip (widgets `copy:`, `film:copy:`; on a narrow thumbnail it drops its name and then hides rather than meet the stack badge), stacked with the original, same albums, no XMP writes; default numbers are checked across the batch before copies are created, while explicit names bypass the counter; deleting a copy dissolves or renumbers the stack (#1493); no “Set Copy as Master”. Reload shares one probe and file facts within a same-file family, retains every selected metadata target and scopes overlapping reads to that family and file; independently relinked copies keep their own facts and preview rechecks, as do stale copies whose parent is already current. Edits, legacy shutter repair and one-step Undo are preserved. | ## C. Views & navigation (VIEW) From 8c6e6ba6eb45b234daee4ce9f186c810cd6cfd4d Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:19:31 +0100 Subject: [PATCH 05/42] Reload: require file reads and record freshness after applying results --- crates/engine/src/cmd/convert.rs | 7 +++-- crates/engine/src/cmd/recheck.rs | 15 ++++++---- crates/engine/src/cmd/reload.rs | 46 ++++++++++++++++------------- crates/engine/src/tests/recheck.rs | 47 ++++++++++++++++++++++++++++++ crates/ui-egui/src/reload.rs | 5 ++-- 5 files changed, 90 insertions(+), 30 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index d8d653fa2e6..85c32c55772 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -359,8 +359,11 @@ pub(crate) fn shares_reload_source(a: &lightcraft_catalog::Photo, b: &lightcraft fn reload(s: &mut Session, p: &Value) -> Result { use crate::cmd::reload as r; let items = r::plan(s, p)?; - let probe = r::file_probe(s); - let results = r::probe(probe.as_ref(), &items, &std::sync::atomic::AtomicBool::new(false), &|_| {}); + if items.is_empty() { + return Ok(r::Reloaded::default().to_json()); + } + let probe = r::file_probe(s).ok_or_else(|| bad("photo.reload", "this session has no file access"))?; + let results = r::probe(Some(&probe), &items, &std::sync::atomic::AtomicBool::new(false), &|_| {}); Ok(r::apply(s, items, results)?.to_json()) } diff --git a/crates/engine/src/cmd/recheck.rs b/crates/engine/src/cmd/recheck.rs index d17d955f68a..dbe1ff5d6ab 100644 --- a/crates/engine/src/cmd/recheck.rs +++ b/crates/engine/src/cmd/recheck.rs @@ -72,18 +72,21 @@ pub fn apply(s: &mut Session, results: Vec<(Stale, std::result::Result = results.into_iter().filter_map(|(item, info)| info.ok().map(|info| (item, info))).collect(); super::reload::include_same_file_copies(&s.catalog, results.iter_mut().map(|(item, _)| item)); + let mut accepted = Vec::new(); for (mut item, info) in results { - let Some(id) = item.accept(s) else { continue }; + let Some(id) = item.current_representative(s) else { continue }; let first = out.updated.len(); - let selected: std::collections::HashSet<_> = item.metadata_targets.into_iter().collect(); - crate::cmd::convert::reload_ops(&s.catalog, id, &info, &mut ops, &mut out.updated, item.source_targets, |id| selected.contains(&id)); + let selected: std::collections::HashSet<_> = std::mem::take(&mut item.metadata_targets).into_iter().collect(); + crate::cmd::convert::reload_ops(&s.catalog, id, &info, &mut ops, &mut out.updated, item.source_targets.iter().copied(), |id| { + selected.contains(&id) + }); if info.preview_only.is_none() { out.cleared.extend(out.updated[first..].iter().copied().filter(|id| s.catalog.photo(*id).is_some_and(|p| p.preview_only.is_some()))); } + accepted.push(item); } - if !ops.is_empty() { - s.apply_system(Op::Batch { ops })?; - } + let result = if ops.is_empty() { Ok(()) } else { s.apply_system(Op::Batch { ops }) }; + super::reload::finish_reads(&mut s.reload_tickets, accepted, result)?; out.cleared.retain(|id| s.catalog.photo(*id).is_some_and(|p| p.develops_raw())); for id in &out.updated { s.media.forget(*id); diff --git a/crates/engine/src/cmd/reload.rs b/crates/engine/src/cmd/reload.rs index e00d9d41c54..1e233bebcfc 100644 --- a/crates/engine/src/cmd/reload.rs +++ b/crates/engine/src/cmd/reload.rs @@ -33,8 +33,8 @@ pub struct Item { } impl Item { - /// Accept a successful read for the still-current members, returning its representative. - pub(crate) fn accept(&mut self, s: &mut Session) -> Option { + /// Find a still-current representative without recording the read before its batch commits. + pub(crate) fn current_representative(&mut self, s: &Session) -> Option { self.source_targets.retain(|id| { s.reload_tickets.valid(*id, self.ticket) && s.catalog.photo(*id).is_some_and(|p| { @@ -42,7 +42,7 @@ impl Item { }) }); let id = *self.source_targets.first()?; - s.reload_tickets.accept(self.family, self.path.clone(), self.ticket).then_some(id) + s.reload_tickets.applied.get(&(self.family, self.path.clone())).is_none_or(|latest| *latest <= self.ticket).then_some(id) } } @@ -80,16 +80,18 @@ impl Tickets { pub(crate) fn valid(&self, id: PhotoId, ticket: u64) -> bool { self.invalidated.get(&id).is_none_or(|cutoff| *cutoff < ticket) } +} - /// Only a newer completed read of this family's file supersedes its result. - pub(crate) fn accept(&mut self, family: PhotoId, path: String, ticket: u64) -> bool { - let key = (family, path); - if self.applied.get(&key).is_some_and(|latest| *latest > ticket) { - return false; +/// Supersede earlier reads after a successful batch, including a successful read with no +/// changes. A partial rollback can leave new facts behind, so preserve their ordering too. +pub(crate) fn finish_reads(tickets: &mut Tickets, accepted: Vec, result: Result<()>) -> Result<()> { + if result.is_ok() || matches!(result, Err(crate::EngineError::Catalog(lightcraft_catalog::CatalogError::PartlyApplied { .. }))) { + for item in accepted { + let latest = tickets.applied.entry((item.family, item.path)).or_default(); + *latest = (*latest).max(item.ticket); } - self.applied.insert(key, ticket); - true } + result } /// The files `p` targets (`ids`, else the selection), grouped by family and path under a new @@ -141,8 +143,7 @@ pub(crate) fn include_same_file_copies<'a>(catalog: &lightcraft_catalog::Catalog } } -/// The session's file probe, to [`probe`] with on a worker thread (`None` in a session without file -/// access, where a reload reads nothing but the file name, as the command does). +/// The session's file probe, to [`probe`] with on a worker thread (`None` without file access). pub fn file_probe(s: &Session) -> Option { s.media.file_probe.clone() } @@ -156,11 +157,15 @@ pub fn probe( cancel: &AtomicBool, progress: &dyn Fn(usize), ) -> Vec> { + let Some(probe) = probe else { + progress(items.len()); + return items.iter().map(|item| Err(format!("{}: this session has no file access", item.path))).collect(); + }; let paths: Vec = items.iter().map(|i| i.path.clone()).collect(); let done = AtomicUsize::new(0); #[cfg(not(target_arch = "wasm32"))] let r = std::thread::scope(|sc| { - let h = sc.spawn(|| crate::import::probe_all(probe, &paths, &done, cancel)); + let h = sc.spawn(|| crate::import::probe_all(Some(probe), &paths, &done, cancel)); while !h.is_finished() { progress(done.load(Ordering::Relaxed)); std::thread::sleep(std::time::Duration::from_millis(50)); @@ -169,7 +174,7 @@ pub fn probe( h.join().unwrap_or_else(|_| paths.iter().map(|p| Err(format!("{p}: could not be read"))).collect()) }); #[cfg(target_arch = "wasm32")] - let r = crate::import::probe_all(probe, &paths, &done, cancel); + let r = crate::import::probe_all(Some(probe), &paths, &done, cancel); progress(done.load(Ordering::Relaxed)); r } @@ -198,16 +203,17 @@ pub fn apply(s: &mut Session, items: Vec, results: Vec = items.into_iter().zip(results).filter_map(|(item, info)| info.ok().map(|info| (item, info))).collect(); include_same_file_copies(&s.catalog, results.iter_mut().map(|(item, _)| item)); + let mut accepted = Vec::new(); for (mut item, info) in results { - let Some(id) = item.accept(s) else { continue }; - let selected: HashSet<_> = item.metadata_targets.into_iter().collect(); + let Some(id) = item.current_representative(s) else { continue }; + let selected: HashSet<_> = std::mem::take(&mut item.metadata_targets).into_iter().collect(); crate::cmd::convert::reload_ops(&s.catalog, id, &info, &mut ops, &mut out.reloaded, item.source_targets.iter().copied(), |id| { selected.contains(&id) }); - out.checked.extend(item.source_targets); - } - if !ops.is_empty() { - s.commit_with_read_invalidation("Reload Changed Files", Op::Batch { ops }, false)?; + out.checked.extend(item.source_targets.iter().copied()); + accepted.push(item); } + let result = if ops.is_empty() { Ok(()) } else { s.commit_with_read_invalidation("Reload Changed Files", Op::Batch { ops }, false) }; + finish_reads(&mut s.reload_tickets, accepted, result)?; Ok(out) } diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index 06a201e5343..dc3f5d1f6ed 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -147,6 +147,53 @@ fn session_without_file_access_refuses() { assert!(x.s.catalog.photo(x.id).unwrap().preview_only.is_some()); } +#[test] +fn reload_without_a_file_reader_preserves_verified_facts() { + use crate::cmd::reload; + let mut x = library("reload-no-reader"); + let before = x.s.catalog.photo(x.id).unwrap().clone(); + x.s.media.file_probe = None; + let options = json!({"id": x.id.0}); + let err = x.s.execute("photo.reload", &options).unwrap_err().to_string(); + assert!(err.contains("no file access"), "{err}"); + + let items = reload::plan(&mut x.s, &options).unwrap(); + let results = reload::probe(None, &items, &std::sync::atomic::AtomicBool::new(false), &|_| {}); + assert!(results.iter().all(Result::is_err)); + assert!(reload::apply(&mut x.s, items, results).unwrap().checked.is_empty()); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), &before); +} + +#[test] +fn rejected_recheck_does_not_supersede_an_older_reload() { + use crate::cmd::reload; + let mut x = checked_orf("rejected-batch"); + let before = x.s.catalog.photo(x.id).unwrap().clone(); + let mut another = (*before).clone(); + another.id = x.s.catalog.alloc_photo_id(); + another.captured = None; + another.source = lightcraft_catalog::Source::File { path: x.dir.join("other.orf").to_string_lossy().into() }; + let other_id = another.id; + x.s.commit("Add", Op::AddPhoto { photo: Box::new(another) }).unwrap(); + + let older = reload::plan(&mut x.s, &json!({"id": x.id.0})).unwrap(); + replace_checked_orf(&x.file); + let old = reload::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + let newer = recheck::stale(&mut x.s, true) + .into_iter() + .map(|item| { + let mut info = old.clone(); + if item.id == other_id { + info.captured = Some("invalid capture date".into()); + } + (item, Ok(info)) + }) + .collect(); + assert!(recheck::apply(&mut x.s, newer).is_err()); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), &before); + assert_eq!(reload::apply(&mut x.s, older, vec![Ok(old)]).unwrap().reloaded, [x.id]); +} + /// Relinked copies must be checked independently, and must not receive their parent's file facts. #[test] fn relinked_copy_rechecks_its_own_file() { diff --git a/crates/ui-egui/src/reload.rs b/crates/ui-egui/src/reload.rs index ae394824d90..e4cc63ea70d 100644 --- a/crates/ui-egui/src/reload.rs +++ b/crates/ui-egui/src/reload.rs @@ -37,14 +37,15 @@ pub fn command(app: &mut LightcraftApp, p: &Value) -> Option, _)| { From 60c6185424b5e8df21ba3ee255db28ab062bf3a9 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:48:16 +0100 Subject: [PATCH 06/42] Reload: report current file read failures in the app and command --- crates/engine/src/cmd/convert.rs | 4 +-- crates/engine/src/cmd/reload.rs | 31 ++++++++++++++++++++--- crates/engine/src/tests/recheck.rs | 14 ++++++++++ crates/ui-egui/src/panels/edit/sliders.rs | 13 +++++++--- crates/ui-egui/src/reload.rs | 7 +++++ crates/ui-egui/src/tests/recheck.rs | 13 ++++++---- 6 files changed, 67 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 85c32c55772..f7b41f702e1 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -355,7 +355,7 @@ pub(crate) fn shares_reload_source(a: &lightcraft_catalog::Photo, b: &lightcraft /// Re-read photos whose files changed on disk (an external editor saved them): new size, /// dimensions and content hash, cached sources dropped. The app runs the same steps -/// ([`crate::cmd::reload`]) with the files read on a worker thread. → {reloaded: [ids]} +/// ([`crate::cmd::reload`]) with the files read on a worker thread. → {reloaded: [ids], failed?: [{id, path, error}]} fn reload(s: &mut Session, p: &Value) -> Result { use crate::cmd::reload as r; let items = r::plan(s, p)?; @@ -429,7 +429,7 @@ pub fn edit_specs() -> Vec { "Reload from Disk", ["Photo"], None, - "{ids?} — re-read photos whose files changed on disk (e.g. saved by an external editor), or raws shown from their embedded preview that can be decoded now; camera fields the catalog lacks are filled in, and so is the lens data the file carries (an untouched photo then gets its lens correction turned on as import would; an edited one keeps its settings); in the app the files are read in the background (activity row `reload`, cancellable) and the reply is {background: true, count} unless `wait: true` → {reloaded}", + "{ids?} — re-read photos whose files changed on disk (e.g. saved by an external editor), or raws shown from their embedded preview that can be decoded now; camera fields the catalog lacks are filled in, and so is the lens data the file carries (an untouched photo then gets its lens correction turned on as import would; an edited one keeps its settings); in the app the files are read in the background (activity row `reload`, cancellable) and the reply is {background: true, count} unless `wait: true` → {reloaded, failed?: [{id, path, error}]}", has_selection, reload ), diff --git a/crates/engine/src/cmd/reload.rs b/crates/engine/src/cmd/reload.rs index 1e233bebcfc..4b1de57fb37 100644 --- a/crates/engine/src/cmd/reload.rs +++ b/crates/engine/src/cmd/reload.rs @@ -179,18 +179,30 @@ pub fn probe( r } -/// What Reload checked successfully and what it changed. +/// What Reload read, changed, or couldn't read. #[derive(Debug, Default)] pub struct Reloaded { pub reloaded: Vec, /// Current targets whose probes succeeded, including photos whose facts were unchanged. pub checked: Vec, + pub failed: Vec, +} + +#[derive(Debug, serde::Serialize)] +pub struct ReadFailure { + pub id: PhotoId, + pub path: String, + pub error: String, } impl Reloaded { - /// `{reloaded: [ids]}`; accepted probes are internal notification bookkeeping. + /// `{reloaded: [ids], failed?: [{id, path, error}]}`. pub fn to_json(&self) -> Value { - json!({"reloaded": self.reloaded.iter().map(|i| i.0).collect::>()}) + let mut value = json!({"reloaded": self.reloaded}); + if !self.failed.is_empty() { + value["failed"] = json!(self.failed); + } + value } } @@ -201,11 +213,22 @@ impl Reloaded { pub fn apply(s: &mut Session, items: Vec, results: Vec>) -> Result { let mut ops = Vec::new(); let mut out = Reloaded::default(); - let mut results: Vec<_> = items.into_iter().zip(results).filter_map(|(item, info)| info.ok().map(|info| (item, info))).collect(); + let mut results: Vec<_> = items.into_iter().zip(results).collect(); include_same_file_copies(&s.catalog, results.iter_mut().map(|(item, _)| item)); let mut accepted = Vec::new(); for (mut item, info) in results { let Some(id) = item.current_representative(s) else { continue }; + let info = match info { + Ok(info) => info, + Err(error) => { + out.failed.extend(item.metadata_targets.into_iter().filter(|id| item.source_targets.contains(id)).map(|id| ReadFailure { + id, + path: item.path.clone(), + error: error.clone(), + })); + continue; + } + }; let selected: HashSet<_> = std::mem::take(&mut item.metadata_targets).into_iter().collect(); crate::cmd::convert::reload_ops(&s.catalog, id, &info, &mut ops, &mut out.reloaded, item.source_targets.iter().copied(), |id| { selected.contains(&id) diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index dc3f5d1f6ed..1dea0186a40 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -164,6 +164,20 @@ fn reload_without_a_file_reader_preserves_verified_facts() { assert_eq!(x.s.catalog.photo(x.id).unwrap(), &before); } +#[test] +fn reload_reports_file_read_errors_while_a_target_is_current() { + use crate::cmd::reload; + let mut x = library("unreadable-source"); + let before = x.s.catalog.photo(x.id).unwrap().clone(); + x.s.media.file_probe = Some(std::sync::Arc::new(|_| Err("drive offline".into()))); + let result = x.s.execute("photo.reload", &json!({"id": x.id.0})).unwrap(); + assert_eq!(result["failed"], json!([{"id": x.id.0, "path": x.file.to_string_lossy(), "error": "drive offline"}])); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), &before); + let items = reload::plan(&mut x.s, &json!({"id": x.id.0})).unwrap(); + x.s.commit("Delete", Op::SetDeleted { id: x.id, deleted: true }).unwrap(); + assert!(reload::apply(&mut x.s, items, vec![Err("drive offline".into())]).unwrap().failed.is_empty()); +} + #[test] fn rejected_recheck_does_not_supersede_an_older_reload() { use crate::cmd::reload; diff --git a/crates/ui-egui/src/panels/edit/sliders.rs b/crates/ui-egui/src/panels/edit/sliders.rs index 7b8e8d2b2df..915ddf1af6f 100644 --- a/crates/ui-egui/src/panels/edit/sliders.rs +++ b/crates/ui-egui/src/panels/edit/sliders.rs @@ -504,11 +504,16 @@ pub(crate) fn reload_preview_only(app: &mut LightcraftApp, ctx: &egui::Context, match app.run("photo.reload", json!({"ids": [id.0]})) { Err(e) => app.toast_error(ctx, e), Ok(r) if r["background"] == true => {} - // nothing to read in the background (a photo without a file): answered in place - Ok(_) if app.session.catalog.photo(id).is_some_and(|p| p.preview_only.is_none()) => { - app.toast(ctx, crate::i18n::tr("This raw is now developed from its raw data")) + Ok(r) => { + // No background work was started: the engine answered in place. + if let Some(error) = r["failed"][0]["error"].as_str() { + app.toast_error(ctx, crate::i18n::tr_format!("Could not read this photo. {error}", error = error)); + } else if app.session.catalog.photo(id).is_some_and(|p| p.preview_only.is_none()) { + app.toast(ctx, crate::i18n::tr("This raw is now developed from its raw data")); + } else { + app.toast(ctx, crate::i18n::tr("This raw variant still can't be decoded")); + } } - Ok(_) => app.toast(ctx, crate::i18n::tr("This raw variant still can't be decoded")), } } diff --git a/crates/ui-egui/src/reload.rs b/crates/ui-egui/src/reload.rs index e4cc63ea70d..4537bd7368c 100644 --- a/crates/ui-egui/src/reload.rs +++ b/crates/ui-egui/src/reload.rs @@ -59,12 +59,16 @@ pub fn command(app: &mut LightcraftApp, p: &Value) -> Option Option crate::i18n::tr("This raw is now developed from its raw data").to_string(), (1, 1, _) if still_preview_only => crate::i18n::tr("This raw variant still can't be decoded").to_string(), diff --git a/crates/ui-egui/src/tests/recheck.rs b/crates/ui-egui/src/tests/recheck.rs index b7ed3203e16..ad4c0ffa7d3 100644 --- a/crates/ui-egui/src/tests/recheck.rs +++ b/crates/ui-egui/src/tests/recheck.rs @@ -183,11 +183,14 @@ fn a_negative_reload_notice_requires_an_accepted_probe_even_when_unchanged() { assert!(crate::tasks::wait(&mut app, &egui::Context::default(), Duration::from_secs(10))); assert_eq!(app.session.catalog.photo(id).unwrap(), &before); assert_eq!(app.session.undo.len(), undo, "none of these Reloads changes the catalog"); - assert_eq!( - app.ui.toast.as_ref().map(|(text, _, _)| text.as_str()), - (case == "unchanged").then_some("This raw variant still can't be decoded"), - "{case}" - ); + let notice = app.ui.toast.as_ref().map(|(text, _, _)| text.as_str()); + match case { + "unreadable" => { + assert!(notice.is_some_and(|text| text.starts_with("Could not read this photo.") && text.contains("preview.dng")), "{notice:?}") + } + "unchanged" => assert_eq!(notice, Some("This raw variant still can't be decoded")), + _ => assert_eq!(notice, None, "{case}"), + } } } From ca2d86ed5623bde741064307768401f680eece1a Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 20:12:40 +0100 Subject: [PATCH 07/42] Reload: bind pending reads to their library opening --- crates/engine/src/cmd/recheck.rs | 2 +- crates/engine/src/cmd/reload.rs | 30 +++++++++++++++--------- crates/engine/src/library.rs | 1 + crates/engine/src/tests/recheck.rs | 37 ++++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/recheck.rs b/crates/engine/src/cmd/recheck.rs index dbe1ff5d6ab..3fec7e08386 100644 --- a/crates/engine/src/cmd/recheck.rs +++ b/crates/engine/src/cmd/recheck.rs @@ -71,7 +71,7 @@ pub fn apply(s: &mut Session, results: Vec<(Stale, std::result::Result = results.into_iter().filter_map(|(item, info)| info.ok().map(|info| (item, info))).collect(); - super::reload::include_same_file_copies(&s.catalog, results.iter_mut().map(|(item, _)| item)); + super::reload::include_same_file_copies(s, results.iter_mut().map(|(item, _)| item)); let mut accepted = Vec::new(); for (mut item, info) in results { let Some(id) = item.current_representative(s) else { continue }; diff --git a/crates/engine/src/cmd/reload.rs b/crates/engine/src/cmd/reload.rs index 4b1de57fb37..727ea717929 100644 --- a/crates/engine/src/cmd/reload.rs +++ b/crates/engine/src/cmd/reload.rs @@ -28,6 +28,7 @@ pub struct Item { /// Same-file family members, including implicit fallback targets. pub(crate) source_targets: Vec, family: PhotoId, + library: u64, /// The [`plan`] it came from, in the order reloads were started (see [`Tickets`]). pub ticket: u64, } @@ -35,6 +36,9 @@ pub struct Item { impl Item { /// Find a still-current representative without recording the read before its batch commits. pub(crate) fn current_representative(&mut self, s: &Session) -> Option { + if self.library != s.library_generation() { + return None; + } self.source_targets.retain(|id| { s.reload_tickets.valid(*id, self.ticket) && s.catalog.photo(*id).is_some_and(|p| { @@ -107,6 +111,7 @@ pub(crate) fn plan_ids(s: &mut Session, ids: Vec) -> Vec { let mut items: Vec = Vec::new(); let mut seen = HashSet::new(); let ticket = s.reload_tickets.next(); + let library = s.library_generation(); for id in ids.into_iter().filter(|id| seen.insert(*id)) { let Some(ph) = s.catalog.photo(id) else { continue }; if ph.deleted { @@ -120,20 +125,22 @@ pub(crate) fn plan_ids(s: &mut Session, ids: Vec) -> Vec { item.metadata_targets.push(id); } else { groups.insert(key, items.len()); - items.push(Item { id, path: path.clone(), metadata_targets: vec![id], source_targets: vec![id], family, ticket }); + items.push(Item { id, path: path.clone(), metadata_targets: vec![id], source_targets: vec![id], family, library, ticket }); } } items } /// Index same-file siblings in one pass at completion, including copies created during the probe. -pub(crate) fn include_same_file_copies<'a>(catalog: &lightcraft_catalog::Catalog, items: impl Iterator) { - let mut groups: std::collections::HashMap<_, _> = - items.map(|item| ((item.family, item.path.as_str()), (item.id, &mut item.source_targets))).collect(); +pub(crate) fn include_same_file_copies<'a>(s: &Session, items: impl Iterator) { + let mut groups: std::collections::HashMap<_, _> = items + .filter(|item| item.library == s.library_generation()) + .map(|item| ((item.family, item.path.as_str()), (item.id, &mut item.source_targets))) + .collect(); if groups.is_empty() { return; } - for ph in catalog.photos().filter(|p| !p.deleted) { + for ph in s.catalog.photos().filter(|p| !p.deleted) { if let Source::File { path } = &ph.source && let Some((id, targets)) = groups.get_mut(&(ph.copy_of.unwrap_or(ph.id), path.as_str())) && ph.id != *id @@ -214,18 +221,19 @@ pub fn apply(s: &mut Session, items: Vec, results: Vec = items.into_iter().zip(results).collect(); - include_same_file_copies(&s.catalog, results.iter_mut().map(|(item, _)| item)); + include_same_file_copies(s, results.iter_mut().map(|(item, _)| item)); let mut accepted = Vec::new(); for (mut item, info) in results { let Some(id) = item.current_representative(s) else { continue }; let info = match info { Ok(info) => info, Err(error) => { - out.failed.extend(item.metadata_targets.into_iter().filter(|id| item.source_targets.contains(id)).map(|id| ReadFailure { - id, - path: item.path.clone(), - error: error.clone(), - })); + let before = out.failed.len(); + let report = |id| ReadFailure { id, path: item.path.clone(), error: error.clone() }; + out.failed.extend(item.metadata_targets.into_iter().filter(|id| item.source_targets.contains(id)).map(report)); + if out.failed.len() == before { + out.failed.push(ReadFailure { id, path: item.path, error }); + } continue; } }; diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index effc5d5e42d..dad14878c88 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -645,6 +645,7 @@ impl Session { // (nothing of the list the last library showed is this one's) self.refresh_view(); self.library_generation = crate::LIBRARY_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + self.reload_tickets = Default::default(); for entry in self.undo.iter_mut().chain(self.redo.iter_mut()) { self.pending_sidecar_repairs.append(&mut entry.retry_sidecars); } diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index 1dea0186a40..8b417334b1b 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -178,6 +178,43 @@ fn reload_reports_file_read_errors_while_a_target_is_current() { assert!(reload::apply(&mut x.s, items, vec![Err("drive offline".into())]).unwrap().failed.is_empty()); } +#[test] +fn reload_failure_follows_the_copy_when_the_original_has_relinked() { + use crate::cmd::reload; + let mut x = library("unreadable-copy"); + let copy = x.s.execute("photo.virtualCopy", &json!({"ids": [x.id.0]})).unwrap()["ids"][0].as_u64().unwrap(); + let items = reload::plan(&mut x.s, &json!({"id": x.id.0})).unwrap(); + let different = x.dir.join("other.cr3"); + std::fs::copy(&x.file, &different).unwrap(); + x.s.execute("photo.relink", &json!({"id": x.id.0, "path": different.to_string_lossy()})).unwrap(); + let result = reload::apply(&mut x.s, items, vec![Err("drive offline".into())]).unwrap(); + assert_eq!(result.to_json()["failed"], json!([{"id": copy, "path": x.file.to_string_lossy(), "error": "drive offline"}])); +} + +#[test] +fn reload_and_recheck_from_an_earlier_library_cannot_update_a_matching_id_and_path() { + use crate::cmd::reload; + let mut x = library("replaced-library"); + let reload_items = reload::plan(&mut x.s, &json!({"id": x.id.0})).unwrap(); + let recheck_items = recheck::stale(&mut x.s, false); + assert_eq!(recheck_items.len(), 1); + let probe = reload::file_probe(&x.s).unwrap(); + let old = probe(&x.file.to_string_lossy()).unwrap(); + decodable_now(&x); + x.s.open_library(x.dir.join("another-library"), false).unwrap(); + let result = x.s.execute("library.import", &json!({"paths": [x.file.to_string_lossy()]})).unwrap(); + assert_eq!(result["imported"], json!([x.id.0])); + let before = x.s.catalog.photo(x.id).unwrap().clone(); + let undo = x.s.undo.len(); + let rechecked = recheck::apply(&mut x.s, recheck_items.into_iter().map(|item| (item, Ok(old.clone()))).collect()).unwrap(); + assert!(rechecked.updated.is_empty()); + let reloaded = reload::apply(&mut x.s, reload_items, vec![Ok(old)]).unwrap(); + assert!(reloaded.checked.is_empty()); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), &before); + assert_eq!(x.s.undo.len(), undo); + assert!(x.s.execute("photo.reload", &json!({"id": x.id.0})).unwrap()["failed"].is_null()); +} + #[test] fn rejected_recheck_does_not_supersede_an_older_reload() { use crate::cmd::reload; From e1a5cd3359355b99a355322dea72f3ba1cb9db6d Mon Sep 17 00:00:00 2001 From: pancake Date: Fri, 27 Nov 2026 19:02:43 +0100 Subject: [PATCH 08/42] Reload: refresh browsed imports with their same-file copies --- crates/engine/src/import/commit.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 450b77f5db5..4205cac71e1 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -286,7 +286,8 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare PreparedItem::Promote(id, fresh) => { // the file was replaced since it was browsed: the record takes what it is now before it joins the library if let Some(info) = &fresh { - crate::cmd::convert::reload_ops(&s.catalog, id, info, &mut ops, &mut Vec::new()); + let targets = s.catalog.photos().filter(|p| p.id == id || p.copy_of == Some(id)).map(|p| p.id); + crate::cmd::convert::reload_ops(&s.catalog, id, info, &mut ops, &mut Vec::new(), targets, |target| target == id); } if s.catalog.photo(id).is_some_and(|p| p.local) { ops.push(Op::SetLocal { id, local: false }); From 899807049564a96588e492d6cf09be3c0aeb444a Mon Sep 17 00:00:00 2001 From: pancake Date: Sun, 29 Nov 2026 17:15:46 +0100 Subject: [PATCH 09/42] Keep the AI Defringe lens cache key while refreshing source facts --- crates/engine/src/media/quick.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 9fd2bd9a6de..9efd11101a5 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -190,6 +190,18 @@ pub(super) fn source_metadata_key(p: &Photo) -> u64 { (k.0 as u64) ^ ((k.0 >> 64) as u64) | 1 } +/// The lens database correction affects AI Defringe's input. File-provided corrections +/// are already covered by the file content key. +pub fn lens_key(p: &Photo) -> u64 { + match &p.embedded_lens { + Some(lens) if lens.source == lightcraft_develop::LensSource::Database => { + let k = Hasher128::new().str("lens").str(&format!("{lens:?}")).finish(); + (k.0 as u64) ^ ((k.0 >> 64) as u64) | 1 + } + _ => 0, + } +} + pub fn source_info(p: &Photo) -> SourceInfo { // Procedural demo scenes are scene-referred HDR (like raw files): use the filmic tone map. // (They are drawn afresh at every size, so they have no original size.) From d7c593b715c2a9c14badef9a15abc6b258a07b82 Mon Sep 17 00:00:00 2001 From: pancake Date: Sun, 29 Nov 2026 17:47:55 +0100 Subject: [PATCH 10/42] Keep earlier source reads valid after a partial rollback --- crates/engine/src/cmd/reload.rs | 24 ++++++++++++---- crates/engine/src/tests/recheck.rs | 44 ++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/reload.rs b/crates/engine/src/cmd/reload.rs index 727ea717929..a1b654f5356 100644 --- a/crates/engine/src/cmd/reload.rs +++ b/crates/engine/src/cmd/reload.rs @@ -86,14 +86,26 @@ impl Tickets { } } -/// Supersede earlier reads after a successful batch, including a successful read with no -/// changes. A partial rollback can leave new facts behind, so preserve their ordering too. +/// Supersede earlier reads for successful probes, including no-op probes. After a partial +/// rollback, only families with changes still in the catalog supersede earlier reads. pub(crate) fn finish_reads(tickets: &mut Tickets, accepted: Vec, result: Result<()>) -> Result<()> { - if result.is_ok() || matches!(result, Err(crate::EngineError::Catalog(lightcraft_catalog::CatalogError::PartlyApplied { .. }))) { - for item in accepted { - let latest = tickets.applied.entry((item.family, item.path)).or_default(); - *latest = (*latest).max(item.ticket); + let retained = match &result { + Ok(()) => None, + Err(crate::EngineError::Catalog(lightcraft_catalog::CatalogError::PartlyApplied { remaining, .. })) => { + let mut ids = HashSet::new(); + remaining.photo_ids(&mut |id| { + ids.insert(id); + }); + Some(ids) } + Err(_) => return result, + }; + for item in accepted { + if retained.as_ref().is_some_and(|ids| !item.source_targets.iter().any(|id| ids.contains(id))) { + continue; + } + let latest = tickets.applied.entry((item.family, item.path)).or_default(); + *latest = (*latest).max(item.ticket); } result } diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index 8b417334b1b..368a42f8192 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -245,6 +245,50 @@ fn rejected_recheck_does_not_supersede_an_older_reload() { assert_eq!(reload::apply(&mut x.s, older, vec![Ok(old)]).unwrap().reloaded, [x.id]); } +#[test] +fn partly_rolled_back_recheck_supersedes_reads_only_for_retained_changes() { + use crate::cmd::reload; + const KELVIN_CAMERA: &str = "SONY ILCA-99M2"; + let mut x = checked_orf("partial-batch"); + let original = x.s.catalog.photo(x.id).unwrap().clone(); + let mut add = |name: &str, wb| { + let mut photo = (*original).clone(); + photo.id = x.s.catalog.alloc_photo_id(); + photo.source = lightcraft_catalog::Source::File { path: x.dir.join(name).to_string_lossy().into() }; + photo.meta.camera = KELVIN_CAMERA.into(); + photo.as_shot_wb = wb; + photo.captured = None; + let id = photo.id; + x.s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + id + }; + // Replacing an invalid old measurement succeeds, but rolling back to it fails. + let retained = add("retained.orf", Some((f64::NAN, 0.0))); + let rejected = add("rejected.orf", None); + let older = reload::plan(&mut x.s, &json!({"ids": [x.id.0, retained.0]})).unwrap(); + replace_checked_orf(&x.file); + let old = reload::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + let newer: Vec<_> = recheck::stale(&mut x.s, true) + .into_iter() + .map(|item| { + let mut info = old.clone(); + if item.id == retained { + info.meta.camera = KELVIN_CAMERA.into(); + info.as_shot_wb = Some((4700.0, 3.0)); + } else if item.id == rejected { + info.captured = Some("invalid capture date".into()); + } + (item, Ok(info)) + }) + .collect(); + + let error = recheck::apply(&mut x.s, newer).unwrap_err(); + assert!(matches!(error, crate::EngineError::Catalog(lightcraft_catalog::CatalogError::PartlyApplied { .. }))); + assert_eq!(x.s.catalog.photo(x.id).unwrap(), &original); + assert_eq!(x.s.catalog.photo(retained).unwrap().as_shot_wb, Some((4700.0, 3.0))); + assert_eq!(reload::apply(&mut x.s, older, vec![Ok(old.clone()), Ok(old)]).unwrap().checked, [x.id]); +} + /// Relinked copies must be checked independently, and must not receive their parent's file facts. #[test] fn relinked_copy_rechecks_its_own_file() { From 3be909347606e3a8894638cb84784ba949293726 Mon Sep 17 00:00:00 2001 From: pancake Date: Wed, 25 Nov 2026 19:30:40 +0100 Subject: [PATCH 11/42] LR-IMP-FORMATS: Keep catalog source facts current on Reload and Relink Use the verified media kind, format, as-shot white balance and lens facts of the current file. Journal the reversible classification as format 16 only after its snapshot header is durable. --- crates/catalog/src/journal.rs | 27 ++++- crates/catalog/src/lib.rs | 12 +- crates/catalog/src/model.rs | 7 +- crates/catalog/src/tests.rs | 2 +- crates/catalog/src/tests_folder_index.rs | 2 +- crates/catalog/src/tests_format_version.rs | 82 ++++++++++++- crates/catalog/src/tests_search_text.rs | 2 +- crates/engine/src/cmd/browse.rs | 1 + crates/engine/src/cmd/convert.rs | 131 ++++++++++++++++++--- crates/engine/src/cmd/missing.rs | 27 +++-- crates/engine/src/files/probe.rs | 15 ++- crates/engine/src/files/tests.rs | 33 ++++++ crates/engine/src/lib.rs | 4 +- crates/engine/src/library.rs | 16 ++- crates/engine/src/relocate.rs | 2 +- crates/engine/src/rename/moves.rs | 2 +- crates/engine/src/tests/focus_scan.rs | 1 + crates/engine/src/tests/import.rs | 110 +++++++++++++++++ crates/engine/src/tests/recheck.rs | 15 +++ crates/engine/src/tests/relocate.rs | 1 + crates/engine/src/tests/view_follow.rs | 2 +- crates/engine/src/tests/xmp.rs | 1 + crates/ui-egui/src/tests/missing_sweep.rs | 9 +- crates/ui-egui/src/tests/recheck.rs | 27 +++++ crates/ui-egui/src/tests/tallies.rs | 2 +- 25 files changed, 486 insertions(+), 47 deletions(-) diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 39225b1a619..a13d6ba575d 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -69,6 +69,7 @@ //! | 13 | Lens Blur | `DevelopSettings.lens_blur`, `Mask.adjust.lens_blur` | //! | 14 | bursts arranged by hand in Assisted Culling | `Analysis.rank` | //! | 15 | per-photo denoiser selection | `DevelopSettings.enhance.denoise_model` | +//! | 16 | probed source classification on Relink and Reload | `Op::Relink.kind` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -113,9 +114,10 @@ use crate::{Catalog, CatalogError, Op, Result}; pub const SNAPSHOT: &str = "catalog.snap"; pub const LOG: &str = "catalog.log"; const FORMAT: &str = "lightcraft-catalog"; +const DENOISER_FORMAT_VERSION: u32 = 15; /// The catalog format this build writes (and the newest it reads). See the module docs → /// *Format versions*; bump it whenever an [`Op`] variant or a serialized field is added. -pub const VERSION: u32 = 15; +pub const VERSION: u32 = 16; /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] @@ -661,7 +663,7 @@ impl Journal { // is appended: a snapshot in this format makes older builds refuse the library instead // of misreading ops or dropping fields they don't know. let older = (!report.created && snapshot_version != Some(VERSION)).then(|| snapshot_version.unwrap_or(0)); - if older.is_some() { + if older.is_some_and(|version| version < DENOISER_FORMAT_VERSION) { catalog.pin_legacy_denoise(resolve)?; } if let Some(at) = damaged_at { @@ -896,17 +898,36 @@ impl Journal { std::mem::take(&mut self.kept_written) } + /// Older readers ignore the classification field, so these ops require a current snapshot. + pub fn needs_snapshot_for(&self, ops: &[Op]) -> bool { + if self.behind.is_none() { + return false; + } + let mut pending: Vec<_> = ops.iter().collect(); + while let Some(op) = pending.pop() { + match op { + Op::Relink { kind: Some(_), .. } => return true, + Op::Batch { ops } => pending.extend(ops), + _ => {} + } + } + false + } + /// Append ops (already applied to the live catalog) durably, in order. pub fn append(&mut self, ops: &[Op]) -> Result<()> { if ops.is_empty() { return Ok(()); } + if self.needs_snapshot_for(ops) { + return Err(CatalogError::Io(format!("save a format v{VERSION} snapshot before journaling source classification"))); + } let t0 = web_time::Instant::now(); let mut buf = String::new(); let mut seq = self.seq; for op in ops { seq = seq.checked_add(1).ok_or_else(|| CatalogError::Corrupt(format!("{LOG}: op counter overflow")))?; - let line = if self.behind.is_some() && has_denoiser_pin(op) { + let line = if self.behind.is_some_and(|version| version < DENOISER_FORMAT_VERSION) && has_denoiser_pin(op) { record(seq, serde_json::to_string(&ProtectedOp::PinnedDenoise { change: op }).unwrap_or_default()) } else { encode_record(seq, op) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index f243cb02cbb..18248951abe 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -217,9 +217,12 @@ pub enum Op { id: PhotoId, file_name: String, source: Source, - /// The file's format when it changes too (Convert to DNG). + /// The file's format when it changes too (Convert to DNG or a fresh probe). #[serde(default, skip_serializing_if = "Option::is_none")] format: Option, + /// A fresh probe's media kind; omitted by older journals and path-only moves. + #[serde(default, skip_serializing_if = "Option::is_none")] + kind: Option, }, /// What a photo's file is now (after it changed on disk: Reload). SetContent { @@ -972,6 +975,7 @@ impl Catalog { Op::SetLabel { .. } => self.changes.now = Aspects::LABEL, Op::SetMeta { .. } => self.changes.now = Aspects::META, Op::SetCaptured { .. } => self.changes.now = Aspects::CAPTURED, + Op::Relink { kind: Some(_), .. } => self.changes.now = Aspects::ALL, Op::SetFile { .. } | Op::Relink { .. } => self.changes.now = Aspects::FILE, Op::SetAnalysis { .. } => self.changes.now = Aspects::ANALYSIS, Op::SetDevelop { .. } | Op::SetVersions { .. } | Op::SetHistory { .. } | Op::PushHistory { .. } | Op::SetHistoryCursor { .. } => { @@ -1231,14 +1235,16 @@ impl Catalog { let p = self.photo_mut(id)?; Op::SetCaptured { id, captured: std::mem::replace(&mut p.captured, captured) } } - Op::Relink { id, file_name, source, format } => { + Op::Relink { id, file_name, source, format, kind } => { if let Some(p) = self.photos.get(&id) { self.index.file_changed(id, file_path(&p.source), file_path(&source)); } let p = self.photo_mut(id)?; let old_name = std::mem::replace(&mut p.file_name, file_name); let old_format = format.map(|f| std::mem::replace(&mut p.format, f)); - let old = Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format }; + let old_kind = kind.map(|k| std::mem::replace(&mut p.kind, k)); + let old = + Op::Relink { id, file_name: old_name, source: std::mem::replace(&mut p.source, source), format: old_format, kind: old_kind }; self.index.text_changed(id, self.photos.get(&id).map(|p| &**p)); old } diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 4b41a510129..e4a320eeeac 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -482,6 +482,11 @@ pub fn preview_stamp(preview_only: &Option) -> String { if preview_only.is_some() { APP_VERSION.to_string() } else { String::new() } } +/// A fresh probe's stamp using the format it actually found, including supported ORFs. +pub fn preview_stamp_for(format: &str, preview_only: &Option) -> String { + if format.eq_ignore_ascii_case("orf") { APP_VERSION.to_string() } else { preview_stamp(preview_only) } +} + impl Photo { /// Keep the newest [`HISTORY_LIMIT`](crate::HISTORY_LIMIT) History steps; the cursor moves with /// its step, or to the oldest step kept when its own is dropped. Returns how many were dropped. @@ -544,7 +549,7 @@ impl Photo { /// The stamp for a fresh probe. Supported ORFs keep it too, so the support-withdrawal /// recheck runs once, without repeatedly probing uncompressed ORFs on every library open. pub fn preview_stamp(&self, preview_only: &Option) -> String { - if self.format.eq_ignore_ascii_case("orf") { APP_VERSION.to_string() } else { preview_stamp(preview_only) } + preview_stamp_for(&self.format, preview_only) } /// A preview-only photo or ORF whose support was checked by another app version (or before /// stamps existed), so this build should probe its file again (issues #662 and #3775). diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index 4e056c03e31..0bba0325c05 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -1019,7 +1019,7 @@ fn photos_changed_since_names_the_photos_whose_read_aspects_changed() { assert_eq!(c.touched_since(start), Some(vec![a, b]), "touched_since says every photo that was touched"); // a photo that comes in, moves or goes let new = add(&mut c, "c.jpg"); - c.apply(Op::Relink { id: a, file_name: "m.jpg".into(), source: Source::File { path: "/p/m.jpg".into() }, format: None }).unwrap(); + c.apply(Op::Relink { id: a, file_name: "m.jpg".into(), source: Source::File { path: "/p/m.jpg".into() }, format: None, kind: None }).unwrap(); c.apply(Op::RemovePhoto { id: b }).unwrap(); assert_eq!(c.photos_changed_since(start, files), Some(vec![a, b, new]), "each once, in id order"); // an op that changes no photo of its own is remembered, and is not in the answer (touched_since gives up on it) diff --git a/crates/catalog/src/tests_folder_index.rs b/crates/catalog/src/tests_folder_index.rs index 2ccbc41d864..ed6ba18ca31 100644 --- a/crates/catalog/src/tests_folder_index.rs +++ b/crates/catalog/src/tests_folder_index.rs @@ -51,7 +51,7 @@ fn the_answers_follow_every_op_that_moves_a_file_and_its_undo() { let steps = [ ("add", Op::AddPhoto { photo: Box::new(added) }), ("set file", Op::SetFile { id: x, file_name: "W.jpg".into(), source: Source::File { path: "/e/W.jpg".into() } }), - ("relink", Op::Relink { id: x, file_name: "v.jpg".into(), source: Source::File { path: "/c/d/v.jpg".into() }, format: None }), + ("relink", Op::Relink { id: x, file_name: "v.jpg".into(), source: Source::File { path: "/c/d/v.jpg".into() }, format: None, kind: None }), ("demo", Op::SetFile { id: x, file_name: "x.jpg".into(), source: Source::Demo { scene: 1 } }), ("remove", Op::RemovePhoto { id }), ]; diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index 43ab99fa1ae..e6987a3651e 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -388,13 +388,91 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v15: `Enhance.denoise_model` (v14: `Analysis.rank`; v13: Lens Blur; v12: `Catalog.grids` and `SegMask.grid`; + /// v16: `Op::Relink.kind`; v15: `Enhance.denoise_model` (v14: `Analysis.rank`; v13: Lens Blur; v12: `Catalog.grids` and `SegMask.grid`; /// v11: `EmbeddedLens.source`; v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`). - const NEWEST_FIELDS: u32 = 15; + const NEWEST_FIELDS: u32 = 16; let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None }); assert_eq!(newest.max(NEWEST_FIELDS), VERSION, "the newest op's or fields' version must be the current format version"); } +#[test] +fn v15_relink_replays_without_kind_and_new_classification_has_an_exact_inverse() { + let mut c = Catalog::new(); + let id = c.alloc_photo_id(); + let mut p = Photo::new(id, Source::File { path: "/old.dng".into() }, "old.dng", "DNG", 4, 3, ""); + p.kind = MediaKind::Raw; + Arc::make_mut(&mut p.develop).enhance.denoise = 25.0; + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + let legacy: Op = serde_json::from_value(serde_json::json!({ + "op": "relink", "id": id.0, "file_name": "moved.dng", + "source": {"type": "file", "path": "/moved.dng"}, "format": "DNG" + })) + .unwrap(); + let record = encode_record(1, &legacy); + assert!(!record.contains("\"kind\""), "old path-only records omit classification"); + let store = MemStore::new(); + store.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":15,\"seq\":0,\"catalog\":{}}}\n", c.to_snapshot()).into_bytes()); + store.set(LOG, format!("{record}\n").into_bytes()); + let (mut journal, mut c, report) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!((report.replayed, report.upgraded_from), (1, Some(15))); + assert_eq!(snapshot_version(&store), u64::from(VERSION)); + assert_eq!(c.photo(id).unwrap().file_name, "moved.dng"); + assert_eq!(c.photo(id).unwrap().source, Source::File { path: "/moved.dng".into() }); + let before = c.photo(id).unwrap().clone(); + assert_eq!(before.kind, MediaKind::Raw); + assert!(before.develop.enhance.denoise_model.is_none(), "upgrading v15 must not pin the legacy v14 denoiser"); + let updated = Op::Relink { + id, + file_name: "image.png".into(), + source: Source::File { path: "/image.png".into() }, + format: Some("PNG".into()), + kind: Some(MediaKind::Image), + }; + let inverse = c.apply(updated.clone()).unwrap(); + assert_eq!((c.photo(id).unwrap().kind, c.photo(id).unwrap().format.as_str()), (MediaKind::Image, "PNG")); + assert!(matches!(&inverse, Op::Relink { kind: Some(MediaKind::Raw), format: Some(format), .. } if format == "DNG")); + c.apply(inverse).unwrap(); + assert_eq!(c.photo(id).unwrap(), &before); + c.apply(updated.clone()).unwrap(); + journal.append(&[updated]).unwrap(); + drop(journal); + let (_, reopened, _) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((reopened.photo(id).unwrap().kind, reopened.photo(id).unwrap().format.as_str()), (MediaKind::Image, "PNG")); +} + +#[test] +fn a_classifying_relink_is_saved_only_after_the_new_format_is_durable() { + let (base, log, _) = legacy_parts(); + let files = MemStore::new(); + files.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":15,\"seq\":2,\"catalog\":{}}}\n", base.to_snapshot()).into_bytes()); + files.set(LOG, log.into_bytes()); + let blocked = Refusing { files: files.clone(), refuse: |name| name == SNAPSHOT }; + let (mut journal, catalog, report) = Journal::open(Box::new(blocked)).unwrap(); + assert!(report.upgraded_from.is_none()); + let id = catalog.photos().next().unwrap().id; + let op = Op::Batch { + ops: vec![Op::Relink { + id, + file_name: "raw.dng".into(), + source: Source::File { path: "/raw.dng".into() }, + format: Some("DNG".into()), + kind: Some(MediaKind::Raw), + }], + }; + let before = files.get(LOG); + assert!(journal.append(std::slice::from_ref(&op)).is_err()); + assert_eq!(files.get(LOG), before); + assert!(journal.append(&[Op::SetRating { id, rating: 5 }]).is_ok(), "older operations remain writable"); + drop(journal); + + let (mut journal, mut base, _) = Journal::open(Box::new(files.clone())).unwrap(); + base.apply(op.clone()).unwrap(); + journal.append(&[op]).unwrap(); + drop(journal); + let (_, reopened, _) = Journal::open(Box::new(files)).unwrap(); + assert_eq!(reopened.photo(id).unwrap(), base.photo(id).unwrap()); +} + // ---- an upgrade keeps what it replaces /// A store whose writes of some files fail. diff --git a/crates/catalog/src/tests_search_text.rs b/crates/catalog/src/tests_search_text.rs index 2c9ae6c6682..69a292a5b5e 100644 --- a/crates/catalog/src/tests_search_text.rs +++ b/crates/catalog/src/tests_search_text.rs @@ -280,7 +280,7 @@ fn the_cache_follows_a_file_name_and_a_format() { assert_eq!((found(&c, "renamed_0042"), found(&c, "plain")), (0, 1)); assert_current(&c); - let undo = c.apply(Op::Relink { id, file_name: "Moved.TIF".into(), source: source.clone(), format: Some("TIFF".into()) }).unwrap(); + let undo = c.apply(Op::Relink { id, file_name: "Moved.TIF".into(), source: source.clone(), format: Some("TIFF".into()), kind: None }).unwrap(); assert_eq!((found(&c, "moved"), found(&c, "tiff"), found(&c, "png")), (1, 1, 0)); assert_eq!((found_by_rule(&c, "moved"), found_by_rule(&c, "tiff"), found_by_rule(&c, "png")), (1, 1, 0)); assert_current(&c); diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 685fcb16b65..39dbf417451 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -727,6 +727,7 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result: file_name, source: lightcraft_catalog::Source::File { path: np.to_string_lossy().to_string() }, format: None, + kind: None, }) .collect(); let n = ops.len(); diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index f7b41f702e1..fd26d7d84ff 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -93,9 +93,16 @@ fn convert(s: &mut Session, p: &Value) -> Result { file_name: file_name.clone(), source: Source::File { path: out.clone() }, format: Some("DNG".into()), + kind: Some(lightcraft_catalog::MediaKind::Raw), }); } - ops.push(Op::Relink { id, file_name, source: Source::File { path: out.clone() }, format: Some("DNG".into()) }); + ops.push(Op::Relink { + id, + file_name, + source: Source::File { path: out.clone() }, + format: Some("DNG".into()), + kind: Some(lightcraft_catalog::MediaKind::Raw), + }); converted.push(json!({"id": id.0, "path": out, "original": path})); } Err(e) => skipped.push(json!([id.0, e])), @@ -205,20 +212,44 @@ fn edit_copy(s: &mut Session, p: &Value, id: lightcraft_catalog::PhotoId, opts: /// file relinked), i.e. a change of [`lightcraft_catalog::Photo::preview_only`], and a /// preview-only photo this version hasn't checked yet: its stamp is refreshed so it isn't probed /// again (see [`lightcraft_catalog::Photo::preview_checked`]). -pub(crate) fn content_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: crate::media::ProbeInfo) -> Option { - let preview_checked = ph.preview_stamp(&info.preview_only); +pub(crate) fn content_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo) -> Option { + // A partial probe must not erase the catalog's classification when it has no format. + let known_type = !info.format.is_empty(); + let format = if known_type { &info.format } else { &ph.format }; + let classification = (known_type && (ph.kind != info.kind || ph.format != info.format)).then(|| Op::Relink { + id, + file_name: ph.file_name.clone(), + source: ph.source.clone(), + format: Some(info.format.clone()), + kind: Some(info.kind), + }); + match (classification, content_facts_op(id, ph, format, info)) { + (Some(classification), Some(content)) => Some(Op::Batch { ops: vec![classification, content] }), + (Some(op), None) | (None, Some(op)) => Some(op), + (None, None) => None, + } +} + +/// Content facts after a caller's classification change, stamped for its effective format. +pub(crate) fn content_facts_op( + id: lightcraft_catalog::PhotoId, + ph: &lightcraft_catalog::Photo, + format: &str, + info: &crate::media::ProbeInfo, +) -> Option { + let preview_checked = lightcraft_catalog::preview_stamp_for(format, &info.preview_only); let same = info.content_hash == ph.content_hash && info.file_size == ph.file_size && (info.width, info.height) == (ph.width, ph.height) && info.preview_only == ph.preview_only && preview_checked == ph.preview_checked; - (!same).then_some(Op::SetContent { + (!same).then(|| Op::SetContent { id, width: info.width, height: info.height, file_size: info.file_size, - content_hash: info.content_hash, - preview_only: info.preview_only, + content_hash: info.content_hash.clone(), + preview_only: info.preview_only.clone(), preview_checked, }) } @@ -307,12 +338,18 @@ pub(crate) fn lens_ops(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog: ops } -/// The op that gives a raw the as-shot white balance its file reads now (`info`, a fresh probe), or none when the -/// catalog already has it or the photo is not a raw edited in Kelvin. A raw imported before its camera's matrices -/// gave it a Kelvin scale keeps the relative scale's 6500 / 0 until a decode or Reload reads the file (issue #730). -pub(crate) fn as_shot_wb_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo) -> Option { +/// Evaluate white balance using the source classification the same batch will apply. +pub(crate) fn reload_wb_op(ph: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo, camera: &str) -> Option { + let (kind, format) = if info.format.is_empty() { (ph.kind, ph.format.as_str()) } else { (info.kind, info.format.as_str()) }; + if !info.format.is_empty() && (kind != lightcraft_catalog::MediaKind::Raw || info.preview_only.is_some()) { + return ph.as_shot_wb.map(|_| Op::SetAsShotWb { id: ph.id, wb: None }); + } let read = info.as_shot_wb.filter(|(t, tint)| t.is_finite() && tint.is_finite())?; - (ph.develops_raw() && !ph.relative_wb() && ph.as_shot_wb != Some(read)).then_some(Op::SetAsShotWb { id, wb: Some(read) }) + (kind == lightcraft_catalog::MediaKind::Raw + && info.preview_only.is_none() + && !lightcraft_catalog::relative_wb_camera(format, camera) + && ph.as_shot_wb != Some(read)) + .then_some(Op::SetAsShotWb { id: ph.id, wb: Some(read) }) } /// The ops that bring photo `id` and its same-file family up to date with what their file is now @@ -338,9 +375,17 @@ pub(crate) fn reload_ops( let mut meta = c.meta.clone(); repair_legacy_shutter(&mut meta, &info.meta).then(|| Op::SetMeta { id: c.id, meta: Box::new(meta) }).into_iter().collect() }; - let wb = as_shot_wb_op(c.id, c, info); + let camera = metadata + .iter() + .rev() + .find_map(|op| match op { + Op::SetMeta { meta, .. } => Some(meta.camera.as_str()), + _ => None, + }) + .unwrap_or(&c.meta.camera); + let wb = reload_wb_op(c, info, camera); let before = ops.len(); - ops.extend(content_op(c.id, c, info.clone()).into_iter().chain(metadata).chain(lens_ops(c.id, c, info)).chain(wb)); + ops.extend(content_op(c.id, c, info).into_iter().chain(metadata).chain(lens_ops(c.id, c, info)).chain(wb)); if ops.len() != before { changed.push(c.id); } @@ -450,6 +495,37 @@ mod tests { use super::*; use lightcraft_catalog::{Photo, PhotoId, Source}; + #[test] + fn review_reload_reads_white_balance_after_classification_and_camera() { + use lightcraft_catalog::MediaKind; + for selected_copy in [false, true] { + let mut s = Session::new(); + let mut photo = Photo::new(PhotoId(1), Source::File { path: "/source.arw".into() }, "source.arw", "PNG", 8, 8, ""); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo.clone()) }).unwrap(); + for id in [PhotoId(2), PhotoId(3)] { + photo.id = id; + photo.copy_of = Some(PhotoId(1)); + photo.kind = MediaKind::Raw; + photo.format = "ARW".into(); + photo.preview_only = Some("old unsupported raw".into()); + photo.meta.camera = if id.0 == 2 { "SONY ILCA-99M2".into() } else { String::new() }; + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo.clone()) }).unwrap(); + } + let mut info = + crate::media::ProbeInfo { kind: MediaKind::Raw, format: "ARW".into(), as_shot_wb: Some((4300.0, 7.0)), ..Default::default() }; + info.meta.camera = "SONY ILCA-99M2".into(); + let ids = if selected_copy { vec![1, 3] } else { vec![1] }; + let items = crate::cmd::reload::plan(&mut s, &json!({"ids": ids})).unwrap(); + crate::cmd::reload::apply(&mut s, items, vec![Ok(info)]).unwrap(); + for id in [PhotoId(1), PhotoId(2)] { + assert_eq!(s.catalog.photo(id).unwrap().as_shot_wb, Some((4300.0, 7.0)), "{id:?}"); + } + let copy = s.catalog.photo(PhotoId(3)).unwrap(); + assert_eq!(copy.as_shot_wb, selected_copy.then_some((4300.0, 7.0))); + assert_eq!(copy.meta.camera, if selected_copy { "SONY ILCA-99M2" } else { "" }); + } + } + /// Reload fills camera fields a photo lacks (a CR3 imported before CR3 metadata was read) and keeps /// everything already set. #[test] @@ -527,7 +603,7 @@ mod tests { info.meta.title = "File title".into(); let mut ops = Vec::new(); let mut changed = Vec::new(); - reload_ops(&cat, source.id, &info, &mut ops, &mut changed, (1..=5).map(PhotoId), |id| id == source.id); + reload_ops(&cat, source.id, &info, &mut ops, &mut changed, cat.photos().map(|p| p.id), |id| id == source.id); for op in ops { cat.apply(op).unwrap(); } @@ -702,4 +778,31 @@ mod tests { let undone = s.catalog.photo(id).unwrap(); assert!(undone.embedded_lens.is_none() && !undone.develop.optics.lens_profile, "one undo step"); } + + #[test] + fn reload_classifies_only_copies_using_the_probed_file() { + let mut cat = lightcraft_catalog::Catalog::new(); + let mut original = Photo::new(PhotoId(1), Source::File { path: "/original.dng".into() }, "original.dng", "DNG", 8, 8, ""); + original.kind = lightcraft_catalog::MediaKind::Raw; + cat.apply(Op::AddPhoto { photo: Box::new(original.clone()) }).unwrap(); + for (id, path) in [(2, "/original.dng"), (3, "/other.dng")] { + let mut copy = original.clone(); + copy.id = PhotoId(id); + copy.copy_of = Some(original.id); + copy.source = Source::File { path: path.into() }; + cat.apply(Op::AddPhoto { photo: Box::new(copy) }).unwrap(); + } + let info = + crate::media::ProbeInfo { width: 8, height: 8, format: "PNG".into(), kind: lightcraft_catalog::MediaKind::Image, ..Default::default() }; + let mut ops = Vec::new(); + let mut changed = Vec::new(); + reload_ops(&cat, original.id, &info, &mut ops, &mut changed, cat.photos().map(|p| p.id), |id| id == original.id); + cat.apply(Op::Batch { ops }).unwrap(); + for id in [1, 2] { + let p = cat.photo(PhotoId(id)).unwrap(); + assert_eq!((p.kind, p.format.as_str()), (lightcraft_catalog::MediaKind::Image, "PNG")); + } + let other = cat.photo(PhotoId(3)).unwrap(); + assert_eq!((other.kind, other.format.as_str()), (lightcraft_catalog::MediaKind::Raw, "DNG")); + } } diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index 167c501a1ec..0294d07ed18 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -110,7 +110,7 @@ pub fn is_missing(cat: &Catalog, avail: &crate::availability::Availability, id: pub(crate) fn relink_op(id: PhotoId, path: &str) -> Op { let file_name = Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string()); - Op::Relink { id, file_name, source: Source::File { path: path.to_string() }, format: None } + Op::Relink { id, file_name, source: Source::File { path: path.to_string() }, format: None, kind: None } } fn relink(s: &mut Session, p: &Value) -> Result { @@ -131,14 +131,25 @@ fn relink(s: &mut Session, p: &Value) -> Result { if s.media.file_probe.is_some() && let (Some(Ok(info)), Some(ph)) = (crate::import::probe_paths(s, std::slice::from_ref(&abs)).pop(), s.catalog.photo(id)) { - ops.extend(crate::cmd::convert::content_op(id, ph, info)); + let known_type = !info.format.is_empty(); + if known_type && let Some(Op::Relink { format, kind, .. }) = ops.first_mut() { + *format = Some(info.format.clone()); + *kind = (ph.kind != info.kind).then_some(info.kind); + } + let format = if known_type { &info.format } else { &ph.format }; + ops.extend(crate::cmd::convert::content_facts_op(id, ph, format, &info)); + let camera = if info.meta.camera.is_empty() { &ph.meta.camera } else { &info.meta.camera }; + if *camera != ph.meta.camera { + let mut meta = ph.meta.clone(); + meta.camera.clone_from(camera); + ops.push(Op::SetMeta { id, meta: Box::new(meta) }); + } + ops.extend(crate::cmd::convert::reload_wb_op(ph, &info, camera)); + if info.embedded_lens != ph.embedded_lens { + ops.push(Op::SetEmbeddedLens { id, lens: info.embedded_lens.map(Box::new) }); + } } - let op = match <[Op; 1]>::try_from(ops) { - Ok([op]) => op, - Err(ops) => Op::Batch { ops }, - }; - s.commit("Relink Photo", op)?; - s.media.forget(id); + s.commit("Relink Photo", Op::Batch { ops })?; Ok(json!({"id": id.0, "path": abs})) } diff --git a/crates/engine/src/files/probe.rs b/crates/engine/src/files/probe.rs index 4bdf22afa9b..1e9c5075bcb 100644 --- a/crates/engine/src/files/probe.rs +++ b/crates/engine/src/files/probe.rs @@ -151,7 +151,14 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { let m = lightcraft_meta::extract(bytes); let (meta, captured) = meta_of(&m); let xmp = embedded_or_exif_xmp(bytes, &m); - if lightcraft_raw::probe(bytes).is_some() { + if let Some(detected) = lightcraft_raw::probe(bytes) { + // ORF decoder and legacy-preview identities must follow the container even after a rename. + let extension = ext_upper(name); + let format = if detected == lightcraft_raw::RawFormat::Orf || extension == "ORF" || extension.is_empty() { + format!("{detected:?}").to_ascii_uppercase() + } else { + extension + }; let raw = match lightcraft_raw::probe_info(bytes).map_err(|e| preview_reason(bytes, e)) { Ok(r) => r, Err(Ok(why)) => { @@ -160,7 +167,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { return Ok(ProbeInfo { width: w, height: h, - format: ext_upper(name), + format, kind: MediaKind::Raw, file_size: bytes.len() as u64, captured, @@ -194,7 +201,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { embedded_lens, width: w, height: h, - format: ext_upper(name), + format, kind: MediaKind::Raw, file_size: bytes.len() as u64, captured, @@ -233,7 +240,7 @@ pub fn probe_bytes(name: &str, bytes: &[u8]) -> Result { } let format = match ext_upper(name).as_str() { "JPG" | "JPEG" => "JPEG".to_string(), - "" => format!("{fmt:?}").to_uppercase(), + "" | "ORF" | "CR3" => format!("{fmt:?}").to_uppercase(), e => e.to_string(), }; Ok(ProbeInfo { diff --git a/crates/engine/src/files/tests.rs b/crates/engine/src/files/tests.rs index b77982255a3..cb75f42a37d 100644 --- a/crates/engine/src/files/tests.rs +++ b/crates/engine/src/files/tests.rs @@ -59,6 +59,39 @@ pub(crate) fn sensor_orf() -> Vec { sensor } +#[test] +fn orf_probes_keep_the_detected_container_when_the_file_is_renamed() { + let rgb = vec![128; 48 * 32 * 3]; + let jpeg = encode_jpeg(&EncodeImage::new(48, 32, 3, Samples::U8(&rgb)), 90, ChromaSubsampling::S420, &EncodeMeta::default()).unwrap(); + let mut preview = tiff_with_preview_strip(&jpeg, 0, Fixture::default()); + preview[..4].copy_from_slice(b"IIRO"); + for (bytes, preview_only) in [(sensor_orf(), false), (preview, true)] { + assert_eq!(lightcraft_raw::probe(&bytes), Some(lightcraft_raw::RawFormat::Orf)); + for name in ["camera.orf", "renamed.dng", "renamed.jpg", "renamed.nef", "renamed"] { + let info = probe_bytes(name, &bytes).unwrap(); + assert_eq!((info.kind, info.format.as_str()), (MediaKind::Raw, "ORF"), "{name}"); + assert_eq!(info.preview_only.is_some(), preview_only, "{name}"); + assert_eq!(info.content_hash, Some(lightcraft_preview::hash_bytes(&bytes).to_string())); + } + } +} + +#[test] +fn followup_dng_named_orf_keeps_its_detected_format() { + let bytes = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + let info = probe_bytes("sensor.orf", &bytes).unwrap(); + assert_eq!((info.kind, info.format.as_str()), (MediaKind::Raw, "DNG")); + assert_eq!(probe_bytes("sensor.nef", &bytes).unwrap().format, "NEF", "unrelated extension policy is unchanged"); +} + +#[test] +fn followup_rendered_image_named_orf_keeps_its_detected_format() { + let image = lightcraft_raster::Rgba8 { width: 2, height: 2, data: vec![[20, 40, 60, 255]; 4] }; + let bytes = lightcraft_codecs::encode_png(&EncodeImage::rgba8(&image), &EncodeMeta::default()).unwrap(); + let info = probe_bytes("rendered.orf", &bytes).unwrap(); + assert_eq!((info.kind, info.format.as_str()), (MediaKind::Image, "PNG")); +} + #[test] fn crw_probes_name_their_camera_from_the_ciff_records() { // no Exif in a CRW: the camera and capture time come from the decoder's records, and the catalog's camera diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b364620c2f7..5002e309893 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -870,8 +870,8 @@ impl Session { /// an undo step, and it leaves the redo stack alone. pub(crate) fn apply_system(&mut self, op: Op) -> Result<()> { let fwd = op.clone(); - let applied = self.catalog.apply(op); - if applied.is_ok() || matches!(applied, Err(CatalogError::PartlyApplied { .. })) { + let applied = self.apply_through(op, Catalog::apply, false); + if applied.is_ok() || matches!(applied, Err(EngineError::Catalog(CatalogError::PartlyApplied { .. }))) { // (a batch only partly taken back changed the catalog all the same: the journal has to say so) self.pending_log.push(fwd); } diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index dad14878c88..7f25ad0813f 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -876,7 +876,21 @@ impl Session { pub fn persist(&mut self) -> Result<()> { let Some(lib) = self.library.as_mut() else { return Ok(()) }; if !self.pending_log.is_empty() { - if let Err(e) = lib.journal.append(&self.pending_log) { + let saved = if self.interaction.is_none() && lib.journal.needs_snapshot_for(&self.pending_log) { + let unlogged = self.pending_log.len() as u64; + let before = lib.journal.seq(); + let result = lib.journal.snapshot_with_unlogged(&self.catalog, unlogged); + match result { + Err(e) if lib.journal.seq() > before => { + log::warn!("library: the format upgrade saved the changes, but could not reset the log: {e}"); + Ok(()) + } + result => result, + } + } else { + lib.journal.append(&self.pending_log) + }; + if let Err(e) = saved { // the ops stay queued (and applied in memory): the next persist retries them let reason = e.to_string(); log::error!("library: {} change(s) not written to disk: {reason}", self.pending_log.len()); diff --git a/crates/engine/src/relocate.rs b/crates/engine/src/relocate.rs index 973e863f0d7..bae574bf617 100644 --- a/crates/engine/src/relocate.rs +++ b/crates/engine/src/relocate.rs @@ -542,7 +542,7 @@ impl Located { } moving.insert(r.id); places.insert(r.to.clone()); - ops.push(Op::Relink { id: r.id, file_name: p.file_name.clone(), source: Source::File { path: r.to }, format: None }); + ops.push(Op::Relink { id: r.id, file_name: p.file_name.clone(), source: Source::File { path: r.to }, format: None, kind: None }); } let relinked = ops.len(); if relinked == 0 { diff --git a/crates/engine/src/rename/moves.rs b/crates/engine/src/rename/moves.rs index 2567ba352c2..9cabfaf8703 100644 --- a/crates/engine/src/rename/moves.rs +++ b/crates/engine/src/rename/moves.rs @@ -168,7 +168,7 @@ pub(crate) fn rest_after_move_back(rest: Op, moved_back: &std::result::Result<() fn rewrite(op: Op, back: &HashSet) -> Op { match op { Op::Batch { ops } => Op::Batch { ops: ops.into_iter().map(|op| rewrite(op, back)).collect() }, - Op::SetFile { id, file_name, source } if back.contains(&id) => Op::Relink { id, file_name, source, format: None }, + Op::SetFile { id, file_name, source } if back.contains(&id) => Op::Relink { id, file_name, source, format: None, kind: None }, op => op, } } diff --git a/crates/engine/src/tests/focus_scan.rs b/crates/engine/src/tests/focus_scan.rs index eadfbdbc2a0..90f334d160c 100644 --- a/crates/engine/src/tests/focus_scan.rs +++ b/crates/engine/src/tests/focus_scan.rs @@ -247,6 +247,7 @@ fn changes_under_a_running_job_are_respected() { file_name: "moved.ARW".into(), source: Source::File { path: moved.to_string_lossy().into() }, format: None, + kind: None, })?; let mut meta = s.catalog.photo(PhotoId(3)).unwrap().meta.clone(); meta.focus = Some(mine.clone()); diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 3a2b46ea95b..1bf1b74548d 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5105,6 +5105,75 @@ fn review_reload_keeps_an_implicit_copy_when_its_selected_parent_moves() { assert_eq!(s.catalog.photo(id).unwrap(), &parent); } +#[test] +fn review_relink_recognizes_an_extensionless_dng() { + use lightcraft_catalog::MediaKind; + let dir = super::TestDir::new("relink-extensionless-raw"); + let image = dir.join("old.png"); + let raw = dir.join("new-source"); + write_png(&image, 10); + std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [image.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + s.execute("develop.set", &json!({"id": id.0, "control": "light.exposure", "value": 0.4})).unwrap(); + let develop = s.catalog.photo(id).unwrap().develop.clone(); + let wb = crate::cmd::reload::file_probe(&s).unwrap()(&raw.to_string_lossy()).unwrap().as_shot_wb; + assert!(wb.is_some()); + s.execute("photo.relink", &json!({"id": id.0, "path": raw.to_string_lossy()})).unwrap(); + let p = s.catalog.photo(id).unwrap(); + assert_eq!((p.kind, p.format.as_str()), (MediaKind::Raw, "DNG")); + assert_eq!(p.as_shot_wb, wb, "the replacement raw supplies its verified As Shot value"); + assert_eq!(p.develop, develop, "the relink preserves the user's Develop settings"); +} + +#[test] +fn followup_relink_replaces_database_lens_without_changing_develop_settings() { + use lightcraft_catalog::Op; + let dir = super::TestDir::new("relink-database-lens"); + let raw = dir.join("sensor.dng"); + let rendered = dir.join("rendered.png"); + std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + write_png(&rendered, 30); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + let lens = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, ..Default::default() }; + s.catalog.apply(Op::SetEmbeddedLens { id, lens: Some(Box::new(lens)) }).unwrap(); + let before = s.catalog.photo(id).unwrap().clone(); + assert!(!before.develop.optics.lens_profile); + s.execute("photo.relink", &json!({"id": id.0, "path": rendered.to_string_lossy()})).unwrap(); + let after = s.catalog.photo(id).unwrap().clone(); + assert!(after.embedded_lens.is_none(), "the old database profile does not belong to the replacement image"); + assert_eq!(after.develop, before.develop, "reading lens facts does not enable a correction"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap(), &before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap(), &after); +} + +#[test] +fn relink_uses_the_replacement_cameras_white_balance_scale() { + use lightcraft_catalog::MediaKind; + let dir = super::TestDir::new("relink-camera-wb"); + let original = dir.join("original.png"); + let replacement = dir.join("replacement.arw"); + write_png(&original, 10); + std::fs::write(&replacement, []).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [original.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + s.media.file_probe = Some(std::sync::Arc::new(|_| { + let mut info = crate::media::ProbeInfo { kind: MediaKind::Raw, format: "ARW".into(), as_shot_wb: Some((4300.0, 7.0)), ..Default::default() }; + info.meta.camera = "SONY ILCA-99M2".into(); + Ok(info) + })); + s.execute("photo.relink", &json!({"id": id.0, "path": replacement.to_string_lossy()})).unwrap(); + let photo = s.catalog.photo(id).unwrap(); + assert!(photo.develops_raw() && !photo.relative_wb()); + assert_eq!(photo.as_shot_wb, Some((4300.0, 7.0))); +} + #[test] fn reload_refreshes_a_copy_created_during_the_probe() { use crate::cmd::reload; @@ -5124,3 +5193,44 @@ fn reload_refreshes_a_copy_created_during_the_probe() { assert!(out.reloaded.contains(©)); assert_eq!(s.catalog.photo(copy).unwrap().content_hash, hash); } + +#[test] +fn reload_repairs_old_source_classification_without_replacing_edits() { + use lightcraft_catalog::{MediaKind, Op}; + for raw in [false, true] { + let dir = super::TestDir::new(&format!("reload-kind-{raw}")); + let file = dir.join(if raw { "sensor.dng" } else { "rendered.png" }); + if raw { + std::fs::write(&file, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + } else { + write_png(&file, 50); + } + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + s.execute("develop.set", &json!({"control": "light.exposure", "value": 0.75})).unwrap(); + let correct = s.catalog.photo(id).unwrap().clone(); + assert!(correct.is_edited()); + let mut old = (*correct).clone(); + old.kind = if raw { MediaKind::Image } else { MediaKind::Raw }; + old.format = if raw { "JPEG" } else { "ORF" }.into(); + old.preview_checked = old.preview_stamp(&old.preview_only); + if !raw { + old.as_shot_wb = Some((4300.0, 7.0)); + } + s.catalog.apply(Op::RemovePhoto { id }).unwrap(); + s.catalog.apply(Op::AddPhoto { photo: Box::new(old) }).unwrap(); + let before = s.catalog.photo(id).unwrap().clone(); + assert_eq!(s.execute("photo.reload", &json!({"ids": [id.0]})).unwrap()["reloaded"], json!([id.0])); + let repaired = s.catalog.photo(id).unwrap().clone(); + assert_eq!((repaired.kind, &repaired.format, &repaired.preview_checked), (correct.kind, &correct.format, &correct.preview_checked)); + assert_eq!((repaired.develop.clone(), repaired.meta.clone()), (before.develop.clone(), before.meta.clone())); + if !raw { + assert_eq!(repaired.as_shot_wb, None); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap(), &before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap(), &repaired); + } +} diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index 368a42f8192..e8f5f2834bc 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -606,3 +606,18 @@ fn overlapping_source_checks(older_recheck: bool) { assert_eq!(x.s.catalog.photo(x.id).unwrap(), ¤t); assert_eq!(x.s.catalog.photo(x.id).unwrap().content_hash, replacement); } + +#[test] +fn review_recheck_does_not_report_a_rendered_image_as_raw_recovery() { + let mut x = library("rendered-replacement"); + let image = lightcraft_codecs::EncodeImage::new(1, 1, 3, lightcraft_codecs::Samples::U8(&[10, 20, 30])); + let png = lightcraft_codecs::encode_png(&image, &Default::default()).unwrap(); + std::fs::write(&x.file, png).unwrap(); + let r = x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert_eq!(r["updated"], json!([x.id.0])); + assert_eq!(r["cleared"], json!([])); + let photo = x.s.catalog.photo(x.id).unwrap(); + assert_eq!(photo.kind, lightcraft_catalog::MediaKind::Image); + assert_eq!(photo.format, "PNG", "the rendered replacement keeps its detected container"); + assert!(photo.preview_only.is_none() && !photo.develops_raw()); +} diff --git a/crates/engine/src/tests/relocate.rs b/crates/engine/src/tests/relocate.rs index 6fb345e15d5..33bfde739a5 100644 --- a/crates/engine/src/tests/relocate.rs +++ b/crates/engine/src/tests/relocate.rs @@ -160,6 +160,7 @@ fn as_written_elsewhere(s: &mut Session, dir: &Scratch, root: &str, sep: &str) { file_name: p.file_name.clone(), source: Source::File { path: format!("{root}{}", rel.join(sep)) }, format: None, + kind: None, }) } _ => None, diff --git a/crates/engine/src/tests/view_follow.rs b/crates/engine/src/tests/view_follow.rs index 115eaaacd6b..60f87cf54fe 100644 --- a/crates/engine/src/tests/view_follow.rs +++ b/crates/engine/src/tests/view_follow.rs @@ -87,7 +87,7 @@ fn edit(s: &mut Session, dice: &mut Dice, ids: &mut Vec, album: u64) { 1 => { let name = format!("REN_{n:04}.jpg"); let source = Source::File { path: format!("/pics/{}/{name}", n % 3) }; - let _ = s.commit("Locate", Op::Relink { id: one, file_name: name, source, format: None }); + let _ = s.commit("Locate", Op::Relink { id: one, file_name: name, source, format: None, kind: None }); return; } 2 if n.is_multiple_of(4) => { diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index c17ec5bc6be..bc103688b0c 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -1554,6 +1554,7 @@ fn convert_to_dng_is_verified_and_atomic() { file_name: "shot.dng".into(), source: lightcraft_catalog::Source::File { path: path.clone() }, format: Some("NEF".into()), + kind: None, }) .unwrap(); s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); diff --git a/crates/ui-egui/src/tests/missing_sweep.rs b/crates/ui-egui/src/tests/missing_sweep.rs index b414ab2d999..5d1ed1e641c 100644 --- a/crates/ui-egui/src/tests/missing_sweep.rs +++ b/crates/ui-egui/src/tests/missing_sweep.rs @@ -202,8 +202,13 @@ fn a_check_over_changing_photos_answers_what_still_holds() { let cat = &mut h.app.session.catalog; cat.apply(Op::RemovePhoto { id: PhotoId(1) }).unwrap(); cat.apply(Op::SetDeleted { id: PhotoId(2), deleted: true }).unwrap(); - let relinked = - Op::Relink { id: PhotoId(3), file_name: "y.jpg".into(), source: Source::File { path: "/share/IMG_9998.jpg".into() }, format: None }; + let relinked = Op::Relink { + id: PhotoId(3), + file_name: "y.jpg".into(), + source: Source::File { path: "/share/IMG_9998.jpg".into() }, + format: None, + kind: None, + }; cat.apply(relinked).unwrap(); cat.apply(Op::AddPhoto { photo: new_photo(PHOTOS + 1, "/share/IMG_0000x.jpg") }).unwrap(); share.open.store(true, Ordering::SeqCst); diff --git a/crates/ui-egui/src/tests/recheck.rs b/crates/ui-egui/src/tests/recheck.rs index ad4c0ffa7d3..79d8152db99 100644 --- a/crates/ui-egui/src/tests/recheck.rs +++ b/crates/ui-egui/src/tests/recheck.rs @@ -379,3 +379,30 @@ fn a_cancelled_reload_reports_only_what_it_did() { } } } + +#[test] +fn a_rendered_replacement_gets_no_raw_recovery_notice() { + for (reload, raw) in [(false, false), (true, false), (false, true), (true, true)] { + let dir = Dir(std::env::temp_dir().join(format!("lc-ui-recheck-rendered-{reload}-{raw}-{}", std::process::id()))); + let (mut app, id) = app_with_stale_file(&dir.0, raw); + if raw { + let photo = app.session.catalog.photo(id).unwrap(); + assert_eq!(photo.kind, lightcraft_catalog::MediaKind::Raw); + let img = lightcraft_raster::Rgba8::from_fn(16, 12, |_, _| [12, 34, 56, 255]); + let o = lightcraft_engine::export::ExportOptions { format: lightcraft_engine::export::ExportFormat::Png, ..Default::default() }; + let png = lightcraft_engine::export::encode_image(&img, &o).unwrap(); + std::fs::write(dir.0.join("files/one.dng"), png).unwrap(); + } + let ctx = egui::Context::default(); + if reload { + crate::panels::edit::reload_preview_only(&mut app, &ctx, id); + } else { + crate::recheck::tick(&mut app); + } + assert!(crate::tasks::wait(&mut app, &ctx, Duration::from_secs(10))); + let photo = app.session.catalog.photo(id).unwrap(); + assert_eq!(photo.kind, lightcraft_catalog::MediaKind::Image); + assert!(photo.preview_only.is_none() && !photo.develops_raw()); + assert!(app.ui.toast.is_none(), "{reload}/{raw}: {:?}", app.ui.toast); + } +} diff --git a/crates/ui-egui/src/tests/tallies.rs b/crates/ui-egui/src/tests/tallies.rs index ffc7408c539..0b9ba09d0be 100644 --- a/crates/ui-egui/src/tests/tallies.rs +++ b/crates/ui-egui/src/tests/tallies.rs @@ -77,7 +77,7 @@ fn a_tally_kept_through_an_edit_is_the_tally_made_from_every_photo() { 0 => { let name = format!("MOVED_{n:03}.jpg"); let source = Source::File { path: format!("/elsewhere/{}/{name}", n % 3) }; - Some(a.session.commit("Locate", Op::Relink { id: PhotoId(id), file_name: name, source, format: None })) + Some(a.session.commit("Locate", Op::Relink { id: PhotoId(id), file_name: name, source, format: None, kind: None })) } 1 => Some( a.session From 64539bed2e04bbf650dce86ad0a635a7a692a28c Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 18:40:17 +0100 Subject: [PATCH 12/42] Relink: compare borrowed source lens facts --- crates/engine/src/cmd/missing.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index 0294d07ed18..6232e9b1eca 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -145,7 +145,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { ops.push(Op::SetMeta { id, meta: Box::new(meta) }); } ops.extend(crate::cmd::convert::reload_wb_op(ph, &info, camera)); - if info.embedded_lens != ph.embedded_lens { + if info.embedded_lens.as_ref() != ph.embedded_lens.as_deref() { ops.push(Op::SetEmbeddedLens { id, lens: info.embedded_lens.map(Box::new) }); } } From 7aeebbec0957bb801aabd60ec55f47682005f9ce Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:06:54 +0100 Subject: [PATCH 13/42] Relink and source history: refresh camera facts and preserve valid caches --- crates/engine/src/cmd/missing.rs | 4 +++- crates/engine/src/lib.rs | 24 +++++++++++++------- crates/engine/src/media/quick.rs | 6 +++-- crates/engine/src/tests/recheck.rs | 35 ++++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index 6232e9b1eca..27678bfeb8e 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -139,9 +139,11 @@ fn relink(s: &mut Session, p: &Value) -> Result { let format = if known_type { &info.format } else { &ph.format }; ops.extend(crate::cmd::convert::content_facts_op(id, ph, format, &info)); let camera = if info.meta.camera.is_empty() { &ph.meta.camera } else { &info.meta.camera }; - if *camera != ph.meta.camera { + let make = if info.meta.make.is_empty() { &ph.meta.make } else { &info.meta.make }; + if *camera != ph.meta.camera || *make != ph.meta.make { let mut meta = ph.meta.clone(); meta.camera.clone_from(camera); + meta.make.clone_from(make); ops.push(Op::SetMeta { id, meta: Box::new(meta) }); } ops.extend(crate::cmd::convert::reload_wb_op(ph, &info, camera)); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5002e309893..aedf48169a0 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -802,18 +802,26 @@ impl Session { let mut pending = vec![&op]; while let Some(op) = pending.pop() { match op { - Op::SetContent { id, .. } => { - invalidated.push((*id, true)); - replaced.push(*id); + Op::SetContent { id, width, height, file_size, content_hash, preview_only, .. } => { + invalidated.push(*id); + if self.catalog.photo(*id).is_some_and(|p| { + (p.width, p.height, p.file_size, &p.content_hash, p.preview_only.is_some()) + != (*width, *height, *file_size, content_hash, preview_only.is_some()) + }) { + replaced.push(*id); + } } Op::SetDevelop { id, settings, .. } if self.catalog.photo(*id).is_some_and(|p| p.develop.enhance.denoise_model != settings.enhance.denoise_model) => { denoise_changed.push(*id); } - Op::SetFile { id, .. } | Op::Relink { id, .. } | Op::RemovePhoto { id } => invalidated.push((*id, true)), - Op::AddPhoto { photo } => invalidated.push((photo.id, true)), - Op::SetAsShotWb { id, .. } | Op::SetEmbeddedLens { id, .. } => invalidated.push((*id, false)), + Op::SetFile { id, .. } + | Op::Relink { id, .. } + | Op::RemovePhoto { id } + | Op::SetAsShotWb { id, .. } + | Op::SetEmbeddedLens { id, .. } => invalidated.push(*id), + Op::AddPhoto { photo } => invalidated.push(photo.id), Op::Batch { ops } => pending.extend(ops), _ => {} } @@ -826,8 +834,8 @@ impl Session { for id in denoise_changed { self.denoise_photo_changed(id); } - for (id, source_changed) in invalidated { - if source_changed && invalidate_reads { + for id in invalidated { + if invalidate_reads { self.reload_tickets.invalidate(id); } self.media.forget(id); diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 9efd11101a5..a99e2889bab 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -175,11 +175,13 @@ pub fn content_key(p: &Photo) -> String { /// Source facts that affect pixels and can change when the source bytes stay the same. /// Include lens data even with the correction off: fitting a raw's starting colour uses the profile. pub(super) fn source_metadata_key(p: &Photo) -> u64 { - let wb = p.as_shot_wb.filter(|_| p.develops_raw() && !p.relative_wb()); - if p.embedded_lens.is_none() && wb.is_none() { + let raw = p.develops_raw(); + let wb = p.as_shot_wb.filter(|_| raw && !p.relative_wb()); + if !raw && p.embedded_lens.is_none() && wb.is_none() { return 0; } let mut key = Hasher128::new(); + key.str("source-mode").u64(u64::from(raw)); if let Some(lens) = &p.embedded_lens { key.str("lens").str(&format!("{lens:?}")); } diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index e8f5f2834bc..5d0db7604d8 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -533,6 +533,41 @@ fn review_a_new_reload_supersedes_an_older_recheck() { overlapping_source_checks(true); } +#[test] +fn undo_of_source_metadata_rejects_a_pending_reload() { + use crate::cmd::reload; + let mut x = checked_orf("undone-source-metadata"); + x.s.commit("Source white balance", Op::SetAsShotWb { id: x.id, wb: Some((4300.0, 7.0)) }).unwrap(); + let items = reload::plan(&mut x.s, &json!({"id": x.id.0})).unwrap(); + let probe = reload::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + x.s.execute("edit.undo", &json!({})).unwrap(); + let out = reload::apply(&mut x.s, items, vec![Ok(probe)]).unwrap(); + assert!(out.checked.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_stamp_only_recheck_keeps_the_face_scan() { + let mut x = checked_orf("face-stamp"); + let p = x.s.catalog.photo(x.id).unwrap().clone(); + x.s.apply_system(Op::SetContent { + id: p.id, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + preview_only: None, + preview_checked: OTHER.into(), + }) + .unwrap(); + x.s.faces.scanned.insert(x.id.0); + x.s.execute("library.recheckPreviewOnly", &json!({})).unwrap(); + assert!(x.s.faces.scanned.contains(x.id.0)); + replace_checked_orf(&x.file); + x.s.execute("library.recheckPreviewOnly", &json!({"all": true})).unwrap(); + assert!(!x.s.faces.scanned.contains(x.id.0)); +} + #[test] fn an_older_reload_finishing_first_keeps_a_newer_pending_read() { use crate::cmd::reload; From 9fb3b225f9ab1fcd76a775a8853e5ef38e8d7689 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:34:33 +0100 Subject: [PATCH 14/42] Relink: refresh lens names and expire stale source reads on history edits --- crates/engine/src/cmd/missing.rs | 4 +++- crates/engine/src/lib.rs | 8 ++++++++ crates/engine/src/media/source.rs | 2 +- crates/engine/src/tests/import.rs | 8 +++++++- crates/engine/src/tests/recheck.rs | 25 +++++++++++++++++++++++++ 5 files changed, 44 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index 27678bfeb8e..ff6275e3c91 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -140,10 +140,12 @@ fn relink(s: &mut Session, p: &Value) -> Result { ops.extend(crate::cmd::convert::content_facts_op(id, ph, format, &info)); let camera = if info.meta.camera.is_empty() { &ph.meta.camera } else { &info.meta.camera }; let make = if info.meta.make.is_empty() { &ph.meta.make } else { &info.meta.make }; - if *camera != ph.meta.camera || *make != ph.meta.make { + let lens = if info.meta.lens.is_empty() { &ph.meta.lens } else { &info.meta.lens }; + if *camera != ph.meta.camera || *make != ph.meta.make || *lens != ph.meta.lens { let mut meta = ph.meta.clone(); meta.camera.clone_from(camera); meta.make.clone_from(make); + meta.lens.clone_from(lens); ops.push(Op::SetMeta { id, meta: Box::new(meta) }); } ops.extend(crate::cmd::convert::reload_wb_op(ph, &info, camera)); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index aedf48169a0..9352e93c10c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -821,6 +821,14 @@ impl Session { | Op::RemovePhoto { id } | Op::SetAsShotWb { id, .. } | Op::SetEmbeddedLens { id, .. } => invalidated.push(*id), + Op::SetMeta { id, meta } + if self + .catalog + .photo(*id) + .is_some_and(|p| p.meta.camera != meta.camera || p.meta.make != meta.make || p.meta.lens != meta.lens) => + { + invalidated.push(*id); + } Op::AddPhoto { photo } => invalidated.push(photo.id), Op::Batch { ops } => pending.extend(ops), _ => {} diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index e10f3c922c6..e3435cac957 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -245,7 +245,7 @@ impl DecodedSource { /// catalog still holds but the decode no longer finds (the original was replaced) is not restored. A database profile /// is never taken from the decode, so a cached render, a fresh decode and the Optics panel all use the one profile the photo holds, and a /// change to it (a database update looked up again, `cmd::lens_refresh`) changes the render keys -/// ([`super::quick::lens_key`]). +/// ([`super::quick::source_metadata_key`]). pub(crate) fn pinned_lens( decoded: Option, catalog: Option, diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 1bf1b74548d..6d54e24049a 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5163,15 +5163,21 @@ fn relink_uses_the_replacement_cameras_white_balance_scale() { let mut s = Session::new().with_fs(); s.execute("library.import", &json!({"paths": [original.to_string_lossy()]})).unwrap(); let id = s.active().unwrap(); - s.media.file_probe = Some(std::sync::Arc::new(|_| { + s.media.file_probe = Some(std::sync::Arc::new(|path| { let mut info = crate::media::ProbeInfo { kind: MediaKind::Raw, format: "ARW".into(), as_shot_wb: Some((4300.0, 7.0)), ..Default::default() }; info.meta.camera = "SONY ILCA-99M2".into(); + if path.ends_with("replacement.arw") { + info.meta.lens = "Replacement lens".into(); + } Ok(info) })); s.execute("photo.relink", &json!({"id": id.0, "path": replacement.to_string_lossy()})).unwrap(); let photo = s.catalog.photo(id).unwrap(); assert!(photo.develops_raw() && !photo.relative_wb()); assert_eq!(photo.as_shot_wb, Some((4300.0, 7.0))); + assert_eq!(photo.meta.lens, "Replacement lens"); + s.execute("photo.relink", &json!({"id": id.0, "path": original.to_string_lossy()})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().meta.lens, "Replacement lens", "an empty probe preserves the stored lens"); } #[test] diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index 5d0db7604d8..66b46cb352a 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -545,6 +545,31 @@ fn undo_of_source_metadata_rejects_a_pending_reload() { assert!(out.checked.is_empty()); } +#[test] +fn undo_and_redo_only_invalidate_pending_reloads_for_source_names() { + use crate::cmd::reload; + let mut x = checked_orf("metadata-history-source-names"); + let id = x.id; + let mut meta = x.s.catalog.photo(id).unwrap().meta.clone(); + meta.camera = "Camera from the previous read".into(); + meta.make = "Maker from the previous read".into(); + meta.lens = "Lens from the previous read".into(); + x.s.commit("Probe-derived metadata", Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let probe = reload::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + for action in ["edit.undo", "edit.redo"] { + let items = reload::plan(&mut x.s, &json!({"id": id.0})).unwrap(); + x.s.execute(action, &json!({})).unwrap(); + let out = reload::apply(&mut x.s, items, vec![Ok(probe.clone())]).unwrap(); + assert!(out.checked.is_empty(), "{action} must reject the older source read"); + } + let mut meta = x.s.catalog.photo(id).unwrap().meta.clone(); + meta.title = "Edited title".into(); + x.s.commit("Photo title", Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let items = reload::plan(&mut x.s, &json!({"id": id.0})).unwrap(); + x.s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(reload::apply(&mut x.s, items, vec![Ok(probe)]).unwrap().checked, [id]); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_stamp_only_recheck_keeps_the_face_scan() { From e04e3af612005800f8550b93489a684c7c073550 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:42:32 +0100 Subject: [PATCH 15/42] Reload: retain the verified source white-balance scale and refresh face scans --- crates/catalog/src/journal.rs | 9 +-- crates/catalog/src/lib.rs | 23 +++++++- crates/catalog/src/local.rs | 3 +- crates/catalog/src/model.rs | 6 +- crates/catalog/src/tests_format_version.rs | 3 +- crates/engine/src/cmd/convert.rs | 66 ++++++++++++++++++---- crates/engine/src/lib.rs | 10 +++- crates/engine/src/media/quick.rs | 6 +- crates/engine/src/tests/recheck.rs | 21 +++++++ 9 files changed, 123 insertions(+), 24 deletions(-) diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index a13d6ba575d..be545b6b7d7 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -69,7 +69,7 @@ //! | 13 | Lens Blur | `DevelopSettings.lens_blur`, `Mask.adjust.lens_blur` | //! | 14 | bursts arranged by hand in Assisted Culling | `Analysis.rank` | //! | 15 | per-photo denoiser selection | `DevelopSettings.enhance.denoise_model` | -//! | 16 | probed source classification on Relink and Reload | `Op::Relink.kind` | +//! | 16 | probed source classification and white balance on Relink and Reload | `Op::Relink.kind`, `Op::SetSourceWb`, `Photo.source_relative_wb` | //! //! Rules: //! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a @@ -898,7 +898,7 @@ impl Journal { std::mem::take(&mut self.kept_written) } - /// Older readers ignore the classification field, so these ops require a current snapshot. + /// Older readers cannot replay these source facts, so the library needs a current snapshot. pub fn needs_snapshot_for(&self, ops: &[Op]) -> bool { if self.behind.is_none() { return false; @@ -906,7 +906,8 @@ impl Journal { let mut pending: Vec<_> = ops.iter().collect(); while let Some(op) = pending.pop() { match op { - Op::Relink { kind: Some(_), .. } => return true, + Op::Relink { kind: Some(_), .. } | Op::SetSourceWb { .. } => return true, + Op::AddPhoto { photo } if photo.source_relative_wb.is_some() => return true, Op::Batch { ops } => pending.extend(ops), _ => {} } @@ -920,7 +921,7 @@ impl Journal { return Ok(()); } if self.needs_snapshot_for(ops) { - return Err(CatalogError::Io(format!("save a format v{VERSION} snapshot before journaling source classification"))); + return Err(CatalogError::Io(format!("save a format v{VERSION} snapshot before journaling source facts"))); } let t0 = web_time::Instant::now(); let mut buf = String::new(); diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 18248951abe..dcaa45f0164 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -253,6 +253,12 @@ pub enum Op { id: PhotoId, wb: Option<(f64, f64)>, }, + /// Source white balance verified from the file when its camera and catalog metadata disagree. + SetSourceWb { + id: PhotoId, + wb: Option<(f64, f64)>, + relative: Option, + }, /// The name shown for a colour label (`None` = its colour's name). SetLabelName { label: ColorLabel, @@ -967,9 +973,12 @@ impl Catalog { self.changes.now = Aspects::ALL; self.touch(*id); } - Op::SetDeleted { .. } | Op::SetLocal { .. } | Op::SetContent { .. } | Op::SetEmbeddedLens { .. } | Op::SetAsShotWb { .. } => { - self.changes.now = Aspects::ALL - } + Op::SetDeleted { .. } + | Op::SetLocal { .. } + | Op::SetContent { .. } + | Op::SetEmbeddedLens { .. } + | Op::SetAsShotWb { .. } + | Op::SetSourceWb { .. } => self.changes.now = Aspects::ALL, Op::SetRating { .. } => self.changes.now = Aspects::RATING, Op::SetFlag { .. } => self.changes.now = Aspects::FLAG, Op::SetLabel { .. } => self.changes.now = Aspects::LABEL, @@ -1271,6 +1280,13 @@ impl Catalog { let p = self.photo_mut(id)?; Op::SetAsShotWb { id, wb: std::mem::replace(&mut p.as_shot_wb, wb) } } + Op::SetSourceWb { id, wb, relative } => { + if wb.is_some_and(|(t, tint)| !(t.is_finite() && tint.is_finite())) { + return Err(CatalogError::Invalid("as-shot white balance is not a number".into())); + } + let p = self.photo_mut(id)?; + Op::SetSourceWb { id, wb: std::mem::replace(&mut p.as_shot_wb, wb), relative: std::mem::replace(&mut p.source_relative_wb, relative) } + } Op::SetFile { id, file_name, source } => { if file_name.trim().is_empty() { return Err(CatalogError::Invalid("empty file name".into())); @@ -1581,6 +1597,7 @@ fn changes_what_albums_test(op: &Op) -> bool { | Op::SetContent { .. } | Op::SetEmbeddedLens { .. } | Op::SetAsShotWb { .. } + | Op::SetSourceWb { .. } | Op::SetRating { .. } | Op::SetFlag { .. } | Op::SetLabel { .. } diff --git a/crates/catalog/src/local.rs b/crates/catalog/src/local.rs index 20cb3d5b45d..c17c353a4b8 100644 --- a/crates/catalog/src/local.rs +++ b/crates/catalog/src/local.rs @@ -340,7 +340,8 @@ impl Op { | Op::Relink { id, .. } | Op::SetContent { id, .. } | Op::SetEmbeddedLens { id, .. } - | Op::SetAsShotWb { id, .. } => out(*id), + | Op::SetAsShotWb { id, .. } + | Op::SetSourceWb { id, .. } => out(*id), Op::AddAlbum { album } => { album.photos.iter().for_each(|p| out(*p)); album.cover.into_iter().for_each(&mut *out); diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index e4a320eeeac..a2afe096b1a 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -383,6 +383,9 @@ pub struct Photo { /// Raw files: the camera's as-shot white balance (Kelvin, tint). #[serde(default)] pub as_shot_wb: Option<(f64, f64)>, + /// The probed file's white-balance scale when it differs from the catalog's camera metadata. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_relative_wb: Option, /// Hash of the file's bytes (hex), for duplicate detection and preview-cache keys. #[serde(default, skip_serializing_if = "Option::is_none")] pub content_hash: Option, @@ -530,6 +533,7 @@ impl Photo { local: false, duration: None, as_shot_wb: None, + source_relative_wb: None, content_hash: None, embedded_lens: None, copy_of: None, @@ -571,7 +575,7 @@ impl Photo { /// [`Photo::fitted_look`] raw whose camera has no colour matrices measured either /// ([`relative_wb_camera`]). Other raws edit white balance in Kelvin. pub fn relative_wb(&self) -> bool { - self.develops_raw() && relative_wb_camera(&self.format, &self.meta.camera) + self.develops_raw() && self.source_relative_wb.unwrap_or_else(|| relative_wb_camera(&self.format, &self.meta.camera)) } /// Every settings holder of this photo that can carry segmentation grids: the develop /// settings, the versions', the history steps' and the import look. A snapshot's shared grid diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index e6987a3651e..be41e61bca4 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -386,9 +386,10 @@ fn op_variants_are_versioned() { Op::SetFolderRecord { .. } => 6, Op::SetAsShotWb { .. } => 7, Op::SetHistoryCursor { .. } => 8, + Op::SetSourceWb { .. } => 16, } } - /// v16: `Op::Relink.kind`; v15: `Enhance.denoise_model` (v14: `Analysis.rank`; v13: Lens Blur; v12: `Catalog.grids` and `SegMask.grid`; + /// v16: `Op::Relink.kind` and `Photo.source_relative_wb`; v15: `Enhance.denoise_model` (v14: `Analysis.rank`; v13: Lens Blur; v12: `Catalog.grids` and `SegMask.grid`; /// v11: `EmbeddedLens.source`; v10: `Mask.on_photo`; v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`). const NEWEST_FIELDS: u32 = 16; let newest = since(&Op::SetHistoryCursor { id: PhotoId(1), cursor: None }); diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index fd26d7d84ff..a398890807c 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -341,15 +341,28 @@ pub(crate) fn lens_ops(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog: /// Evaluate white balance using the source classification the same batch will apply. pub(crate) fn reload_wb_op(ph: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo, camera: &str) -> Option { let (kind, format) = if info.format.is_empty() { (ph.kind, ph.format.as_str()) } else { (info.kind, info.format.as_str()) }; - if !info.format.is_empty() && (kind != lightcraft_catalog::MediaKind::Raw || info.preview_only.is_some()) { - return ph.as_shot_wb.map(|_| Op::SetAsShotWb { id: ph.id, wb: None }); - } - let read = info.as_shot_wb.filter(|(t, tint)| t.is_finite() && tint.is_finite())?; - (kind == lightcraft_catalog::MediaKind::Raw - && info.preview_only.is_none() - && !lightcraft_catalog::relative_wb_camera(format, camera) - && ph.as_shot_wb != Some(read)) - .then_some(Op::SetAsShotWb { id: ph.id, wb: Some(read) }) + let (wb, mode) = if kind == lightcraft_catalog::MediaKind::Raw && info.preview_only.is_none() { + let inferred = lightcraft_catalog::relative_wb_camera(format, camera); + let relative = if !info.meta.camera.is_empty() { + lightcraft_catalog::relative_wb_camera(format, &info.meta.camera) + } else if format.eq_ignore_ascii_case(&ph.format) { + ph.source_relative_wb.unwrap_or(inferred) + } else { + inferred + }; + let previous = ph.as_shot_wb.filter(|_| ph.relative_wb() == relative); + let measured = info.as_shot_wb.filter(|(t, tint)| !relative && t.is_finite() && tint.is_finite()); + (measured.or(previous), (relative != inferred).then_some(relative)) + } else if info.format.is_empty() { + return None; + } else { + (None, None) + }; + if mode != ph.source_relative_wb { + Some(Op::SetSourceWb { id: ph.id, wb, relative: mode }) + } else { + (wb != ph.as_shot_wb).then_some(Op::SetAsShotWb { id: ph.id, wb }) + } } /// The ops that bring photo `id` and its same-file family up to date with what their file is now @@ -508,7 +521,7 @@ mod tests { photo.kind = MediaKind::Raw; photo.format = "ARW".into(); photo.preview_only = Some("old unsupported raw".into()); - photo.meta.camera = if id.0 == 2 { "SONY ILCA-99M2".into() } else { String::new() }; + photo.meta.camera = if id.0 == 2 { "SONY ILCE-7M2".into() } else { String::new() }; s.catalog.apply(Op::AddPhoto { photo: Box::new(photo.clone()) }).unwrap(); } let mut info = @@ -518,14 +531,43 @@ mod tests { let items = crate::cmd::reload::plan(&mut s, &json!({"ids": ids})).unwrap(); crate::cmd::reload::apply(&mut s, items, vec![Ok(info)]).unwrap(); for id in [PhotoId(1), PhotoId(2)] { - assert_eq!(s.catalog.photo(id).unwrap().as_shot_wb, Some((4300.0, 7.0)), "{id:?}"); + let photo = s.catalog.photo(id).unwrap(); + assert_eq!(photo.as_shot_wb, Some((4300.0, 7.0)), "{id:?}"); + assert!(!photo.relative_wb(), "{id:?}"); } + assert_eq!(s.catalog.photo(PhotoId(2)).unwrap().meta.camera, "SONY ILCE-7M2"); let copy = s.catalog.photo(PhotoId(3)).unwrap(); - assert_eq!(copy.as_shot_wb, selected_copy.then_some((4300.0, 7.0))); + assert_eq!(copy.as_shot_wb, Some((4300.0, 7.0))); + assert!(!copy.relative_wb()); assert_eq!(copy.meta.camera, if selected_copy { "SONY ILCA-99M2" } else { "" }); } } + #[test] + fn reload_changes_the_source_key_when_white_balance_mode_changes_without_a_measurement() { + let id = PhotoId(1); + let mut s = Session::new(); + let mut photo = Photo::new(id, Source::File { path: "/source.arw".into() }, "source.arw", "ARW", 8, 8, ""); + photo.kind = lightcraft_catalog::MediaKind::Raw; + photo.meta.camera = "SONY ILCE-7M2".into(); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + let old = s.render_job(id, 32, 32, false, true).unwrap(); + let mut info = + crate::media::ProbeInfo { kind: lightcraft_catalog::MediaKind::Raw, format: "ARW".into(), width: 8, height: 8, ..Default::default() }; + info.meta.camera = "SONY ILCA-99M2".into(); + let items = crate::cmd::reload::plan(&mut s, &json!({"id": id.0})).unwrap(); + crate::cmd::reload::apply(&mut s, items, vec![Ok(info)]).unwrap(); + let p = s.catalog.photo(id).unwrap(); + assert_eq!(p.meta.camera, "SONY ILCE-7M2"); + assert!(p.as_shot_wb.is_none() && !p.relative_wb()); + let updated = s.render_job(id, 32, 32, false, true).unwrap(); + assert_ne!(old.source_key, updated.source_key); + assert_ne!(old.key, updated.key); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.catalog.photo(id).unwrap().relative_wb()); + assert_eq!(old.source_key, s.render_job(id, 32, 32, false, true).unwrap().source_key); + } + /// Reload fills camera fields a photo lacks (a CR3 imported before CR3 metadata was read) and keeps /// everything already set. #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9352e93c10c..99ce4ae8a41 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -816,10 +816,18 @@ impl Session { { denoise_changed.push(*id); } + Op::Relink { id, kind, .. } => { + invalidated.push(*id); + if let Some(kind) = kind + && self.catalog.photo(*id).is_some_and(|p| p.kind != *kind) + { + replaced.push(*id); + } + } Op::SetFile { id, .. } - | Op::Relink { id, .. } | Op::RemovePhoto { id } | Op::SetAsShotWb { id, .. } + | Op::SetSourceWb { id, .. } | Op::SetEmbeddedLens { id, .. } => invalidated.push(*id), Op::SetMeta { id, meta } if self diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index a99e2889bab..9bac542b3ab 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -176,12 +176,16 @@ pub fn content_key(p: &Photo) -> String { /// Include lens data even with the correction off: fitting a raw's starting colour uses the profile. pub(super) fn source_metadata_key(p: &Photo) -> u64 { let raw = p.develops_raw(); - let wb = p.as_shot_wb.filter(|_| raw && !p.relative_wb()); + let kelvin = raw && !p.relative_wb(); + let wb = p.as_shot_wb.filter(|_| kelvin); if !raw && p.embedded_lens.is_none() && wb.is_none() { return 0; } let mut key = Hasher128::new(); key.str("source-mode").u64(u64::from(raw)); + if kelvin && wb.is_none() { + key.str("kelvin-white-balance"); + } if let Some(lens) = &p.embedded_lens { key.str("lens").str(&format!("{lens:?}")); } diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index 66b46cb352a..7ab718eaa05 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -593,6 +593,27 @@ fn a_stamp_only_recheck_keeps_the_face_scan() { assert!(!x.s.faces.scanned.contains(x.id.0)); } +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn relink_reclassification_invalidates_face_scan_without_changing_file_facts() { + let mut x = checked_orf("face-kind"); + let photo = x.s.catalog.photo(x.id).unwrap().clone(); + x.s.faces.scanned.insert(x.id.0); + let rename = Op::Relink { id: x.id, file_name: photo.file_name.clone(), source: photo.source.clone(), format: None, kind: None }; + x.s.commit("Relink same source", rename).unwrap(); + assert!(x.s.faces.scanned.contains(x.id.0)); + let reclassify = Op::Relink { + id: x.id, + file_name: photo.file_name.clone(), + source: photo.source.clone(), + format: None, + kind: Some(lightcraft_catalog::MediaKind::Image), + }; + x.s.commit("Relink different kind", reclassify).unwrap(); + assert!(!x.s.faces.scanned.contains(x.id.0)); + assert_eq!(x.s.catalog.photo(x.id).unwrap().content_hash, photo.content_hash); +} + #[test] fn an_older_reload_finishing_first_keeps_a_newer_pending_read() { use crate::cmd::reload; From dd0a09d4f4848daead68a0c82d00beb998a4d7f5 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:48:16 +0100 Subject: [PATCH 16/42] Library: retry queued edits before switching catalogs --- crates/engine/src/library.rs | 3 +++ crates/engine/src/tests/persist.rs | 22 ++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 7f25ad0813f..a742a32b796 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -607,6 +607,9 @@ impl Session { // what its log's thread was handed reach the file before the new journal reads it. When // that can't be written, the open fails and the current library stays open with what its // thread holds (retried): read now, the files would miss it (review of #3557). + if self.library.is_some() && !self.pending_log.is_empty() { + self.persist()?; + } if let Some(old) = self.library.as_mut() { if let Err(e) = old.journal.wait() { log::error!("library: {e}"); diff --git a/crates/engine/src/tests/persist.rs b/crates/engine/src/tests/persist.rs index 7e789de8d3a..0a69f53e237 100644 --- a/crates/engine/src/tests/persist.rs +++ b/crates/engine/src/tests/persist.rs @@ -115,6 +115,28 @@ fn failed_append_fails_the_command_and_is_retried() { assert_eq!((p.rating, p.flag), (4, Flag::Pick)); } +#[test] +fn switching_libraries_retries_the_queue_and_preserves_it_if_the_save_fails() { + let store = Flaky::default(); + let mut s = open(&store, true); + let id = s.selection.active.unwrap(); + let generation = s.library_generation(); + store.set_failing(true); + assert!(matches!(s.execute("photo.rate", &json!({"rating": 4})), Err(EngineError::NotSaved(_)))); + let other = MemStore::new(); + let other_stores = || LibraryStores { dir: "other".into(), catalog: Box::new(other.clone()), files: Box::new(MemStore::new()), on_disk: false }; + assert!(matches!(s.open_library_in(other_stores(), false), Err(EngineError::NotSaved(_)))); + assert_eq!(s.library_generation(), generation); + assert_eq!(s.catalog.photo(id).unwrap().rating, 4); + assert_eq!(s.unsaved().map(|(count, _)| count), Some(1)); + assert!(other.get("catalog.snap").is_none()); + store.set_failing(false); + s.open_library_in(other_stores(), false).unwrap(); + assert_ne!(s.library_generation(), generation); + assert!(s.catalog.is_empty()); + assert_eq!(open(&store, false).catalog.photo(id).unwrap().rating, 4); +} + /// Undo is a command like any other: a failed write of its op is reported, and retried. #[test] fn failed_append_of_undo_is_reported_and_retried() { From 0d7aef7bb2494faad0596591df43747f81d7cb98 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 20:12:40 +0100 Subject: [PATCH 17/42] Refresh source lens, exposure and white balance consistently --- crates/engine/src/cmd/convert.rs | 50 +++++++++++++++++++++++++++--- crates/engine/src/cmd/missing.rs | 7 +++-- crates/engine/src/lib.rs | 10 +++--- crates/engine/src/media/quick.rs | 3 ++ crates/engine/src/tests/import.rs | 50 +++++++++++++++++++++++++----- crates/engine/src/tests/recheck.rs | 21 +++++++++++++ 6 files changed, 122 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index a398890807c..50f296ddc25 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -299,6 +299,24 @@ pub(crate) fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft ops } +/// A change to any metadata field a pending file probe could write back. +pub(crate) fn source_metadata_changed(old: &lightcraft_catalog::Meta, new: &lightcraft_catalog::Meta) -> bool { + old.camera != new.camera + || old.make != new.make + || old.lens != new.lens + || old.lens_make != new.lens_make + || old.shutter != new.shutter + || old.exposure_time != new.exposure_time + || old.focal_mm != new.focal_mm + || old.aperture != new.aperture + || old.iso != new.iso + || old.flash != new.flash + || old.exposure_bias != new.exposure_bias + || old.serial_number != new.serial_number + || old.gps != new.gps + || old.focus != new.focus +} + /// Repair only the shutter data an old import wrote, keeping independently edited metadata. fn repair_legacy_shutter(m: &mut lightcraft_catalog::Meta, src: &lightcraft_catalog::Meta) -> bool { if m.exposure_time.is_none() @@ -339,18 +357,22 @@ pub(crate) fn lens_ops(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog: } /// Evaluate white balance using the source classification the same batch will apply. -pub(crate) fn reload_wb_op(ph: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo, camera: &str) -> Option { +pub(crate) fn reload_wb_op(ph: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo, camera: &str, same_path: bool) -> Option { let (kind, format) = if info.format.is_empty() { (ph.kind, ph.format.as_str()) } else { (info.kind, info.format.as_str()) }; let (wb, mode) = if kind == lightcraft_catalog::MediaKind::Raw && info.preview_only.is_none() { + let same_source = match (super::missing::stored_hash(ph), info.content_hash.as_deref()) { + (Some(old), Some(new)) => old == new, + _ => same_path && (info.file_size == 0 || ph.file_size == 0 || ph.file_size == info.file_size), + }; let inferred = lightcraft_catalog::relative_wb_camera(format, camera); let relative = if !info.meta.camera.is_empty() { lightcraft_catalog::relative_wb_camera(format, &info.meta.camera) - } else if format.eq_ignore_ascii_case(&ph.format) { + } else if same_source && format.eq_ignore_ascii_case(&ph.format) { ph.source_relative_wb.unwrap_or(inferred) } else { inferred }; - let previous = ph.as_shot_wb.filter(|_| ph.relative_wb() == relative); + let previous = ph.as_shot_wb.filter(|_| same_source && ph.relative_wb() == relative); let measured = info.as_shot_wb.filter(|(t, tint)| !relative && t.is_finite() && tint.is_finite()); (measured.or(previous), (relative != inferred).then_some(relative)) } else if info.format.is_empty() { @@ -396,7 +418,7 @@ pub(crate) fn reload_ops( _ => None, }) .unwrap_or(&c.meta.camera); - let wb = reload_wb_op(c, info, camera); + let wb = reload_wb_op(c, info, camera, true); let before = ops.len(); ops.extend(content_op(c.id, c, info).into_iter().chain(metadata).chain(lens_ops(c.id, c, info)).chain(wb)); if ops.len() != before { @@ -568,6 +590,26 @@ mod tests { assert_eq!(old.source_key, s.render_job(id, 32, 32, false, true).unwrap().source_key); } + #[test] + fn reclassification_changes_the_render_identity_for_legacy_white_balance() { + let id = PhotoId(1); + let mut s = Session::new(); + let source = Source::File { path: "/source.dng".into() }; + let mut photo = Photo::new(id, source.clone(), "source.dng", "ARW", 8, 8, ""); + photo.kind = lightcraft_catalog::MediaKind::Raw; + photo.meta.camera = "SONY ILCA-99M2".into(); + photo.as_shot_wb = Some((4300.0, 7.0)); + photo.content_hash = Some("same bytes".into()); + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + let before = s.render_job(id, 32, 32, false, true).unwrap(); + assert!(crate::media::source_info(s.catalog.photo(id).unwrap()).legacy_relative_wb); + s.catalog.apply(Op::Relink { id, file_name: "source.dng".into(), source, format: Some("DNG".into()), kind: None }).unwrap(); + let after = s.render_job(id, 32, 32, false, true).unwrap(); + assert!(!crate::media::source_info(s.catalog.photo(id).unwrap()).legacy_relative_wb); + assert_ne!(before.source_key, after.source_key); + assert_ne!(before.key, after.key); + } + /// Reload fills camera fields a photo lacks (a CR3 imported before CR3 metadata was read) and keeps /// everything already set. #[test] diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index ff6275e3c91..f536eb27124 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -141,14 +141,17 @@ fn relink(s: &mut Session, p: &Value) -> Result { let camera = if info.meta.camera.is_empty() { &ph.meta.camera } else { &info.meta.camera }; let make = if info.meta.make.is_empty() { &ph.meta.make } else { &info.meta.make }; let lens = if info.meta.lens.is_empty() { &ph.meta.lens } else { &info.meta.lens }; - if *camera != ph.meta.camera || *make != ph.meta.make || *lens != ph.meta.lens { + let lens_make = if info.meta.lens_make.is_empty() { &ph.meta.lens_make } else { &info.meta.lens_make }; + if *camera != ph.meta.camera || *make != ph.meta.make || *lens != ph.meta.lens || *lens_make != ph.meta.lens_make { let mut meta = ph.meta.clone(); meta.camera.clone_from(camera); meta.make.clone_from(make); meta.lens.clone_from(lens); + meta.lens_make.clone_from(lens_make); ops.push(Op::SetMeta { id, meta: Box::new(meta) }); } - ops.extend(crate::cmd::convert::reload_wb_op(ph, &info, camera)); + let same_path = matches!(&ph.source, Source::File { path } if *path == abs); + ops.extend(crate::cmd::convert::reload_wb_op(ph, &info, camera, same_path)); if info.embedded_lens.as_ref() != ph.embedded_lens.as_deref() { ops.push(Op::SetEmbeddedLens { id, lens: info.embedded_lens.map(Box::new) }); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 99ce4ae8a41..d6bf537c7a9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -829,12 +829,10 @@ impl Session { | Op::SetAsShotWb { id, .. } | Op::SetSourceWb { id, .. } | Op::SetEmbeddedLens { id, .. } => invalidated.push(*id), - Op::SetMeta { id, meta } - if self - .catalog - .photo(*id) - .is_some_and(|p| p.meta.camera != meta.camera || p.meta.make != meta.make || p.meta.lens != meta.lens) => - { + Op::SetMeta { id, meta } if self.catalog.photo(*id).is_some_and(|p| cmd::convert::source_metadata_changed(&p.meta, meta)) => { + invalidated.push(*id); + } + Op::SetCaptured { id, captured } if self.catalog.photo(*id).is_some_and(|p| p.captured != *captured) => { invalidated.push(*id); } Op::AddPhoto { photo } => invalidated.push(photo.id), diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 9bac542b3ab..9ff2205e4aa 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -186,6 +186,9 @@ pub(super) fn source_metadata_key(p: &Photo) -> u64 { if kelvin && wb.is_none() { key.str("kelvin-white-balance"); } + if kelvin && p.fitted_look() { + key.str("legacy-relative-white-balance"); + } if let Some(lens) = &p.embedded_lens { key.str("lens").str(&format!("{lens:?}")); } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 6d54e24049a..71921b51218 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5168,6 +5168,7 @@ fn relink_uses_the_replacement_cameras_white_balance_scale() { info.meta.camera = "SONY ILCA-99M2".into(); if path.ends_with("replacement.arw") { info.meta.lens = "Replacement lens".into(); + info.meta.lens_make = "Replacement maker".into(); } Ok(info) })); @@ -5176,8 +5177,47 @@ fn relink_uses_the_replacement_cameras_white_balance_scale() { assert!(photo.develops_raw() && !photo.relative_wb()); assert_eq!(photo.as_shot_wb, Some((4300.0, 7.0))); assert_eq!(photo.meta.lens, "Replacement lens"); + assert_eq!(photo.meta.lens_make, "Replacement maker"); s.execute("photo.relink", &json!({"id": id.0, "path": original.to_string_lossy()})).unwrap(); - assert_eq!(s.catalog.photo(id).unwrap().meta.lens, "Replacement lens", "an empty probe preserves the stored lens"); + let meta = &s.catalog.photo(id).unwrap().meta; + assert_eq!((meta.lens.as_str(), meta.lens_make.as_str()), ("Replacement lens", "Replacement maker")); +} + +#[test] +fn relink_keeps_a_missing_white_balance_measurement_only_for_the_same_content() { + use lightcraft_catalog::{MediaKind, Op}; + let dir = super::TestDir::new("relink-missing-wb"); + let original = dir.join("original.dng"); + let moved = dir.join("moved.dng"); + let other = dir.join("other.dng"); + let raw = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + for path in [&original, &moved, &other] { + std::fs::write(path, &raw).unwrap(); + } + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [original.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + let measured = Some((4300.0, 7.0)); + s.commit("Set as shot", Op::SetAsShotWb { id, wb: measured }).unwrap(); + let old = s.catalog.photo(id).unwrap().clone(); + s.media.file_probe = Some(std::sync::Arc::new(move |path| { + let changed = path.ends_with("other.dng"); + Ok(crate::media::ProbeInfo { + kind: MediaKind::Raw, + format: "DNG".into(), + width: old.width, + height: old.height, + file_size: old.file_size, + content_hash: if changed { Some("replacement-content".into()) } else { old.content_hash.clone() }, + ..Default::default() + }) + })); + s.execute("photo.relink", &json!({"path": moved.to_string_lossy()})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().as_shot_wb, measured, "identical contents retain their measured fallback"); + s.execute("photo.relink", &json!({"path": other.to_string_lossy()})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().as_shot_wb, None); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap().as_shot_wb, measured); } #[test] @@ -5221,9 +5261,7 @@ fn reload_repairs_old_source_classification_without_replacing_edits() { old.kind = if raw { MediaKind::Image } else { MediaKind::Raw }; old.format = if raw { "JPEG" } else { "ORF" }.into(); old.preview_checked = old.preview_stamp(&old.preview_only); - if !raw { - old.as_shot_wb = Some((4300.0, 7.0)); - } + old.as_shot_wb = Some((4300.0, 7.0)); s.catalog.apply(Op::RemovePhoto { id }).unwrap(); s.catalog.apply(Op::AddPhoto { photo: Box::new(old) }).unwrap(); let before = s.catalog.photo(id).unwrap().clone(); @@ -5231,9 +5269,7 @@ fn reload_repairs_old_source_classification_without_replacing_edits() { let repaired = s.catalog.photo(id).unwrap().clone(); assert_eq!((repaired.kind, &repaired.format, &repaired.preview_checked), (correct.kind, &correct.format, &correct.preview_checked)); assert_eq!((repaired.develop.clone(), repaired.meta.clone()), (before.develop.clone(), before.meta.clone())); - if !raw { - assert_eq!(repaired.as_shot_wb, None); - } + assert_eq!(repaired.as_shot_wb, correct.as_shot_wb); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.catalog.photo(id).unwrap(), &before); s.execute("edit.redo", &json!({})).unwrap(); diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index 7ab718eaa05..46d9487fb82 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -570,6 +570,27 @@ fn undo_and_redo_only_invalidate_pending_reloads_for_source_names() { assert_eq!(reload::apply(&mut x.s, items, vec![Ok(probe)]).unwrap().checked, [id]); } +#[test] +fn undo_of_exposure_metadata_rejects_a_pending_reload() { + use crate::cmd::reload; + let mut x = checked_orf("undo-exposure"); + let id = x.id; + let mut meta = x.s.catalog.photo(id).unwrap().meta.clone(); + let old = meta.exposure_time; + meta.shutter = "0.4 s".into(); + meta.exposure_time = Some(0.4); + x.s.commit("Correct shutter", Op::SetMeta { id, meta: Box::new(meta) }).unwrap(); + let items = reload::plan(&mut x.s, &json!({"id": id.0})).unwrap(); + let mut probe = reload::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + probe.meta.shutter = "0.4 s".into(); + probe.meta.exposure_time = Some(0.4); + x.s.execute("edit.undo", &json!({})).unwrap(); + assert!(reload::apply(&mut x.s, items, vec![Ok(probe.clone())]).unwrap().checked.is_empty()); + assert_eq!(x.s.catalog.photo(id).unwrap().meta.exposure_time, old); + let new = reload::plan(&mut x.s, &json!({"id": id.0})).unwrap(); + assert_eq!(reload::apply(&mut x.s, new, vec![Ok(probe)]).unwrap().checked, [id]); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn a_stamp_only_recheck_keeps_the_face_scan() { From 85f3525343a675bbeb33e687be1550140c2be2e7 Mon Sep 17 00:00:00 2001 From: pancake Date: Sun, 29 Nov 2026 17:14:28 +0100 Subject: [PATCH 18/42] Reload: keep decoded sources after GPS-only edits --- crates/engine/src/cmd/convert.rs | 3 +-- crates/engine/src/lib.rs | 14 ++++++++++++-- crates/engine/src/tests/recheck.rs | 19 +++++++++++++++++++ 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 50f296ddc25..9682108d744 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -300,7 +300,7 @@ pub(crate) fn fill_missing_meta(id: lightcraft_catalog::PhotoId, ph: &lightcraft } /// A change to any metadata field a pending file probe could write back. -pub(crate) fn source_metadata_changed(old: &lightcraft_catalog::Meta, new: &lightcraft_catalog::Meta) -> bool { +pub(crate) fn render_metadata_changed(old: &lightcraft_catalog::Meta, new: &lightcraft_catalog::Meta) -> bool { old.camera != new.camera || old.make != new.make || old.lens != new.lens @@ -313,7 +313,6 @@ pub(crate) fn source_metadata_changed(old: &lightcraft_catalog::Meta, new: &ligh || old.flash != new.flash || old.exposure_bias != new.exposure_bias || old.serial_number != new.serial_number - || old.gps != new.gps || old.focus != new.focus } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index d6bf537c7a9..5d6583ebe23 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -797,6 +797,7 @@ impl Session { // import batch here would clone every photo, although commit already keeps the journal copy. let mut invalidated = Vec::new(); let mut denoise_changed = Vec::new(); + let mut reads_only = Vec::new(); // photos whose file was replaced: the faces made from the old pixels go too (issue #1524) let mut replaced = Vec::new(); let mut pending = vec![&op]; @@ -829,8 +830,14 @@ impl Session { | Op::SetAsShotWb { id, .. } | Op::SetSourceWb { id, .. } | Op::SetEmbeddedLens { id, .. } => invalidated.push(*id), - Op::SetMeta { id, meta } if self.catalog.photo(*id).is_some_and(|p| cmd::convert::source_metadata_changed(&p.meta, meta)) => { - invalidated.push(*id); + Op::SetMeta { id, meta } => { + if let Some(photo) = self.catalog.photo(*id) { + if cmd::convert::render_metadata_changed(&photo.meta, meta) { + invalidated.push(*id); + } else if invalidate_reads && photo.meta.gps != meta.gps { + reads_only.push(*id); + } + } } Op::SetCaptured { id, captured } if self.catalog.photo(*id).is_some_and(|p| p.captured != *captured) => { invalidated.push(*id); @@ -848,6 +855,9 @@ impl Session { for id in denoise_changed { self.denoise_photo_changed(id); } + for id in reads_only { + self.reload_tickets.invalidate(id); + } for id in invalidated { if invalidate_reads { self.reload_tickets.invalidate(id); diff --git a/crates/engine/src/tests/recheck.rs b/crates/engine/src/tests/recheck.rs index 46d9487fb82..0d4946c764f 100644 --- a/crates/engine/src/tests/recheck.rs +++ b/crates/engine/src/tests/recheck.rs @@ -570,6 +570,25 @@ fn undo_and_redo_only_invalidate_pending_reloads_for_source_names() { assert_eq!(reload::apply(&mut x.s, items, vec![Ok(probe)]).unwrap().checked, [id]); } +#[test] +fn editing_gps_rejects_a_pending_reload_and_keeps_the_decoded_source() { + use crate::cmd::reload; + use crate::media::SourceLevel; + let mut x = library("gps-edit-pending-reload"); + let id = x.id; + x.s.render_now(id, 96, 64).unwrap(); + let decoded = x.s.media.get(id, SourceLevel::Thumb).unwrap(); + let items = reload::plan(&mut x.s, &json!({"id": id.0})).unwrap(); + let probe = reload::file_probe(&x.s).unwrap()(&x.file.to_string_lossy()).unwrap(); + + x.s.execute("photo.setMeta", &json!({"ids": [id.0], "gps": [45.0, 7.0]})).unwrap(); + + let cached = x.s.media.get(id, SourceLevel::Thumb).unwrap(); + assert!(std::sync::Arc::ptr_eq(&decoded, &cached)); + assert!(reload::apply(&mut x.s, items, vec![Ok(probe)]).unwrap().checked.is_empty()); + assert_eq!(x.s.catalog.photo(id).unwrap().meta.gps, Some((45.0, 7.0))); +} + #[test] fn undo_of_exposure_metadata_rejects_a_pending_reload() { use crate::cmd::reload; From 8d40ba3152d6662a911401298a4872ccb57884ae Mon Sep 17 00:00:00 2001 From: pancake Date: Wed, 25 Nov 2026 19:31:25 +0100 Subject: [PATCH 19/42] LR-IMP-FORMATS: Keep verified DNG output facts and duplicate handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use the generated file’s facts for Convert to DNG and Copy as DNG, preserve input metadata, and reconcile output hashes for duplicates and Restore. --- assets/ATTRIBUTION.md | 2 +- crates/engine/src/cmd/convert.rs | 31 +-- crates/engine/src/import/commit.rs | 222 +++++++++++++++++--- crates/engine/src/import/files.rs | 1 + crates/engine/src/import/job.rs | 110 +++++++++- crates/engine/src/import/scan.rs | 16 +- crates/engine/src/import/tests_known.rs | 2 +- crates/engine/src/tests/import.rs | 260 ++++++++++++++++++++++++ crates/engine/src/tests/xmp.rs | 2 +- 9 files changed, 580 insertions(+), 66 deletions(-) diff --git a/assets/ATTRIBUTION.md b/assets/ATTRIBUTION.md index 15c2ded7367..5656b2b6e23 100644 --- a/assets/ATTRIBUTION.md +++ b/assets/ATTRIBUTION.md @@ -28,7 +28,7 @@ covers a whole directory), or if a licence file referenced in the Licence column | `crates/raw/src/chart_table.rs` | Chart-measured camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D50) for the Canon EOS D60 | LightCraft contributors; ColorChecker photographs taken by Robert Woldberg on the maintainer's EOS D60 | original work: fitted to our own CRWs of a ColorChecker Classic (post-November-2014 formulation) under a ~2,900 K tungsten bulb (11 frames) and direct sun (~4,850 K, 20 frames); reference colours: X-Rite's published L*a*b* (D50) for the chart, as packaged by [colour-science](https://github.com/colour-science/colour) (BSD-3-Clause), used for fitting only and not shipped; method in `clean-room/crw/10-chart-calibration.md` | MIT OR Apache-2.0 | 2026-10-25 | kept by hand: a 3×3 matrix per illuminant fitted on chromaticity with neutral held at D50; no Adobe or third-party camera matrix, no number from a GPL raw decoder | | `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none | | `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a | -| `crates/ui-egui/src/tests/recheck.rs`, `crates/engine/src/{files/tests.rs,tests/{recheck,import}.rs}` (runtime fixtures) | Generated source and Reload fixtures | LightCraft contributors | original work: procedural RGB pixels, a linear DNG generated by LightCraft and a synthetic uncompressed ORF | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-11-25 | generated at runtime, no binary fixture committed | +| `crates/ui-egui/src/tests/recheck.rs`, `crates/engine/src/{files/tests.rs,tests/{recheck,import}.rs}` (runtime fixtures) | Generated source and Reload fixtures | LightCraft contributors | original work: procedural RGB pixels, linear DNGs generated by LightCraft (including a one-sample-bit mutation for mixed-content Restore), and a synthetic uncompressed ORF | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-11-25 | generated at runtime, no binary fixture committed | | `crates/ui-egui/src/icons.rs` | UI icons drawn as vector paths in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-09-30 | n/a | | `crates/ui-egui/src/panels/person.rs` | Up arrow on the People page bulk-confirm control, drawn in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-10-13 | n/a | | `docs/images/*-tetons.jpg`, `docs/images/grid-pd.jpg` (screenshots containing it) | "The Tetons and the Snake River" | Ansel Adams (1942), U.S. National Archives | https://commons.wikimedia.org/wiki/File:Adams_The_Tetons_and_the_Snake_River.jpg | Public domain (U.S. federal government work) | 2026-09-30 | developed in LightCraft; shown inside app screenshots | diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 9682108d744..2b7e21f22d3 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -19,18 +19,22 @@ fn dng_names(path: &str) -> impl Iterator { } /// Write the DNG for raw file `path` (develop settings in `packet`) next to it under a free name; -/// returns the new path. An empty `packet` writes no XMP. +/// returns the new path and its file facts. An empty `packet` writes no XMP. /// /// The DNG is checked before anyone relies on it (Convert to DNG relinks the photo to it, Copy as /// DNG deletes the raw copy): the encoded file must decode to the same raw data, and it is /// written to a temp file, synced, read back identical and only then given its name — never /// replacing an existing file. On any failure no DNG is left behind and the raw stays in use. -pub(crate) fn write_dng_for(s: &Session, path: &str, packet: String) -> std::result::Result { +pub(crate) fn write_dng_for(s: &Session, path: &str, packet: String) -> std::result::Result<(String, crate::media::ProbeInfo), String> { write_dng_with(s.media.file_bytes.as_ref(), path, packet) } /// [`write_dng_for`] without the session (imports convert on a worker thread). -pub(crate) fn write_dng_with(file_bytes: Option<&crate::merge::ByteReader>, path: &str, packet: String) -> std::result::Result { +pub(crate) fn write_dng_with( + file_bytes: Option<&crate::merge::ByteReader>, + path: &str, + packet: String, +) -> std::result::Result<(String, crate::media::ProbeInfo), String> { let bytes = match file_bytes { Some(r) => r(path)?, None => std::fs::read(path).map_err(|e| format!("{path}: {e}"))?, @@ -52,9 +56,11 @@ pub(crate) fn write_dng_with(file_bytes: Option<&crate::merge::ByteReader>, path return Err(format!("{path}: the DNG written for it doesn't hold the same raw data; the raw is kept")); } drop((raw, back)); + // Generated bytes need their own identity; retaining the raw's hash can reuse unrelated proxies. + let info = crate::files::probe_bytes("converted.dng", &dng)?; let out = lightcraft_catalog::safe_file::write_new_unique(&mut dng_names(path), &dng) .map_err(|e| format!("{path}: could not write its DNG ({e}); the raw is kept"))?; - Ok(out.to_string_lossy().to_string()) + Ok((out.to_string_lossy().to_string(), info)) } fn convert(s: &mut Session, p: &Value) -> Result { @@ -84,25 +90,20 @@ fn convert(s: &mut Session, p: &Value) -> Result { } let packet = crate::sidecar::sidecar_packet(&ph, &s.catalog); match write_dng_for(s, path, packet) { - Ok(out) => { + Ok((out, info)) => { let file_name = Path::new(&out).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); // virtual copies of this photo follow it to the DNG - for c in s.catalog.photos().filter(|c| c.copy_of == Some(id)) { + for c in s.catalog.photos().filter(|c| c.copy_of == Some(id)).chain(std::iter::once(&ph)) { ops.push(Op::Relink { id: c.id, file_name: file_name.clone(), source: Source::File { path: out.clone() }, - format: Some("DNG".into()), - kind: Some(lightcraft_catalog::MediaKind::Raw), + format: Some(info.format.clone()), + kind: Some(info.kind), }); + ops.extend(content_facts_op(c.id, c, &info.format, &info)); + ops.extend(reload_wb_op(c, &info, &info.meta.camera)); } - ops.push(Op::Relink { - id, - file_name, - source: Source::File { path: out.clone() }, - format: Some("DNG".into()), - kind: Some(lightcraft_catalog::MediaKind::Raw), - }); converted.push(json!({"id": id.0, "path": out, "original": path})); } Err(e) => skipped.push(json!([id.0, e])), diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 4205cac71e1..8b3e0adaf10 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -1,6 +1,6 @@ use super::defaults::apply_import_defaults; use super::files::copy_into; -use super::job::{Prepared, PreparedItem, ReadyFile}; +use super::job::{Prepared, PreparedItem, ReadyFile, RestoreCheck, RestoreTarget, normalize_import_path, restore_stamp}; use super::types::{BackupCopy, Duplicate, FileFacts, ImportOptions, ImportReport, Kept, Moved, OnDeleted}; use super::{HashMap, Op, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; @@ -142,8 +142,8 @@ pub(super) fn run_transfers( /// Copy or move one planned file (and Copy as DNG); its item. fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> PreparedItem { let Transfer { path, mut info, sidecar, dir, how, dng, backup } = t; + let mut input_hash = None; let mut placed = None; - let mut converted = false; let mut stored = match how { How::Place { name } => match crate::import_move::place(Path::new(&path), &dir, &name) { Ok(pl) => { @@ -163,18 +163,28 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P let weight = usize::try_from(info.file_size).unwrap_or(usize::MAX).saturating_mul(6); let _permit = crate::memory::work_gate().acquire(weight); match crate::cmd::convert::write_dng_with(file_bytes, &stored, String::new()) { - Ok(dng) => { + Ok((dng, output)) => { let _ = std::fs::remove_file(&stored); stored = dng; - converted = true; - info.format = "DNG".into(); + // Keep input metadata and XMP, but describe the bytes actually stored. The alias + // keeps duplicate input raws identifiable until this import is committed. + input_hash = info.content_hash.clone().filter(|h| Some(h) != output.content_hash.as_ref()); + info = ProbeInfo { + width: output.width, + height: output.height, + format: output.format, + kind: output.kind, + file_size: output.file_size, + content_hash: output.content_hash, + preview_only: output.preview_only, + ..info + }; } Err(e) => log::warn!("import {path}: copy as DNG: {e}"), } } - let backup = - backup.map(|(root, to)| back_up(&path, &stored, placed.as_ref(), &root, &to, if converted { None } else { info.content_hash.as_deref() })); - PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed, backup })) + let backup = backup.map(|(root, to)| back_up(&path, &stored, placed.as_ref(), &root, &to, info.content_hash.as_deref())); + PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash, sidecar, placed, backup })) } /// The backup copy of a file an import put at `stored` inside `root` — with a Move's sidecars beside @@ -212,14 +222,17 @@ fn back_up( Ok(copy.to_string_lossy().to_string()) } -/// A trashed photo's file is not where the library had it (never on the web, where paths are -/// storage keys, not files). -fn trashed_file_is_gone(cat: &lightcraft_catalog::Catalog, id: PhotoId) -> bool { - !cfg!(target_arch = "wasm32") - && match cat.photo(id).map(|p| &p.source) { - Some(Source::File { path }) => !Path::new(path).exists(), - _ => false, - } +/// Restore follows the matching content when the old name is missing or has been reused. +fn trashed_file_differs(photo: &Photo, hash: Option<&str>, check: Option<&RestoreCheck>) -> bool { + let Source::File { path } = &photo.source else { return false }; + if cfg!(target_arch = "wasm32") || hash.is_none() || photo.content_hash.as_deref() != hash { + return false; + } + match check { + Some(check) if check.path == *path && Some(check.hash.as_str()) == hash => check.stamp.is_none() || restore_stamp(path) != check.stamp, + // The catalog changed after preparation. Prefer the verified matching input. + _ => true, + } } /// What a new record takes from its file, as a file import gives it: the file's metadata and @@ -254,6 +267,66 @@ impl Session { } } +// A transfer can reuse its input file; aliases must not turn that original into a disposable copy. +fn same_import_file(a: &str, b: &str) -> bool { + normalize_import_path(a) == normalize_import_path(b) + || std::fs::canonicalize(a).ok().zip(std::fs::canonicalize(b).ok()).is_some_and(|(a, b)| a == b) +} + +// Reconcile hashes learned after conversion, including ordinary files later in the batch. +// Only the catalog owner decides whether a redundant output is disposable or restores a missing file. +fn ready_duplicate( + s: &Session, + opts: &ImportOptions, + added: &mut HashMap, + restored: &[u64], + checks: &HashMap, + ready: ReadyFile, +) -> PreparedItem { + let existing = ready.info.content_hash.as_ref().and_then(|h| added.get(h).copied()); + let Some(id) = existing else { return PreparedItem::Ready(Box::new(ready)) }; + let photo = s.catalog.photo(id); + // A preceding item may already have planned this photo's replacement in the pending batch. + let pending = restored.contains(&id.0); + let same_path = photo.is_some_and(|p| match &p.source { + Source::File { path } => same_import_file(path, &ready.stored), + _ => false, + }); + let relocate = !pending + && !same_path + && opts.on_deleted == OnDeleted::Restore + && photo.is_some_and(|p| p.deleted && trashed_file_differs(p, ready.info.content_hash.as_deref(), checks.get(&id))); + if !relocate + && !same_path + && let Some(placed) = &ready.placed + { + crate::import_move::rollback(placed); + } + if ready.placed.is_none() + && !same_path + && !relocate + // Add entries retain their original path, including aliases. + && !same_import_file(&ready.path, &ready.stored) + && let Err(e) = std::fs::remove_file(&ready.stored) + { + return PreparedItem::Failed(ready.path, format!("could not remove duplicate output {}: {e}", ready.stored)); + } + added.extend(ready.input_hash.into_iter().map(|h| (h, id))); + PreparedItem::Duplicate { + path: if relocate { ready.stored } else { ready.path }, + existing: Some(id), + reason: "content", + hash: ready.info.content_hash, + restore: if relocate { RestoreTarget::Relink } else { RestoreTarget::Keep }, + file: Some(Box::new(FileFacts { + meta: ready.info.meta, + captured: ready.info.captured, + orientation: ready.info.orientation, + sidecar: ready.sidecar, + })), + } +} + /// The catalog half of an import: add the photos [`ImportJob::prepare`] readied (one undoable op; /// a Move's sources are removed once it is saved). On a failed commit a Move's placed files are /// taken back. @@ -265,8 +338,25 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare // Move: placed at the destination, sources untouched until the records are committed // (with its backup: where it was made, or why it wasn't, so the source stays) let mut placed: Vec<(crate::import_move::Placed, Option>)> = Vec::new(); - // photos added by this batch, by content (a duplicate of a file earlier in the import names it) - let mut new_hash: HashMap = HashMap::new(); + // Current converted outputs, then this batch's additions and input aliases. Keep only the + // hashes this batch asks about, even for a library of millions of photos. + let converted_hashes = prepared.items.iter().filter_map(|it| match it { + PreparedItem::Ready(r) if r.input_hash.is_some() && !opts.local => r.info.content_hash.as_deref(), + _ => None, + }); + // Local records count only when this same atomic import already promotes them into the library. + let promoted: std::collections::HashSet<_> = prepared + .items + .iter() + .filter_map(|it| match it { + PreparedItem::Promote(id, _) => Some(*id), + _ => None, + }) + .collect(); + let mut new_hash = super::scan::library_hashes( + s.catalog.photos().filter(|p| (!p.local || promoted.contains(&p.id)) && !(p.deleted && opts.on_deleted == OnDeleted::Fresh)), + converted_hashes, + ); // Fresh: trashed photos a new import replaces (by content or by file), each removed once let (mut trash_hash, mut trash_path): (HashMap, HashMap) = Default::default(); if opts.on_deleted == OnDeleted::Fresh { @@ -282,6 +372,10 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let mut purge: Vec = Vec::new(); let mut purged: std::collections::HashSet = Default::default(); for it in prepared.items { + let it = match it { + PreparedItem::Ready(r) if !opts.local => ready_duplicate(s, opts, &mut new_hash, &report.restored, &prepared.restore_checks, *r), + it => it, + }; match it { PreparedItem::Promote(id, fresh) => { // the file was replaced since it was browsed: the record takes what it is now before it joins the library @@ -303,11 +397,11 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare } report.imported.push(id.0); } - PreparedItem::Duplicate { path, existing, reason, hash, file } => { + PreparedItem::Duplicate { path, existing, reason, hash, restore, file } => { let existing = existing.or_else(|| { - let h = hash?; + let h = hash.as_ref()?; new_hash - .get(&h) + .get(h) .copied() .or_else(|| s.catalog.photos().find(|p| !p.local && p.content_hash.as_deref() == Some(h.as_str())).map(|p| p.id)) }); @@ -317,12 +411,18 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare Some(id) if opts.on_deleted == OnDeleted::Restore && !opts.local => { if !report.restored.contains(&id.0) { ops.push(Op::SetDeleted { id, deleted: false }); - // matched by content from another path, and the file the record - // points at is gone (moved, renamed): the photo follows the file - // (not onto a path another record holds, a file only browsed in Local) - if reason == "content" - && trashed_file_is_gone(&s.catalog, id) - && !s.catalog.photos().any(|p| matches!(&p.source, Source::File { path: held } if *held == path)) + let relink = match restore { + RestoreTarget::Relink => true, + RestoreTarget::Keep => false, + RestoreTarget::Decide => { + reason == "content" + && s.catalog + .photo(id) + .is_some_and(|p| trashed_file_differs(p, hash.as_deref(), prepared.restore_checks.get(&id))) + } + }; + if relink + && !s.catalog.photos().any(|p| p.id != id && matches!(&p.source, Source::File { path: held } if *held == path)) { ops.push(crate::cmd::missing::relink_op(id, &path)); } @@ -337,14 +437,14 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare PreparedItem::Failed(path, e) => report.failed.push((path, e)), PreparedItem::Kept(k) => report.kept.push(k), PreparedItem::Ready(r) => { - let ReadyFile { path, stored, info, sidecar, placed: pl, backup } = *r; + let ReadyFile { path, stored, info, input_hash, sidecar, placed: pl, backup } = *r; let backed_up = note_backup(&mut report, &path, &stored, backup); placed.extend(pl.map(|p| (p, backed_up))); let id = s.catalog.alloc_photo_id(); - if let Some(h) = &info.content_hash { + for h in info.content_hash.iter().chain(&input_hash) { new_hash.insert(h.clone(), id); } - for old in info.content_hash.as_ref().and_then(|h| trash_hash.get(h)).into_iter().chain(trash_path.get(&stored)) { + for old in info.content_hash.iter().chain(&input_hash).filter_map(|h| trash_hash.get(h)).chain(trash_path.get(&stored)) { if purged.insert(*old) { purge.push(*old); } @@ -664,3 +764,65 @@ mod clock_tests { assert_eq!(lightcraft_catalog::dates::normalize_iso(&local).as_deref(), Some(local.as_str())); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn review_ordinary_dng_deduplicates_after_a_converted_output() { + mixed_dng_outputs(true); + } + + #[test] + fn review_converted_output_deduplicates_after_an_ordinary_dng() { + mixed_dng_outputs(false); + } + + fn mixed_dng_outputs(converted_first: bool) { + for copied in [false, true] { + let dir = std::env::temp_dir().join(format!("lc-ready-dng-{converted_first}-{copied}-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let raw = dir.join("input.orf"); + let original = dir.join("ordinary.dng"); + let converted = dir.join("converted.dng"); + let stored = if copied { dir.join("copied.dng") } else { original.clone() }; + std::fs::write(&raw, b"input raw").unwrap(); + for file in [&original, &converted, &stored] { + std::fs::write(file, b"same DNG output").unwrap(); + } + let info = ProbeInfo { + kind: lightcraft_catalog::MediaKind::Raw, + format: "DNG".into(), + width: 2, + height: 2, + file_size: 15, + content_hash: Some(lightcraft_preview::hash_bytes(b"same DNG output").to_string()), + ..Default::default() + }; + let ready = |path: PathBuf, stored: PathBuf, input_hash| { + PreparedItem::Ready(Box::new(ReadyFile { + path: path.to_string_lossy().into(), + stored: stored.to_string_lossy().into(), + info: info.clone(), + input_hash, + sidecar: None, + placed: None, + })) + }; + let mut items = vec![ready(raw.clone(), converted, Some("input raw hash".into())), ready(dir.join("./ordinary.dng"), stored, None)]; + if !converted_first { + items.reverse(); + } + let mut s = Session::new(); + let opts = ImportOptions { mode: crate::import::ImportMode::Copy, ..Default::default() }; + let r = commit_prepared(&mut s, &opts, "", Prepared { scanned: 2, items, ..Default::default() }).unwrap(); + assert!(r.failed.is_empty(), "{r:?}"); + assert_eq!((r.imported.len(), r.duplicates.len()), (1, 1), "{r:?}"); + assert_eq!(r.duplicates[0].existing, Some(r.imported[0])); + assert_eq!(std::fs::read(&original).unwrap(), b"same DNG output", "an in-place original or alias is never removed"); + assert_eq!(std::fs::read(&raw).unwrap(), b"input raw"); + std::fs::remove_dir_all(dir).unwrap(); + } + } +} diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index a38031ae397..f6843474a6e 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -661,6 +661,7 @@ mod prepared_tests { path: path.to_string_lossy().into(), stored: path.to_string_lossy().into(), info: ProbeInfo { format: "JPG".into(), ..ProbeInfo::default() }, + input_hash: None, sidecar: None, placed: None, backup: None, diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 96781be7a4a..b2d261c7742 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -46,6 +46,8 @@ pub struct ImportJob { local_sizes: HashMap, /// content hash → the photo that has it (`None`: a file earlier in this import) pub(super) by_hash: HashMap>, + /// Paths of deleted duplicates, captured before the worker starts. + restore_sources: HashMap, pub(super) probe: Option, file_bytes: Option, /// Probes from a preceding scan (not read again). @@ -72,6 +74,29 @@ pub struct Prepared { /// What [`ImportJob::prepare`]'s folder walk left out. pub skipped: super::types::Skipped, pub(super) items: Vec, + pub(super) restore_checks: HashMap, +} + +#[derive(Debug)] +pub(super) struct RestoreCheck { + pub(super) path: String, + pub(super) hash: String, + pub(super) stamp: Option<(u64, std::time::SystemTime)>, +} + +pub(super) fn restore_stamp(path: &str) -> Option<(u64, std::time::SystemTime)> { + let meta = std::fs::metadata(path).ok()?; + if !meta.is_file() { + return None; + } + Some((meta.len(), meta.modified().ok()?)) +} + +#[derive(Debug)] +pub(super) enum RestoreTarget { + Decide, + Keep, + Relink, } #[derive(Debug)] @@ -84,6 +109,7 @@ pub(super) enum PreparedItem { existing: Option, reason: &'static str, hash: Option, + restore: RestoreTarget, /// What the file itself says, when it was read ([`Duplicate::file`]). file: Option>, }, @@ -97,6 +123,8 @@ pub(super) struct ReadyFile { pub(super) path: String, pub(super) stored: String, pub(super) info: ProbeInfo, + /// Copy as DNG's original input identity, only for this job's duplicate lookup. + pub(super) input_hash: Option, pub(super) sidecar: Option, pub(super) placed: Option, /// [`ImportOptions::backup`]: its backup copy, or why it has none. `None`: no backup asked for. @@ -144,9 +172,9 @@ impl Prepared { items.push(item); continue; }; - let ReadyFile { path, stored, info, sidecar, placed, backup } = *ready; + let ReadyFile { path, stored, info, input_hash, sidecar, placed, backup } = *ready; let existing_path = paths.get(&normalize_import_path(&stored)).copied().or_else(|| paths.get(&normalize_import_path(&path)).copied()); - let existing_hash = info.content_hash.as_ref().and_then(|hash| hashes.get(hash).copied()); + let existing_hash = info.content_hash.iter().chain(&input_hash).find_map(|hash| hashes.get(hash).copied()); if let Some(existing) = existing_path.or(existing_hash) { if let Some(placed) = &placed { crate::import_move::rollback(placed); @@ -156,10 +184,11 @@ impl Prepared { existing: Some(existing), reason: if existing_path.is_some() { "path" } else { "content" }, hash: info.content_hash, + restore: RestoreTarget::Decide, file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), }); } else { - items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed, backup }))); + items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash, sidecar, placed, backup }))); } } self.items = items; @@ -200,7 +229,7 @@ pub fn backup_refusal(s: &Session, opts: &ImportOptions) -> Option { backup_folder_error(mode, transfer, root.as_deref(), Path::new(backup)) } -fn normalize_import_path(path: &str) -> String { +pub(super) fn normalize_import_path(path: &str) -> String { let path = path.replace('\\', "/"); if cfg!(windows) { path.to_lowercase() } else { path } } @@ -246,6 +275,7 @@ impl ImportJob { by_path: HashMap::new(), local_sizes: HashMap::new(), by_hash: HashMap::new(), + restore_sources: HashMap::new(), probe: s.media.file_probe.clone(), file_bytes: s.media.file_bytes.clone(), cache: std::mem::take(&mut s.import_probes), @@ -335,6 +365,12 @@ impl ImportJob { && let Some(h) = &p.content_hash { self.by_hash.insert(h.clone(), Some(p.id)); + if p.deleted + && self.opts.on_deleted == OnDeleted::Restore + && let Source::File { path } = &p.source + { + self.restore_sources.insert(p.id, (path.clone(), h.clone())); + } } } Some(library) @@ -367,7 +403,14 @@ impl ImportJob { } }, Some((id, _, _)) => { - out.items.push(PreparedItem::Duplicate { path: f, existing: Some(id), reason: "path", hash: None, file: None }); + out.items.push(PreparedItem::Duplicate { + path: f, + existing: Some(id), + reason: "path", + hash: None, + restore: RestoreTarget::Decide, + file: None, + }); self.done.fetch_add(1, Relaxed); } None => todo.push(f), @@ -382,7 +425,7 @@ impl ImportJob { // (here or in a previous batch) counts as the library's from then on if let Some(h) = &hash { if let Some(existing) = self.by_hash.get(h) { - return PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, file: None }; + return PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, restore: RestoreTarget::Decide, file: None }; } self.by_hash.insert(h.clone(), Some(id)); } @@ -551,6 +594,7 @@ impl ImportJob { existing, reason: "content", hash: Some(hash), + restore: RestoreTarget::Decide, file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), })); continue; @@ -629,12 +673,56 @@ impl ImportJob { .backup_root .as_ref() .map(|_| Err("already inside the destination or the library: added where it is, so no backup copy was made".into())); - plan.slots.push(Slot::Item(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, sidecar, placed: None, backup })))); + plan.slots + .push(Slot::Item(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash: None, sidecar, placed: None, backup })))); } self.run_plan(&mut plan, &mut out, cancel); + // Input hashes are aliases only while this batch can resolve them to a verified + // output. A later batch may have to generate that output again to restore it. + let outputs: std::collections::HashSet<_> = out + .items + .iter() + .filter_map(|item| match item { + PreparedItem::Ready(r) => r.info.content_hash.as_deref(), + _ => None, + }) + .collect(); + for item in &out.items { + if let PreparedItem::Ready(r) = item + && let Some(alias) = &r.input_hash + && !outputs.contains(alias.as_str()) + && self.by_hash.get(alias) == Some(&None) + { + self.by_hash.remove(alias); + } + } + self.prepare_restore_checks(&mut out, cancel); out } + /// Verify only the old originals this batch matched, on the preparation worker. + fn prepare_restore_checks(&self, out: &mut Prepared, cancel: &std::sync::atomic::AtomicBool) { + for item in &out.items { + if cancel.load(std::sync::atomic::Ordering::Relaxed) { + break; + } + let id = match item { + PreparedItem::Duplicate { existing, reason: "content", hash: Some(hash), .. } => { + existing.or_else(|| self.by_hash.get(hash).copied().flatten()) + } + PreparedItem::Ready(r) => r.info.content_hash.as_ref().and_then(|hash| self.by_hash.get(hash).copied().flatten()), + _ => None, + }; + let Some(id) = id else { continue }; + let Some((path, hash)) = self.restore_sources.get(&id) else { continue }; + out.restore_checks.entry(id).or_insert_with(|| { + let stamp = restore_stamp(path) + .filter(|stamp| crate::cmd::missing::file_hash(path).as_deref() == Some(hash) && restore_stamp(path) == Some(*stamp)); + RestoreCheck { path: path.clone(), hash: hash.clone(), stamp } + }); + } + } + /// Run the transfers `plan` collected (on several threads) and append its items to `out` in /// file order. Transfers not started because `cancel` was set leave no item. fn run_plan(&mut self, plan: &mut Plan, out: &mut Prepared, cancel: &std::sync::atomic::AtomicBool) { @@ -649,10 +737,10 @@ impl ImportJob { None => continue, }, }; - if let PreparedItem::Ready(r) = &item - && let Some(h) = &r.info.content_hash - { - self.by_hash.insert(h.clone(), None); + if let PreparedItem::Ready(r) = &item { + for h in r.info.content_hash.iter().chain(&r.input_hash) { + self.by_hash.entry(h.clone()).or_insert(None); + } } out.items.push(item); } diff --git a/crates/engine/src/import/scan.rs b/crates/engine/src/import/scan.rs index 8e322f726e7..34e0c5f111f 100644 --- a/crates/engine/src/import/scan.rs +++ b/crates/engine/src/import/scan.rs @@ -1,6 +1,6 @@ use super::files::{BrowsedFile, Seen, browsed_files_changed, expand, expand_report_knowing, is_supported, probe_all, reusable_probes}; use super::types::ImportCandidate; -use super::{HashMap, ListedFolders, Path, PathBuf, PhotoId, ProbeInfo, Session, Source}; +use super::{HashMap, ListedFolders, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; /// What a [`scan`] needs from the session, so it can run on another thread (a folder on a network /// share can take minutes to read). @@ -51,16 +51,18 @@ pub(super) fn library_files(library: &lightcraft_catalog::Catalog, files: &[Stri } /// Which photo of the library has each of the contents `hashes` (the later one where several -/// have it; a copy that was only browsed in Local isn't in the library). One pass over the library, and an entry only for a content that was asked about. -pub(super) fn library_hashes<'a>(library: &lightcraft_catalog::Catalog, hashes: impl Iterator) -> HashMap { +/// have it). One pass over the library, and an entry only for a content that was asked about. +pub(super) fn library_hashes<'a>( + photos: impl Iterator>, + hashes: impl Iterator, +) -> HashMap { let wanted: std::collections::HashSet<&str> = hashes.collect(); let mut by_hash = HashMap::new(); if wanted.is_empty() { return by_hash; } - for p in library.photos() { - if !p.local - && let Some(h) = &p.content_hash + for p in photos { + if let Some(h) = &p.content_hash && wanted.contains(h.as_str()) { by_hash.insert(h.clone(), p.id); @@ -391,7 +393,7 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec, progress: &Sc // (and the browsed files the library has by path: they are offered unless it has the content too) .chain(by_path.values().filter(|(_, c, _)| c.local).filter_map(|(_, _, h)| h.as_deref())); let mut seen_hash: HashMap> = - library_hashes(&input.library, probed_hashes).into_iter().map(|(h, id)| (h, Some(id.0))).collect(); + library_hashes(input.library.photos().filter(|p| !p.local), probed_hashes).into_iter().map(|(h, id)| (h, Some(id.0))).collect(); let mut out = Vec::with_capacity(files.len()); let mut kept = HashMap::new(); // (a content's browsed first copy: its path, until the first file of its own with that content stands in for it) diff --git a/crates/engine/src/import/tests_known.rs b/crates/engine/src/import/tests_known.rs index 3814dc54409..a9138caaa75 100644 --- a/crates/engine/src/import/tests_known.rs +++ b/crates/engine/src/import/tests_known.rs @@ -85,7 +85,7 @@ fn a_scan_knows_who_has_the_contents_it_probed() { // (the content of /pics/006/a.jpg, which /pics/007/c.jpg has too; and one nobody has) let shared = format!("{:032x}", 6 * 3); let nobody = format!("{:032x}", 999_999); - let known = library_hashes(&c, [shared.as_str(), nobody.as_str()].into_iter()); + let known = library_hashes(c.photos(), [shared.as_str(), nobody.as_str()].into_iter()); assert_eq!(known.len(), 1); let whole: HashMap = c.photos().filter_map(|p| p.content_hash.clone().map(|h| (h, p.id))).collect(); assert_eq!(known.get(&shared), whole.get(&shared)); diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 71921b51218..b4f9112f5a4 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5276,3 +5276,263 @@ fn reload_repairs_old_source_classification_without_replacing_edits() { assert_eq!(s.catalog.photo(id).unwrap(), &repaired); } } + +#[test] +fn followup_copy_as_dng_does_not_discard_an_output_matching_only_local() { + copy_as_dng_with_local_match(false); +} + +#[test] +fn followup_copy_as_dng_deduplicates_against_a_pending_local_promotion() { + copy_as_dng_with_local_match(true); +} + +fn copy_as_dng_with_local_match(promote: bool) { + use crate::import::{ImportMode, ImportOptions, Organize}; + use lightcraft_catalog::Source; + let dir = super::TestDir::new(&format!("copy-dng-local-output-{promote}")); + let input = dir.join("sensor.nef"); + std::fs::write(&input, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + let (generated, _) = crate::cmd::convert::write_dng_with(None, &input.to_string_lossy(), String::new()).unwrap(); + let browsed = dir.join("browsed.dng"); + std::fs::rename(generated, &browsed).unwrap(); + let expected = std::fs::read(&browsed).unwrap(); + let mut s = Session::new().with_fs(); + let local = + crate::import::import_with(&mut s, &[browsed.to_string_lossy().into()], &ImportOptions { local: true, ..Default::default() }).unwrap(); + let local_id = PhotoId(local.imported[0]); + let destination = dir.join("copies"); + let opts = ImportOptions { + mode: ImportMode::Copy, + destination: Some(destination.to_string_lossy().into()), + organize: Organize::Flat, + convert_dng: true, + ..Default::default() + }; + let input_path = input.to_string_lossy().to_string(); + let paths = if promote { vec![browsed.to_string_lossy().into(), input_path.clone()] } else { vec![input_path.clone()] }; + let added = crate::import::import_with(&mut s, &paths, &opts).unwrap(); + assert_eq!(added.imported.len(), 1, "a Local match is not yet a library duplicate: {added:?}"); + assert!(added.failed.is_empty(), "{added:?}"); + assert_eq!(added.duplicates.len(), usize::from(promote), "{added:?}"); + let id = PhotoId(added.imported[0]); + assert_eq!(s.catalog.photo(local_id).unwrap().local, !promote); + assert_eq!(id == local_id, promote); + let photo = s.catalog.photo(id).unwrap(); + assert!(!photo.local); + let Source::File { path } = &photo.source else { panic!("file photo") }; + assert_eq!(std::fs::read(path).unwrap(), expected); + let again = crate::import::import_with(&mut s, &[input_path], &opts).unwrap(); + assert!(again.imported.is_empty() && again.failed.is_empty(), "{again:?}"); + assert_eq!(again.duplicates.len(), 1); + assert_eq!(again.duplicates[0].existing, Some(id.0), "real library duplicates keep their policy"); + assert_eq!(copy_dng_output_names(&destination).len(), usize::from(!promote)); + assert_eq!(std::fs::read(&browsed).unwrap(), expected); +} + +#[test] +fn convert_to_dng_refreshes_copy_classification_and_undo_redo() { + use lightcraft_catalog::{MediaKind, Op, Source}; + let dir = super::TestDir::new("convert-copy-kind"); + let raw = dir.join("sensor.dng"); + let png = dir.join("rendered.png"); + std::fs::write(&raw, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + write_png(&png, 30); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [raw.to_string_lossy()]})).unwrap(); + let parent = s.active().unwrap(); + // The existing conversion fixture uses a tiny DNG catalogued as NEF to exercise the command. + let photo = s.catalog.photo(parent).unwrap(); + s.catalog + .apply(Op::Relink { id: parent, file_name: photo.file_name.clone(), source: photo.source.clone(), format: Some("NEF".into()), kind: None }) + .unwrap(); + let copy = s.execute("photo.virtualCopy", &json!({"ids": [parent.0]})).unwrap(); + let copy = PhotoId(copy["ids"][0].as_u64().unwrap()); + s.execute("photo.relink", &json!({"id": copy.0, "path": png.to_string_lossy()})).unwrap(); + s.catalog.apply(Op::SetAsShotWb { id: copy, wb: None }).unwrap(); + s.execute("develop.set", &json!({"ids": [copy.0], "control": "light.exposure", "value": 0.4})).unwrap(); + let before = s.catalog.photo(copy).unwrap().clone(); + let parent_before = s.catalog.photo(parent).unwrap().clone(); + assert_eq!((before.kind, before.format.as_str()), (MediaKind::Image, "PNG")); + let converted = s.execute("photo.convertToDng", &json!({"ids": [parent.0]})).unwrap(); + assert_eq!(converted["converted"].as_array().unwrap().len(), 1, "{converted}"); + let output = Source::File { path: converted["converted"][0]["path"].as_str().unwrap().into() }; + let output_wb = + crate::files::probe_bytes("converted.dng", &std::fs::read(converted["converted"][0]["path"].as_str().unwrap()).unwrap()).unwrap().as_shot_wb; + assert!(output_wb.is_some()); + for id in [parent, copy] { + let photo = s.catalog.photo(id).unwrap(); + assert_eq!((photo.kind, photo.format.as_str()), (MediaKind::Raw, "DNG"), "known DNG output is always raw"); + assert_eq!(photo.source, output); + assert_eq!(photo.as_shot_wb, output_wb, "every relinked record uses the generated DNG's As Shot facts"); + } + let after = s.catalog.photo(copy).unwrap().clone(); + assert_eq!(after.develop, before.develop); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(copy).unwrap(), &before); + assert_eq!(s.catalog.photo(parent).unwrap(), &parent_before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(copy).unwrap(), &after); +} + +#[test] +fn copy_as_dng_keeps_input_metadata_and_deduplicates_across_jobs_and_reopen() { + use crate::import::{ImportMode, ImportOptions, Organize}; + use lightcraft_catalog::{MediaKind, Source}; + let dir = super::TestDir::new("copy-dng-output-facts"); + let library = dir.join("library"); + let destination = dir.join("destination"); + let paths: Vec<_> = ["first.orf", "second.orf"].map(|name| dir.join(name).to_string_lossy().to_string()).into(); + let xmp = r#""#; + let input = crate::tests_xmp::synthetic_dng_with(Some(xmp), Default::default()); + for path in &paths { + std::fs::write(path, &input).unwrap(); + } + // Describe a formerly preview-only vendor raw with distinct input metadata; the tiny DNG supplies its pixels. + let mut info = crate::files::probe_bytes("sensor.orf", &input).unwrap(); + info.format = "ORF".into(); + info.preview_only = Some("old unsupported compression".into()); + info.meta.camera = "input camera".into(); + info.captured = Some("2020-02-03T04:05:06".into()); + info.file_modified = Some("2021-03-04T05:06:07".into()); + info.as_shot_wb = Some((4300.0, 7.0)); + let probe: crate::media::FileProbe = std::sync::Arc::new(move |path| { + let bytes = std::fs::read(path).map_err(|e| e.to_string())?; + Ok(crate::media::ProbeInfo { + content_hash: Some(lightcraft_preview::hash_bytes(&bytes).to_string()), + file_size: bytes.len() as u64, + ..info.clone() + }) + }); + let opts = ImportOptions { + mode: ImportMode::Copy, + destination: Some(destination.to_string_lossy().into()), + organize: Organize::Flat, + convert_dng: true, + ..Default::default() + }; + let mut s = Session::new().with_fs(); + s.open_library(&library, false).unwrap(); + s.media.file_probe = Some(probe.clone()); + let report = crate::import::import_with(&mut s, &paths, &opts).unwrap(); + assert!(report.failed.is_empty(), "{report:?}"); + assert_eq!(report.imported.len(), 1, "{report:?}"); + let id = PhotoId(report.imported[0]); + assert_eq!(report.duplicates.len(), 1, "{report:?}"); + assert_eq!(report.duplicates[0].existing, Some(id.0)); + let photo = s.catalog.photo(id).unwrap().clone(); + let Source::File { path: output } = &photo.source else { panic!("file photo") }; + let bytes = std::fs::read(output).unwrap(); + assert_eq!((photo.kind, photo.format.as_str(), &photo.preview_only), (MediaKind::Raw, "DNG", &None)); + assert_eq!(photo.content_hash, Some(lightcraft_preview::hash_bytes(&bytes).to_string())); + assert_ne!(photo.content_hash, Some(lightcraft_preview::hash_bytes(&input).to_string())); + assert_eq!(photo.file_size, bytes.len() as u64); + assert_eq!(photo.meta.camera, "input camera"); + assert_eq!(photo.captured.as_deref(), Some("2020-02-03T04:05:06")); + assert_eq!(photo.as_shot_wb, Some((4300.0, 7.0))); + assert_eq!(photo.rating, 2); + assert_eq!(photo.develop.light.exposure, 0.7); + let inventory = || copy_dng_output_names(&destination); + let kept = inventory(); + assert_eq!(kept.len(), 1, "only the generated DNG remains"); + for reopen in [false, true] { + if reopen { + assert!(!s.media.smart_dir.as_ref().unwrap().exists(), "this fixture builds no proxies or opening-refresh writers"); + s.persist().unwrap(); + drop(s); + s = Session::new().with_fs(); + s.open_library(&library, false).unwrap(); + s.media.file_probe = Some(probe.clone()); + } + let again = crate::import::import_with(&mut s, &paths, &opts).unwrap(); + assert!(again.imported.is_empty() && again.failed.is_empty(), "{again:?}"); + assert_eq!(again.duplicates.len(), 2, "{again:?}"); + assert!(again.duplicates.iter().all(|duplicate| duplicate.existing == Some(id.0)), "{again:?}"); + assert_eq!(inventory(), kept, "a repeated conversion leaves no orphan DNG"); + assert_eq!(s.catalog.photo(id).unwrap(), &photo); + } + assert_copy_as_dng_restores(&mut s, id, &paths, &opts, &bytes); + assert!(paths.iter().all(|path| std::fs::read(path).unwrap() == input)); +} + +fn assert_copy_as_dng_restores(s: &mut Session, id: PhotoId, paths: &[String], opts: &crate::import::ImportOptions, bytes: &[u8]) { + use lightcraft_catalog::{MediaKind, Source}; + let dir = Path::new(&paths[0]).parent().unwrap(); + let destination = Path::new(opts.destination.as_deref().unwrap()); + let input = std::fs::read(&paths[0]).unwrap(); + let inventory = || copy_dng_output_names(destination); + // Recreate the same destination (also through a directory alias), then a differently named + // DNG. None may be deleted as disposable or relinked to the input raw with stale DNG facts. + for (i, path) in [&paths[0], &paths[0], &paths[1]].into_iter().enumerate() { + #[cfg(unix)] + if i == 1 { + let alias = dir.join("destination-alias"); + std::os::unix::fs::symlink(destination, &alias).unwrap(); + let photo = s.catalog.photo(id).unwrap(); + let source = Source::File { path: alias.join(&photo.file_name).to_string_lossy().into() }; + s.catalog.apply(lightcraft_catalog::Op::Relink { id, file_name: photo.file_name.clone(), source, format: None, kind: None }).unwrap(); + } + #[cfg(not(unix))] + if i == 1 { + continue; + } + let Source::File { path: old } = &s.catalog.photo(id).unwrap().source else { panic!("file photo") }; + std::fs::remove_file(old).unwrap(); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap(); + let restored = crate::import::import_with(s, std::slice::from_ref(path), opts).unwrap(); + assert_eq!(restored.restored, [id.0], "{restored:?}"); + assert!(restored.failed.is_empty() && restored.imported.is_empty(), "{restored:?}"); + let restored = s.catalog.photo(id).unwrap(); + let Source::File { path: restored_path } = &restored.source else { panic!("file photo") }; + assert_eq!(Path::new(restored_path).extension().unwrap(), "dng", "Restore keeps the newly written DNG, not the input raw"); + assert_eq!(std::fs::read(restored_path).unwrap(), bytes); + assert_eq!(restored.content_hash, Some(lightcraft_preview::hash_bytes(bytes).to_string())); + assert_eq!((restored.kind, restored.format.as_str(), &restored.preview_only), (MediaKind::Raw, "DNG", &None)); + assert_eq!(inventory(), [Path::new(restored_path).file_name().unwrap()], "only the restored DNG remains"); + } + // Different input identities can encode to identical DNGs. Both transfers reach commit; + // only the first replacement may survive a Restore planned against the still-missing path. + let padded_path = dir.join("padded.orf").to_string_lossy().to_string(); + let mut padded = input.clone(); + padded.extend_from_slice(&[0; 16]); + assert_ne!(lightcraft_preview::hash_bytes(&padded), lightcraft_preview::hash_bytes(&input)); + std::fs::write(&padded_path, &padded).unwrap(); + for incoming in [[paths[0].clone(), padded_path.clone()], [padded_path.clone(), paths[0].clone()]] { + let Source::File { path: old } = &s.catalog.photo(id).unwrap().source else { panic!("file photo") }; + std::fs::remove_file(old).unwrap(); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap(); + let restored = crate::import::import_with(s, &incoming, opts).unwrap(); + assert_eq!(restored.restored, [id.0], "{restored:?}"); + assert!(restored.failed.is_empty() && restored.imported.is_empty(), "{restored:?}"); + let Source::File { path: restored_path } = &s.catalog.photo(id).unwrap().source else { panic!("file photo") }; + assert_eq!(std::fs::read(restored_path).unwrap(), bytes); + assert_eq!(inventory(), [Path::new(restored_path).file_name().unwrap()], "a pending Restore keeps only its live replacement"); + assert_eq!(std::fs::read(&padded_path).unwrap(), padded); + } + // Another transfer may fill the missing name with different pixels before commit. + let Source::File { path: old } = s.catalog.photo(id).unwrap().source.clone() else { panic!("file photo") }; + std::fs::remove_file(&old).unwrap(); + s.execute("library.select", &json!({"ids": [id.0]})).unwrap(); + s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap(); + let different = dir.join("different").join(Path::new(&old).file_name().unwrap()).with_extension("orf"); + let mut raw = lightcraft_raw::decode(&input).unwrap(); + let lightcraft_raw::RawData::U16(samples) = &mut raw.data else { panic!("integer fixture") }; + samples[0] ^= 1; + std::fs::create_dir_all(different.parent().unwrap()).unwrap(); + std::fs::write(&different, lightcraft_raw::write_dng(&raw, &Default::default()).unwrap()).unwrap(); + let restored = crate::import::import_with(s, &[different.to_string_lossy().into(), paths[1].clone()], opts).unwrap(); + assert_eq!(restored.restored, [id.0], "{restored:?}"); + assert_eq!(restored.imported.len(), 1, "the different image remains an independent import: {restored:?}"); + let Source::File { path } = &s.catalog.photo(id).unwrap().source else { panic!("file photo") }; + assert_ne!(path, &old, "Restore follows the matching content, not a reused name"); + assert_eq!(std::fs::read(path).unwrap(), bytes); + assert_ne!(std::fs::read(old).unwrap(), bytes); +} + +fn copy_dng_output_names(destination: &Path) -> Vec { + let mut files: Vec<_> = std::fs::read_dir(destination).unwrap().map(|entry| entry.unwrap().file_name()).collect(); + files.sort(); + files +} diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index bc103688b0c..ff234802ae1 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -1860,7 +1860,7 @@ fn dngs_of_raws_without_colour_matrices_carry_the_colour_they_open_with() { Ok(()) }; crate::export::export_batch(&mut s, &[id], &o, &crate::export::Destination { dir: "x".into(), exact: None }, &mut write, &|_| false).unwrap(); - let converted = crate::cmd::convert::write_dng_with(None, &path.to_string_lossy(), String::new()).unwrap(); + let (converted, _) = crate::cmd::convert::write_dng_with(None, &path.to_string_lossy(), String::new()).unwrap(); for (how, dng) in [("export", exported), ("convert", std::fs::read(&converted).unwrap())] { let back = lightcraft_raw::decode(&dng).unwrap(); assert!(back.color.color_matrix[0].is_some() && back.color.illuminant[0] != 0, "{model} {how}: {:?}", back.color); From 4fea32182643ca40763814dde157274454b1dd2f Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 18:48:06 +0100 Subject: [PATCH 20/42] Test DNG restore across import batches and isolate test directories --- crates/engine/src/tests/import.rs | 52 +++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index b4f9112f5a4..a37029a26e5 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5531,6 +5531,58 @@ fn assert_copy_as_dng_restores(s: &mut Session, id: PhotoId, paths: &[String], o assert_ne!(std::fs::read(old).unwrap(), bytes); } +#[test] +fn copy_as_dng_restore_uses_the_verified_output_across_batches() { + use crate::import::{ImportJob, ImportMode, ImportOptions, Organize, commit_prepared}; + use lightcraft_catalog::{Op, Source}; + for remove_after_preparation in [false, true] { + let dir = super::TestDir::new(&format!("copy-dng-restore-batch-{remove_after_preparation}")); + let destination = dir.join("copies"); + let source = ["first.nef", "second.nef"].map(|name| dir.join(name).to_string_lossy().into_owned()); + let raw = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + for path in &source { + std::fs::write(path, &raw).unwrap(); + } + let mut session = Session::new().with_fs(); + let opts = ImportOptions { + mode: ImportMode::Copy, + destination: Some(destination.to_string_lossy().into()), + organize: Organize::Flat, + convert_dng: true, + ..Default::default() + }; + let cancel = std::sync::atomic::AtomicBool::new(false); + let mut job = ImportJob::new(&mut session, opts.clone()).unwrap(); + let first = job.prepare(&source[..1], &cancel); + let r = commit_prepared(&mut session, &opts, job.now(), first).unwrap(); + let id = PhotoId(r.imported[0]); + let Source::File { path: old } = session.catalog.photo(id).unwrap().source.clone() else { panic!("file photo") }; + let output = std::fs::read(&old).unwrap(); + assert_ne!(output, raw); + session.catalog.apply(Op::SetDeleted { id, deleted: true }).unwrap(); + + if remove_after_preparation { + // A new job sees the deleted record and verifies that its old DNG is still intact. + job = ImportJob::new(&mut session, opts.clone()).unwrap(); + } else { + // The original job must not mistake a previous batch's input alias for a catalog hash. + std::fs::remove_file(&old).unwrap(); + } + let second = job.prepare(&source[1..], &cancel); + if remove_after_preparation { + std::fs::remove_file(&old).unwrap(); + } + let r = commit_prepared(&mut session, &opts, job.now(), second).unwrap(); + assert_eq!(r.restored, [id.0], "{r:?}"); + assert!(r.failed.is_empty() && r.imported.is_empty(), "{r:?}"); + let photo = session.catalog.photo(id).unwrap(); + let Source::File { path } = &photo.source else { panic!("file photo") }; + assert_eq!(Path::new(path).extension().unwrap(), "dng"); + assert_eq!(std::fs::read(path).unwrap(), output); + assert_eq!(photo.content_hash, Some(lightcraft_preview::hash_bytes(&output).to_string())); + } +} + fn copy_dng_output_names(destination: &Path) -> Vec { let mut files: Vec<_> = std::fs::read_dir(destination).unwrap().map(|entry| entry.unwrap().file_name()).collect(); files.sort(); From f9c5de7b1ddc1cc5b46c039974538795c0fd59ac Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:06:54 +0100 Subject: [PATCH 21/42] DNG Restore: verify path hits and preserve current source facts --- crates/engine/src/cmd/convert.rs | 3 ++ crates/engine/src/import/commit.rs | 15 ++++++-- crates/engine/src/import/job.rs | 57 ++++++++++++++++++++++++---- crates/engine/src/tests/import.rs | 60 ++++++++++++++++++++++++++++-- 4 files changed, 120 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 2b7e21f22d3..8cc2d2b928c 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -103,6 +103,9 @@ fn convert(s: &mut Session, p: &Value) -> Result { }); ops.extend(content_facts_op(c.id, c, &info.format, &info)); ops.extend(reload_wb_op(c, &info, &info.meta.camera)); + if info.embedded_lens.as_ref() != c.embedded_lens.as_deref() { + ops.push(Op::SetEmbeddedLens { id: c.id, lens: info.embedded_lens.clone().map(Box::new) }); + } } converted.push(json!({"id": id.0, "path": out, "original": path})); } diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 8b3e0adaf10..704fc37531c 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -230,8 +230,8 @@ fn trashed_file_differs(photo: &Photo, hash: Option<&str>, check: Option<&Restor } match check { Some(check) if check.path == *path && Some(check.hash.as_str()) == hash => check.stamp.is_none() || restore_stamp(path) != check.stamp, - // The catalog changed after preparation. Prefer the verified matching input. - _ => true, + // This photo moved or was deleted after the worker captured the catalog. + _ => crate::cmd::missing::file_hash(path).as_deref() != hash, } } @@ -302,6 +302,7 @@ fn ready_duplicate( { crate::import_move::rollback(placed); } + added.extend(ready.input_hash.iter().map(|h| (h.clone(), id))); if ready.placed.is_none() && !same_path && !relocate @@ -311,7 +312,6 @@ fn ready_duplicate( { return PreparedItem::Failed(ready.path, format!("could not remove duplicate output {}: {e}", ready.stored)); } - added.extend(ready.input_hash.into_iter().map(|h| (h, id))); PreparedItem::Duplicate { path: if relocate { ready.stored } else { ready.path }, existing: Some(id), @@ -409,6 +409,15 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare match trashed { // (browsing a folder in Local only looks: it never restores) Some(id) if opts.on_deleted == OnDeleted::Restore && !opts.local => { + if reason == "path" + && !cfg!(target_arch = "wasm32") + && let Some(photo) = s.catalog.photo(id) + && let Some(expected) = photo.content_hash.as_deref() + && crate::cmd::missing::file_hash(&path).as_deref() != Some(expected) + { + report.failed.push((path, "the file at this deleted photo's path has changed".into())); + continue; + } if !report.restored.contains(&id.0) { ops.push(Op::SetDeleted { id, deleted: false }); let relink = match restore { diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index b2d261c7742..4738cfec194 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -81,15 +81,40 @@ pub struct Prepared { pub(super) struct RestoreCheck { pub(super) path: String, pub(super) hash: String, - pub(super) stamp: Option<(u64, std::time::SystemTime)>, + pub(super) stamp: Option, + // Windows does not expose the file change time through stable Rust. Hold the original + // open without write or delete sharing from verification through catalog reconciliation. + #[cfg(windows)] + _read_guard: Option, } -pub(super) fn restore_stamp(path: &str) -> Option<(u64, std::time::SystemTime)> { +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct RestoreStamp { + len: u64, + modified: std::time::SystemTime, + #[cfg(unix)] + identity: (u64, u64, i64, i64), + #[cfg(windows)] + created: u64, +} + +pub(super) fn restore_stamp(path: &str) -> Option { + #[cfg(unix)] + use std::os::unix::fs::MetadataExt; + #[cfg(windows)] + use std::os::windows::fs::MetadataExt; let meta = std::fs::metadata(path).ok()?; if !meta.is_file() { return None; } - Some((meta.len(), meta.modified().ok()?)) + Some(RestoreStamp { + len: meta.len(), + modified: meta.modified().ok()?, + #[cfg(unix)] + identity: (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec()), + #[cfg(windows)] + created: meta.creation_time(), + }) } #[derive(Debug)] @@ -230,8 +255,7 @@ pub fn backup_refusal(s: &Session, opts: &ImportOptions) -> Option { } pub(super) fn normalize_import_path(path: &str) -> String { - let path = path.replace('\\', "/"); - if cfg!(windows) { path.to_lowercase() } else { path } + if cfg!(windows) { path.replace('\\', "/").to_lowercase() } else { path.to_owned() } } impl ImportJob { @@ -390,6 +414,8 @@ impl ImportJob { use std::sync::atomic::Ordering::Relaxed; for (f, verdict) in files.into_iter().zip(verdicts) { match self.by_path.get(f.as_str()).cloned() { + // A known deleted path is only a candidate. Its bytes might belong to another photo now. + Some((id, _, _)) if !local && self.restore_sources.contains_key(&id) => todo.push(f), Some((id, true, hash)) if !local => match verdict { // ✕ before its size was looked at: nothing is decided about it, so it isn't promoted Some(BrowsedFile::Unchecked) => {} @@ -716,9 +742,24 @@ impl ImportJob { let Some(id) = id else { continue }; let Some((path, hash)) = self.restore_sources.get(&id) else { continue }; out.restore_checks.entry(id).or_insert_with(|| { - let stamp = restore_stamp(path) - .filter(|stamp| crate::cmd::missing::file_hash(path).as_deref() == Some(hash) && restore_stamp(path) == Some(*stamp)); - RestoreCheck { path: path.clone(), hash: hash.clone(), stamp } + #[cfg(windows)] + let read_guard = { + use std::os::windows::fs::OpenOptionsExt; + const FILE_SHARE_READ: u32 = 1; + std::fs::OpenOptions::new().read(true).share_mode(FILE_SHARE_READ).open(path).ok() + }; + let stamp = restore_stamp(path); + #[cfg(windows)] + let stamp = stamp.filter(|_| read_guard.is_some()); + let stamp = + stamp.filter(|stamp| crate::cmd::missing::file_hash(path).as_deref() == Some(hash) && restore_stamp(path) == Some(*stamp)); + RestoreCheck { + path: path.clone(), + hash: hash.clone(), + stamp, + #[cfg(windows)] + _read_guard: read_guard, + } }); } } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index a37029a26e5..e63335f3202 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5535,8 +5535,8 @@ fn assert_copy_as_dng_restores(s: &mut Session, id: PhotoId, paths: &[String], o fn copy_as_dng_restore_uses_the_verified_output_across_batches() { use crate::import::{ImportJob, ImportMode, ImportOptions, Organize, commit_prepared}; use lightcraft_catalog::{Op, Source}; - for remove_after_preparation in [false, true] { - let dir = super::TestDir::new(&format!("copy-dng-restore-batch-{remove_after_preparation}")); + for case in if cfg!(unix) { &[0, 1, 2][..] } else { &[0][..] } { + let dir = super::TestDir::new(&format!("copy-dng-restore-batch-{case}")); let destination = dir.join("copies"); let source = ["first.nef", "second.nef"].map(|name| dir.join(name).to_string_lossy().into_owned()); let raw = crate::tests_xmp::synthetic_dng_with(None, Default::default()); @@ -5561,7 +5561,7 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { assert_ne!(output, raw); session.catalog.apply(Op::SetDeleted { id, deleted: true }).unwrap(); - if remove_after_preparation { + if *case != 0 { // A new job sees the deleted record and verifies that its old DNG is still intact. job = ImportJob::new(&mut session, opts.clone()).unwrap(); } else { @@ -5569,8 +5569,17 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { std::fs::remove_file(&old).unwrap(); } let second = job.prepare(&source[1..], &cancel); - if remove_after_preparation { + if *case == 1 { std::fs::remove_file(&old).unwrap(); + } else if *case == 2 { + use std::io::Write; + let mtime = std::fs::metadata(&old).unwrap().modified().unwrap(); + let mut different = output.clone(); + different[0] ^= 1; + let mut f = std::fs::File::create(&old).unwrap(); + f.write_all(&different).unwrap(); + f.set_modified(mtime).unwrap(); + assert_eq!(std::fs::metadata(&old).unwrap().modified().unwrap(), mtime); } let r = commit_prepared(&mut session, &opts, job.now(), second).unwrap(); assert_eq!(r.restored, [id.0], "{r:?}"); @@ -5583,6 +5592,49 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { } } +#[test] +fn a_reused_deleted_path_does_not_claim_a_dng_restore() { + use crate::import::{ImportMode, ImportOptions, Organize}; + use lightcraft_catalog::Op; + let dir = super::TestDir::new("dng-restore-reused"); + let input = dir.join("incoming.nef"); + let raw = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + std::fs::write(&input, raw).unwrap(); + let destination = dir.join("copies"); + let opts = ImportOptions { + mode: ImportMode::Copy, + destination: Some(destination.to_string_lossy().into()), + organize: Organize::Flat, + convert_dng: true, + ..Default::default() + }; + let input = input.to_string_lossy().into_owned(); + let mut s = Session::new().with_fs(); + let report = crate::import::import_with(&mut s, std::slice::from_ref(&input), &opts).unwrap(); + let id = PhotoId(report.imported[0]); + let old = file_source_path(s.catalog.photo(id).unwrap()); + let wanted = std::fs::read(&old).unwrap(); + s.catalog.apply(Op::SetDeleted { id, deleted: true }).unwrap(); + let mut changed = lightcraft_raw::decode(&wanted).unwrap(); + let lightcraft_raw::RawData::U16(samples) = &mut changed.data else { panic!("integer fixture") }; + samples[0] ^= 1; + let other = lightcraft_raw::write_dng(&changed, &Default::default()).unwrap(); + std::fs::write(&old, &other).unwrap(); + let report = crate::import::import_with(&mut s, &[old.clone(), input], &opts).unwrap(); + assert_eq!(report.restored, [id.0], "{report:?}"); + let path = file_source_path(s.catalog.photo(id).unwrap()); + assert_ne!(path, old); + assert_eq!(std::fs::read(path).unwrap(), wanted); + assert_eq!(std::fs::read(old).unwrap(), other); +} + +fn file_source_path(p: &lightcraft_catalog::Photo) -> String { + match &p.source { + lightcraft_catalog::Source::File { path } => path.clone(), + _ => panic!("file photo"), + } +} + fn copy_dng_output_names(destination: &Path) -> Vec { let mut files: Vec<_> = std::fs::read_dir(destination).unwrap().map(|entry| entry.unwrap().file_name()).collect(); files.sort(); From d8bb842196fc9c7bc1891d78d256262ec6d6a5c8 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:10:24 +0100 Subject: [PATCH 22/42] Keep failed same-path replacements out of Restore --- crates/engine/src/import/commit.rs | 13 +++++++++++-- crates/engine/src/import/job.rs | 5 ++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 704fc37531c..b326643b1e7 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -293,9 +293,11 @@ fn ready_duplicate( _ => false, }); let relocate = !pending - && !same_path && opts.on_deleted == OnDeleted::Restore && photo.is_some_and(|p| p.deleted && trashed_file_differs(p, ready.info.content_hash.as_deref(), checks.get(&id))); + if relocate && same_path { + return PreparedItem::Failed(ready.path, format!("the verified output at {} changed before Restore", ready.stored)); + } if !relocate && !same_path && let Some(placed) = &ready.placed @@ -419,7 +421,6 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare continue; } if !report.restored.contains(&id.0) { - ops.push(Op::SetDeleted { id, deleted: false }); let relink = match restore { RestoreTarget::Relink => true, RestoreTarget::Keep => false, @@ -430,6 +431,14 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare .is_some_and(|p| trashed_file_differs(p, hash.as_deref(), prepared.restore_checks.get(&id))) } }; + if relink + && let Some(Source::File { path: existing }) = s.catalog.photo(id).map(|p| &p.source) + && same_import_file(existing, &path) + { + report.failed.push((path, "the file changed before Restore".into())); + continue; + } + ops.push(Op::SetDeleted { id, deleted: false }); if relink && !s.catalog.photos().any(|p| p.id != id && matches!(&p.source, Source::File { path: held } if *held == path)) { diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 4738cfec194..aeade141b17 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -415,7 +415,10 @@ impl ImportJob { for (f, verdict) in files.into_iter().zip(verdicts) { match self.by_path.get(f.as_str()).cloned() { // A known deleted path is only a candidate. Its bytes might belong to another photo now. - Some((id, _, _)) if !local && self.restore_sources.contains_key(&id) => todo.push(f), + Some((id, _, _)) if !local && self.restore_sources.contains_key(&id) => { + self.cache.remove(&f); + todo.push(f); + } Some((id, true, hash)) if !local => match verdict { // ✕ before its size was looked at: nothing is decided about it, so it isn't promoted Some(BrowsedFile::Unchecked) => {} From 2f43eca92b562d8318468f8cc97ff6bffec6c348 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:19:31 +0100 Subject: [PATCH 23/42] DNG conversion: preserve independently relinked virtual copies --- crates/engine/src/cmd/convert.rs | 4 ++-- crates/engine/src/tests/import.rs | 28 +++++++++++++++++++++++----- docs/parity-checklist.md | 2 +- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index 8cc2d2b928c..da6a2585cab 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -92,8 +92,8 @@ fn convert(s: &mut Session, p: &Value) -> Result { match write_dng_for(s, path, packet) { Ok((out, info)) => { let file_name = Path::new(&out).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); - // virtual copies of this photo follow it to the DNG - for c in s.catalog.photos().filter(|c| c.copy_of == Some(id)).chain(std::iter::once(&ph)) { + // Copies that read this file follow its conversion. Independently relinked copies keep their own source. + for c in s.catalog.photos().filter(|c| c.copy_of == Some(id) && shares_reload_source(c, &ph)).chain(std::iter::once(&ph)) { ops.push(Op::Relink { id: c.id, file_name: file_name.clone(), diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index e63335f3202..0fbdbc52d80 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5348,8 +5348,22 @@ fn convert_to_dng_refreshes_copy_classification_and_undo_redo() { .unwrap(); let copy = s.execute("photo.virtualCopy", &json!({"ids": [parent.0]})).unwrap(); let copy = PhotoId(copy["ids"][0].as_u64().unwrap()); - s.execute("photo.relink", &json!({"id": copy.0, "path": png.to_string_lossy()})).unwrap(); + let independent = s.execute("photo.virtualCopy", &json!({"ids": [parent.0]})).unwrap(); + let independent = PhotoId(independent["ids"][0].as_u64().unwrap()); + s.execute("photo.relink", &json!({"id": independent.0, "path": png.to_string_lossy()})).unwrap(); + let independent_before = s.catalog.photo(independent).unwrap().clone(); + let shared = s.catalog.photo(copy).unwrap(); + s.catalog + .apply(Op::Relink { + id: copy, + file_name: shared.file_name.clone(), + source: shared.source.clone(), + format: Some("PNG".into()), + kind: Some(MediaKind::Image), + }) + .unwrap(); s.catalog.apply(Op::SetAsShotWb { id: copy, wb: None }).unwrap(); + s.catalog.apply(Op::SetEmbeddedLens { id: copy, lens: Some(Box::default()) }).unwrap(); s.execute("develop.set", &json!({"ids": [copy.0], "control": "light.exposure", "value": 0.4})).unwrap(); let before = s.catalog.photo(copy).unwrap().clone(); let parent_before = s.catalog.photo(parent).unwrap().clone(); @@ -5357,22 +5371,26 @@ fn convert_to_dng_refreshes_copy_classification_and_undo_redo() { let converted = s.execute("photo.convertToDng", &json!({"ids": [parent.0]})).unwrap(); assert_eq!(converted["converted"].as_array().unwrap().len(), 1, "{converted}"); let output = Source::File { path: converted["converted"][0]["path"].as_str().unwrap().into() }; - let output_wb = - crate::files::probe_bytes("converted.dng", &std::fs::read(converted["converted"][0]["path"].as_str().unwrap()).unwrap()).unwrap().as_shot_wb; - assert!(output_wb.is_some()); + let output_info = + crate::files::probe_bytes("converted.dng", &std::fs::read(converted["converted"][0]["path"].as_str().unwrap()).unwrap()).unwrap(); + assert!(output_info.as_shot_wb.is_some()); for id in [parent, copy] { let photo = s.catalog.photo(id).unwrap(); assert_eq!((photo.kind, photo.format.as_str()), (MediaKind::Raw, "DNG"), "known DNG output is always raw"); assert_eq!(photo.source, output); - assert_eq!(photo.as_shot_wb, output_wb, "every relinked record uses the generated DNG's As Shot facts"); + assert_eq!(photo.as_shot_wb, output_info.as_shot_wb, "every relinked record uses the generated DNG's As Shot facts"); + assert_eq!(photo.embedded_lens.as_deref(), output_info.embedded_lens.as_ref()); } + assert_eq!(s.catalog.photo(independent).unwrap(), &independent_before); let after = s.catalog.photo(copy).unwrap().clone(); assert_eq!(after.develop, before.develop); s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.catalog.photo(copy).unwrap(), &before); assert_eq!(s.catalog.photo(parent).unwrap(), &parent_before); + assert_eq!(s.catalog.photo(independent).unwrap(), &independent_before); s.execute("edit.redo", &json!({})).unwrap(); assert_eq!(s.catalog.photo(copy).unwrap(), &after); + assert_eq!(s.catalog.photo(independent).unwrap(), &independent_before); } #[test] diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 0f7abefffb7..6686ce74228 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -726,7 +726,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-COMMENTS | Comments panel | P2 | ⬜ | | | | LRC-LIB-VISUALSEARCH | Find similar photos | P2 | ✅ | `cmd:library.findSimilar`, `crates/pipeline/src/cull.rs` (`signature`), `crates/engine/src/cmd/similar.rs`, `crates/ui-egui/src/find_similar.rs` | photo menu / Photo ▸ Find Similar Photos: look-alike photos (composition and tones), most similar first, as a filter (`only`); the app reads the photos on a worker thread under an activity row with ✕ | | LRC-LIB-MISSING | Missing files & relink | P1 | ✅ | `cmd:library.missing`, `cmd:photo.relink`, `cmd:library.findMissing`, `cmd:file.findMissing`, `cmd:photo.locate`, `crates/engine/src/cmd/missing.rs`, `crates/catalog/src/model.rs` (`Photo::library_file`), `crates/ui-egui/src/missing_sweep.rs`, `crates/ui-egui/src/panels/left.rs` (`locate_missing_item`), `crates/ui-egui/src/thumb.rs` | File → Find Missing Photos… (anywhere in a folder: same name, size and content hash; renamed files by size + content hash; same name and size alone only when unambiguous — look-alikes are skipped and reported; searched on a worker thread, one undo step), photo menu → Locate Missing File…; a folder or disk row's Locate Missing Files… chooses its new location and scopes the same recursive background finder to that folder and its subfolders. Unreadable files show a warning icon in the grid and the filmstrip (widgets `badge:failed:`, `film:failed:`) whose tooltip says why and where to go (Locate Missing File… for a missing original, else Reload from Disk), and a reason in the loupe; undo never moves files. Missing Photos in the sidebar (counted on a worker thread; the view, the Info panel, the grid's context menu and thumbnails read file availability from a cache a worker thread fills, so an offline NAS never stalls a frame); it covers library photos only — Local browse records are never checked, for the count, the view, `library.missing` and Find Missing alike | -| LRC-LIB-CONVERT | Convert to DNG | P2 | ✅ | `cmd:photo.convertToDng`, `crates/engine/src/cmd/convert.rs` | Photo ▸ Convert to DNG: lossless DNG next to the raw with the settings embedded, photo (and its virtual copies) relinked; originals kept; undoable; the DNG is decoded and compared with the raw data, written to a temp file, synced, read back and only then given a free name (never replacing a file) — a failed write leaves no DNG and the photo on its raw (issue #106) | +| LRC-LIB-CONVERT | Convert to DNG | P2 | ✅ | `cmd:photo.convertToDng`, `crates/engine/src/cmd/convert.rs` | Photo ▸ Convert to DNG: lossless DNG next to the raw with the settings embedded, photo and its same-file virtual copies relinked; originals kept; undoable; the DNG is decoded and compared with the raw data, written to a temp file, synced, read back and only then given a free name (never replacing a file) — a failed write leaves no DNG and the photo on its raw (issue #106) | | LRC-LIB-PREVIEWS | Build / discard previews | P1 | ✅ | `cmd:library.buildPreviews`, `cmd:library.previewProgress`, `cmd:library.cancelPreviews`, `cmd:library.clearPreviews`, `crates/engine/src/cmd/previews.rs`, `crates/preview/src/lib.rs`, `crates/engine/src/tests/preview_prep.rs` | File ▸ Previews: build standard-sized (as big as the loupe shows photos on this screen, at least 2048 px, or the Settings → Performance size) or 1:1 previews of the selected photos (more than one) or every photo in view, in the background (a row in the activity stack, ✕ to stop), discard the cache; disk thumbnail + view cache. The loupe shows a built preview that is big enough as the photo (fitted down, no render); a build skips photos whose previews are there and writes each to disk before it counts it; the disk cache's automatic size makes room for every photo of the library (about 1.5 MB a photo, no ceiling: a low drive is told once per session, see LR-PREF-LOCALSTORAGE), and memory for previews follows the memory budget | | LRC-PERF-PREP | Prepare photos in the background (beyond Lightroom) | P1 | 🟡 | `cmd:prefs.backgroundPrep`, `cmd:prefs.setBackgroundPrep`, `crates/engine/src/prep.rs`, `crates/ui-egui/src/dialogs/settings/performance.rs` | Settings ▸ Performance ▸ Prepare photos in the background, per mode (Culling, Library, Editing), app-wide or for one library: previews of every photo in view built in the spare time once the user steps through photos (yields to the photo on screen, nearest photos first in the direction of travel, one cancellable row), photos ahead rendered for the loupe (0 = off), eye focus strips ahead, which photos (every / picks, rated and labelled / only the one on screen); editing keeps the next photos decoded. Not yet: face detection, AI masks and AI Denoise as background jobs of these settings (they keep their own switches) | | LRC-LIB-SLIDESHOW-IMPROMPTU | Impromptu slideshow | P2 | ✅ | `cmd:view.slideshow` | see LR-VIEW-SLIDESHOW | From faf141bbe7a59a94987a84a6982f6fe753c532a1 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:35:29 +0100 Subject: [PATCH 24/42] DNG Restore: verify output ownership and defer redundant copy cleanup --- crates/catalog/src/safe_file.rs | 51 +++++--- crates/engine/src/cmd/convert.rs | 8 +- crates/engine/src/import/commit.rs | 179 ++++++++++++++++++++++------- crates/engine/src/import/files.rs | 5 +- crates/engine/src/import/job.rs | 98 +++++++++++++--- crates/engine/src/import_move.rs | 33 +++--- crates/engine/src/tests/import.rs | 57 ++++++++- crates/engine/src/tests/xmp.rs | 2 +- 8 files changed, 334 insertions(+), 99 deletions(-) diff --git a/crates/catalog/src/safe_file.rs b/crates/catalog/src/safe_file.rs index 2ed0acb5e19..7ae10a7024b 100644 --- a/crates/catalog/src/safe_file.rs +++ b/crates/catalog/src/safe_file.rs @@ -28,7 +28,7 @@ use std::cell::Cell; use std::fs::{self, File, OpenOptions}; -use std::io::{self, Write}; +use std::io::{self, Seek, Write}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -117,7 +117,7 @@ fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> { let dir = parent_of(path); for _ in 0..1000 { let tmp = dir.join(format!(".lightcraft-{}-{}.tmp", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); - match OpenOptions::new().write(true).create_new(true).open(&tmp) { + match OpenOptions::new().read(true).write(true).create_new(true).open(&tmp) { Ok(f) => return Ok((tmp, f)), Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, Err(e) => return Err(e), @@ -127,8 +127,8 @@ fn create_temp(path: &Path) -> io::Result<(PathBuf, File)> { } /// Write a temp file next to `path` with what `fill` writes, synced to disk when `sync`. On -/// failure the temp file is removed. Returns its path and length. -fn write_temp(path: &Path, sync: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result<(PathBuf, u64)> { +/// failure the temp file is removed. Returns its path, length and open handle. +fn write_temp(path: &Path, sync: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result<(PathBuf, u64, File)> { let (tmp, file) = create_temp(path)?; let r = (|| { let limit = FAIL_AFTER.with(Cell::get); @@ -140,10 +140,10 @@ fn write_temp(path: &Path, sync: bool, fill: &mut dyn FnMut(&mut dyn Write) -> i if sync { sync_file(&f)?; } - Ok(n) + Ok((n, f)) })(); match r { - Ok(n) => Ok((tmp, n)), + Ok((n, file)) => Ok((tmp, n, file)), Err(e) => { let _ = fs::remove_file(&tmp); Err(e) @@ -172,7 +172,8 @@ pub fn write_atomic_nosync(path: &Path, data: &[u8]) -> io::Result<()> { /// Temp file (synced when `sync`) renamed over `path`, then the folder synced when `sync`. fn replace_with(path: &Path, sync: bool, fill: &mut dyn FnMut(&mut dyn Write) -> io::Result<()>) -> io::Result { - let (tmp, n) = write_temp(path, sync, fill)?; + let (tmp, n, file) = write_temp(path, sync, fill)?; + drop(file); if let Err(e) = fs::rename(&tmp, path) { let _ = fs::remove_file(&tmp); return Err(e); @@ -193,16 +194,22 @@ pub fn write_new(path: &Path, data: &[u8]) -> io::Result<()> { /// `IMG_1.dng`, `IMG_1-2.dng`, …): the file is written once and then given the first name that /// is not taken. Returns that name; `AlreadyExists` when every candidate is taken. pub fn write_new_unique(candidates: &mut dyn Iterator, data: &[u8]) -> io::Result { + write_new_unique_open(candidates, data).map(|(path, _)| path) +} + +/// Like [`write_new_unique`], also returns the verified file handle so a caller can track the +/// file it created even if the name is reused later. +pub fn write_new_unique_open(candidates: &mut dyn Iterator, data: &[u8]) -> io::Result<(PathBuf, File)> { let mut candidates = candidates.peekable(); let Some(first) = candidates.peek().cloned() else { return Err(io::Error::new(io::ErrorKind::InvalidInput, "no file name to write")); }; - let (tmp, _) = write_temp(&first, true, &mut |w| w.write_all(data))?; + let (tmp, _, mut file) = write_temp(&first, true, &mut |w| w.write_all(data))?; let r = (|| { // Kept (issue #134 point 4): these files replace raws (Convert / Copy as DNG) or become // library photos (merges). On a local disk the read usually comes from the cache, but on a // network volume it can go back to the server, and next to encoding a DNG it costs little. - if !same_content(&tmp, data)? { + if !same_content(&mut file, data)? { return Err(io::Error::other("the written file reads back different (failing drive or connection?)")); } for path in candidates.by_ref().take(100_000) { @@ -219,7 +226,7 @@ pub fn write_new_unique(candidates: &mut dyn Iterator, data: &[u })(); // after a hard link the temp name is a second name of the new file; after a rename it's gone let _ = fs::remove_file(&tmp); - r + r.map(|path| (path, file)) } /// Give the complete temp file `tmp` the name `path`, unless that is taken. @@ -245,10 +252,10 @@ fn publish_new_by_rename(tmp: &Path, path: &Path, before_claim: &dyn Fn()) -> io Ok(()) } -/// Does the file at `path` hold exactly `data`? -fn same_content(path: &Path, data: &[u8]) -> io::Result { +/// Does the open file hold exactly `data`? +fn same_content(f: &mut File, data: &[u8]) -> io::Result { use std::io::Read; - let mut f = File::open(path)?; + f.rewind()?; if f.metadata()?.len() != data.len() as u64 { return Ok(false); } @@ -268,6 +275,13 @@ fn same_content(path: &Path, data: &[u8]) -> io::Result { } } +/// Volume and file number of an opened file on Windows, when the file system supplies both. +#[cfg(windows)] +pub fn open_file_id(file: &File) -> Option<(u64, u64)> { + let (volume, index) = windows_file_id(file).ok()?; + (index != 0).then_some((volume, index)) +} + /// Do `a` and `b` name the same existing file (through hard links, symlinks, `..`, /// case-insensitive names)? pub fn same_file(a: &Path, b: &Path) -> bool { @@ -322,10 +336,15 @@ fn compare_files(a: &Path, b: &Path, strict: bool) -> io::Result { /// The volume serial number and file index of `a` and `b`, read while both files are open. #[cfg(windows)] fn file_ids(a: &Path, b: &Path) -> io::Result<((u64, u64), (u64, u64))> { - use winapi_util::{Handle, file::information}; + use winapi_util::Handle; let (ha, hb) = (Handle::from_path_any(a)?, Handle::from_path_any(b)?); - let (ia, ib) = (information(&ha)?, information(&hb)?); - Ok(((ia.volume_serial_number(), ia.file_index()), (ib.volume_serial_number(), ib.file_index()))) + Ok((windows_file_id(&ha)?, windows_file_id(&hb)?)) +} + +#[cfg(windows)] +fn windows_file_id(file: impl winapi_util::AsHandleRef) -> io::Result<(u64, u64)> { + let info = winapi_util::file::information(file)?; + Ok((info.volume_serial_number(), info.file_index())) } /// The comparison uses each file's volume serial number and file index. Strict mode returns an error for file index 0. diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index da6a2585cab..e242f3194b2 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -26,7 +26,7 @@ fn dng_names(path: &str) -> impl Iterator { /// written to a temp file, synced, read back identical and only then given its name — never /// replacing an existing file. On any failure no DNG is left behind and the raw stays in use. pub(crate) fn write_dng_for(s: &Session, path: &str, packet: String) -> std::result::Result<(String, crate::media::ProbeInfo), String> { - write_dng_with(s.media.file_bytes.as_ref(), path, packet) + write_dng_with(s.media.file_bytes.as_ref(), path, packet).map(|(path, info, _)| (path, info)) } /// [`write_dng_for`] without the session (imports convert on a worker thread). @@ -34,7 +34,7 @@ pub(crate) fn write_dng_with( file_bytes: Option<&crate::merge::ByteReader>, path: &str, packet: String, -) -> std::result::Result<(String, crate::media::ProbeInfo), String> { +) -> std::result::Result<(String, crate::media::ProbeInfo, std::fs::File), String> { let bytes = match file_bytes { Some(r) => r(path)?, None => std::fs::read(path).map_err(|e| format!("{path}: {e}"))?, @@ -58,9 +58,9 @@ pub(crate) fn write_dng_with( drop((raw, back)); // Generated bytes need their own identity; retaining the raw's hash can reuse unrelated proxies. let info = crate::files::probe_bytes("converted.dng", &dng)?; - let out = lightcraft_catalog::safe_file::write_new_unique(&mut dng_names(path), &dng) + let (out, file) = lightcraft_catalog::safe_file::write_new_unique_open(&mut dng_names(path), &dng) .map_err(|e| format!("{path}: could not write its DNG ({e}); the raw is kept"))?; - Ok((out.to_string_lossy().to_string(), info)) + Ok((out.to_string_lossy().to_string(), info, file)) } fn convert(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index b326643b1e7..9459373c10d 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -1,6 +1,6 @@ use super::defaults::apply_import_defaults; use super::files::copy_into; -use super::job::{Prepared, PreparedItem, ReadyFile, RestoreCheck, RestoreTarget, normalize_import_path, restore_stamp}; +use super::job::{CopyOutput, Prepared, PreparedItem, ReadyFile, RestoreCheck, RestoreTarget, normalize_import_path, restore_stamp}; use super::types::{BackupCopy, Duplicate, FileFacts, ImportOptions, ImportReport, Kept, Moved, OnDeleted}; use super::{HashMap, Op, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source}; @@ -144,6 +144,7 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P let Transfer { path, mut info, sidecar, dir, how, dng, backup } = t; let mut input_hash = None; let mut placed = None; + let mut copy = None; let mut stored = match how { How::Place { name } => match crate::import_move::place(Path::new(&path), &dir, &name) { Ok(pl) => { @@ -154,7 +155,10 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P Err(e) => return PreparedItem::Failed(path, e), }, How::Copy { name } => match copy_into(&dir, &path, name.as_deref(), info.content_hash.as_deref()) { - Ok(p) => p, + Ok((p, file)) => { + copy = Some(CopyOutput::new(file)); + p + } Err(e) => return PreparedItem::Failed(path, e), }, }; @@ -163,9 +167,15 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P let weight = usize::try_from(info.file_size).unwrap_or(usize::MAX).saturating_mul(6); let _permit = crate::memory::work_gate().acquire(weight); match crate::cmd::convert::write_dng_with(file_bytes, &stored, String::new()) { - Ok((dng, output)) => { - let _ = std::fs::remove_file(&stored); + Ok((dng, output, file)) => { + if !copy.as_ref().is_some_and(|c| c.is_current(&stored, info.content_hash.as_deref())) { + return PreparedItem::Failed(path, format!("the copied raw at {stored} changed before cleanup; the DNG at {dng} was kept")); + } + if let Err(e) = std::fs::remove_file(&stored) { + return PreparedItem::Failed(path, format!("could not remove the copied raw at {stored}: {e}; the DNG at {dng} was kept")); + } stored = dng; + copy = Some(CopyOutput::new(file)); // Keep input metadata and XMP, but describe the bytes actually stored. The alias // keeps duplicate input raws identifiable until this import is committed. input_hash = info.content_hash.clone().filter(|h| Some(h) != output.content_hash.as_ref()); @@ -184,7 +194,7 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P } } let backup = backup.map(|(root, to)| back_up(&path, &stored, placed.as_ref(), &root, &to, info.content_hash.as_deref())); - PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash, sidecar, placed, backup })) + PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash, copy, sidecar, placed, backup })) } /// The backup copy of a file an import put at `stored` inside `root` — with a Move's sidecars beside @@ -222,17 +232,24 @@ fn back_up( Ok(copy.to_string_lossy().to_string()) } +fn has_verified_content(path: &str, hash: Option<&str>) -> bool { + let (Some(hash), Some(stamp)) = (hash, restore_stamp(path)) else { return false }; + crate::cmd::missing::file_hash(path).as_deref() == Some(hash) && restore_stamp(path) == Some(stamp) +} + /// Restore follows the matching content when the old name is missing or has been reused. fn trashed_file_differs(photo: &Photo, hash: Option<&str>, check: Option<&RestoreCheck>) -> bool { let Source::File { path } = &photo.source else { return false }; if cfg!(target_arch = "wasm32") || hash.is_none() || photo.content_hash.as_deref() != hash { return false; } - match check { - Some(check) if check.path == *path && Some(check.hash.as_str()) == hash => check.stamp.is_none() || restore_stamp(path) != check.stamp, - // This photo moved or was deleted after the worker captured the catalog. - _ => crate::cmd::missing::file_hash(path).as_deref() != hash, + if check + .is_some_and(|check| check.path == *path && Some(check.hash.as_str()) == hash && check.stamp.is_some() && restore_stamp(path) == check.stamp) + { + return false; } + // A changed stamp can still name the same bytes, and the catalog may have changed since preparation. + !has_verified_content(path, hash) } /// What a new record takes from its file, as a file import gives it: the file's metadata and @@ -273,6 +290,33 @@ fn same_import_file(a: &str, b: &str) -> bool { || std::fs::canonicalize(a).ok().zip(std::fs::canonicalize(b).ok()).is_some_and(|(a, b)| a == b) } +struct RedundantCopy { + path: String, + output: Option, + hash: Option, + restoring: Option, +} + +impl RedundantCopy { + fn remove(self, s: &Session, checks: &HashMap, report: &mut ImportReport) { + if let Some(id) = self.restoring { + let Some(photo) = s.catalog.photo(id).filter(|p| !p.deleted) else { return }; + if photo.library_file().is_some_and(|path| same_import_file(path, &self.path)) { + return; + } + if trashed_file_differs(photo, self.hash.as_deref(), checks.get(&id)) { + report.failed.push((self.path, "the restored source changed; the redundant output was kept".into())); + return; + } + } + if !self.output.is_some_and(|c| c.is_current(&self.path, self.hash.as_deref())) { + report.failed.push((self.path, "the duplicate output changed or could not be identified; cleanup was skipped".into())); + } else if let Err(e) = std::fs::remove_file(&self.path) { + report.failed.push((self.path, format!("could not remove the duplicate output: {e}"))); + } + } +} + // Reconcile hashes learned after conversion, including ordinary files later in the batch. // Only the catalog owner decides whether a redundant output is disposable or restores a missing file. fn ready_duplicate( @@ -281,6 +325,7 @@ fn ready_duplicate( added: &mut HashMap, restored: &[u64], checks: &HashMap, + cleanup: &mut Vec, ready: ReadyFile, ) -> PreparedItem { let existing = ready.info.content_hash.as_ref().and_then(|h| added.get(h).copied()); @@ -292,9 +337,8 @@ fn ready_duplicate( Source::File { path } => same_import_file(path, &ready.stored), _ => false, }); - let relocate = !pending - && opts.on_deleted == OnDeleted::Restore - && photo.is_some_and(|p| p.deleted && trashed_file_differs(p, ready.info.content_hash.as_deref(), checks.get(&id))); + let restoring = opts.on_deleted == OnDeleted::Restore && photo.is_some_and(|p| p.deleted); + let relocate = !pending && restoring && photo.is_some_and(|p| trashed_file_differs(p, ready.info.content_hash.as_deref(), checks.get(&id))); if relocate && same_path { return PreparedItem::Failed(ready.path, format!("the verified output at {} changed before Restore", ready.stored)); } @@ -305,21 +349,26 @@ fn ready_duplicate( crate::import_move::rollback(placed); } added.extend(ready.input_hash.iter().map(|h| (h.clone(), id))); - if ready.placed.is_none() - && !same_path - && !relocate + let restore = if relocate { + RestoreTarget::Relink(ready.copy) + } else { // Add entries retain their original path, including aliases. - && !same_import_file(&ready.path, &ready.stored) - && let Err(e) = std::fs::remove_file(&ready.stored) - { - return PreparedItem::Failed(ready.path, format!("could not remove duplicate output {}: {e}", ready.stored)); - } + if ready.placed.is_none() && !same_path && !same_import_file(&ready.path, &ready.stored) { + cleanup.push(RedundantCopy { + path: ready.stored.clone(), + output: ready.copy, + hash: ready.info.content_hash.clone(), + restoring: restoring.then_some(id), + }); + } + RestoreTarget::Keep + }; PreparedItem::Duplicate { path: if relocate { ready.stored } else { ready.path }, existing: Some(id), reason: "content", hash: ready.info.content_hash, - restore: if relocate { RestoreTarget::Relink } else { RestoreTarget::Keep }, + restore, file: Some(Box::new(FileFacts { meta: ready.info.meta, captured: ready.info.captured, @@ -329,6 +378,13 @@ fn ready_duplicate( } } +fn replacement_is_current(path: &str, hash: Option<&str>, output: Option<&CopyOutput>) -> bool { + match output { + Some(copy) => copy.is_current(path, hash), + None => has_verified_content(path, hash), + } +} + /// The catalog half of an import: add the photos [`ImportJob::prepare`] readied (one undoable op; /// a Move's sources are removed once it is saved). On a failed commit a Move's placed files are /// taken back. @@ -337,6 +393,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let mut report = ImportReport { scanned: prepared.scanned, skipped: prepared.skipped, ..Default::default() }; let mut default_denoiser = None; let mut ops = Vec::new(); + let mut cleanup = Vec::new(); // Move: placed at the destination, sources untouched until the records are committed // (with its backup: where it was made, or why it wasn't, so the source stays) let mut placed: Vec<(crate::import_move::Placed, Option>)> = Vec::new(); @@ -375,7 +432,9 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let mut purged: std::collections::HashSet = Default::default(); for it in prepared.items { let it = match it { - PreparedItem::Ready(r) if !opts.local => ready_duplicate(s, opts, &mut new_hash, &report.restored, &prepared.restore_checks, *r), + PreparedItem::Ready(r) if !opts.local => { + ready_duplicate(s, opts, &mut new_hash, &report.restored, &prepared.restore_checks, &mut cleanup, *r) + } it => it, }; match it { @@ -415,35 +474,39 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare && !cfg!(target_arch = "wasm32") && let Some(photo) = s.catalog.photo(id) && let Some(expected) = photo.content_hash.as_deref() - && crate::cmd::missing::file_hash(&path).as_deref() != Some(expected) + && !has_verified_content(&path, Some(expected)) { report.failed.push((path, "the file at this deleted photo's path has changed".into())); continue; } if !report.restored.contains(&id.0) { - let relink = match restore { - RestoreTarget::Relink => true, - RestoreTarget::Keep => false, - RestoreTarget::Decide => { - reason == "content" - && s.catalog - .photo(id) - .is_some_and(|p| trashed_file_differs(p, hash.as_deref(), prepared.restore_checks.get(&id))) + let Some(photo) = s.catalog.photo(id) else { continue }; + let differs = || trashed_file_differs(photo, hash.as_deref(), prepared.restore_checks.get(&id)); + let relink = match &restore { + RestoreTarget::Relink(_) => true, + RestoreTarget::Keep if differs() => { + report.failed.push((path, "the original changed before Restore; the duplicate output was kept".into())); + continue; } + RestoreTarget::Keep => false, + RestoreTarget::Decide => reason == "content" && differs(), }; - if relink - && let Some(Source::File { path: existing }) = s.catalog.photo(id).map(|p| &p.source) - && same_import_file(existing, &path) - { - report.failed.push((path, "the file changed before Restore".into())); - continue; + if relink { + let copy = match &restore { + RestoreTarget::Relink(copy) => copy.as_ref(), + _ => None, + }; + if matches!(&photo.source, Source::File { path: existing } if same_import_file(existing, &path)) + || !replacement_is_current(&path, hash.as_deref(), copy) + { + report.failed.push((path, "the replacement file changed before Restore".into())); + continue; + } + if !s.catalog.photos().any(|p| p.id != id && matches!(&p.source, Source::File { path: held } if *held == path)) { + ops.push(crate::cmd::missing::relink_op(id, &path)); + } } ops.push(Op::SetDeleted { id, deleted: false }); - if relink - && !s.catalog.photos().any(|p| p.id != id && matches!(&p.source, Source::File { path: held } if *held == path)) - { - ops.push(crate::cmd::missing::relink_op(id, &path)); - } report.restored.push(id.0); } } @@ -542,6 +605,11 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare placed.iter().for_each(|(p, _)| crate::import_move::rollback(p)); return Err(e); } + // A failed Restore must leave any verified duplicate available. Remove unused copies only + // after the catalog publishes its choice, and only when their original identity still matches. + for copy in cleanup { + copy.remove(s, &prepared.restore_checks, &mut report); + } if !placed.is_empty() { finish_moves(s, placed, log0, &mut report); } @@ -797,6 +865,31 @@ mod tests { mixed_dng_outputs(false); } + #[test] + fn redundant_dng_is_kept_if_the_restored_source_changes() { + let dir = crate::tests::TestDir::new("redundant-dng-after-restore"); + let path = dir.join("retained.dng").to_string_lossy().into_owned(); + let copy = dir.join("redundant.dng").to_string_lossy().into_owned(); + let content = b"verified DNG"; + let hash = lightcraft_preview::hash_bytes(content).to_string(); + std::fs::write(&path, content).unwrap(); + std::fs::write(©, content).unwrap(); + let output = CopyOutput::new(std::fs::File::open(©).unwrap()); + let mut s = Session::new(); + let id = s.catalog.alloc_photo_id(); + let mut photo = Photo::new(id, Source::File { path: path.clone() }, "retained.dng", "DNG", 1, 1, ""); + photo.content_hash = Some(hash.clone()); + photo.deleted = true; + s.catalog.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap(); + let cleanup = RedundantCopy { path: copy.clone(), output: Some(output), hash: Some(hash), restoring: Some(id) }; + s.commit("Restore", Op::SetDeleted { id, deleted: false }).unwrap(); + std::fs::write(path, b"replaced since restore").unwrap(); + let mut report = ImportReport::default(); + cleanup.remove(&s, &HashMap::new(), &mut report); + assert_eq!(std::fs::read(copy).unwrap(), content); + assert_eq!(report.failed.len(), 1); + } + fn mixed_dng_outputs(converted_first: bool) { for copied in [false, true] { let dir = std::env::temp_dir().join(format!("lc-ready-dng-{converted_first}-{copied}-{}", std::process::id())); @@ -824,6 +917,8 @@ mod tests { stored: stored.to_string_lossy().into(), info: info.clone(), input_hash, + copy: (!same_import_file(&path.to_string_lossy(), &stored.to_string_lossy())) + .then(|| CopyOutput::new(std::fs::File::open(&stored).unwrap())), sidecar: None, placed: None, })) diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index f6843474a6e..7fd27f5308f 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -530,12 +530,12 @@ pub(super) fn browsed_files_changed(files: &[(&str, u64)], cancel: &std::sync::a /// new path. The copy is verified ([`crate::import_move::copy_new`]: a new file, synced and /// checked against `probe_hash`, the content hash the probe computed — or compared byte for byte /// with the source when there is none); a bad one is removed and the photo reported as failed. -pub(super) fn copy_into(dir: &Path, src: &str, name: Option<&str>, probe_hash: Option<&str>) -> Result { +pub(super) fn copy_into(dir: &Path, src: &str, name: Option<&str>, probe_hash: Option<&str>) -> Result<(String, std::fs::File), String> { let name = name .map(str::to_string) .unwrap_or_else(|| Path::new(src).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "photo".into())); let expect = probe_hash.and_then(lightcraft_preview::Hash128::parse); - crate::import_move::copy_new(Path::new(src), dir, &name, expect).map(|p| p.to_string_lossy().to_string()) + crate::import_move::copy_new(Path::new(src), dir, &name, expect).map(|(p, file)| (p.to_string_lossy().to_string(), file)) } #[cfg(test)] @@ -662,6 +662,7 @@ mod prepared_tests { stored: path.to_string_lossy().into(), info: ProbeInfo { format: "JPG".into(), ..ProbeInfo::default() }, input_hash: None, + copy: None, sidecar: None, placed: None, backup: None, diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index aeade141b17..5ace151e0ea 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -98,30 +98,85 @@ pub(super) struct RestoreStamp { created: u64, } +impl RestoreStamp { + fn from_metadata(meta: std::fs::Metadata) -> Option { + #[cfg(unix)] + use std::os::unix::fs::MetadataExt; + #[cfg(windows)] + use std::os::windows::fs::MetadataExt; + if !meta.is_file() { + return None; + } + #[cfg(unix)] + if meta.ino() == 0 { + return None; + } + Some(Self { + len: meta.len(), + modified: meta.modified().ok()?, + #[cfg(unix)] + identity: (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec()), + #[cfg(windows)] + created: meta.creation_time(), + }) + } +} + pub(super) fn restore_stamp(path: &str) -> Option { - #[cfg(unix)] - use std::os::unix::fs::MetadataExt; + RestoreStamp::from_metadata(std::fs::metadata(path).ok()?) +} + +/// Identity from the transfer's own file handle, so another file at its destination is never +/// considered a redundant copy just because the path or bytes match. +#[derive(Debug)] +pub(super) struct CopyOutput { + stamp: Option, #[cfg(windows)] - use std::os::windows::fs::MetadataExt; - let meta = std::fs::metadata(path).ok()?; - if !meta.is_file() { - return None; + identity: Option<(u64, u64)>, +} + +impl CopyOutput { + pub(super) fn new(file: std::fs::File) -> Self { + Self { + stamp: file.metadata().ok().and_then(RestoreStamp::from_metadata), + #[cfg(windows)] + identity: lightcraft_catalog::safe_file::open_file_id(&file), + } } - Some(RestoreStamp { - len: meta.len(), - modified: meta.modified().ok()?, + + pub(super) fn is_current(&self, path: &str, expected: Option<&str>) -> bool { + // In particular, a symlink to the file we wrote is not an output that we own. + let Some(stamp) = std::fs::symlink_metadata(path).ok().and_then(RestoreStamp::from_metadata) else { return false }; #[cfg(unix)] - identity: (meta.dev(), meta.ino(), meta.ctime(), meta.ctime_nsec()), + { + let _ = expected; + Some(stamp) == self.stamp + } #[cfg(windows)] - created: meta.creation_time(), - }) + { + let identity = std::fs::File::open(path).ok().and_then(|f| lightcraft_catalog::safe_file::open_file_id(&f)); + // On Windows the last write time can update when the writer closes, and a later + // writer can restore it. When a content hash is available, check the actual bytes. + identity.is_some() + && identity == self.identity + && self.stamp.is_some_and(|old| old.len == stamp.len) + && expected.map_or(self.stamp == Some(stamp), |hash| { + crate::cmd::missing::file_hash(path).as_deref() == Some(hash) && restore_stamp(path) == Some(stamp) + }) + } + #[cfg(not(any(unix, windows)))] + { + let _ = (self.stamp, stamp, expected); + false + } + } } #[derive(Debug)] pub(super) enum RestoreTarget { Decide, Keep, - Relink, + Relink(Option), } #[derive(Debug)] @@ -150,6 +205,7 @@ pub(super) struct ReadyFile { pub(super) info: ProbeInfo, /// Copy as DNG's original input identity, only for this job's duplicate lookup. pub(super) input_hash: Option, + pub(super) copy: Option, pub(super) sidecar: Option, pub(super) placed: Option, /// [`ImportOptions::backup`]: its backup copy, or why it has none. `None`: no backup asked for. @@ -197,7 +253,7 @@ impl Prepared { items.push(item); continue; }; - let ReadyFile { path, stored, info, input_hash, sidecar, placed, backup } = *ready; + let ReadyFile { path, stored, info, input_hash, copy, sidecar, placed, backup } = *ready; let existing_path = paths.get(&normalize_import_path(&stored)).copied().or_else(|| paths.get(&normalize_import_path(&path)).copied()); let existing_hash = info.content_hash.iter().chain(&input_hash).find_map(|hash| hashes.get(hash).copied()); if let Some(existing) = existing_path.or(existing_hash) { @@ -213,7 +269,7 @@ impl Prepared { file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), }); } else { - items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash, sidecar, placed, backup }))); + items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash, copy, sidecar, placed, backup }))); } } self.items = items; @@ -702,8 +758,16 @@ impl ImportJob { .backup_root .as_ref() .map(|_| Err("already inside the destination or the library: added where it is, so no backup copy was made".into())); - plan.slots - .push(Slot::Item(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash: None, sidecar, placed: None, backup })))); + plan.slots.push(Slot::Item(PreparedItem::Ready(Box::new(ReadyFile { + path, + stored, + info, + input_hash: None, + copy: None, + sidecar, + placed: None, + backup, + })))); } self.run_plan(&mut plan, &mut out, cancel); // Input hashes are aliases only while this batch can resolve them to a verified diff --git a/crates/engine/src/import_move.rs b/crates/engine/src/import_move.rs index 985caeea3d8..0be1bef76d5 100644 --- a/crates/engine/src/import_move.rs +++ b/crates/engine/src/import_move.rs @@ -21,7 +21,7 @@ //! and on Unix it silently replaces an existing destination.) use std::fs::{self, File, OpenOptions}; -use std::io::{self, Read, Write}; +use std::io::{self, Read, Seek, Write}; use std::path::{Path, PathBuf}; /// A photo put in place by [`place`]; its source is untouched. @@ -250,14 +250,14 @@ pub(crate) fn place(src: &Path, dir: &Path, name: &str) -> Result) -> Result { +pub(crate) fn copy_new(src: &Path, dir: &Path, name: &str, expect: Option) -> Result<(PathBuf, File), String> { fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; let (stem, ext) = match name.rsplit_once('.') { Some((s, e)) if !s.is_empty() => (s.to_string(), format!(".{e}")), @@ -266,7 +266,7 @@ pub(crate) fn copy_new(src: &Path, dir: &Path, name: &str, expect: Option return Ok(d), + Ok(file) => return Ok((d, file)), Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, Err(e) => return Err(format!("copy {}: {e} (nothing was imported from it; the original is untouched)", src.display())), } @@ -403,14 +403,14 @@ fn link_or_copy(src: &Path, dst: &Path) -> io::Result<()> { } } // Move keeps the byte-for-byte comparison: the source is deleted on the strength of it - copy_verified(src, dst, None) + copy_verified(src, dst, None).map(|_| ()) } /// Copy into a new file, sync it to disk and verify it: against `expect` (the probe's hash of the /// source) when given, else byte for byte against the source. On any failure the partial copy is /// removed. -pub(crate) fn copy_verified(src: &Path, dst: &Path, expect: Option) -> io::Result<()> { - let mut out = OpenOptions::new().write(true).create_new(true).open(dst)?; +pub(crate) fn copy_verified(src: &Path, dst: &Path, expect: Option) -> io::Result { + let mut out = OpenOptions::new().read(true).write(true).create_new(true).open(dst)?; let r = (|| { let mut inp = File::open(src)?; if injected(Fault::FailWrite) { @@ -430,8 +430,9 @@ pub(crate) fn copy_verified(src: &Path, dst: &Path, expect: Option { + Some(h) if hash_file(&mut out)? != h => { Err(io::Error::other("the copy differs from the original as it was read for the import (a bad copy, or the file changed meanwhile)")) } Some(_) => Ok(()), @@ -439,20 +440,22 @@ pub(crate) fn copy_verified(src: &Path, dst: &Path, expect: Option Ok(()), } })(); - drop(out); - if r.is_err() { - let _ = fs::remove_file(dst); + match r { + Ok(()) => Ok(out), + Err(e) => { + drop(out); + let _ = fs::remove_file(dst); + Err(e) + } } - r } /// [`lightcraft_preview::hash_bytes`] of a file's content, read in chunks. -fn hash_file(path: &Path) -> io::Result { - let mut f = File::open(path)?; +fn hash_file(f: &mut File) -> io::Result { let mut h = lightcraft_preview::Hasher128::new(); let mut buf = vec![0u8; 1 << 20]; loop { - let n = fill(&mut f, &mut buf)?; + let n = fill(f, &mut buf)?; if n == 0 { return Ok(h.finish()); } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 0fbdbc52d80..1ffb9c8a384 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5293,7 +5293,7 @@ fn copy_as_dng_with_local_match(promote: bool) { let dir = super::TestDir::new(&format!("copy-dng-local-output-{promote}")); let input = dir.join("sensor.nef"); std::fs::write(&input, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); - let (generated, _) = crate::cmd::convert::write_dng_with(None, &input.to_string_lossy(), String::new()).unwrap(); + let (generated, _, _) = crate::cmd::convert::write_dng_with(None, &input.to_string_lossy(), String::new()).unwrap(); let browsed = dir.join("browsed.dng"); std::fs::rename(generated, &browsed).unwrap(); let expected = std::fs::read(&browsed).unwrap(); @@ -5553,7 +5553,7 @@ fn assert_copy_as_dng_restores(s: &mut Session, id: PhotoId, paths: &[String], o fn copy_as_dng_restore_uses_the_verified_output_across_batches() { use crate::import::{ImportJob, ImportMode, ImportOptions, Organize, commit_prepared}; use lightcraft_catalog::{Op, Source}; - for case in if cfg!(unix) { &[0, 1, 2][..] } else { &[0][..] } { + for case in if cfg!(unix) { &[0, 1, 2, 3][..] } else { &[0][..] } { let dir = super::TestDir::new(&format!("copy-dng-restore-batch-{case}")); let destination = dir.join("copies"); let source = ["first.nef", "second.nef"].map(|name| dir.join(name).to_string_lossy().into_owned()); @@ -5598,6 +5598,10 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { f.write_all(&different).unwrap(); f.set_modified(mtime).unwrap(); assert_eq!(std::fs::metadata(&old).unwrap().modified().unwrap(), mtime); + } else if *case == 3 { + let mtime = std::fs::metadata(&old).unwrap().modified().unwrap(); + std::fs::File::options().write(true).open(&old).unwrap().set_modified(mtime - std::time::Duration::from_secs(60)).unwrap(); + assert_ne!(std::fs::metadata(&old).unwrap().modified().unwrap(), mtime); } let r = commit_prepared(&mut session, &opts, job.now(), second).unwrap(); assert_eq!(r.restored, [id.0], "{r:?}"); @@ -5607,6 +5611,55 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { assert_eq!(Path::new(path).extension().unwrap(), "dng"); assert_eq!(std::fs::read(path).unwrap(), output); assert_eq!(photo.content_hash, Some(lightcraft_preview::hash_bytes(&output).to_string())); + if *case == 3 { + assert_eq!(path, &old, "a new modification time alone does not move the restored photo"); + assert_eq!(copy_dng_output_names(&destination).len(), 1); + } + } +} + +#[test] +fn copy_as_dng_preserves_a_replaced_duplicate_output_and_refuses_it_for_restore() { + use crate::import::{ImportJob, ImportMode, ImportOptions, Organize, commit_prepared}; + use lightcraft_catalog::Op; + for deleted in [false, true] { + let dir = super::TestDir::new(&format!("copy-dng-replaced-output-{deleted}")); + let destination = dir.join("copies"); + let first = dir.join("first.nef").to_string_lossy().into_owned(); + let second = dir.join("second.nef").to_string_lossy().into_owned(); + let raw = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + for path in [&first, &second] { + std::fs::write(path, &raw).unwrap(); + } + let mut session = Session::new().with_fs(); + let opts = ImportOptions { + mode: ImportMode::Copy, + destination: Some(destination.to_string_lossy().into()), + organize: Organize::Flat, + convert_dng: true, + ..Default::default() + }; + let report = crate::import::import_with(&mut session, &[first], &opts).unwrap(); + let id = PhotoId(report.imported[0]); + let original = file_source_path(session.catalog.photo(id).unwrap()); + if deleted { + session.catalog.apply(Op::SetDeleted { id, deleted: true }).unwrap(); + std::fs::remove_file(&original).unwrap(); + } + let mut job = ImportJob::new(&mut session, opts.clone()).unwrap(); + let batch = job.prepare(&[second], &std::sync::atomic::AtomicBool::new(false)); + let generated = destination.join("second.dng"); + let displaced = dir.join("displaced.dng"); + std::fs::rename(&generated, &displaced).unwrap(); + // A byte-identical replacement is still somebody else's file. + let bytes = std::fs::read(&displaced).unwrap(); + std::fs::write(&generated, &bytes).unwrap(); + let report = commit_prepared(&mut session, &opts, job.now(), batch).unwrap(); + assert_eq!(report.failed.len(), 1, "{report:?}"); + assert!(report.restored.is_empty() && report.imported.is_empty(), "{report:?}"); + assert_eq!(std::fs::read(&generated).unwrap(), bytes); + let photo = session.catalog.photo(id).unwrap(); + assert_eq!((photo.deleted, file_source_path(photo)), (deleted, original)); } } diff --git a/crates/engine/src/tests/xmp.rs b/crates/engine/src/tests/xmp.rs index ff234802ae1..8ca790fd335 100644 --- a/crates/engine/src/tests/xmp.rs +++ b/crates/engine/src/tests/xmp.rs @@ -1860,7 +1860,7 @@ fn dngs_of_raws_without_colour_matrices_carry_the_colour_they_open_with() { Ok(()) }; crate::export::export_batch(&mut s, &[id], &o, &crate::export::Destination { dir: "x".into(), exact: None }, &mut write, &|_| false).unwrap(); - let (converted, _) = crate::cmd::convert::write_dng_with(None, &path.to_string_lossy(), String::new()).unwrap(); + let (converted, _, _) = crate::cmd::convert::write_dng_with(None, &path.to_string_lossy(), String::new()).unwrap(); for (how, dng) in [("export", exported), ("convert", std::fs::read(&converted).unwrap())] { let back = lightcraft_raw::decode(&dng).unwrap(); assert!(back.color.color_matrix[0].is_some() && back.color.illuminant[0] != 0, "{model} {how}: {:?}", back.color); From 9548172c9cec1a1396e2f00f37c6ba62f4bd6aba Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:42:32 +0100 Subject: [PATCH 25/42] Restore verified legacy DNGs and preserve database lens corrections --- crates/engine/src/cmd/convert.rs | 31 ++++++---- crates/engine/src/cmd/missing.rs | 2 +- crates/engine/src/import/commit.rs | 90 +++++++++++++++++++++--------- crates/engine/src/import/job.rs | 84 ++++++++++++++++++++++------ crates/engine/src/tests/import.rs | 78 +++++++++++++++++++++++++- 5 files changed, 230 insertions(+), 55 deletions(-) diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index e242f3194b2..d072d00f526 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -45,14 +45,7 @@ pub(crate) fn write_dng_with( let dng = lightcraft_raw::write_dng(&raw, &lightcraft_raw::DngWriteOptions { xmp: (!packet.is_empty()).then_some(packet), ..Default::default() }) .map_err(|e| e.to_string())?; let back = lightcraft_raw::decode(&dng).map_err(|e| format!("{path}: the DNG written for it doesn't decode ({e}); the raw is kept"))?; - let same = match (&back.data, &raw.data) { - (lightcraft_raw::RawData::U16(a), lightcraft_raw::RawData::U16(b)) => a == b, - (lightcraft_raw::RawData::F32(a), lightcraft_raw::RawData::F32(b)) => { - a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()) - } - _ => false, - }; - if (back.width, back.height, back.cpp) != (raw.width, raw.height, raw.cpp) || !same { + if !same_raw_samples(&raw, &back) { return Err(format!("{path}: the DNG written for it doesn't hold the same raw data; the raw is kept")); } drop((raw, back)); @@ -63,6 +56,23 @@ pub(crate) fn write_dng_with( Ok((out.to_string_lossy().to_string(), info, file)) } +pub(crate) fn same_raw_samples(a: &lightcraft_raw::RawImage, b: &lightcraft_raw::RawImage) -> bool { + if (a.width, a.height, a.cpp) != (b.width, b.height, b.cpp) { + return false; + } + match (&a.data, &b.data) { + (lightcraft_raw::RawData::U16(a), lightcraft_raw::RawData::U16(b)) => a == b, + (lightcraft_raw::RawData::F32(a), lightcraft_raw::RawData::F32(b)) => { + a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits()) + } + _ => false, + } +} + +pub(crate) fn converted_lens(photo: &lightcraft_catalog::Photo, info: &crate::media::ProbeInfo) -> Option { + info.embedded_lens.or_else(|| photo.embedded_lens.as_deref().copied().filter(|lens| lens.source == lightcraft_develop::LensSource::Database)) +} + fn convert(s: &mut Session, p: &Value) -> Result { const C: &str = "photo.convertToDng"; let ids = s.targets(p)?; @@ -103,8 +113,9 @@ fn convert(s: &mut Session, p: &Value) -> Result { }); ops.extend(content_facts_op(c.id, c, &info.format, &info)); ops.extend(reload_wb_op(c, &info, &info.meta.camera)); - if info.embedded_lens.as_ref() != c.embedded_lens.as_deref() { - ops.push(Op::SetEmbeddedLens { id: c.id, lens: info.embedded_lens.clone().map(Box::new) }); + let lens = converted_lens(c, &info); + if lens.as_ref() != c.embedded_lens.as_deref() { + ops.push(Op::SetEmbeddedLens { id: c.id, lens: lens.map(Box::new) }); } } converted.push(json!({"id": id.0, "path": out, "original": path})); diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index f536eb27124..370a8faf294 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -170,7 +170,7 @@ pub(crate) fn stored_hash(p: &Photo) -> Option<&str> { pub(crate) fn file_hash(path: &str) -> Option { use std::io::Read; // the opened file must be regular (a FIFO or device would never end), and no more than its size at open is read - let file = std::fs::File::open(path).ok()?; + let file = crate::read_file::open_for_read(path).ok()?; let meta = file.metadata().ok().filter(|m| m.is_file())?; hash_reader(file.take(meta.len())) } diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 9459373c10d..cf56d126f24 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -385,6 +385,67 @@ fn replacement_is_current(path: &str, hash: Option<&str>, output: Option<&CopyOu } } +fn restore_legacy_dng(photo: &Photo, check: Option<&RestoreCheck>, ops: &mut Vec) -> Option<()> { + let Source::File { path } = &photo.source else { return None }; + let check = check.filter(|check| check.path == *path && photo.content_hash.as_deref() == Some(check.hash.as_str()))?; + let info = check.legacy_dng.as_ref()?; + if check.stamp != restore_stamp(path) && !has_verified_content(path, info.content_hash.as_deref()) { + return None; + } + ops.extend(crate::cmd::convert::content_facts_op(photo.id, photo, &info.format, info)); + let camera = if info.meta.camera.is_empty() { &photo.meta.camera } else { &info.meta.camera }; + ops.extend(crate::cmd::convert::reload_wb_op(photo, info, camera)); + let lens = crate::cmd::convert::converted_lens(photo, info); + if lens.as_ref() != photo.embedded_lens.as_deref() { + ops.push(Op::SetEmbeddedLens { id: photo.id, lens: lens.map(Box::new) }); + } + Some(()) +} + +/// Append a duplicate's Restore only after verifying the file it will reference. +fn restore_duplicate( + photo: &Photo, + path: &str, + reason: &str, + hash: Option<&str>, + target: &RestoreTarget, + check: Option<&RestoreCheck>, + ops: &mut Vec, +) -> Result<(), &'static str> { + if reason == "content" { + let differs = || trashed_file_differs(photo, hash, check); + let relink = match target { + RestoreTarget::Decide { format: Some(format) } + if !cfg!(target_arch = "wasm32") + && photo.format.eq_ignore_ascii_case("DNG") + && !format.is_empty() + && !format.eq_ignore_ascii_case("DNG") => + { + restore_legacy_dng(photo, check, ops).ok_or("the existing DNG could not be verified against this raw; the photo stays deleted")?; + false + } + RestoreTarget::Decide { .. } => differs(), + RestoreTarget::Keep if differs() => return Err("the original changed before Restore; the duplicate output was kept"), + RestoreTarget::Keep => false, + RestoreTarget::Relink(_) => true, + }; + if relink { + let copy = match target { + RestoreTarget::Relink(copy) => copy.as_ref(), + _ => None, + }; + if matches!(&photo.source, Source::File { path: existing } if same_import_file(existing, path)) + || !replacement_is_current(path, hash, copy) + { + return Err("the replacement file changed before Restore"); + } + ops.push(crate::cmd::missing::relink_op(photo.id, path)); + } + } + ops.push(Op::SetDeleted { id: photo.id, deleted: false }); + Ok(()) +} + /// The catalog half of an import: add the photos [`ImportJob::prepare`] readied (one undoable op; /// a Move's sources are removed once it is saved). On a failed commit a Move's placed files are /// taken back. @@ -481,33 +542,10 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare } if !report.restored.contains(&id.0) { let Some(photo) = s.catalog.photo(id) else { continue }; - let differs = || trashed_file_differs(photo, hash.as_deref(), prepared.restore_checks.get(&id)); - let relink = match &restore { - RestoreTarget::Relink(_) => true, - RestoreTarget::Keep if differs() => { - report.failed.push((path, "the original changed before Restore; the duplicate output was kept".into())); - continue; - } - RestoreTarget::Keep => false, - RestoreTarget::Decide => reason == "content" && differs(), - }; - if relink { - let copy = match &restore { - RestoreTarget::Relink(copy) => copy.as_ref(), - _ => None, - }; - if matches!(&photo.source, Source::File { path: existing } if same_import_file(existing, &path)) - || !replacement_is_current(&path, hash.as_deref(), copy) - { - report.failed.push((path, "the replacement file changed before Restore".into())); - continue; - } - if !s.catalog.photos().any(|p| p.id != id && matches!(&p.source, Source::File { path: held } if *held == path)) { - ops.push(crate::cmd::missing::relink_op(id, &path)); - } + match restore_duplicate(photo, &path, reason, hash.as_deref(), &restore, prepared.restore_checks.get(&id), &mut ops) { + Ok(()) => report.restored.push(id.0), + Err(reason) => report.failed.push((path, reason.into())), } - ops.push(Op::SetDeleted { id, deleted: false }); - report.restored.push(id.0); } } _ => { diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 5ace151e0ea..8dfd4da3d14 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -47,7 +47,7 @@ pub struct ImportJob { /// content hash → the photo that has it (`None`: a file earlier in this import) pub(super) by_hash: HashMap>, /// Paths of deleted duplicates, captured before the worker starts. - restore_sources: HashMap, + restore_sources: HashMap, pub(super) probe: Option, file_bytes: Option, /// Probes from a preceding scan (not read again). @@ -77,11 +77,19 @@ pub struct Prepared { pub(super) restore_checks: HashMap, } +#[derive(Debug)] +struct RestoreSource { + path: String, + hash: String, + format: String, +} + #[derive(Debug)] pub(super) struct RestoreCheck { pub(super) path: String, pub(super) hash: String, pub(super) stamp: Option, + pub(super) legacy_dng: Option>, // Windows does not expose the file change time through stable Rust. Hold the original // open without write or delete sharing from verification through catalog reconciliation. #[cfg(windows)] @@ -174,7 +182,7 @@ impl CopyOutput { #[derive(Debug)] pub(super) enum RestoreTarget { - Decide, + Decide { format: Option }, Keep, Relink(Option), } @@ -265,7 +273,7 @@ impl Prepared { existing: Some(existing), reason: if existing_path.is_some() { "path" } else { "content" }, hash: info.content_hash, - restore: RestoreTarget::Decide, + restore: RestoreTarget::Decide { format: Some(info.format) }, file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), }); } else { @@ -314,6 +322,29 @@ pub(super) fn normalize_import_path(path: &str) -> String { if cfg!(windows) { path.replace('\\', "/").to_lowercase() } else { path.to_owned() } } +/// Older Copy as DNG records kept the input hash. Repair the record only when the input still +/// has that hash and the DNG still contains the input's sensor samples. +fn probe_legacy_dng(path: &str, input: &str, hash: &str) -> Option { + use crate::read_file::{MAX_MEDIA_BYTES, read_regular}; + let input_len = std::fs::metadata(input).ok()?.len(); + let dng_len = std::fs::metadata(path).ok()?.len(); + let weight = usize::try_from(input_len.saturating_add(dng_len)).unwrap_or(usize::MAX).saturating_mul(6); + let _permit = crate::memory::work_gate().acquire(weight); + let bytes = read_regular(input, MAX_MEDIA_BYTES).ok()?; + if lightcraft_preview::hash_bytes(&bytes).to_string() != hash { + return None; + } + let source = lightcraft_raw::decode(&bytes).ok()?; + drop(bytes); + let bytes = read_regular(path, MAX_MEDIA_BYTES).ok()?; + let dng = lightcraft_raw::decode(&bytes).ok()?; + if dng.format != lightcraft_raw::RawFormat::Dng || source.cfa != dng.cfa || !crate::cmd::convert::same_raw_samples(&source, &dng) { + return None; + } + drop((source, dng)); + crate::files::probe_bytes(path, &bytes).ok() +} + impl ImportJob { /// Snapshot what an import with `opts` needs from the session (no file-system calls). Takes /// the probes a preceding scan left ([`Session::import_probes`]). @@ -449,7 +480,7 @@ impl ImportJob { && self.opts.on_deleted == OnDeleted::Restore && let Source::File { path } = &p.source { - self.restore_sources.insert(p.id, (path.clone(), h.clone())); + self.restore_sources.insert(p.id, RestoreSource { path: path.clone(), hash: h.clone(), format: p.format.clone() }); } } } @@ -493,7 +524,7 @@ impl ImportJob { existing: Some(id), reason: "path", hash: None, - restore: RestoreTarget::Decide, + restore: RestoreTarget::Decide { format: None }, file: None, }); self.done.fetch_add(1, Relaxed); @@ -510,7 +541,14 @@ impl ImportJob { // (here or in a previous batch) counts as the library's from then on if let Some(h) = &hash { if let Some(existing) = self.by_hash.get(h) { - return PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, restore: RestoreTarget::Decide, file: None }; + return PreparedItem::Duplicate { + path: f, + existing: *existing, + reason: "content", + hash, + restore: RestoreTarget::Decide { format: None }, + file: None, + }; } self.by_hash.insert(h.clone(), Some(id)); } @@ -679,7 +717,7 @@ impl ImportJob { existing, reason: "content", hash: Some(hash), - restore: RestoreTarget::Decide, + restore: RestoreTarget::Decide { format: Some(info.format) }, file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), })); continue; @@ -799,15 +837,15 @@ impl ImportJob { if cancel.load(std::sync::atomic::Ordering::Relaxed) { break; } - let id = match item { - PreparedItem::Duplicate { existing, reason: "content", hash: Some(hash), .. } => { - existing.or_else(|| self.by_hash.get(hash).copied().flatten()) - } - PreparedItem::Ready(r) => r.info.content_hash.as_ref().and_then(|hash| self.by_hash.get(hash).copied().flatten()), - _ => None, + let (id, incoming) = match item { + PreparedItem::Duplicate { + path, existing, reason: "content", hash: Some(hash), restore: RestoreTarget::Decide { format }, .. + } => (existing.or_else(|| self.by_hash.get(hash).copied().flatten()), format.as_deref().map(|format| (path.as_str(), format))), + PreparedItem::Ready(r) => (r.info.content_hash.as_ref().and_then(|hash| self.by_hash.get(hash).copied().flatten()), None), + _ => (None, None), }; let Some(id) = id else { continue }; - let Some((path, hash)) = self.restore_sources.get(&id) else { continue }; + let Some(RestoreSource { path, hash, format }) = self.restore_sources.get(&id) else { continue }; out.restore_checks.entry(id).or_insert_with(|| { #[cfg(windows)] let read_guard = { @@ -818,12 +856,26 @@ impl ImportJob { let stamp = restore_stamp(path); #[cfg(windows)] let stamp = stamp.filter(|_| read_guard.is_some()); - let stamp = - stamp.filter(|stamp| crate::cmd::missing::file_hash(path).as_deref() == Some(hash) && restore_stamp(path) == Some(*stamp)); + let mut legacy_dng = None; + let stamp = stamp.filter(|stamp| { + if crate::cmd::missing::file_hash(path).as_deref() == Some(hash) { + return restore_stamp(path) == Some(*stamp); + } + if format.eq_ignore_ascii_case("DNG") + && let Some((input, input_format)) = incoming + && !input_format.is_empty() + && !input_format.eq_ignore_ascii_case("DNG") + && !cfg!(target_arch = "wasm32") + { + legacy_dng = probe_legacy_dng(path, input, hash).filter(|_| restore_stamp(path) == Some(*stamp)).map(Box::new); + } + legacy_dng.is_some() + }); RestoreCheck { path: path.clone(), hash: hash.clone(), stamp, + legacy_dng, #[cfg(windows)] _read_guard: read_guard, } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 1ffb9c8a384..4d5d40334f2 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5364,6 +5364,8 @@ fn convert_to_dng_refreshes_copy_classification_and_undo_redo() { .unwrap(); s.catalog.apply(Op::SetAsShotWb { id: copy, wb: None }).unwrap(); s.catalog.apply(Op::SetEmbeddedLens { id: copy, lens: Some(Box::default()) }).unwrap(); + let database_lens = lightcraft_develop::EmbeddedLens { source: lightcraft_develop::LensSource::Database, ..Default::default() }; + s.catalog.apply(Op::SetEmbeddedLens { id: parent, lens: Some(Box::new(database_lens)) }).unwrap(); s.execute("develop.set", &json!({"ids": [copy.0], "control": "light.exposure", "value": 0.4})).unwrap(); let before = s.catalog.photo(copy).unwrap().clone(); let parent_before = s.catalog.photo(parent).unwrap().clone(); @@ -5379,7 +5381,8 @@ fn convert_to_dng_refreshes_copy_classification_and_undo_redo() { assert_eq!((photo.kind, photo.format.as_str()), (MediaKind::Raw, "DNG"), "known DNG output is always raw"); assert_eq!(photo.source, output); assert_eq!(photo.as_shot_wb, output_info.as_shot_wb, "every relinked record uses the generated DNG's As Shot facts"); - assert_eq!(photo.embedded_lens.as_deref(), output_info.embedded_lens.as_ref()); + let lens = output_info.embedded_lens.as_ref().or((id == parent).then_some(&database_lens)); + assert_eq!(photo.embedded_lens.as_deref(), lens); } assert_eq!(s.catalog.photo(independent).unwrap(), &independent_before); let after = s.catalog.photo(copy).unwrap().clone(); @@ -5553,7 +5556,7 @@ fn assert_copy_as_dng_restores(s: &mut Session, id: PhotoId, paths: &[String], o fn copy_as_dng_restore_uses_the_verified_output_across_batches() { use crate::import::{ImportJob, ImportMode, ImportOptions, Organize, commit_prepared}; use lightcraft_catalog::{Op, Source}; - for case in if cfg!(unix) { &[0, 1, 2, 3][..] } else { &[0][..] } { + for case in if cfg!(unix) { &[0, 1, 2, 3, 4][..] } else { &[0][..] } { let dir = super::TestDir::new(&format!("copy-dng-restore-batch-{case}")); let destination = dir.join("copies"); let source = ["first.nef", "second.nef"].map(|name| dir.join(name).to_string_lossy().into_owned()); @@ -5602,6 +5605,15 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { let mtime = std::fs::metadata(&old).unwrap().modified().unwrap(); std::fs::File::options().write(true).open(&old).unwrap().set_modified(mtime - std::time::Duration::from_secs(60)).unwrap(); assert_ne!(std::fs::metadata(&old).unwrap().modified().unwrap(), mtime); + } else if *case == 4 { + let mtime = std::fs::metadata(&old).unwrap().modified().unwrap(); + let incoming = dir.join("incoming.dng"); + let mut changed = output.clone(); + changed[0] ^= 1; + std::fs::write(&incoming, changed).unwrap(); + std::fs::File::options().write(true).open(&incoming).unwrap().set_modified(mtime).unwrap(); + std::fs::rename(&incoming, &old).unwrap(); + assert_eq!(std::fs::metadata(&old).unwrap().modified().unwrap(), mtime); } let r = commit_prepared(&mut session, &opts, job.now(), second).unwrap(); assert_eq!(r.restored, [id.0], "{r:?}"); @@ -5614,6 +5626,68 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { if *case == 3 { assert_eq!(path, &old, "a new modification time alone does not move the restored photo"); assert_eq!(copy_dng_output_names(&destination).len(), 1); + } else if *case == 4 { + assert_ne!(path, &old, "a different file with the same mtime is not the original"); + } + } +} + +#[test] +fn legacy_copy_as_dng_restores_only_the_matching_converted_sensor() { + use crate::import::{ImportMode, ImportOptions, Organize}; + use lightcraft_catalog::Op; + for replaced in [false, true] { + let dir = super::TestDir::new(&format!("legacy-copy-as-dng-restore-{replaced}")); + let raw_path = dir.join("source.orf").to_string_lossy().into_owned(); + let raw_bytes = crate::files::tests::sensor_orf(); + std::fs::write(&raw_path, &raw_bytes).unwrap(); + let mut s = Session::new().with_fs(); + let opts = ImportOptions { + mode: ImportMode::Copy, + destination: Some(dir.join("copies").to_string_lossy().into()), + organize: Organize::Flat, + convert_dng: true, + ..Default::default() + }; + let report = crate::import::import_with(&mut s, std::slice::from_ref(&raw_path), &opts).unwrap(); + let id = PhotoId(report.imported[0]); + let photo = s.catalog.photo(id).unwrap(); + let original = file_source_path(photo); + let expected = photo.content_hash.clone(); + assert_eq!(photo.format, "DNG"); + let raw_hash = Some(lightcraft_preview::hash_bytes(&raw_bytes).to_string()); + assert_ne!(expected, raw_hash); + s.catalog + .apply(Op::SetContent { + id, + width: photo.width, + height: photo.height, + file_size: raw_bytes.len() as u64, + content_hash: raw_hash, + preview_only: None, + preview_checked: String::new(), + }) + .unwrap(); + s.catalog.apply(Op::SetDeleted { id, deleted: true }).unwrap(); + let before = s.catalog.photo(id).unwrap().clone(); + if replaced { + let mut other = lightcraft_raw::decode(&std::fs::read(&original).unwrap()).unwrap(); + let lightcraft_raw::RawData::U16(samples) = &mut other.data else { panic!("integer fixture") }; + samples[0] ^= 1; + std::fs::write(&original, lightcraft_raw::write_dng(&other, &Default::default()).unwrap()).unwrap(); + } + let report = crate::import::import_with(&mut s, &[raw_path], &ImportOptions::default()).unwrap(); + let photo = s.catalog.photo(id).unwrap(); + assert_eq!(file_source_path(photo), original); + if replaced { + assert_eq!(photo, &before); + assert!(report.restored.is_empty() && report.failed.len() == 1, "{report:?}"); + } else { + assert_eq!(report.restored, [id.0], "{report:?}"); + assert_eq!(photo.content_hash, expected); + assert_eq!(photo.file_size, std::fs::metadata(original).unwrap().len()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap(), &before); } } } From adac54e3b97698892fa47d25156d97eb834b7865 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:44:12 +0100 Subject: [PATCH 26/42] Validate same-path restores alongside content restores --- crates/engine/src/import/commit.rs | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index cf56d126f24..596a9725368 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -412,7 +412,14 @@ fn restore_duplicate( check: Option<&RestoreCheck>, ops: &mut Vec, ) -> Result<(), &'static str> { - if reason == "content" { + if reason == "path" { + if !cfg!(target_arch = "wasm32") + && let Some(expected) = photo.content_hash.as_deref() + && !has_verified_content(path, Some(expected)) + { + return Err("the file at this deleted photo's path has changed"); + } + } else if reason == "content" { let differs = || trashed_file_differs(photo, hash, check); let relink = match target { RestoreTarget::Decide { format: Some(format) } @@ -531,15 +538,6 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare match trashed { // (browsing a folder in Local only looks: it never restores) Some(id) if opts.on_deleted == OnDeleted::Restore && !opts.local => { - if reason == "path" - && !cfg!(target_arch = "wasm32") - && let Some(photo) = s.catalog.photo(id) - && let Some(expected) = photo.content_hash.as_deref() - && !has_verified_content(&path, Some(expected)) - { - report.failed.push((path, "the file at this deleted photo's path has changed".into())); - continue; - } if !report.restored.contains(&id.0) { let Some(photo) = s.catalog.photo(id) else { continue }; match restore_duplicate(photo, &path, reason, hash.as_deref(), &restore, prepared.restore_checks.get(&id), &mut ops) { From 9f1e06f2a64fa3e288e0ea366b68808415991ed3 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 20:12:46 +0100 Subject: [PATCH 27/42] Verify converted DNG ownership and reconcile deleted source paths --- Cargo.lock | 1 + crates/catalog/Cargo.toml | 1 + crates/catalog/src/safe_file.rs | 21 ++++++-- crates/engine/src/cmd/convert.rs | 2 +- crates/engine/src/import/commit.rs | 49 +++++++++++++++---- crates/engine/src/import/files.rs | 1 + crates/engine/src/import/job.rs | 77 ++++++++++++++++++++++++++---- crates/engine/src/tests/import.rs | 44 +++++++++++++++-- crates/wincolor/Cargo.toml | 1 + crates/wincolor/src/lib.rs | 24 +++++++++- 10 files changed, 192 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1cb259e8604..ac9fcd29d5e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5729,6 +5729,7 @@ dependencies = [ "lightcraft-meta", "lightcraft-raw", "lightcraft-testkit", + "lightcraft-wincolor", "log", "proptest", "serde", diff --git a/crates/catalog/Cargo.toml b/crates/catalog/Cargo.toml index aecd1f97d03..e900e8ce27e 100644 --- a/crates/catalog/Cargo.toml +++ b/crates/catalog/Cargo.toml @@ -21,6 +21,7 @@ chrono = { workspace = true } web-time = { workspace = true } [target.'cfg(windows)'.dependencies] +lightcraft-wincolor = { workspace = true } winapi-util = { workspace = true } [dev-dependencies] diff --git a/crates/catalog/src/safe_file.rs b/crates/catalog/src/safe_file.rs index 7ae10a7024b..791168f2da2 100644 --- a/crates/catalog/src/safe_file.rs +++ b/crates/catalog/src/safe_file.rs @@ -275,12 +275,8 @@ fn same_content(f: &mut File, data: &[u8]) -> io::Result { } } -/// Volume and file number of an opened file on Windows, when the file system supplies both. #[cfg(windows)] -pub fn open_file_id(file: &File) -> Option<(u64, u64)> { - let (volume, index) = windows_file_id(file).ok()?; - (index != 0).then_some((volume, index)) -} +pub use lightcraft_wincolor::open_file_id; /// Do `a` and `b` name the same existing file (through hard links, symlinks, `..`, /// case-insensitive names)? @@ -360,6 +356,21 @@ fn same_file_id(a: (u64, u64), b: (u64, u64), strict: bool) -> io::Result mod tests { use super::*; + #[cfg(windows)] + #[test] + fn full_windows_file_id_distinguishes_files_with_identical_bytes() { + let dir = temp("full-file-id"); + let original = dir.join("original"); + let replacement = dir.join("replacement"); + for path in [&original, &replacement] { + fs::write(path, b"same data").unwrap(); + } + let id = |path| open_file_id(&File::open(path).unwrap()).expect("test volume supports file IDs"); + assert_eq!(id(&original), id(&original)); + assert_ne!(id(&original), id(&replacement)); + fs::remove_dir_all(dir).unwrap(); + } + fn temp(tag: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("lc-safe-file-{tag}-{}", std::process::id())); let _ = fs::remove_dir_all(&d); diff --git a/crates/engine/src/cmd/convert.rs b/crates/engine/src/cmd/convert.rs index d072d00f526..7a64501c639 100644 --- a/crates/engine/src/cmd/convert.rs +++ b/crates/engine/src/cmd/convert.rs @@ -112,7 +112,7 @@ fn convert(s: &mut Session, p: &Value) -> Result { kind: Some(info.kind), }); ops.extend(content_facts_op(c.id, c, &info.format, &info)); - ops.extend(reload_wb_op(c, &info, &info.meta.camera)); + ops.extend(reload_wb_op(c, &info, &info.meta.camera, false)); let lens = converted_lens(c, &info); if lens.as_ref() != c.embedded_lens.as_deref() { ops.push(Op::SetEmbeddedLens { id: c.id, lens: lens.map(Box::new) }); diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 596a9725368..b282eb610a7 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -145,6 +145,7 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P let mut input_hash = None; let mut placed = None; let mut copy = None; + let mut generated_dng = false; let mut stored = match how { How::Place { name } => match crate::import_move::place(Path::new(&path), &dir, &name) { Ok(pl) => { @@ -156,7 +157,7 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P }, How::Copy { name } => match copy_into(&dir, &path, name.as_deref(), info.content_hash.as_deref()) { Ok((p, file)) => { - copy = Some(CopyOutput::new(file)); + copy = Some(CopyOutput::new(file, None)); p } Err(e) => return PreparedItem::Failed(path, e), @@ -175,7 +176,8 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P return PreparedItem::Failed(path, format!("could not remove the copied raw at {stored}: {e}; the DNG at {dng} was kept")); } stored = dng; - copy = Some(CopyOutput::new(file)); + copy = Some(CopyOutput::new(file, output.content_hash.as_deref())); + generated_dng = true; // Keep input metadata and XMP, but describe the bytes actually stored. The alias // keeps duplicate input raws identifiable until this import is committed. input_hash = info.content_hash.clone().filter(|h| Some(h) != output.content_hash.as_ref()); @@ -194,7 +196,7 @@ fn run_transfer(t: Transfer, file_bytes: Option<&crate::merge::ByteReader>) -> P } } let backup = backup.map(|(root, to)| back_up(&path, &stored, placed.as_ref(), &root, &to, info.content_hash.as_deref())); - PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash, copy, sidecar, placed, backup })) + PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash, copy, generated_dng, sidecar, placed, backup })) } /// The backup copy of a file an import put at `stored` inside `root` — with a Move's sidecars beside @@ -378,6 +380,11 @@ fn ready_duplicate( } } +fn invalid_generated_output(ready: &ReadyFile) -> bool { + ready.generated_dng + && !ready.info.content_hash.as_deref().is_some_and(|hash| ready.copy.as_ref().is_some_and(|copy| copy.is_current(&ready.stored, Some(hash)))) +} + fn replacement_is_current(path: &str, hash: Option<&str>, output: Option<&CopyOutput>) -> bool { match output { Some(copy) => copy.is_current(path, hash), @@ -394,7 +401,7 @@ fn restore_legacy_dng(photo: &Photo, check: Option<&RestoreCheck>, ops: &mut Vec } ops.extend(crate::cmd::convert::content_facts_op(photo.id, photo, &info.format, info)); let camera = if info.meta.camera.is_empty() { &photo.meta.camera } else { &info.meta.camera }; - ops.extend(crate::cmd::convert::reload_wb_op(photo, info, camera)); + ops.extend(crate::cmd::convert::reload_wb_op(photo, info, camera, true)); let lens = crate::cmd::convert::converted_lens(photo, info); if lens.as_ref() != photo.embedded_lens.as_deref() { ops.push(Op::SetEmbeddedLens { id: photo.id, lens: lens.map(Box::new) }); @@ -462,13 +469,14 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let mut default_denoiser = None; let mut ops = Vec::new(); let mut cleanup = Vec::new(); + let mut unverified_dng_paths = Vec::new(); // Move: placed at the destination, sources untouched until the records are committed // (with its backup: where it was made, or why it wasn't, so the source stays) let mut placed: Vec<(crate::import_move::Placed, Option>)> = Vec::new(); // Current converted outputs, then this batch's additions and input aliases. Keep only the // hashes this batch asks about, even for a library of millions of photos. let converted_hashes = prepared.items.iter().filter_map(|it| match it { - PreparedItem::Ready(r) if r.input_hash.is_some() && !opts.local => r.info.content_hash.as_deref(), + PreparedItem::Ready(r) if r.generated_dng && !opts.local => r.info.content_hash.as_deref(), _ => None, }); // Local records count only when this same atomic import already promotes them into the library. @@ -500,6 +508,9 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let mut purged: std::collections::HashSet = Default::default(); for it in prepared.items { let it = match it { + PreparedItem::Ready(r) if invalid_generated_output(&r) => { + PreparedItem::Failed(r.path, format!("the converted output at {} changed before import", r.stored)) + } PreparedItem::Ready(r) if !opts.local => { ready_duplicate(s, opts, &mut new_hash, &report.restored, &prepared.restore_checks, &mut cleanup, *r) } @@ -526,6 +537,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare } report.imported.push(id.0); } + PreparedItem::UnverifiedDngPath { id, path, hash } => unverified_dng_paths.push((id, path, hash)), PreparedItem::Duplicate { path, existing, reason, hash, restore, file } => { let existing = existing.or_else(|| { let h = hash.as_ref()?; @@ -646,6 +658,12 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare for copy in cleanup { copy.remove(s, &prepared.restore_checks, &mut report); } + report.failed.extend(unverified_dng_paths.into_iter().filter_map(|(id, path, hash)| { + let restored_here = s.catalog.photo(id).is_some_and(|photo| { + photo.content_hash.is_some() && photo.content_hash == hash && photo.library_file().is_some_and(|source| same_import_file(source, &path)) + }); + (!restored_here).then_some((path, "this DNG could not be verified as the deleted photo's original; it was left untouched".into())) + })); if !placed.is_empty() { finish_moves(s, placed, log0, &mut report); } @@ -891,6 +909,19 @@ mod clock_tests { mod tests { use super::*; + #[test] + fn an_in_place_edit_before_capturing_the_dng_stamp_does_not_become_verified() { + let dir = crate::tests::TestDir::new("changed-before-dng-stamp"); + let path = dir.join("output.dng"); + let bytes = b"verified contents"; + let hash = lightcraft_preview::hash_bytes(bytes).to_string(); + let (_, file) = lightcraft_catalog::safe_file::write_new_unique_open(&mut std::iter::once(path.clone()), bytes).unwrap(); + std::fs::write(&path, b"modified contents").unwrap(); + let output = CopyOutput::new(file, Some(&hash)); + assert!(!output.is_current(&path.to_string_lossy(), Some(&hash))); + assert_eq!(std::fs::read(&path).unwrap(), b"modified contents"); + } + #[test] fn review_ordinary_dng_deduplicates_after_a_converted_output() { mixed_dng_outputs(true); @@ -910,7 +941,7 @@ mod tests { let hash = lightcraft_preview::hash_bytes(content).to_string(); std::fs::write(&path, content).unwrap(); std::fs::write(©, content).unwrap(); - let output = CopyOutput::new(std::fs::File::open(©).unwrap()); + let output = CopyOutput::new(std::fs::File::open(©).unwrap(), Some(&hash)); let mut s = Session::new(); let id = s.catalog.alloc_photo_id(); let mut photo = Photo::new(id, Source::File { path: path.clone() }, "retained.dng", "DNG", 1, 1, ""); @@ -947,14 +978,16 @@ mod tests { content_hash: Some(lightcraft_preview::hash_bytes(b"same DNG output").to_string()), ..Default::default() }; - let ready = |path: PathBuf, stored: PathBuf, input_hash| { + let ready = |path: PathBuf, stored: PathBuf, input_hash: Option| { + let generated_dng = input_hash.is_some(); PreparedItem::Ready(Box::new(ReadyFile { path: path.to_string_lossy().into(), stored: stored.to_string_lossy().into(), info: info.clone(), input_hash, + generated_dng, copy: (!same_import_file(&path.to_string_lossy(), &stored.to_string_lossy())) - .then(|| CopyOutput::new(std::fs::File::open(&stored).unwrap())), + .then(|| CopyOutput::new(std::fs::File::open(&stored).unwrap(), info.content_hash.as_deref())), sidecar: None, placed: None, })) diff --git a/crates/engine/src/import/files.rs b/crates/engine/src/import/files.rs index 7fd27f5308f..3af06c8c0d3 100644 --- a/crates/engine/src/import/files.rs +++ b/crates/engine/src/import/files.rs @@ -663,6 +663,7 @@ mod prepared_tests { info: ProbeInfo { format: "JPG".into(), ..ProbeInfo::default() }, input_hash: None, copy: None, + generated_dng: false, sidecar: None, placed: None, backup: None, diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index 8dfd4da3d14..d2dbb32b08c 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -139,14 +139,31 @@ pub(super) fn restore_stamp(path: &str) -> Option { #[derive(Debug)] pub(super) struct CopyOutput { stamp: Option, + #[cfg(unix)] + verified_hash: Option, #[cfg(windows)] - identity: Option<(u64, u64)>, + identity: Option<(u64, [u8; 16])>, } impl CopyOutput { - pub(super) fn new(file: std::fs::File) -> Self { + pub(super) fn new(file: std::fs::File, expected: Option<&str>) -> Self { + let stamp = file.metadata().ok().and_then(RestoreStamp::from_metadata); + // Publishing an output can change its ctime. Bind the stamp available after publication + // to the verified bytes on the worker, before the catalog thread sees the DNG. + #[cfg(unix)] + let verified_hash = { + use std::io::Seek; + let mut file = file; + expected.filter(|hash| stamp.is_some_and(|stamp| file.rewind().is_ok() && verified_bytes(&file, stamp, hash))).map(str::to_owned) + }; + #[cfg(unix)] + let stamp = stamp.filter(|_| expected.is_none() || verified_hash.is_some()); + #[cfg(not(unix))] + let _ = expected; Self { - stamp: file.metadata().ok().and_then(RestoreStamp::from_metadata), + stamp, + #[cfg(unix)] + verified_hash, #[cfg(windows)] identity: lightcraft_catalog::safe_file::open_file_id(&file), } @@ -154,22 +171,29 @@ impl CopyOutput { pub(super) fn is_current(&self, path: &str, expected: Option<&str>) -> bool { // In particular, a symlink to the file we wrote is not an output that we own. - let Some(stamp) = std::fs::symlink_metadata(path).ok().and_then(RestoreStamp::from_metadata) else { return false }; + let Some(stamp) = copy_path_stamp(path) else { return false }; #[cfg(unix)] { - let _ = expected; Some(stamp) == self.stamp + && expected.is_none_or(|hash| { + self.verified_hash.as_deref() == Some(hash) + || crate::read_file::open_for_read(path) + .is_ok_and(|file| verified_bytes(&file, stamp, hash) && copy_path_stamp(path) == Some(stamp)) + }) } #[cfg(windows)] { - let identity = std::fs::File::open(path).ok().and_then(|f| lightcraft_catalog::safe_file::open_file_id(&f)); + let Ok(file) = crate::read_file::open_for_read(path) else { return false }; + let identity = lightcraft_catalog::safe_file::open_file_id(&file); // On Windows the last write time can update when the writer closes, and a later // writer can restore it. When a content hash is available, check the actual bytes. identity.is_some() && identity == self.identity && self.stamp.is_some_and(|old| old.len == stamp.len) && expected.map_or(self.stamp == Some(stamp), |hash| { - crate::cmd::missing::file_hash(path).as_deref() == Some(hash) && restore_stamp(path) == Some(stamp) + verified_bytes(&file, stamp, hash) + && copy_path_stamp(path) == Some(stamp) + && crate::read_file::open_for_read(path).ok().and_then(|f| lightcraft_catalog::safe_file::open_file_id(&f)) == identity }) } #[cfg(not(any(unix, windows)))] @@ -180,6 +204,17 @@ impl CopyOutput { } } +fn copy_path_stamp(path: &str) -> Option { + std::fs::symlink_metadata(path).ok().and_then(RestoreStamp::from_metadata) +} + +#[cfg(any(unix, windows))] +fn verified_bytes(file: &std::fs::File, stamp: RestoreStamp, hash: &str) -> bool { + use std::io::Read; + let file_stamp = || file.metadata().ok().and_then(RestoreStamp::from_metadata); + file_stamp() == Some(stamp) && crate::cmd::missing::hash_reader(file.take(stamp.len)).as_deref() == Some(hash) && file_stamp() == Some(stamp) +} + #[derive(Debug)] pub(super) enum RestoreTarget { Decide { format: Option }, @@ -192,6 +227,13 @@ pub(super) enum PreparedItem { /// A Local (browsed) record imported for real; with what its file is now when the file was replaced since it was /// browsed (the record is brought up to date). Promote(PhotoId, Option>), + /// A deleted DNG at its old path with a different hash. A matching input raw can prove that + /// the record old versions wrote (with the raw's hash) actually belongs to this DNG. + UnverifiedDngPath { + id: PhotoId, + path: String, + hash: Option, + }, Duplicate { path: String, existing: Option, @@ -214,6 +256,7 @@ pub(super) struct ReadyFile { /// Copy as DNG's original input identity, only for this job's duplicate lookup. pub(super) input_hash: Option, pub(super) copy: Option, + pub(super) generated_dng: bool, pub(super) sidecar: Option, pub(super) placed: Option, /// [`ImportOptions::backup`]: its backup copy, or why it has none. `None`: no backup asked for. @@ -261,7 +304,7 @@ impl Prepared { items.push(item); continue; }; - let ReadyFile { path, stored, info, input_hash, copy, sidecar, placed, backup } = *ready; + let ReadyFile { path, stored, info, input_hash, copy, generated_dng, sidecar, placed, backup } = *ready; let existing_path = paths.get(&normalize_import_path(&stored)).copied().or_else(|| paths.get(&normalize_import_path(&path)).copied()); let existing_hash = info.content_hash.iter().chain(&input_hash).find_map(|hash| hashes.get(hash).copied()); if let Some(existing) = existing_path.or(existing_hash) { @@ -277,7 +320,7 @@ impl Prepared { file: Some(Box::new(FileFacts { meta: info.meta, captured: info.captured, orientation: info.orientation, sidecar })), }); } else { - items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash, copy, sidecar, placed, backup }))); + items.push(PreparedItem::Ready(Box::new(ReadyFile { path, stored, info, input_hash, copy, generated_dng, sidecar, placed, backup }))); } } self.items = items; @@ -557,6 +600,16 @@ impl ImportJob { PreparedItem::Promote(id, None) } + fn unverified_dng_path(&self, path: &str, info: &ProbeInfo) -> Option { + let (id, _, _) = self.by_path.get(path)?; + let source = self.restore_sources.get(id)?; + (!self.opts.local + && source.format.eq_ignore_ascii_case("DNG") + && info.format.eq_ignore_ascii_case("DNG") + && info.content_hash.as_deref() != Some(&source.hash)) + .then_some(*id) + } + /// [`ImportJob::prepare`] for files [`ImportJob::expand`] returned. pub fn prepare_files(&mut self, files: Vec, cancel: &std::sync::atomic::AtomicBool) -> Prepared { use std::sync::atomic::Ordering::Relaxed; @@ -633,6 +686,11 @@ impl ImportJob { }; // (this file's place in the lookups above: files that failed to probe have none) let found_sidecar = found.next().flatten(); + if let Some(id) = self.unverified_dng_path(&path, &info) { + self.done.fetch_add(1, Relaxed); + plan.slots.push(Slot::Item(PreparedItem::UnverifiedDngPath { id, path, hash: info.content_hash })); + continue; + } // a copy of a file whose transfer is still pending: a duplicate only if that one succeeds if !opts.local && let Some(h) = &info.content_hash @@ -802,6 +860,7 @@ impl ImportJob { info, input_hash: None, copy: None, + generated_dng: false, sidecar, placed: None, backup, diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 4d5d40334f2..b4b5d9e2c9e 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5636,8 +5636,8 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { fn legacy_copy_as_dng_restores_only_the_matching_converted_sensor() { use crate::import::{ImportMode, ImportOptions, Organize}; use lightcraft_catalog::Op; - for replaced in [false, true] { - let dir = super::TestDir::new(&format!("legacy-copy-as-dng-restore-{replaced}")); + for (replaced, raw_first) in [(false, false), (false, true), (true, false)] { + let dir = super::TestDir::new(&format!("legacy-copy-as-dng-restore-{replaced}-{raw_first}")); let raw_path = dir.join("source.orf").to_string_lossy().into_owned(); let raw_bytes = crate::files::tests::sensor_orf(); std::fs::write(&raw_path, &raw_bytes).unwrap(); @@ -5676,14 +5676,21 @@ fn legacy_copy_as_dng_restores_only_the_matching_converted_sensor() { samples[0] ^= 1; std::fs::write(&original, lightcraft_raw::write_dng(&other, &Default::default()).unwrap()).unwrap(); } - let report = crate::import::import_with(&mut s, &[raw_path], &ImportOptions::default()).unwrap(); + let solo = crate::import::import_with(&mut s, std::slice::from_ref(&original), &ImportOptions::default()).unwrap(); + assert!(solo.imported.is_empty() && solo.restored.is_empty() && solo.failed.len() == 1, "{solo:?}"); + assert_eq!(s.catalog.photo(id).unwrap(), &before); + let paths = if raw_first { [raw_path, original.clone()] } else { [original.clone(), raw_path] }; + let report = crate::import::import_with(&mut s, &paths, &ImportOptions::default()).unwrap(); + assert!(report.imported.is_empty()); + assert_eq!(s.catalog.photos().count(), 1); let photo = s.catalog.photo(id).unwrap(); assert_eq!(file_source_path(photo), original); if replaced { assert_eq!(photo, &before); - assert!(report.restored.is_empty() && report.failed.len() == 1, "{report:?}"); + assert!(report.restored.is_empty() && report.failed.len() == 2, "{report:?}"); } else { assert_eq!(report.restored, [id.0], "{report:?}"); + assert!(report.failed.is_empty(), "{report:?}"); assert_eq!(photo.content_hash, expected); assert_eq!(photo.file_size, std::fs::metadata(original).unwrap().len()); s.execute("edit.undo", &json!({})).unwrap(); @@ -5767,12 +5774,41 @@ fn a_reused_deleted_path_does_not_claim_a_dng_restore() { std::fs::write(&old, &other).unwrap(); let report = crate::import::import_with(&mut s, &[old.clone(), input], &opts).unwrap(); assert_eq!(report.restored, [id.0], "{report:?}"); + assert!(report.imported.is_empty() && report.failed.len() == 1, "{report:?}"); let path = file_source_path(s.catalog.photo(id).unwrap()); assert_ne!(path, old); assert_eq!(std::fs::read(path).unwrap(), wanted); assert_eq!(std::fs::read(old).unwrap(), other); } +#[test] +fn a_changed_generated_dng_never_gets_a_new_catalog_record() { + use crate::import::{ImportJob, ImportMode, ImportOptions, Organize, commit_prepared}; + let dir = super::TestDir::new("dng-changed-before-add"); + let source = dir.join("source.orf"); + let destination = dir.join("copies"); + std::fs::write(&source, crate::files::tests::sensor_orf()).unwrap(); + let opts = ImportOptions { + mode: ImportMode::Copy, + destination: Some(destination.to_string_lossy().into()), + organize: Organize::Flat, + convert_dng: true, + ..Default::default() + }; + let mut s = Session::new().with_fs(); + let mut job = ImportJob::new(&mut s, opts.clone()).unwrap(); + let batch = job.prepare(&[source.to_string_lossy().into_owned()], &std::sync::atomic::AtomicBool::new(false)); + let output = destination.join("source.dng"); + let mut bytes = std::fs::read(&output).unwrap(); + bytes[0] ^= 1; + std::fs::write(&output, &bytes).unwrap(); + let report = commit_prepared(&mut s, &opts, job.now(), batch).unwrap(); + assert!(report.imported.is_empty() && report.failed.len() == 1, "{report:?}"); + assert!(s.catalog.is_empty()); + assert_eq!(std::fs::read(&output).unwrap(), bytes); + assert!(source.is_file()); +} + fn file_source_path(p: &lightcraft_catalog::Photo) -> String { match &p.source { lightcraft_catalog::Source::File { path } => path.clone(), diff --git a/crates/wincolor/Cargo.toml b/crates/wincolor/Cargo.toml index 8cf4739a112..3dbd2bde799 100644 --- a/crates/wincolor/Cargo.toml +++ b/crates/wincolor/Cargo.toml @@ -17,6 +17,7 @@ windows-sys = { version = "0.61", features = [ "Win32_Graphics_Gdi", "Win32_UI_ColorSystem", "Win32_Devices_Display", + "Win32_Storage_FileSystem", ] } [dev-dependencies] diff --git a/crates/wincolor/src/lib.rs b/crates/wincolor/src/lib.rs index 8a1112ad0d8..241a005a6be 100644 --- a/crates/wincolor/src/lib.rs +++ b/crates/wincolor/src/lib.rs @@ -17,8 +17,8 @@ //! //! The Win32 calls (`MonitorFromWindow`, `GetMonitorInfoW`, `EnumDisplayDevicesW`, the `Wcs…` //! profile functions, `QueryDisplayConfig` + `DisplayConfigGetDeviceInfo`) are in the `win32` module, -//! the only place besides `crates/sysmem` where LightCraft allows `unsafe`. The API is safe, and any -//! failure answers [`MonitorColor::Unknown`]. +//! along with the Win32 call for identifying an open file. This is the only place besides +//! `crates/sysmem` where LightCraft allows `unsafe`. The APIs are safe. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use std::path::PathBuf; @@ -53,6 +53,13 @@ pub fn monitor_color(hwnd: isize) -> MonitorColor { } } +/// The volume serial number and full 128-bit identity of an opened Windows file. Returns +/// `None` when the file system or driver does not supply a reliable identifier. +#[cfg(windows)] +pub fn open_file_id(file: &std::fs::File) -> Option<(u64, [u8; 16])> { + win32::open_file_id(file) +} + /// `true` when Windows colour-manages the desktop on a display with these advanced-colour flags /// (`DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO`'s bit field): advanced colour enabled (bit 1: HDR, or /// Auto Color Management) or wide colour enforced (bit 2). @@ -86,6 +93,7 @@ mod win32 { use super::{MonitorColor, managed, settled_by_windows, until_nul}; use std::ffi::OsString; use std::os::windows::ffi::OsStringExt; + use std::os::windows::io::AsRawHandle; use std::path::PathBuf; use windows_sys::Win32::Devices::Display::{ DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO, DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER, @@ -97,6 +105,7 @@ mod win32 { CreateDCW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteDC, EnumDisplayDevicesW, GetMonitorInfoW, MONITOR_DEFAULTTONEAREST, MONITORINFO, MONITORINFOEXW, MonitorFromWindow, }; + use windows_sys::Win32::Storage::FileSystem::{FILE_ID_INFO, FileIdInfo, GetFileInformationByHandleEx}; use windows_sys::Win32::UI::ColorSystem::{ CPST_NONE, CPT_ICC, GetColorDirectoryW, GetICMProfileW, WCS_PROFILE_MANAGEMENT_SCOPE_CURRENT_USER, WCS_PROFILE_MANAGEMENT_SCOPE_SYSTEM_WIDE, WcsGetDefaultColorProfile, WcsGetDefaultColorProfileSize, WcsGetUsePerUserProfiles, @@ -111,6 +120,17 @@ mod win32 { /// The longest profile name read, in bytes (names are file names in the colour directory). const MAX_NAME_BYTES: u32 = 64 << 10; + pub fn open_file_id(file: &std::fs::File) -> Option<(u64, [u8; 16])> { + let mut info = FILE_ID_INFO::default(); + // SAFETY: the open File owns the handle for the call, and the writable buffer has exactly + // the type and size that GetFileInformationByHandleEx expects for FileIdInfo. + let ok = unsafe { + GetFileInformationByHandleEx(file.as_raw_handle(), FileIdInfo, (&mut info as *mut FILE_ID_INFO).cast(), size_of::() as u32) + }; + let id = info.FileId.Identifier; + (ok != 0 && id != [0; 16]).then_some((info.VolumeSerialNumber, id)) + } + pub fn monitor_color(hwnd: isize) -> MonitorColor { let Some(device) = monitor_device(hwnd) else { return MonitorColor::Unknown }; // (an advanced-colour state that can't be read, as on Windows before 10 1709 or with a From c68db5875976610e2a4abef50c586ef85794ebde Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 20:15:36 +0100 Subject: [PATCH 28/42] Separate import reconciliation from catalog commit --- crates/engine/src/import/commit.rs | 44 ++++++++++++++++++------------ 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index b282eb610a7..5a76241fcd7 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -385,6 +385,15 @@ fn invalid_generated_output(ready: &ReadyFile) -> bool { && !ready.info.content_hash.as_deref().is_some_and(|hash| ready.copy.as_ref().is_some_and(|copy| copy.is_current(&ready.stored, Some(hash)))) } +fn report_unverified_dng_paths(s: &Session, report: &mut ImportReport, paths: Vec<(PhotoId, String, Option)>) { + report.failed.extend(paths.into_iter().filter_map(|(id, path, hash)| { + let restored_here = s.catalog.photo(id).is_some_and(|photo| { + photo.content_hash.is_some() && photo.content_hash == hash && photo.library_file().is_some_and(|source| same_import_file(source, &path)) + }); + (!restored_here).then_some((path, "this DNG could not be verified as the deleted photo's original; it was left untouched".into())) + })); +} + fn replacement_is_current(path: &str, hash: Option<&str>, output: Option<&CopyOutput>) -> bool { match output { Some(copy) => copy.is_current(path, hash), @@ -460,6 +469,22 @@ fn restore_duplicate( Ok(()) } +/// Deleted records that Fresh can replace, indexed by their last known hash and path. +fn fresh_replacement_targets(s: &Session, on_deleted: OnDeleted) -> (HashMap, HashMap) { + let (mut hashes, mut paths) = (HashMap::new(), HashMap::new()); + if on_deleted == OnDeleted::Fresh { + for photo in s.catalog.photos().filter(|p| p.deleted) { + if let Some(hash) = &photo.content_hash { + hashes.insert(hash.clone(), photo.id); + } + if let Source::File { path } = &photo.source { + paths.insert(path.clone(), photo.id); + } + } + } + (hashes, paths) +} + /// The catalog half of an import: add the photos [`ImportJob::prepare`] readied (one undoable op; /// a Move's sources are removed once it is saved). On a failed commit a Move's placed files are /// taken back. @@ -493,17 +518,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare converted_hashes, ); // Fresh: trashed photos a new import replaces (by content or by file), each removed once - let (mut trash_hash, mut trash_path): (HashMap, HashMap) = Default::default(); - if opts.on_deleted == OnDeleted::Fresh { - for p in s.catalog.photos().filter(|p| p.deleted) { - if let Some(h) = &p.content_hash { - trash_hash.insert(h.clone(), p.id); - } - if let Source::File { path } = &p.source { - trash_path.insert(path.clone(), p.id); - } - } - } + let (trash_hash, trash_path) = fresh_replacement_targets(s, opts.on_deleted); let mut purge: Vec = Vec::new(); let mut purged: std::collections::HashSet = Default::default(); for it in prepared.items { @@ -658,12 +673,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare for copy in cleanup { copy.remove(s, &prepared.restore_checks, &mut report); } - report.failed.extend(unverified_dng_paths.into_iter().filter_map(|(id, path, hash)| { - let restored_here = s.catalog.photo(id).is_some_and(|photo| { - photo.content_hash.is_some() && photo.content_hash == hash && photo.library_file().is_some_and(|source| same_import_file(source, &path)) - }); - (!restored_here).then_some((path, "this DNG could not be verified as the deleted photo's original; it was left untouched".into())) - })); + report_unverified_dng_paths(s, &mut report, unverified_dng_paths); if !placed.is_empty() { finish_moves(s, placed, log0, &mut report); } From 12491c428dcdf6067ec5307785272614d73a0767 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 20:31:27 +0100 Subject: [PATCH 29/42] Preserve browsed-photograph imports during DNG reconciliation --- crates/engine/src/import/commit.rs | 101 +++++++++++++++++++---------- crates/engine/src/import/job.rs | 40 +++++------- crates/engine/src/tests/import.rs | 40 ++++++++++++ 3 files changed, 125 insertions(+), 56 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 5a76241fcd7..3ead0fefee0 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -418,16 +418,22 @@ fn restore_legacy_dng(photo: &Photo, check: Option<&RestoreCheck>, ops: &mut Vec Some(()) } +struct DuplicateSource<'a> { + path: &'a str, + reason: &'a str, + hash: Option<&'a str>, +} + /// Append a duplicate's Restore only after verifying the file it will reference. fn restore_duplicate( + s: &Session, photo: &Photo, - path: &str, - reason: &str, - hash: Option<&str>, + source: DuplicateSource<'_>, target: &RestoreTarget, check: Option<&RestoreCheck>, ops: &mut Vec, ) -> Result<(), &'static str> { + let DuplicateSource { path, reason, hash } = source; if reason == "path" { if !cfg!(target_arch = "wasm32") && let Some(expected) = photo.content_hash.as_deref() @@ -462,13 +468,62 @@ fn restore_duplicate( { return Err("the replacement file changed before Restore"); } - ops.push(crate::cmd::missing::relink_op(photo.id, path)); + let held = s.catalog.photos().any(|p| p.id != photo.id && matches!(&p.source, Source::File { path: own } if own == path)); + if held { + // A matching browsed twin can restore a catalog record whose original is offline, + // but the twin must keep its own path. Keep changed originals and unavailable + // generated replacements in the trash instead of pointing at different bytes. + let missing = matches!(&photo.source, Source::File { path: original } + if std::fs::metadata(original).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)); + if !missing || !matches!(target, RestoreTarget::Decide { .. }) { + return Err("the matching file already belongs to another photo; the photo stays deleted"); + } + } else { + ops.push(crate::cmd::missing::relink_op(photo.id, path)); + } } } ops.push(Op::SetDeleted { id: photo.id, deleted: false }); Ok(()) } +fn promotion_hash<'a>(s: &'a Session, id: PhotoId, fresh: Option<&'a ProbeInfo>) -> Option<&'a str> { + let photo = s.catalog.photo(id).filter(|p| !p.deleted)?; + match fresh { + Some(info) if photo.local => info.content_hash.as_deref(), + _ => photo.content_hash.as_deref(), + } +} + +fn promote_photo(s: &Session, id: PhotoId, fresh: Option<&ProbeInfo>, ops: &mut Vec) { + if !s.catalog.photo(id).is_some_and(|p| p.local && !p.deleted) { + return; + } + if let Some(info) = fresh { + let targets = s.catalog.photos().filter(|p| p.id == id || p.copy_of == Some(id)).map(|p| p.id); + crate::cmd::convert::reload_ops(&s.catalog, id, info, ops, &mut Vec::new(), targets, |target| target == id); + } + ops.push(Op::SetLocal { id, local: false }); +} + +/// Record hashes a transfer can match, using the new content for browsed files that will be promoted. +fn prepared_hashes(s: &Session, opts: &ImportOptions, items: &[PreparedItem]) -> HashMap { + let converted = items.iter().filter_map(|it| match it { + PreparedItem::Ready(r) if r.generated_dng && !opts.local => r.info.content_hash.as_deref(), + _ => None, + }); + let mut hashes = + super::scan::library_hashes(s.catalog.photos().filter(|p| !(p.local || p.deleted && opts.on_deleted == OnDeleted::Fresh)), converted); + for item in items { + if let PreparedItem::Promote(id, fresh) = item + && let Some(hash) = promotion_hash(s, *id, fresh.as_deref()) + { + hashes.entry(hash.to_owned()).or_insert(*id); + } + } + hashes +} + /// Deleted records that Fresh can replace, indexed by their last known hash and path. fn fresh_replacement_targets(s: &Session, on_deleted: OnDeleted) -> (HashMap, HashMap) { let (mut hashes, mut paths) = (HashMap::new(), HashMap::new()); @@ -500,23 +555,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare let mut placed: Vec<(crate::import_move::Placed, Option>)> = Vec::new(); // Current converted outputs, then this batch's additions and input aliases. Keep only the // hashes this batch asks about, even for a library of millions of photos. - let converted_hashes = prepared.items.iter().filter_map(|it| match it { - PreparedItem::Ready(r) if r.generated_dng && !opts.local => r.info.content_hash.as_deref(), - _ => None, - }); - // Local records count only when this same atomic import already promotes them into the library. - let promoted: std::collections::HashSet<_> = prepared - .items - .iter() - .filter_map(|it| match it { - PreparedItem::Promote(id, _) => Some(*id), - _ => None, - }) - .collect(); - let mut new_hash = super::scan::library_hashes( - s.catalog.photos().filter(|p| (!p.local || promoted.contains(&p.id)) && !(p.deleted && opts.on_deleted == OnDeleted::Fresh)), - converted_hashes, - ); + let mut new_hash = prepared_hashes(s, opts, &prepared.items); // Fresh: trashed photos a new import replaces (by content or by file), each removed once let (trash_hash, trash_path) = fresh_replacement_targets(s, opts.on_deleted); let mut purge: Vec = Vec::new(); @@ -533,19 +572,11 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare }; match it { PreparedItem::Promote(id, fresh) => { - // the file was replaced since it was browsed: the record takes what it is now before it joins the library - if let Some(info) = &fresh { - let targets = s.catalog.photos().filter(|p| p.id == id || p.copy_of == Some(id)).map(|p| p.id); - crate::cmd::convert::reload_ops(&s.catalog, id, info, &mut ops, &mut Vec::new(), targets, |target| target == id); - } - if s.catalog.photo(id).is_some_and(|p| p.local) { - ops.push(Op::SetLocal { id, local: false }); - } + promote_photo(s, id, fresh.as_deref(), &mut ops); note_no_backup_in_place(s, opts, id, &mut report); // "Import as new": a trashed photo with the same content is replaced, as for a new file - let content = - fresh.as_ref().and_then(|i| i.content_hash.clone()).or_else(|| s.catalog.photo(id).and_then(|p| p.content_hash.clone())); - if let Some(old) = content.as_ref().and_then(|h| trash_hash.get(h)) + let content = promotion_hash(s, id, fresh.as_deref()); + if let Some(old) = content.and_then(|h| trash_hash.get(h)) && purged.insert(*old) { purge.push(*old); @@ -567,7 +598,8 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare Some(id) if opts.on_deleted == OnDeleted::Restore && !opts.local => { if !report.restored.contains(&id.0) { let Some(photo) = s.catalog.photo(id) else { continue }; - match restore_duplicate(photo, &path, reason, hash.as_deref(), &restore, prepared.restore_checks.get(&id), &mut ops) { + let source = DuplicateSource { path: &path, reason, hash: hash.as_deref() }; + match restore_duplicate(s, photo, source, &restore, prepared.restore_checks.get(&id), &mut ops) { Ok(()) => report.restored.push(id.0), Err(reason) => report.failed.push((path, reason.into())), } @@ -581,7 +613,7 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare PreparedItem::Failed(path, e) => report.failed.push((path, e)), PreparedItem::Kept(k) => report.kept.push(k), PreparedItem::Ready(r) => { - let ReadyFile { path, stored, info, input_hash, sidecar, placed: pl, backup } = *r; + let ReadyFile { path, stored, info, input_hash, sidecar, placed: pl, backup, .. } = *r; let backed_up = note_backup(&mut report, &path, &stored, backup); placed.extend(pl.map(|p| (p, backed_up))); let id = s.catalog.alloc_photo_id(); @@ -1000,6 +1032,7 @@ mod tests { .then(|| CopyOutput::new(std::fs::File::open(&stored).unwrap(), info.content_hash.as_deref())), sidecar: None, placed: None, + backup: None, })) }; let mut items = vec![ready(raw.clone(), converted, Some("input raw hash".into())), ready(dir.join("./ordinary.dng"), stored, None)]; diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index d2dbb32b08c..fd911424786 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -41,9 +41,8 @@ pub struct ImportJob { pub(super) library: Option<(lightcraft_catalog::Catalog, bool)>, /// path → (photo, a Local browse record?) pub(super) by_path: HashMap)>, - /// path → the size the record of a browsed (Local) file has: a file of another size has been replaced since - /// it was browsed ([`super::files::browsed_files_changed`]) - local_sizes: HashMap, + /// path → the recorded size and format of a browsed (Local) file + local_files: HashMap, /// content hash → the photo that has it (`None`: a file earlier in this import) pub(super) by_hash: HashMap>, /// Paths of deleted duplicates, captured before the worker starts. @@ -427,7 +426,7 @@ impl ImportJob { backup_root, library: Some((s.catalog.clone(), fresh)), by_path: HashMap::new(), - local_sizes: HashMap::new(), + local_files: HashMap::new(), by_hash: HashMap::new(), restore_sources: HashMap::new(), probe: s.media.file_probe.clone(), @@ -511,7 +510,7 @@ impl ImportJob { if let Source::File { path } = &p.source { self.by_path.insert(path.clone(), (p.id, p.local, p.content_hash.clone())); if p.local { - self.local_sizes.insert(path.clone(), p.file_size); + self.local_files.insert(path.clone(), (p.file_size, p.format.clone())); } } // (a copy that was only browsed in Local isn't in the library) @@ -535,13 +534,18 @@ impl ImportJob { fn sort_by_library( &mut self, files: Vec, - verdicts: Vec>, - local: bool, + cancel: &std::sync::atomic::AtomicBool, out: &mut Prepared, - changed: &mut HashMap, - todo: &mut Vec, - ) { + ) -> (Vec, HashMap) { use std::sync::atomic::Ordering::Relaxed; + let local = self.opts.local; + let is_browsed = |f: &String| !local && matches!(self.by_path.get(f.as_str()), Some((_, true, _))); + let browsed: Vec<(&str, u64)> = + files.iter().filter(|f| is_browsed(f)).map(|f| (f.as_str(), self.local_files.get(f.as_str()).map_or(0, |(size, _)| *size))).collect(); + let mut looked_at = browsed_files_changed(&browsed, cancel).into_iter(); + let verdicts: Vec> = files.iter().map(|f| is_browsed(f).then(|| looked_at.next()).flatten()).collect(); + let mut todo = Vec::new(); + let mut changed = HashMap::new(); for (f, verdict) in files.into_iter().zip(verdicts) { match self.by_path.get(f.as_str()).cloned() { // A known deleted path is only a candidate. Its bytes might belong to another photo now. @@ -575,6 +579,7 @@ impl ImportJob { None => todo.push(f), } } + (todo, changed) } /// A browsed file this import brings into the library (its size unchanged): a duplicate of a library photo with @@ -584,12 +589,13 @@ impl ImportJob { // (here or in a previous batch) counts as the library's from then on if let Some(h) = &hash { if let Some(existing) = self.by_hash.get(h) { + let format = self.local_files.get(&f).map(|(_, format)| format.clone()); return PreparedItem::Duplicate { path: f, existing: *existing, reason: "content", hash, - restore: RestoreTarget::Decide { format: None }, + restore: RestoreTarget::Decide { format }, file: None, }; } @@ -619,17 +625,7 @@ impl ImportJob { let opts = self.opts.clone(); let mode = self.mode; let mut out = Prepared { scanned: files.len(), ..Default::default() }; - let mut todo = Vec::new(); - // browsed files replaced since: probed again with `todo`, their records brought up to date as they join the library - let mut changed: HashMap = HashMap::new(); - // the sizes of the browsed files this import would promote, looked at together before they are decided one by one - // (a file promoted in an earlier batch isn't asked about again; one path twice in a batch is, and its second answer is unused) - let is_browsed = |f: &String| !opts.local && matches!(self.by_path.get(f.as_str()), Some((_, true, _))); - let browsed: Vec<(&str, u64)> = - files.iter().filter(|f| is_browsed(f)).map(|f| (f.as_str(), self.local_sizes.get(f.as_str()).copied().unwrap_or(0))).collect(); - let mut looked_at = browsed_files_changed(&browsed, cancel).into_iter(); - let verdicts: Vec> = files.iter().map(|f| is_browsed(f).then(|| looked_at.next()).flatten()).collect(); - self.sort_by_library(files, verdicts, opts.local, &mut out, &mut changed, &mut todo); + let (todo, mut changed) = self.sort_by_library(files, cancel, &mut out); // files a preceding scan already probed are not read again (a network share is slow to read), // as long as they are still there, as they were: a file gone or changed since is probed again diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index b4b5d9e2c9e..971d566c4e8 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5287,6 +5287,46 @@ fn followup_copy_as_dng_deduplicates_against_a_pending_local_promotion() { copy_as_dng_with_local_match(true); } +#[test] +fn copy_as_dng_compares_a_replaced_browsed_file_using_its_fresh_hash() { + use crate::import::{ImportMode, ImportOptions, Organize}; + for updated_matches in [false, true] { + let dir = super::TestDir::new(&format!("copy-dng-fresh-browse-{updated_matches}")); + let raw = dir.join("source.orf"); + std::fs::write(&raw, crate::files::tests::sensor_orf()).unwrap(); + let (encoded, _, _) = crate::cmd::convert::write_dng_with(None, &raw.to_string_lossy(), String::new()).unwrap(); + let dng = std::fs::read(encoded).unwrap(); + let mut changed = lightcraft_raw::decode(&dng).unwrap(); + let lightcraft_raw::RawData::U16(samples) = &mut changed.data else { panic!("integer fixture") }; + samples[0] ^= 1; + let mut different = lightcraft_raw::write_dng(&changed, &Default::default()).unwrap(); + different.resize(different.len().max(dng.len()) + 16, 0); + let (before, after) = if updated_matches { (&different, &dng) } else { (&dng, &different) }; + let local_path = dir.join("browsed.dng").to_string_lossy().into_owned(); + std::fs::write(&local_path, before).unwrap(); + let mut s = Session::new().with_fs(); + let browsed = + crate::import::import_with(&mut s, std::slice::from_ref(&local_path), &ImportOptions { local: true, ..Default::default() }).unwrap(); + let local = PhotoId(browsed.imported[0]); + std::fs::write(&local_path, after).unwrap(); + let destination = dir.join("copies"); + let opts = ImportOptions { + mode: ImportMode::Copy, + destination: Some(destination.to_string_lossy().into()), + organize: Organize::Flat, + convert_dng: true, + ..Default::default() + }; + let report = crate::import::import_with(&mut s, &[raw.to_string_lossy().into_owned(), local_path], &opts).unwrap(); + assert!(report.failed.is_empty(), "{report:?}"); + assert_eq!((report.imported.len(), report.duplicates.len()), (if updated_matches { 1 } else { 2 }, usize::from(updated_matches))); + let promoted = s.catalog.photo(local).unwrap(); + assert!(promoted.in_library()); + assert_eq!(promoted.content_hash, Some(lightcraft_preview::hash_bytes(after).to_string())); + assert_eq!(copy_dng_output_names(&destination).len(), usize::from(!updated_matches)); + } +} + fn copy_as_dng_with_local_match(promote: bool) { use crate::import::{ImportMode, ImportOptions, Organize}; use lightcraft_catalog::Source; From fe158eb50e61b175f2ebbb1f1d04db2403b2c548 Mon Sep 17 00:00:00 2001 From: pancake Date: Sat, 28 Nov 2026 01:53:06 +0100 Subject: [PATCH 30/42] =?UTF-8?q?DNG=20Restore:=20reuse=20the=20worker?= =?UTF-8?q?=E2=80=99s=20file=20verification?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crates/engine/src/import/commit.rs | 48 +++++++++++++++++++++++------- crates/engine/src/import/job.rs | 30 ++++++++++++------- 2 files changed, 58 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 3ead0fefee0..0c79e07bcfb 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -234,8 +234,11 @@ fn back_up( Ok(copy.to_string_lossy().to_string()) } -fn has_verified_content(path: &str, hash: Option<&str>) -> bool { +fn has_verified_content(path: &str, hash: Option<&str>, check: Option<&RestoreCheck>) -> bool { let (Some(hash), Some(stamp)) = (hash, restore_stamp(path)) else { return false }; + if let Some(matches) = check.and_then(|check| check.content_matches(path, hash, stamp)) { + return matches; + } crate::cmd::missing::file_hash(path).as_deref() == Some(hash) && restore_stamp(path) == Some(stamp) } @@ -245,13 +248,8 @@ fn trashed_file_differs(photo: &Photo, hash: Option<&str>, check: Option<&Restor if cfg!(target_arch = "wasm32") || hash.is_none() || photo.content_hash.as_deref() != hash { return false; } - if check - .is_some_and(|check| check.path == *path && Some(check.hash.as_str()) == hash && check.stamp.is_some() && restore_stamp(path) == check.stamp) - { - return false; - } // A changed stamp can still name the same bytes, and the catalog may have changed since preparation. - !has_verified_content(path, hash) + !has_verified_content(path, hash, check) } /// What a new record takes from its file, as a file import gives it: the file's metadata and @@ -397,7 +395,7 @@ fn report_unverified_dng_paths(s: &Session, report: &mut ImportReport, paths: Ve fn replacement_is_current(path: &str, hash: Option<&str>, output: Option<&CopyOutput>) -> bool { match output { Some(copy) => copy.is_current(path, hash), - None => has_verified_content(path, hash), + None => has_verified_content(path, hash, None), } } @@ -405,7 +403,7 @@ fn restore_legacy_dng(photo: &Photo, check: Option<&RestoreCheck>, ops: &mut Vec let Source::File { path } = &photo.source else { return None }; let check = check.filter(|check| check.path == *path && photo.content_hash.as_deref() == Some(check.hash.as_str()))?; let info = check.legacy_dng.as_ref()?; - if check.stamp != restore_stamp(path) && !has_verified_content(path, info.content_hash.as_deref()) { + if check.stamp != restore_stamp(path) && !has_verified_content(path, info.content_hash.as_deref(), None) { return None; } ops.extend(crate::cmd::convert::content_facts_op(photo.id, photo, &info.format, info)); @@ -437,7 +435,7 @@ fn restore_duplicate( if reason == "path" { if !cfg!(target_arch = "wasm32") && let Some(expected) = photo.content_hash.as_deref() - && !has_verified_content(path, Some(expected)) + && !has_verified_content(path, Some(expected), check) { return Err("the file at this deleted photo's path has changed"); } @@ -951,6 +949,36 @@ mod clock_tests { mod tests { use super::*; + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn restore_preparation_keeps_the_verdict_for_a_reused_original_path() { + let dir = crate::tests::TestDir::new("restore-worker-verdict"); + let original = dir.join("original.dng").to_string_lossy().into_owned(); + let incoming = dir.join("incoming.dng").to_string_lossy().into_owned(); + let dng = crate::tests_xmp::synthetic_dng_with(None, Default::default()); + std::fs::write(&original, &dng).unwrap(); + std::fs::write(&incoming, &dng).unwrap(); + let mut s = Session::new().with_fs(); + let opts = ImportOptions::default(); + let report = crate::import::import_with(&mut s, std::slice::from_ref(&original), &opts).unwrap(); + let id = PhotoId(report.imported[0]); + s.catalog.apply(Op::SetDeleted { id, deleted: true }).unwrap(); + let hash = s.catalog.photo(id).unwrap().content_hash.clone().unwrap(); + std::fs::write(&original, b"a different file now occupies this path").unwrap(); + + let mut job = crate::import::ImportJob::new(&mut s, opts.clone()).unwrap(); + let batch = job.prepare(std::slice::from_ref(&incoming), &std::sync::atomic::AtomicBool::new(false)); + let check = &batch.restore_checks[&id]; + let observed = restore_stamp(&original).unwrap(); + assert_eq!(check.content_matches(&original, &hash, observed), Some(false)); + assert_eq!(check.content_matches(&original, &hash, restore_stamp(&incoming).unwrap()), None); + + let report = commit_prepared(&mut s, &opts, job.now(), batch).unwrap(); + assert_eq!(report.restored, [id.0]); + assert_eq!(s.catalog.photo(id).unwrap().library_file(), Some(incoming.as_str())); + assert_eq!(std::fs::read(original).unwrap(), b"a different file now occupies this path"); + } + #[test] fn an_in_place_edit_before_capturing_the_dng_stamp_does_not_become_verified() { let dir = crate::tests::TestDir::new("changed-before-dng-stamp"); diff --git a/crates/engine/src/import/job.rs b/crates/engine/src/import/job.rs index fd911424786..7f30228124a 100644 --- a/crates/engine/src/import/job.rs +++ b/crates/engine/src/import/job.rs @@ -88,6 +88,7 @@ pub(super) struct RestoreCheck { pub(super) path: String, pub(super) hash: String, pub(super) stamp: Option, + content_matches: Option, pub(super) legacy_dng: Option>, // Windows does not expose the file change time through stable Rust. Hold the original // open without write or delete sharing from verification through catalog reconciliation. @@ -95,6 +96,13 @@ pub(super) struct RestoreCheck { _read_guard: Option, } +impl RestoreCheck { + /// Reuse a definite worker verdict while it still describes this source. + pub(super) fn content_matches(&self, path: &str, hash: &str, stamp: RestoreStamp) -> Option { + self.content_matches.filter(|_| self.path == path && self.hash == hash && self.stamp == Some(stamp)) + } +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct RestoreStamp { len: u64, @@ -893,9 +901,10 @@ impl ImportJob { break; } let (id, incoming) = match item { - PreparedItem::Duplicate { - path, existing, reason: "content", hash: Some(hash), restore: RestoreTarget::Decide { format }, .. - } => (existing.or_else(|| self.by_hash.get(hash).copied().flatten()), format.as_deref().map(|format| (path.as_str(), format))), + PreparedItem::Duplicate { path, existing, reason: "content" | "path", hash, restore: RestoreTarget::Decide { format }, .. } => ( + existing.or_else(|| self.by_hash.get(hash.as_ref()?).copied().flatten()), + format.as_deref().map(|format| (path.as_str(), format)), + ), PreparedItem::Ready(r) => (r.info.content_hash.as_ref().and_then(|hash| self.by_hash.get(hash).copied().flatten()), None), _ => (None, None), }; @@ -911,26 +920,27 @@ impl ImportJob { let stamp = restore_stamp(path); #[cfg(windows)] let stamp = stamp.filter(|_| read_guard.is_some()); + let mut content_matches = None; let mut legacy_dng = None; let stamp = stamp.filter(|stamp| { - if crate::cmd::missing::file_hash(path).as_deref() == Some(hash) { - return restore_stamp(path) == Some(*stamp); - } - if format.eq_ignore_ascii_case("DNG") + content_matches = crate::cmd::missing::file_hash(path).map(|actual| actual == *hash); + if content_matches != Some(true) + && format.eq_ignore_ascii_case("DNG") && let Some((input, input_format)) = incoming && !input_format.is_empty() && !input_format.eq_ignore_ascii_case("DNG") && !cfg!(target_arch = "wasm32") { - legacy_dng = probe_legacy_dng(path, input, hash).filter(|_| restore_stamp(path) == Some(*stamp)).map(Box::new); + legacy_dng = probe_legacy_dng(path, input, hash).map(Box::new); } - legacy_dng.is_some() + (content_matches.is_some() || legacy_dng.is_some()) && restore_stamp(path) == Some(*stamp) }); RestoreCheck { path: path.clone(), hash: hash.clone(), stamp, - legacy_dng, + content_matches, + legacy_dng: legacy_dng.filter(|_| stamp.is_some()), #[cfg(windows)] _read_guard: read_guard, } From 0835d60ed245988d5490ffb18736b93b26f9bee8 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 3 Dec 2026 14:17:58 +0100 Subject: [PATCH 31/42] DNG import: verify the backup mirrors the converted output --- crates/engine/src/tests/import.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 971d566c4e8..19754885188 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5443,6 +5443,7 @@ fn copy_as_dng_keeps_input_metadata_and_deduplicates_across_jobs_and_reopen() { let dir = super::TestDir::new("copy-dng-output-facts"); let library = dir.join("library"); let destination = dir.join("destination"); + let backup = dir.join("backup"); let paths: Vec<_> = ["first.orf", "second.orf"].map(|name| dir.join(name).to_string_lossy().to_string()).into(); let xmp = r#""#; let input = crate::tests_xmp::synthetic_dng_with(Some(xmp), Default::default()); @@ -5468,6 +5469,7 @@ fn copy_as_dng_keeps_input_metadata_and_deduplicates_across_jobs_and_reopen() { let opts = ImportOptions { mode: ImportMode::Copy, destination: Some(destination.to_string_lossy().into()), + backup: Some(backup.to_string_lossy().into()), organize: Organize::Flat, convert_dng: true, ..Default::default() @@ -5484,6 +5486,10 @@ fn copy_as_dng_keeps_input_metadata_and_deduplicates_across_jobs_and_reopen() { let photo = s.catalog.photo(id).unwrap().clone(); let Source::File { path: output } = &photo.source else { panic!("file photo") }; let bytes = std::fs::read(output).unwrap(); + assert!(report.backup_failed.is_empty(), "{report:?}"); + assert_eq!(report.backups.len(), 1, "{report:?}"); + assert_eq!(report.backups[0].path, *output); + assert_eq!(std::fs::read(backup.join(Path::new(output).file_name().unwrap())).unwrap(), bytes); assert_eq!((photo.kind, photo.format.as_str(), &photo.preview_only), (MediaKind::Raw, "DNG", &None)); assert_eq!(photo.content_hash, Some(lightcraft_preview::hash_bytes(&bytes).to_string())); assert_ne!(photo.content_hash, Some(lightcraft_preview::hash_bytes(&input).to_string())); From bdad4a65104c68a1bf581042dfa28773f6dae4bd Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 3 Dec 2026 14:19:53 +0100 Subject: [PATCH 32/42] DNG import: cover valid replacements and redundant output cleanup --- crates/engine/src/import/commit.rs | 8 +++++++- crates/engine/src/tests/import.rs | 21 ++++++++++++++------- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/import/commit.rs b/crates/engine/src/import/commit.rs index 0c79e07bcfb..cbef1bf46e6 100644 --- a/crates/engine/src/import/commit.rs +++ b/crates/engine/src/import/commit.rs @@ -1063,7 +1063,8 @@ mod tests { backup: None, })) }; - let mut items = vec![ready(raw.clone(), converted, Some("input raw hash".into())), ready(dir.join("./ordinary.dng"), stored, None)]; + let mut items = + vec![ready(raw.clone(), converted.clone(), Some("input raw hash".into())), ready(dir.join("./ordinary.dng"), stored.clone(), None)]; if !converted_first { items.reverse(); } @@ -1075,6 +1076,11 @@ mod tests { assert_eq!(r.duplicates[0].existing, Some(r.imported[0])); assert_eq!(std::fs::read(&original).unwrap(), b"same DNG output", "an in-place original or alias is never removed"); assert_eq!(std::fs::read(&raw).unwrap(), b"input raw"); + if !converted_first { + assert!(!converted.exists(), "remove the redundant converted output"); + } else if copied { + assert!(!stored.exists(), "remove the redundant copied output"); + } std::fs::remove_dir_all(dir).unwrap(); } } diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 19754885188..596a26cdd6f 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -5636,15 +5636,23 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { std::fs::remove_file(&old).unwrap(); } let second = job.prepare(&source[1..], &cancel); + let replacement = matches!(*case, 2 | 4).then(|| { + let mut image = lightcraft_raw::decode(&raw).unwrap(); + crate::camera_preview::with_starting_colour(&mut image, &raw); + image.orientation = lightcraft_geom::Orientation::Rotate90; + let changed = lightcraft_raw::write_dng(&image, &Default::default()).unwrap(); + assert_ne!(changed, output); + assert_eq!(changed.len(), output.len()); + assert_eq!(lightcraft_raw::decode(&changed).unwrap().orientation, image.orientation); + changed + }); if *case == 1 { std::fs::remove_file(&old).unwrap(); } else if *case == 2 { use std::io::Write; let mtime = std::fs::metadata(&old).unwrap().modified().unwrap(); - let mut different = output.clone(); - different[0] ^= 1; let mut f = std::fs::File::create(&old).unwrap(); - f.write_all(&different).unwrap(); + f.write_all(replacement.as_ref().unwrap()).unwrap(); f.set_modified(mtime).unwrap(); assert_eq!(std::fs::metadata(&old).unwrap().modified().unwrap(), mtime); } else if *case == 3 { @@ -5654,9 +5662,7 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { } else if *case == 4 { let mtime = std::fs::metadata(&old).unwrap().modified().unwrap(); let incoming = dir.join("incoming.dng"); - let mut changed = output.clone(); - changed[0] ^= 1; - std::fs::write(&incoming, changed).unwrap(); + std::fs::write(&incoming, replacement.as_ref().unwrap()).unwrap(); std::fs::File::options().write(true).open(&incoming).unwrap().set_modified(mtime).unwrap(); std::fs::rename(&incoming, &old).unwrap(); assert_eq!(std::fs::metadata(&old).unwrap().modified().unwrap(), mtime); @@ -5672,8 +5678,9 @@ fn copy_as_dng_restore_uses_the_verified_output_across_batches() { if *case == 3 { assert_eq!(path, &old, "a new modification time alone does not move the restored photo"); assert_eq!(copy_dng_output_names(&destination).len(), 1); - } else if *case == 4 { + } else if let Some(replacement) = replacement { assert_ne!(path, &old, "a different file with the same mtime is not the original"); + assert_eq!(std::fs::read(old).unwrap(), replacement); } } } From 82306b6f8f987b582866a0b75ed0336940925637 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 3 Dec 2026 14:22:55 +0100 Subject: [PATCH 33/42] DNG import: retain the backup copy result after verification --- crates/engine/src/import_move.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/import_move.rs b/crates/engine/src/import_move.rs index 0be1bef76d5..6d5bb7d92d3 100644 --- a/crates/engine/src/import_move.rs +++ b/crates/engine/src/import_move.rs @@ -299,7 +299,7 @@ pub(crate) fn backup_copy(file: &Path, root: &Path, backup: &Path, expect: Optio inject(Fault::CorruptBackup); } match r { - Ok(()) => Ok(dst), + Ok(_) => Ok(dst), Err(e) if e.kind() == io::ErrorKind::AlreadyExists => match same_bytes(file, &dst) { Ok(true) => Ok(dst), Ok(false) => Err(format!("a different file is already at {}: it was left as it is, and no backup copy was made", dst.display())), From 5d600d161ca4f93f71a5fdfdec4538b5b6b74bc8 Mon Sep 17 00:00:00 2001 From: pancake Date: Wed, 25 Nov 2026 19:32:57 +0100 Subject: [PATCH 34/42] LR-CLOUD-SMARTPREVIEW: Preserve compatible proxy interpretations Keep raw sensor and embedded-preview pixels in separate proxy identities and retain older bytes for Undo and recovery. Validate offline candidates on workers, keeping the existing ORF proxy policy until the shared-decoder migration. --- assets/ATTRIBUTION.md | 2 +- crates/engine/src/availability.rs | 91 +++- crates/engine/src/cmd/previews.rs | 137 ++++-- crates/engine/src/media.rs | 5 +- crates/engine/src/media/cache.rs | 10 +- crates/engine/src/media/quick.rs | 4 +- crates/engine/src/media/source.rs | 11 +- crates/engine/src/smart.rs | 245 ++++++++-- crates/engine/src/smart/availability.rs | 141 ++++++ crates/engine/src/smart/tests.rs | 113 +++++ crates/engine/src/tests.rs | 2 + crates/engine/src/tests/import.rs | 189 ++++---- .../engine/src/tests/smart_interpretation.rs | 441 ++++++++++++++++++ crates/ui-egui/src/app/frame.rs | 2 + crates/ui-egui/src/control.rs | 37 ++ crates/ui-egui/src/panels/right/info.rs | 7 +- crates/ui-egui/src/tests/offline.rs | 29 ++ 17 files changed, 1290 insertions(+), 176 deletions(-) create mode 100644 crates/engine/src/smart/availability.rs create mode 100644 crates/engine/src/tests/smart_interpretation.rs diff --git a/assets/ATTRIBUTION.md b/assets/ATTRIBUTION.md index 5656b2b6e23..ee12b6be19d 100644 --- a/assets/ATTRIBUTION.md +++ b/assets/ATTRIBUTION.md @@ -28,7 +28,7 @@ covers a whole directory), or if a licence file referenced in the Licence column | `crates/raw/src/chart_table.rs` | Chart-measured camera colour matrices (DNG ColorMatrix1/2 and ForwardMatrix1/2 for Standard Illuminant A and D50) for the Canon EOS D60 | LightCraft contributors; ColorChecker photographs taken by Robert Woldberg on the maintainer's EOS D60 | original work: fitted to our own CRWs of a ColorChecker Classic (post-November-2014 formulation) under a ~2,900 K tungsten bulb (11 frames) and direct sun (~4,850 K, 20 frames); reference colours: X-Rite's published L*a*b* (D50) for the chart, as packaged by [colour-science](https://github.com/colour-science/colour) (BSD-3-Clause), used for fitting only and not shipped; method in `clean-room/crw/10-chart-calibration.md` | MIT OR Apache-2.0 | 2026-10-25 | kept by hand: a 3×3 matrix per illuminant fitted on chromaticity with neutral held at D50; no Adobe or third-party camera matrix, no number from a GPL raw decoder | | `assets/camera-tone/sony-dro-off.json` | Sony global tone curve with the Dynamic Range Optimizer off (32 knots), built into LightCraft for ARWs shot with DRO on | LightCraft contributors; source photographs by raw.pixls.us contributors | original work: tone curve quantile-matched over the pooled pixel pairs of 12 CC0 raw.pixls.us ARWs (DRO off, Standard creative style; ILCE-3500, -5000, -6600, -7CR, -7M3 ×3, -7S, -9M2, ILCA-77M2, SLT-A57, NEX-F3) and their embedded camera JPEGs; the file lists each source URL and SHA-256 and how the curve was derived (see also `docs/camera-preview-colour.md`); aggregate tone statistics only, no image content; no Adobe or third-party profile data | MIT OR Apache-2.0 (sources CC0) | 2026-10-09 | none | | `crates/scenes/` (generated images) | Procedural demo photographs | LightCraft contributors | original work (generated at runtime, no source imagery) | MIT OR Apache-2.0 | 2026-09-30 | n/a | -| `crates/ui-egui/src/tests/recheck.rs`, `crates/engine/src/{files/tests.rs,tests/{recheck,import}.rs}` (runtime fixtures) | Generated source and Reload fixtures | LightCraft contributors | original work: procedural RGB pixels, linear DNGs generated by LightCraft (including a one-sample-bit mutation for mixed-content Restore), and a synthetic uncompressed ORF | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-11-25 | generated at runtime, no binary fixture committed | +| `crates/ui-egui/src/tests/recheck.rs`, `crates/engine/src/{files/tests.rs,tests/{recheck,import,smart_interpretation}.rs}` (runtime fixtures) | Generated source and Reload fixtures | LightCraft contributors | original work: procedural RGB pixels, linear DNGs generated by LightCraft (including a one-sample-bit mutation for mixed-content Restore), and a synthetic uncompressed ORF | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | 2026-11-25 | generated at runtime, no binary fixture committed | | `crates/ui-egui/src/icons.rs` | UI icons drawn as vector paths in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-09-30 | n/a | | `crates/ui-egui/src/panels/person.rs` | Up arrow on the People page bulk-confirm control, drawn in code | LightCraft contributors | original work | MIT OR Apache-2.0 | 2026-10-13 | n/a | | `docs/images/*-tetons.jpg`, `docs/images/grid-pd.jpg` (screenshots containing it) | "The Tetons and the Snake River" | Ansel Adams (1942), U.S. National Archives | https://commons.wikimedia.org/wiki/File:Adams_The_Tetons_and_the_Snake_River.jpg | Public domain (U.S. federal government work) | 2026-09-30 | developed in LightCraft; shown inside app screenshots | diff --git a/crates/engine/src/availability.rs b/crates/engine/src/availability.rs index f78c4fb4890..eda2eca2b33 100644 --- a/crates/engine/src/availability.rs +++ b/crates/engine/src/availability.rs @@ -53,6 +53,9 @@ struct State { /// The files found not there (and not found there since). gone: HashSet, worker: bool, + /// The sole worker's current probe, and whether a write/delete made its answer obsolete. + in_flight: Option, + invalidated: bool, /// Bumped when the sweep under way is dropped for another one ([`Availability::restart_sweeps`]). sweep_epoch: u64, /// Whether file work a sweep gives way to is going on. @@ -121,6 +124,23 @@ impl Availability { self.background.is_some() } + /// Forget a changed file and refuse any probe that began before the change. A queued or + /// in-flight request is rechecked; otherwise the next caller queues it. Never performs I/O. + pub fn invalidate(&self, path: &str) { + let mut st = lock(&self.state); + st.known.remove(path); + if st.gone.remove(path) { + st.gone_generation += 1; + } + if st.in_flight.as_deref() == Some(path) { + st.invalidated = true; + } + drop(st); + if let Some(wake) = &self.background { + wake(); + } + } + /// Does `path` exist? Synchronous mode: checked now. Background mode: the cached answer /// (`None` while unknown); unknown or stale answers are queued for the worker. pub fn exists(&self, path: &str) -> Option { @@ -215,6 +235,7 @@ impl Availability { } } + /// Drain requested checks before sweeps, refusing answers invalidated while their probe ran. fn spawn_worker(&self, wake: Waker) { let (state, probe) = (self.state.clone(), self.probe.clone()); let started = std::thread::Builder::new().name("lc-availability".into()).spawn(move || { @@ -233,7 +254,7 @@ impl Availability { } st = lock(&state); } - match st.queue.pop_front() { + let next = match st.queue.pop_front() { Some(p) => (p, true), None => loop { let Some(p) = st.sweep.pop_front() else { @@ -245,11 +266,25 @@ impl Availability { break (p, false); } }, - } + }; + st.in_flight = Some(next.0.clone()); + st.invalidated = false; + next }; let ok = probe(&path); let wakes = { let mut st = lock(&state); + st.in_flight = None; + if st.invalidated { + // The answer predates a write/delete. Keep the request pending and + // retry instead of restoring stale state after the invalidation. + st.queued.insert(path.clone()); + // An explicit request may already be queued behind this sweep's probe. + if !st.queue.contains(&path) { + st.queue.push_back(path); + } + continue; + } if asked { st.queued.remove(&path); } @@ -295,6 +330,58 @@ mod tests { assert_eq!(n.load(Ordering::SeqCst), 3, "every question is a fresh check"); } + /// Invalidation wins over a probe already in flight, for both stale positive and negative answers. + #[test] + fn invalidation_rechecks_in_flight_answers_before_caching_them() { + for previous in [false, true] { + let mut a = Availability::default(); + let count = Arc::new(AtomicUsize::new(0)); + let (started, starts) = std::sync::mpsc::channel(); + let (release, released) = std::sync::mpsc::channel(); + let released = Mutex::new(released); + a.set_probe(Arc::new(move |_| { + let n = count.fetch_add(1, Ordering::SeqCst); + started.send(n).unwrap(); + released.lock().unwrap().recv().unwrap(); + if n == 0 { previous } else { !previous } + })); + a.run_in_background(Arc::new(|| {})); + assert_eq!(a.exists("changed"), None); + assert_eq!(starts.recv_timeout(Duration::from_secs(5)).unwrap(), 0); + a.invalidate("changed"); + release.send(()).unwrap(); + assert_eq!(starts.recv_timeout(Duration::from_secs(5)).unwrap(), 1); + assert_eq!(a.exists("changed"), None, "the obsolete answer was not restored"); + release.send(()).unwrap(); + wait_until("new answer", || a.exists("changed") == Some(!previous)); + } + } + + #[test] + fn review_invalidated_sweep_reuses_the_explicit_queued_request() { + let mut a = Availability::default(); + let count = Arc::new(AtomicUsize::new(0)); + let calls = count.clone(); + let (started, starts) = std::sync::mpsc::channel(); + let (release, released) = std::sync::mpsc::channel(); + let released = Mutex::new(released); + a.set_probe(Arc::new(move |_| { + if calls.fetch_add(1, Ordering::SeqCst) == 0 { + started.send(()).unwrap(); + released.lock().unwrap().recv().unwrap(); + } + true + })); + a.run_in_background(Arc::new(|| {})); + assert!(a.sweep(vec!["changed".into()])); + starts.recv_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(a.exists("changed"), None); + a.invalidate("changed"); + release.send(()).unwrap(); + wait_until("invalidated sweep and explicit request", || !lock(&a.state).worker); + assert_eq!(count.load(Ordering::SeqCst), 2, "one queued request already retries the obsolete sweep answer"); + } + #[test] fn background_answers_from_the_cache_without_blocking() { let mut a = Availability::default(); diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 8ab8345a1eb..fcb5f7ab59d 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -662,9 +662,17 @@ fn build(s: &mut Session, p: &Value) -> Result { Ok(state.json()) } -/// One proxy job: the photo, its path, how to load its original, and the versions that apply. +/// One proxy job, including its compatible older identity and applicable versions. #[cfg(not(target_arch = "wasm32"))] -type SmartJob = (lightcraft_catalog::PhotoId, std::path::PathBuf, Option, Ages); +struct SmartJob { + id: lightcraft_catalog::PhotoId, + path: crate::smart::PreviewPath, + source: Option, + ages: Ages, + /// Only identities that no unselected photo uses, in either folder layout. + discard_paths: Vec, + availability: crate::smart::Availability, +} /// DNG tone fits also go stale, although DNGs keep their own matrix and Kelvin white-balance scale. /// So do preview-only raws: their proxy is the embedded JPEG, read in the colour space the raw @@ -693,11 +701,9 @@ impl Ages { Ages { look: preview_fitted_look(p), source: p.develops_raw() } } /// Whether the complete proxy at `path` is out of date in a way that applies to this photo: for the look (an older - /// fit, or an older encoding, [`crate::smart::is_stale_for`]) or for the raw decode. Never when any of - /// its versions comes from a newer build: rewriting it would take that one back (a build with all of them is the - /// one to bring it up to date). + /// fit, or an older encoding, [`crate::smart::is_stale_for`]) or for the raw decode. fn stale(self, path: &std::path::Path) -> bool { - !crate::smart::from_newer_build(path) && (crate::smart::is_stale_for(path, self.look) || (self.source && crate::smart::source_stale(path))) + crate::smart::is_stale_for(path, self.look) || (self.source && crate::smart::source_stale(path)) } } @@ -765,27 +771,33 @@ fn smart_run( std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; } } - for (id, path, source, ages) in jobs { + for SmartJob { id, path, source, ages, discard_paths, availability } in jobs { if state.is_some_and(|(st, _)| st.cancel.load(Ordering::Relaxed)) { break; } let _one = SMART_WRITE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let candidates = path.candidates(); // Read either the new shard or a pre-upgrade flat file, without making new work // depend on having the original online. - let path = crate::smart::existing_file_path(dir, path); if discard { - if std::fs::remove_file(&path).is_ok() { - n.removed += 1; + for path in discard_paths { + if std::fs::remove_file(&path).is_ok() { + n.removed += 1; + } } } else { + let reusable = path.load_with_path().ok().map(|(path, _)| path); + let valid = reusable.is_some(); + let existing = reusable.unwrap_or_else(|| path.resolve()); + let expected_raw = path.expected_raw(); + let path = path.write_path(); // a complete, current proxy is kept; a missing or damaged one (cut short by a crash or a // full drive) is (re)built, and so is one written by an older encoding, camera-look // fit or raw decode (see `smart::ENCODE_VERSION`, `camera_preview::LOOK_VERSION` and // `smart::SOURCE_VERSION`) when its original can be read - let damaged = path.exists(); - let valid = damaged && crate::smart::is_valid(&path); - let newer = valid && crate::smart::from_newer_build(&path); - let stale = valid && !newer && ages.stale(&path); + let damaged = existing.exists(); + let newer = valid && crate::smart::from_newer_build(&existing); + let stale = valid && !newer && ages.stale(&existing); if valid && !stale { n.built += 1; if newer { @@ -801,8 +813,9 @@ fn smart_run( // atomic: a failed write leaves no partial proxy that would pass for a built one; // and synced (issue #134): built so the photo can be edited while its original // is offline, when it is the only copy — the sync is small next to the decode + let mut loaded = false; let r = source - .ok_or_else(|| "nothing to build from".to_string()) + .ok_or_else(|| "original unavailable; reconnect it and use Build Smart Previews".to_string()) .and_then(|s| s.load_source()) .and_then(|src| { if src.from_proxy || src.reduced { @@ -811,6 +824,14 @@ fn smart_run( if crate::lens_profiles::generation() != generation { return Err("lens database changed while decoding the smart preview; retry the build".to_string()); } + loaded = true; + // Undo can restore preview-only ORF catalog facts, but not the old + // decoder. Never store new sensor pixels under that JPEG identity. + if let Some(expected) = expected_raw + && src.info.as_ref().is_none_or(|info| info.raw != expected) + { + return Err("source interpretation changed; use Reload from Disk before building smart previews".into()); + } let info = src.info_or(Default::default()); crate::smart::encode_with_lens_key(&src.image, Some(&info), lens_key) }) @@ -821,7 +842,7 @@ fn smart_run( std::fs::create_dir(parent).map_err(|e| format!("{}: {e}", parent.display()))?; } crate::smart::invalidate_look_check_for_write(dir, lens_key)?; - lightcraft_catalog::safe_file::write_atomic(&path, &b).map_err(|e| format!("{}: {e}", path.display())) + lightcraft_catalog::safe_file::write_atomic(path, &b).map_err(|e| format!("{}: {e}", path.display())) }); match r { Ok(()) => { @@ -835,21 +856,23 @@ fn smart_run( } } } - Err(e) if stale => { + Err(e) if valid && stale && !loaded => { // offline (or unreadable) original: the proxy is all there is, keep its look - log::info!("smart preview {} keeps its older look: {e}", path.display()); + log::info!("smart preview {} keeps its older look: {e}", existing.display()); n.built += 1; n.stale_kept += 1; } Err(e) => { - n.failed.push(json!([id.0, e])); if let Some((st, _)) = state { st.failed.fetch_add(1, Ordering::Relaxed); + *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e.clone()); } + n.failed.push(json!([id.0, e])); } } } } + availability.invalidate(&candidates); if let Some((st, task)) = state { let done = st.done.fetch_add(1, Ordering::Relaxed).saturating_add(1); task.progress(done as u64, st.total as u64); @@ -889,16 +912,29 @@ fn smart(s: &mut Session, p: &Value) -> Result { return queued; } let mut jobs: Vec = Vec::new(); + let selected: std::collections::HashSet<_> = ids.iter().copied().collect(); + let retained: std::collections::HashSet<_> = if discard { + s.catalog + .photos() + .filter(|p| !selected.contains(&p.id) && matches!(p.source, lightcraft_catalog::Source::File { .. })) + .flat_map(|p| crate::smart::PreviewPath::new(&dir, p).candidates()) + .collect() + } else { + Default::default() + }; for id in ids { let Some(ph) = s.catalog.photo(id).cloned() else { continue }; if !matches!(ph.source, lightcraft_catalog::Source::File { .. }) { continue; } - let path = crate::smart::sharded_file_path(&dir, &ph); + let path = crate::smart::PreviewPath::new(&dir, &ph); + // Copies can share the current decoder identity as well as the content-only legacy + // identity. Deleting either would strand an unselected photo whose original is offline. + let discard_paths = if discard { path.candidates().into_iter().filter(|p| !retained.contains(p)).collect() } else { Vec::new() }; // Decode the original afresh, with the photo's hot-pixel setting. Cached sources may // carry an imported profile or predate the lens database captured by smart_run. let source = (!discard).then(|| s.media.origin_ref_of(&ph, crate::media::SourceLevel::Preview.max_edge())); - jobs.push((id, path, source, Ages::of(&ph))); + jobs.push(SmartJob { id, path, source, ages: Ages::of(&ph), discard_paths, availability: s.media.smart_availability.clone() }); } let custom = s.smart_previews_dir.is_some(); if background { @@ -954,11 +990,24 @@ pub(crate) fn refresh_stale_smart_previews(s: &mut Session) -> Option = s.catalog.photos().filter(|p| matches!(p.source, lightcraft_catalog::Source::File { .. })).collect(); - let jobs: Vec = - photos.iter().map(|p| (p.id, crate::smart::sharded_file_path(&dir, p), Some(s.media.origin_ref_of(p, max_edge)), Ages::of(p))).collect(); + let jobs: Vec = photos + .iter() + .map(|p| SmartJob { + id: p.id, + path: crate::smart::PreviewPath::new(&dir, p), + source: Some(s.media.origin_ref_of(p, max_edge)), + ages: Ages::of(p), + discard_paths: Vec::new(), + availability: s.media.smart_availability.clone(), + }) + .collect(); + let task = s.activity.start("smartPreviews", "Building smart previews", Cancel::No); std::thread::Builder::new() .name("lc-smart-look".into()) - .spawn(move || refresh_stale(&dir, jobs)) + .spawn(move || { + let _task = task; + refresh_stale(&dir, jobs); + }) .map_err(|e| log::warn!("smart previews: could not start the look refresh: {e}")) .ok() } @@ -971,14 +1020,15 @@ fn refresh_stale(dir: &std::path::Path, jobs: Vec) { let _one = SMART_WRITE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); (crate::lens_profiles::generation(), crate::lens_profiles::cache_key()) }; - let stale: Vec = jobs - .into_iter() - .map(|(id, path, source, ages)| (id, crate::smart::existing_file_path(dir, path), source, ages)) - .filter(|(_, path, _, ages)| ages.stale(path)) - .collect(); + let stale: Vec = + jobs.into_iter().filter(|job| job.path.needs_refresh(|path| !crate::smart::from_newer_build(path) && job.ages.stale(path))).collect(); if !stale.is_empty() { // `custom`: the folder is there already, and must not be recreated if it went away since match smart_run(dir, true, false, stale, None) { + Ok(n) if !n.failed.is_empty() => { + log::warn!("smart previews: look refresh needs attention: {:?}", n.failed); + return; + } Ok(n) => log::info!( "smart previews: {} refreshed to the current camera look and raw decode, {} kept (original offline)", n.refreshed, @@ -1063,12 +1113,22 @@ fn smart_location(s: &mut Session, p: &Value) -> Result { Ok(r) } -/// Whether photo `id` has a smart preview. -pub fn has_smart_preview(s: &Session, id: lightcraft_catalog::PhotoId) -> bool { - match (&s.media.smart_dir, s.catalog.photo(id)) { - (Some(dir), Some(p)) => crate::smart::is_valid(&crate::smart::file_path(dir, p)), - _ => false, - } +/// Snapshot a status query without filesystem work. The returned job checks both the original +/// and proxy on its caller's thread, so desktop control requests can run it on a worker. +pub fn smart_status_job(s: &Session, p: &Value) -> Result Value + Send + 'static> { + let id = s.targets(p)?.first().copied().ok_or_else(|| bad("photo.smartPreview", "no photo"))?; + let photo = s.catalog.photo(id); + let original = photo.and_then(|p| match &p.source { + lightcraft_catalog::Source::File { path } => Some(path.clone()), + _ => None, + }); + let preview = s.media.smart_dir.as_ref().zip(photo).map(|(dir, p)| crate::smart::PreviewPath::new(dir, p)); + let exists = s.media.availability.probe(); + Ok(move || { + let online = original.as_ref().is_none_or(|path| exists(path)); + let smart = preview.is_some_and(|path| path.load_with_path().is_ok()); + json!({"smartPreview": smart, "originalOnline": online}) + }) } pub fn specs() -> Vec { @@ -1094,12 +1154,7 @@ pub fn specs() -> Vec { smart_location ), cmd!(query "photo.smartPreview", "Smart Preview Status", [], None, "{id?} → {smartPreview: bool, originalOnline: bool}", always, |s, p| { - let id = s.targets(p)?.first().copied().ok_or_else(|| bad("photo.smartPreview", "no photo"))?; - let online = match s.catalog.photo(id).map(|p| p.source.clone()) { - Some(lightcraft_catalog::Source::File { path }) => std::path::Path::new(&path).exists(), - _ => true, - }; - Ok(json!({"smartPreview": has_smart_preview(s, id), "originalOnline": online})) + Ok(smart_status_job(s, p)?()) }), cmd!( "library.buildPreviews", diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index d2924545490..389ffbf7df6 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -37,7 +37,8 @@ mod source; pub use cache::DenoiseIndex; #[cfg(test)] pub(crate) use cache::rendered_budget; -pub use quick::{QuickJob, QuickSource, content_key, lens_key, source_info}; +pub(crate) use quick::decoder_key; + pub use quick::{QuickJob, QuickSource, content_key, lens_key, source_info}; pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_cached, fit_for_display}; #[cfg(test)] use settings_hash::SETTINGS_HASH_ENTRIES; @@ -78,6 +79,8 @@ pub struct MediaCache { /// Whether originals (and smart previews) are on disk: cached and checked off the UI thread /// in the app (see [`crate::availability`]). pub availability: crate::availability::Availability, + /// Compatible, decodable smart previews: background-checked for UI status in the app. + pub smart_availability: crate::smart::Availability, scenes: Vec, /// Rendered thumbnails (memory, plus disk once a library is attached). pub rendered: Arc, diff --git a/crates/engine/src/media/cache.rs b/crates/engine/src/media/cache.rs index 7a36a253724..a5e021147dc 100644 --- a/crates/engine/src/media/cache.rs +++ b/crates/engine/src/media/cache.rs @@ -68,6 +68,7 @@ impl Default for MediaCache { file_bytes: None, smart_dir: None, availability: Default::default(), + smart_availability: Default::default(), scenes: Vec::new(), rendered: Arc::new(PreviewCache::memory(rendered_budget(budget))), denoise: DenoiseIndex::default(), @@ -370,12 +371,9 @@ impl MediaCache { // be offline is tried first and its smart preview is the render worker's fallback. #[cfg(not(target_arch = "wasm32"))] if let (Source::File { path }, Some(dir)) = (&p.source, &self.smart_dir) { - let sharded = crate::smart::sharded_file_path(dir, p); - let legacy = dir.join(crate::smart::file_name(p)); - let sp = if self.availability.exists(&sharded.to_string_lossy()) == Some(true) { sharded } else { legacy }; - // (a proxy cut short fails to load, like the offline original; the worker's fallback - // in `SourceRef::load` only uses a proxy that passes `smart::is_valid`) - if self.availability.is_offline(path) && self.availability.exists(&sp.to_string_lossy()) == Some(true) { + let sp = crate::smart::PreviewPath::new(dir, p); + // Cached validation establishes pixel compatibility; existence alone cannot. + if self.availability.is_offline(path) && self.smart_availability.exists(dir, p) { return SourceRef::Smart { path: sp }; } let mut r = self.origin_ref(&p.source, max_edge); diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 9ff2205e4aa..525b605065b 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -136,8 +136,8 @@ pub(super) fn embedded_thumb_key(k: Hash128) -> Hash128 { /// ORF decoding changed when compressed sensor support was withdrawn. Keep its old renders /// out even before catalog rechecking finishes, and distinguish sensor from preview-only /// pixels after Reload. Other formats keep their existing keys. This is deliberately not -/// part of `content_key`: smart previews and denoise products identify the original file. -pub(super) fn decoder_key(p: &Photo) -> u64 { +/// part of `content_key`: source-file and denoise identities stay stable across decoder changes. +pub(crate) fn decoder_key(p: &Photo) -> u64 { if !p.format.eq_ignore_ascii_case("ORF") { return 0; } diff --git a/crates/engine/src/media/source.rs b/crates/engine/src/media/source.rs index e3435cac957..daff4652e09 100644 --- a/crates/engine/src/media/source.rs +++ b/crates/engine/src/media/source.rs @@ -276,7 +276,7 @@ pub enum SourceRef { loader: Option, /// The photo's smart preview, used when the original can't be read (offline drive). The /// UI thread never checks whether the original is there; the render worker finds out. - fallback: Option, + fallback: Option, /// The photo has a cached denoised picture: load it with the plain one (see [`PairLoader`]). denoise: Option<(DenoiseSpec, PairLoader)>, /// The photo's imported camera profile (id and profile): its raw file is developed with it. @@ -288,7 +288,7 @@ pub enum SourceRef { }, /// A smart preview standing in for a missing original. Smart { - path: std::path::PathBuf, + path: crate::smart::PreviewPath, }, } @@ -297,6 +297,7 @@ impl SourceRef { self.load_source().map(|s| s.image) } + /// Resolve this reference to pixels and decoder facts, trying a compatible proxy when its original cannot be read. pub fn load_source(&self) -> Result { let image = match self { SourceRef::Loaded(a) => return Ok((**a).clone()), @@ -362,14 +363,14 @@ impl SourceRef { // An offline original renders from its smart preview (no decoder facts: header ones). return match (r, fallback) { #[cfg(not(target_arch = "wasm32"))] - (Err(e), Some(sp)) if denoise.as_ref().is_none_or(|(spec, _)| spec.make.is_none()) && crate::smart::is_valid(sp) => { - crate::smart::load(sp).map_err(|e2| format!("{e}; smart preview: {e2}")) + (Err(e), Some(sp)) if denoise.as_ref().is_none_or(|(spec, _)| spec.make.is_none()) => { + sp.load().map_err(|e2| format!("{e}; smart preview: {e2}")) } (r, _) => r, }; } #[cfg(not(target_arch = "wasm32"))] - SourceRef::Smart { path } => return crate::smart::load(path), + SourceRef::Smart { path } => return path.load(), #[cfg(target_arch = "wasm32")] SourceRef::Smart { .. } => return Err("smart previews are not available here".into()), }; diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index 1aa7980adf3..bb9510ee138 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -17,28 +17,120 @@ use lightcraft_pipeline::masks::{MatteKind, Mattes}; use lightcraft_pipeline::tone::CameraTone; use lightcraft_raster::{Image, Rgb32f, Rgba8}; +mod availability; +pub use availability::Availability; + const MAGIC: &[u8] = b"LCSP1\n"; -/// The proxy's file name for a photo (by its content, so copies share one). +/// Raw proxies retain their sensor/preview interpretation; rendered-image identities stay unchanged. +fn raw_interpretation(p: &Photo) -> Option { + // Keep the existing ORF proxy policy until the shared-decoder migration. + (p.kind == lightcraft_catalog::MediaKind::Raw && !p.format.eq_ignore_ascii_case("ORF")).then(|| p.develops_raw()) +} + +/// The proxy's file name by content and raw interpretation, so matching copies share one. pub fn file_name(p: &Photo) -> String { - let h = lightcraft_preview::Hasher128::new().str(&crate::media::content_key(p)).finish(); - format!("{:032x}.lcsp", h.0) + let mut key = lightcraft_preview::Hasher128::new(); + key.str(&crate::media::content_key(p)); + if let Some(raw) = raw_interpretation(p) { + key.str("raw-proxy-v1").u64(u64::from(raw)).u64(crate::media::decoder_key(p)); + } + format!("{:032x}.lcsp", key.finish().0) } -/// The default sharded location of a proxy. A two-character hex prefix bounds each -/// folder to about 1/256 of the library's smart previews. +/// The default sharded location of a proxy; the two-character prefix bounds each folder. pub fn sharded_file_path(dir: &Path, p: &Photo) -> PathBuf { - let name = file_name(p); + shard(dir, &file_name(p)) +} + +fn shard(dir: &Path, name: &str) -> PathBuf { match name.get(..2) { - Some(shard) => dir.join(shard).join(&name), - None => dir.join(&name), + Some(shard) => dir.join(shard).join(name), + None => dir.join(name), + } +} + +/// Immutable proxy candidates. Construction does no I/O; workers check stored interpretation. +#[derive(Clone)] +pub struct PreviewPath { + dir: PathBuf, + current: PathBuf, + previous: Option, + raw: Option, +} + +impl PreviewPath { + pub(crate) fn new(dir: &Path, p: &Photo) -> Self { + let raw = raw_interpretation(p); + let previous = raw.map(|_| { + let h = lightcraft_preview::Hasher128::new().str(&crate::media::content_key(p)).finish(); + shard(dir, &format!("{:032x}.lcsp", h.0)) + }); + Self { dir: dir.to_path_buf(), current: sharded_file_path(dir, p), previous, raw } + } + + /// Current and content-only legacy identities, in both folder layouts. + pub(crate) fn candidates(&self) -> Vec { + std::iter::once(&self.current) + .chain(self.previous.iter()) + .flat_map(|path| std::iter::once(path.clone()).chain(path.file_name().map(|name| self.dir.join(name)))) + .collect() + } + + /// Rebuilds write only their captured interpretation; older identities remain read-only. + pub(crate) fn write_path(&self) -> &Path { + &self.current + } + + pub(crate) fn expected_raw(&self) -> Option { + self.raw } + + /// Retention and repair need to find any remaining file, even when its pixels cannot be used. + pub(crate) fn resolve(&self) -> PathBuf { + self.candidates().into_iter().find(|path| path.exists()).unwrap_or_else(|| self.current.clone()) + } + + /// Existing but incompatible/damaged proxies must not make the opening refresh look complete. + pub(crate) fn needs_refresh(&self, is_stale: impl FnOnce(&Path) -> bool) -> bool { + self.candidates().iter().any(|path| path.exists()) && self.load_with_path().map_or(true, |(path, _)| is_stale(&path)) + } + + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn load(&self) -> Result { + self.load_with_path().map(|(_, source)| source) + } + + /// Framing alone cannot establish that the JPEG decodes or the facts match its consumer. + pub(crate) fn load_with_path(&self) -> Result<(PathBuf, crate::media::DecodedSource), String> { + let mut error = format!("{}: missing or incomplete smart preview", self.current.display()); + for path in self.candidates() { + match load_compatible(&path, self.raw) { + Ok(source) => return Ok((path, source)), + Err(e) => error = e, + } + } + Err(format!("{error}; reconnect the original and use Build Smart Previews")) + } +} + +fn load_compatible(path: &Path, expected: Option) -> Result { + // Unknown legacy raw facts cannot prove either interpretation. Rendered images keep their old fallback. + if !is_valid(path) || expected.is_some_and(|raw| stored_raw(path) != Some(raw)) { + return Err(format!("{}: missing or incompatible smart preview", path.display())); + } + let source = load(path)?; + // Recheck the facts read with the pixels; the file may have changed since the cheap prefilter. + if expected.is_some_and(|raw| source.info.as_ref().is_none_or(|info| info.raw != raw)) { + return Err("smart preview has no compatible source facts".into()); + } + Ok(source) } -/// Read an existing proxy in either layout. New proxies use the sharded location; previews -/// made by older releases still load and can be moved with smartPreviewsLocation. +/// Locate any existing proxy for retention/repair, in either layout or identity. +/// Use `PreviewPath` loading to check whether its pixels are compatible. pub fn file_path(dir: &Path, p: &Photo) -> PathBuf { - existing_file_path(dir, sharded_file_path(dir, p)) + PreviewPath::new(dir, p).resolve() } /// Resolve a sharded path to an older flat file when present. Call only off the UI thread: @@ -55,6 +147,52 @@ pub fn existing_file_path(dir: &Path, sharded: PathBuf) -> PathBuf { /// The most header [`is_valid`] reads (the JSON line before the JPEG). const HEADER_MAX: u64 = 4096; +/// Bound JSON independently of matte planes without dropping supported DNG tables. At 24 JSON +/// bytes per float, two 2^22-gain maps plus three 2^20-entry RGB profile tables need 408 MiB; +/// 512 MiB leaves room for their structure and the other facts. Keep encode and reads in agreement. +const FACTS_MAX: usize = 512 * 1024 * 1024; + +/// Total encoded proxy budget, including JPEG, facts and matte planes. Leave another 512 MiB +/// beyond the supported facts budget for pixels and mattes; reject larger proxies explicitly +/// rather than allocating from an untrusted file length. Encoding obeys the same limit. +const FILE_MAX: usize = 1024 * 1024 * 1024; + +/// Prefilter the bounded interpretation without allocating camera tables or matte planes. +/// Loading validates the complete facts with their actual pixels. +fn stored_raw(path: &Path) -> Option { + use std::io::{Read, Seek, SeekFrom}; + let mut f = std::fs::File::open(path).ok()?; + let file_len = f.metadata().ok()?.len(); + if file_len > FILE_MAX as u64 { + return None; + } + let mut head = Vec::new(); + (&mut f).take(HEADER_MAX).read_to_end(&mut head).ok()?; + let rest = head.strip_prefix(MAGIC)?; + let nl = rest.iter().position(|b| *b == b'\n')?; + let header: serde_json::Value = serde_json::from_slice(rest.get(..nl)?).ok()?; + let tail = header.get("tail")?.as_u64()?; + let start = file_len.checked_sub(tail)?; + if tail < 4 || start <= (MAGIC.len() + nl + 3) as u64 { + return None; + } + f.seek(SeekFrom::Start(start)).ok()?; + let mut n = [0; 4]; + f.read_exact(&mut n).ok()?; + let n = u64::from(u32::from_le_bytes(n)); + // File-derived lengths are hostile. Camera facts fit within this budget; the potentially + // much larger matte planes follow the JSON and are not needed for the raw flag. + if n > FACTS_MAX as u64 || n > tail - 4 { + return None; + } + #[derive(serde::Deserialize)] + struct Interpretation { + raw: bool, + } + let facts: Interpretation = serde_json::from_reader(std::io::BufReader::new(f.take(n))).ok()?; + Some(facts.raw) +} + /// The header field that records which version of the camera-look fit (`camera_preview::LOOK_VERSION`) /// wrote the proxy's pixels (colour matrix and profile are baked into them) and stored tone curve. const LOOK_FIELD: &str = "look_version"; @@ -130,9 +268,26 @@ struct StoredMatte { len: usize, } +/// Use the same shape and length checks for compatibility and decoding, without allocating +/// matte planes just to inspect an offline proxy. Every tail byte must belong to a known matte. +fn parse_facts(json: &[u8], plane_bytes: u64) -> Option { + if json.len() > FACTS_MAX { + return None; + } + let facts: SmartFacts = serde_json::from_slice(json).ok()?; + let mut total = 0_u64; + for m in &facts.mattes { + MatteKind::from_code(m.kind)?; + if m.w == 0 || m.h == 0 || m.w.checked_mul(m.h)? != m.len { + return None; + } + total = total.checked_add(m.len as u64)?; + } + (total == plane_bytes).then_some(facts) +} + /// The facts and mattes a proxy's tail holds: the length-prefixed JSON, then one byte plane per -/// stored matte. `None` for an old proxy or a malformed tail; like a missing curve, the offline -/// render then keeps its header facts. +/// stored matte. `None` means the declared tail is malformed and must not be used. fn stored_facts(head: &serde_json::Value, bytes: &[u8]) -> Option<(SmartFacts, Mattes)> { let tail = usize::try_from(head.get("tail")?.as_u64()?).ok()?; if tail == 0 || tail > bytes.len() { @@ -140,19 +295,14 @@ fn stored_facts(head: &serde_json::Value, bytes: &[u8]) -> Option<(SmartFacts, M } let t = bytes.get(bytes.len() - tail..)?; let n = u32::from_le_bytes(t.get(..4)?.try_into().ok()?) as usize; - let facts: SmartFacts = serde_json::from_slice(t.get(4..4 + n)?).ok()?; + let mut at = 4_usize.checked_add(n)?; + let facts = parse_facts(t.get(4..at)?, t.len().checked_sub(at)? as u64)?; let mut mattes = Mattes::default(); - let mut at = 4 + n; for m in &facts.mattes { let kind = MatteKind::from_code(m.kind)?; - if m.w == 0 || m.h == 0 || m.w.checked_mul(m.h)? != m.len { - return None; - } - mattes.push(kind, Image { width: m.w, height: m.h, data: t.get(at..at.checked_add(m.len)?)?.to_vec() }); - at += m.len; - } - if at != t.len() { - return None; + let end = at.checked_add(m.len)?; + mattes.push(kind, Image { width: m.w, height: m.h, data: t.get(at..end)?.to_vec() }); + at = end; } Some((facts, mattes)) } @@ -227,17 +377,33 @@ pub(crate) fn encode_with_lens_key(img: &Rgb32f, info: Option<&SourceInfo>, lens mattes: matte_list, }; let facts = serde_json::to_vec(&facts).map_err(|e| e.to_string())?; + if facts.len() > FACTS_MAX { + return Err("smart preview facts too large".into()); + } let n = u32::try_from(facts.len()).map_err(|_| "smart preview facts too large")?; tail.extend_from_slice(&n.to_le_bytes()); tail.extend_from_slice(&facts); if let Some(m) = i.mattes.as_deref() { for (_, a) in m.iter() { + if tail.len().checked_add(a.data.len()).is_none_or(|n| n > FILE_MAX) { + return Err("smart preview exceeds the file-size budget".into()); + } tail.extend_from_slice(&a.data); } } head["tail"] = serde_json::json!(tail.len()); } - out.extend_from_slice(head.to_string().as_bytes()); + let head = head.to_string(); + let total = out + .len() + .checked_add(head.len()) + .and_then(|n| n.checked_add(1)) + .and_then(|n| n.checked_add(jpg.len())) + .and_then(|n| n.checked_add(tail.len())); + if total.is_none_or(|n| n > FILE_MAX) { + return Err("smart preview exceeds the file-size budget".into()); + } + out.extend_from_slice(head.as_bytes()); out.push(b'\n'); out.extend_from_slice(&jpg); out.extend_from_slice(&tail); @@ -245,24 +411,31 @@ pub(crate) fn encode_with_lens_key(img: &Rgb32f, info: Option<&SourceInfo>, lens } /// Decode a smart preview back into a source image, its stored camera tone curve and the stored -/// decoder facts (an invalid curve or tail is ignored, like a missing one). +/// decoder facts. Older proxies without a tail remain supported; a declared malformed tail fails. pub fn decode(bytes: &[u8]) -> Result<(Rgb32f, Option, Option), String> { + if bytes.len() > FILE_MAX { + return Err("smart preview exceeds the file-size budget".into()); + } let rest = bytes.strip_prefix(MAGIC).ok_or("not a smart preview")?; - let nl = rest.iter().position(|b| *b == b'\n').ok_or("bad smart preview")?; + let nl = rest.iter().take(HEADER_MAX as usize - MAGIC.len()).position(|b| *b == b'\n').ok_or("bad smart preview")?; let head: serde_json::Value = serde_json::from_slice(&rest[..nl]).map_err(|e| e.to_string())?; let scale = head["scale"].as_f64().unwrap_or(1.0) as f32; let tone = head.get("tone").and_then(|t| serde_json::from_value::(t.clone()).ok()); - let tail = head.get("tail").and_then(serde_json::Value::as_u64).and_then(|t| usize::try_from(t).ok()).unwrap_or(0); + let tail = match head.get("tail") { + None => 0, + Some(t) => usize::try_from(t.as_u64().ok_or("bad smart preview tail")?).map_err(|_| "bad smart preview tail")?, + }; let start = MAGIC.len() + nl + 1; let end = bytes.len().saturating_sub(tail); if end <= start { return Err("bad smart preview".into()); } + let facts = if tail == 0 { None } else { Some(stored_facts(&head, bytes).ok_or("bad smart preview facts")?) }; let d = lightcraft_codecs::decode(bytes.get(start..end).ok_or("bad smart preview")?, Default::default()).map_err(|e| e.to_string())?; // the decoder undoes the sRGB encoding; the values are the source's own primaries let mut img = d.image; img.data.iter_mut().for_each(|c| *c = c.map(|v| v * scale)); - let info = stored_facts(&head, bytes).map(|(f, mattes)| SourceInfo { + let info = facts.map(|(f, mattes)| SourceInfo { raw: f.raw, as_shot_temp: f.as_shot_temp, as_shot_tint: f.as_shot_tint, @@ -636,9 +809,21 @@ pub fn mark_source_checked(dir: &Path) -> Result<(), String> { mark(dir, SOURCE_MARKER, &[u64::from(SOURCE_VERSION)], None) } -/// Load the proxy at `path`. +/// Load a size-bounded proxy. Bound the actual read too, since a file can grow after metadata. pub fn load(path: &Path) -> Result { - let b = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?; + use std::io::Read; + let file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let len = file.metadata().map_err(|e| e.to_string())?.len(); + if len > FILE_MAX as u64 { + return Err("smart preview exceeds the file-size budget".into()); + } + let mut b = Vec::new(); + let reserve = usize::try_from(len + 1).map_err(|_| "smart preview exceeds the file-size budget")?; + b.try_reserve_exact(reserve).map_err(|e| format!("smart preview cannot be allocated: {e}"))?; + file.take(len + 1).read_to_end(&mut b).map_err(|e| format!("{}: {e}", path.display()))?; + if b.len() as u64 != len { + return Err("smart preview changed while reading".into()); + } decode(&b).map(|(image, camera_tone, info)| crate::media::DecodedSource { image: Arc::new(image), info, diff --git a/crates/engine/src/smart/availability.rs b/crates/engine/src/smart/availability.rs new file mode 100644 index 00000000000..6bd67f79b9d --- /dev/null +++ b/crates/engine/src/smart/availability.rs @@ -0,0 +1,141 @@ +//! Cached, worker-checked proxy availability for UI status. Existence alone cannot establish +//! that an older ORF proxy contains sensor pixels, or that a JPEG can actually be decoded. + +use std::path::Path; +use std::sync::Arc; + +use lightcraft_catalog::Photo; + +use crate::availability::{Availability as FileAvailability, Waker}; + +/// Cached validation is separate for ordinary, preview-derived and sensor-derived proxies. +#[derive(Clone, Debug)] +pub struct Availability { + any: FileAvailability, + preview: FileAvailability, + sensor: FileAvailability, +} + +impl Default for Availability { + fn default() -> Self { + let cache = |expected| { + let mut cache = FileAvailability::default(); + cache.set_probe(Arc::new(move |path| super::load_compatible(Path::new(path), expected).is_ok())); + cache + }; + Self { any: cache(None), preview: cache(Some(false)), sensor: cache(Some(true)) } + } +} + +impl Availability { + /// UI callers only queue requests and read cached answers; workers perform validation. + pub fn run_in_background(&mut self, wake: Waker) { + for cache in [&mut self.any, &mut self.preview, &mut self.sensor] { + cache.run_in_background(wake.clone()); + } + } + + pub fn is_background(&self) -> bool { + self.any.is_background() && self.preview.is_background() && self.sensor.is_background() + } + + /// Writes and explicit discards invalidate every interpretation, including in-flight probes. + pub(crate) fn invalidate(&self, paths: &[std::path::PathBuf]) { + for path in paths { + let path = path.to_string_lossy(); + for cache in [&self.any, &self.preview, &self.sensor] { + cache.invalidate(&path); + } + } + } + + pub fn exists(&self, dir: &Path, photo: &Photo) -> bool { + let preview = super::PreviewPath::new(dir, photo); + let cache = self.cache_for(preview.expected_raw()); + preview.candidates().iter().any(|path| cache.exists(&path.to_string_lossy()) == Some(true)) + } + + fn cache_for(&self, expected: Option) -> &FileAvailability { + match expected { + None => &self.any, + Some(false) => &self.preview, + Some(true) => &self.sensor, + } + } + + #[cfg(test)] + pub(crate) fn checked_missing(&self, dir: &Path, photo: &Photo) -> bool { + let preview = super::PreviewPath::new(dir, photo); + let cache = self.cache_for(preview.expected_raw()); + preview.candidates().iter().all(|path| cache.is_gone(&path.to_string_lossy())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Mutex, mpsc}; + use std::time::{Duration, Instant}; + + /// Every interpretation is validated off the caller's thread. + #[test] + fn every_proxy_interpretation_is_checked_on_a_worker() { + let mut availability = Availability::default(); + let dir = crate::tests::TestDir::new("smart-proxy-worker"); + let caller = std::thread::current().id(); + let calls = Arc::new(Mutex::new(Vec::new())); + for (cache, expected) in [(&mut availability.any, None), (&mut availability.preview, Some(false)), (&mut availability.sensor, Some(true))] { + let calls = calls.clone(); + let probe = cache.probe(); + cache.set_probe(Arc::new(move |path| { + calls.lock().unwrap().push((expected, std::thread::current().id())); + probe(path) + })); + } + let (wake, receive) = mpsc::channel(); + availability.run_in_background(Arc::new(move || { + let _ = wake.send(()); + })); + for (format, preview_only) in [("JPEG", false), ("DNG", true), ("DNG", false)] { + let mut p = + Photo::new(lightcraft_catalog::PhotoId(1), lightcraft_catalog::Source::File { path: "offline".into() }, "offline", format, 8, 8, ""); + p.kind = if format == "JPEG" { lightcraft_catalog::MediaKind::Image } else { lightcraft_catalog::MediaKind::Raw }; + p.preview_only = preview_only.then(|| "old decoder".into()); + let preview = crate::smart::PreviewPath::new(&dir, &p); + let path = preview.write_path(); + let image = lightcraft_raster::Rgb32f::filled(8, 8, [0.2; 3]); + let info = preview.expected_raw().map(|raw| lightcraft_pipeline::SourceInfo { raw, ..Default::default() }); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let valid = crate::smart::encode(&image, info.as_ref()).unwrap(); + let invalid = if let Some(info) = &info { + crate::smart::encode(&image, Some(&lightcraft_pipeline::SourceInfo { raw: !info.raw, ..Default::default() })).unwrap() + } else { + let mut bytes = valid.clone(); + let jpeg = bytes.iter().enumerate().filter(|&(_, byte)| *byte == b'\n').nth(1).unwrap().0 + 1; + let end = bytes.len() - 2; + bytes[jpeg + 2..end].fill(0); + bytes + }; + std::fs::write(path, invalid).unwrap(); + assert!(crate::smart::is_valid(path), "the proxy has valid framing"); + let deadline = Instant::now() + Duration::from_secs(5); + while !availability.checked_missing(&dir, &p) { + assert!(!availability.exists(&dir, &p), "the worker rejects incompatible facts or damaged JPEG pixels"); + let remaining = deadline.checked_duration_since(Instant::now()).expect("the worker rejects the invalid proxy"); + receive.recv_timeout(remaining).unwrap(); + } + std::fs::write(path, valid).unwrap(); + availability.invalidate(&[path.to_path_buf()]); + let deadline = Instant::now() + Duration::from_secs(5); + while !availability.exists(&dir, &p) { + let remaining = deadline.checked_duration_since(Instant::now()).expect("the real proxy is validated on a worker"); + receive.recv_timeout(remaining).unwrap(); + } + } + let calls = calls.lock().unwrap(); + for expected in [None, Some(false), Some(true)] { + assert!(calls.iter().any(|(kind, _)| *kind == expected)); + } + assert!(calls.iter().all(|(_, thread)| *thread != caller)); + } +} diff --git a/crates/engine/src/smart/tests.rs b/crates/engine/src/smart/tests.rs index e1b5320ba51..5de6308fbaa 100644 --- a/crates/engine/src/smart/tests.rs +++ b/crates/engine/src/smart/tests.rs @@ -459,7 +459,65 @@ fn explicit_lens_identity_is_kept_by_encoder_and_scan_marker() { mark_look_checked_with_lens_key(&dir, captured).unwrap(); assert_eq!(marker(&dir, LOOK_MARKER), [future_fit, ENCODE_VERSION, 42, 99]); assert!(!look_checked(&dir), "a newer version cannot cover the current lens identity"); + std::fs::remove_dir_all(dir).unwrap(); +} +/// The original bytes stay the same when a decoder's interpretation changes. +#[test] +fn raw_proxy_names_distinguish_sensor_and_preview_pixels() { + use lightcraft_catalog::{PhotoId, Source}; + for format in ["DNG", "NEF", "ORF"] { + let mut sensor = Photo::new(PhotoId(1), Source::File { path: "photo.raw".into() }, "photo.raw", format, 8, 8, ""); + sensor.kind = lightcraft_catalog::MediaKind::Raw; + let mut preview = sensor.clone(); + preview.preview_only = Some("old decoder".into()); + assert_eq!(crate::media::content_key(&sensor), crate::media::content_key(&preview)); + assert_ne!(file_name(&sensor), file_name(&preview), "{format}: the two interpretations must never overwrite each other"); + } +} + +#[test] +fn legacy_raw_proxies_require_matching_recorded_interpretation() { + use lightcraft_catalog::{PhotoId, Source}; + for expected in [false, true] { + for recorded in [None, Some(false), Some(true)] { + let dir = temp(&format!("raw-legacy-{expected}-{recorded:?}")); + let mut photo = + Photo::new(PhotoId(1), Source::File { path: dir.join("offline.dng").to_string_lossy().into() }, "offline.dng", "DNG", 8, 8, ""); + photo.kind = lightcraft_catalog::MediaKind::Raw; + photo.preview_only = (!expected).then(|| "old decoder".into()); + let hash = lightcraft_preview::Hasher128::new().str(&crate::media::content_key(&photo)).finish(); + let old = dir.join(format!("{:032x}.lcsp", hash.0)); + let info = recorded.map(|raw| SourceInfo { raw, ..Default::default() }); + let bytes = encode(&Rgb32f::filled(8, 8, [0.2; 3]), info.as_ref()).unwrap(); + std::fs::write(&old, &bytes).unwrap(); + assert!(file_path(&dir, &photo).exists(), "retention still sees the legacy file"); + let mut media = crate::media::MediaCache::default(); + media.smart_dir = Some(dir.clone()); + let source = media.source_ref(&photo, crate::media::SourceLevel::Preview).load_source(); + assert_eq!(source.is_ok(), recorded == Some(expected), "expected={expected}, recorded={recorded:?}"); + assert_eq!(std::fs::read(&old).unwrap(), bytes, "incompatible legacy data stays on disk"); + std::fs::remove_dir_all(dir).unwrap(); + } + } +} + +#[test] +fn ordinary_jpeg_legacy_proxy_without_facts_remains_usable() { + use lightcraft_catalog::{PhotoId, Source}; + let dir = temp("jpeg-legacy-no-facts"); + let photo = Photo::new(PhotoId(1), Source::File { path: dir.join("offline.jpg").to_string_lossy().into() }, "offline.jpg", "JPEG", 8, 8, ""); + let hash = lightcraft_preview::Hasher128::new().str(&crate::media::content_key(&photo)).finish(); + let old = dir.join(format!("{:032x}.lcsp", hash.0)); + let bytes = encode(&Rgb32f::filled(8, 8, [0.2; 3]), None).unwrap(); + std::fs::write(&old, &bytes).unwrap(); + assert_eq!(file_name(&photo), old.file_name().unwrap().to_string_lossy()); + assert_eq!(file_path(&dir, &photo), old); + let mut media = crate::media::MediaCache::default(); + media.smart_dir = Some(dir.clone()); + let source = media.source_ref(&photo, crate::media::SourceLevel::Preview).load_source().unwrap(); + assert!(source.from_proxy); + assert!(source.info.is_none()); std::fs::remove_dir_all(dir).unwrap(); } @@ -494,3 +552,58 @@ fn a_scan_cannot_clear_pending_behind_a_newer_marker_for_another_database() { assert!(look_checked(&dir), "a stable scan with the recorded key clears pending"); std::fs::remove_dir_all(dir).unwrap(); } + +#[test] +fn a_hostile_facts_length_cannot_establish_raw_compatibility() { + use lightcraft_catalog::{MediaKind, PhotoId, Source}; + let dir = temp("facts-length"); + let mut photo = Photo::new(PhotoId(1), Source::File { path: dir.join("missing.dng").to_string_lossy().into() }, "missing.dng", "DNG", 8, 8, ""); + photo.kind = MediaKind::Raw; + let path = sharded_file_path(&dir, &photo); + let mut bytes = encode(&Rgb32f::filled(8, 8, [0.2; 3]), Some(&SourceInfo { raw: true, ..Default::default() })).unwrap(); + let end = MAGIC.len() + bytes[MAGIC.len()..].iter().position(|b| *b == b'\n').unwrap(); + let header: serde_json::Value = serde_json::from_slice(&bytes[MAGIC.len()..end]).unwrap(); + let tail = bytes.len() - header["tail"].as_u64().unwrap() as usize; + bytes[tail..tail + 4].copy_from_slice(&u32::MAX.to_le_bytes()); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, &bytes).unwrap(); + assert!(is_valid(&path), "the JPEG framing remains complete"); + assert!(decode(&bytes).is_err()); + assert!(PreviewPath::new(&dir, &photo).load_with_path().is_err()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn followup_incompatible_dng_proxy_does_not_hide_a_reconnected_original() { + reconnected_dng_proxy(false); +} + +#[test] +fn followup_compatible_dng_proxy_keeps_the_offline_smart_route() { + reconnected_dng_proxy(true); +} + +fn reconnected_dng_proxy(compatible: bool) { + use lightcraft_catalog::{MediaKind, PhotoId, Source}; + let dir = temp(&format!("dng-reconnected-compatibility-{compatible}")); + let original = dir.join("original.dng"); + std::fs::write(&original, b"reconnected original").unwrap(); + let mut photo = Photo::new(PhotoId(1), Source::File { path: original.to_string_lossy().into() }, "original.dng", "DNG", 8, 8, ""); + photo.kind = MediaKind::Raw; + let hash = lightcraft_preview::Hasher128::new().str(&crate::media::content_key(&photo)).finish(); + let legacy = dir.join(format!("{:032x}.lcsp", hash.0)); + let bytes = encode(&Rgb32f::filled(8, 8, [0.2; 3]), Some(&SourceInfo { raw: compatible, ..Default::default() })).unwrap(); + std::fs::write(&legacy, &bytes).unwrap(); + let mut media = crate::media::MediaCache::default(); + media.smart_dir = Some(dir.clone()); + let stale = original.to_string_lossy().to_string(); + media.availability.set_probe(Arc::new(move |p| p != stale && std::path::Path::new(p).exists())); + media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::filled(8, 8, [0.4; 3]), SourceInfo { raw: true, ..Default::default() })))); + let route = media.source_ref(&photo, crate::media::SourceLevel::Preview); + assert_eq!(matches!(&route, crate::media::SourceRef::Smart { .. }), compatible); + let source = route.load_source().unwrap(); + assert_eq!(source.from_proxy, compatible); + assert!(source.info.unwrap().raw); + assert_eq!(std::fs::read(&legacy).unwrap(), bytes, "routing does not discard retained data"); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cbade11502c..27c975ffd0a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -63,6 +63,8 @@ mod slide; mod slideshow_export; #[cfg(not(target_arch = "wasm32"))] mod slow_drive; +#[cfg(not(target_arch = "wasm32"))] +mod smart_interpretation; mod spots; mod sync; mod task_queue; diff --git a/crates/engine/src/tests/import.rs b/crates/engine/src/tests/import.rs index 596a26cdd6f..61ad99cbf7e 100644 --- a/crates/engine/src/tests/import.rs +++ b/crates/engine/src/tests/import.rs @@ -3113,13 +3113,13 @@ impl SmartLookCase { fn new(format: &str) -> Self { let src = temp_dir(&format!("smartlook-src-{format}")); let lib = temp_dir(&format!("smartlook-lib-{format}")); - write_png(&src.join("a.png"), 3); + std::fs::write(src.join("a.dng"), crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); write_png(&src.join("b.png"), 9); let mut session = Session::new().with_fs(); session.open_library(&lib, false).unwrap(); - session.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy(), src.join("b.png").to_string_lossy()]})).unwrap(); + session.execute("library.import", &json!({"paths": [src.join("a.dng").to_string_lossy(), src.join("b.png").to_string_lossy()]})).unwrap(); let find = |s: &Session, name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().id; - let (id, png_id) = (find(&session, "a.png"), find(&session, "b.png")); + let (id, png_id) = (find(&session, "a.dng"), find(&session, "b.png")); // `a` stands for a raw that takes the per-file camera look (the test loader decodes its pixels) let mut raw = (**session.catalog.photo(id).unwrap()).clone(); raw.format = format.into(); @@ -3328,50 +3328,30 @@ fn a_stale_refresh_never_rebuilds_a_proxy_from_itself() { #[test] fn smart_previews_of_raws_from_an_older_decode_are_refreshed() { use std::sync::atomic::{AtomicUsize, Ordering}; - let src = temp_dir("smartsource-src"); - let lib = temp_dir("smartsource-lib"); - for (name, seed) in [("a.png", 3), ("b.png", 9), ("c.png", 5)] { - write_png(&src.join(name), seed); - } - let mut s = Session::new().with_fs(); - s.open_library(&lib, false).unwrap(); - let paths: Vec = ["a.png", "b.png", "c.png"].iter().map(|n| src.join(n).to_string_lossy().to_string()).collect(); - s.execute("library.import", &json!({ "paths": paths })).unwrap(); - let find = |s: &Session, name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().id; - let (arw, dng, png) = (find(&s, "a.png"), find(&s, "b.png"), find(&s, "c.png")); - // `a` and `b` stand for raws (the test loader decodes their pixels): an ARW (fitted look) and a DNG (none) - for (id, format) in [(arw, "ARW"), (dng, "DNG")] { - let mut raw = (**s.catalog.photo(id).unwrap()).clone(); - raw.format = format.into(); - raw.kind = lightcraft_catalog::MediaKind::Raw; - s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id }).unwrap(); - s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(raw) }).unwrap(); - } - let photo = |s: &Session, id| s.catalog.photo(id).unwrap().clone(); - assert!(photo(&s, arw).fitted_look() && !photo(&s, dng).fitted_look() && photo(&s, dng).develops_raw() && !photo(&s, png).develops_raw()); - s.execute("library.select", &json!({"ids": [arw.0, dng.0, png.0], "active": arw.0})).unwrap(); - let dir = s.media.smart_dir.clone().unwrap(); - let file = |s: &Session, id| crate::smart::sharded_file_path(&dir, &photo(s, id)); - let (arw_file, dng_file, png_file) = (file(&s, arw), file(&s, dng), file(&s, png)); + let mut fixture = SmartFixture::new("smartsource"); + let s = &mut fixture.s; + let dir = &fixture.dir; + let [arw, dng, png] = fixture.ids; + let [arw_file, dng_file, png_file] = &fixture.files; + let photo = |id| s.catalog.photo(id).unwrap(); + assert!(photo(arw).fitted_look() && !photo(dng).fitted_look() && photo(dng).develops_raw() && !photo(png).develops_raw()); let calls = std::sync::Arc::new(AtomicUsize::new(0)); let plain = s.media.file_loader.clone().unwrap(); s.media.file_loader = Some(look_loader(plain, test_tone(1.5), calls.clone())); - let r = s.execute("library.smartPreviews", &json!({})).unwrap(); - assert_eq!((r["built"].as_u64(), r["refreshed"].as_u64()), (Some(3), Some(0)), "{r}"); - for f in [&arw_file, &dng_file, &png_file] { + for f in [arw_file, dng_file, png_file] { assert_eq!(smart_header(f)["source_version"], json!(crate::smart::SOURCE_VERSION), "the writer stamps the decode version"); assert!(!crate::smart::source_stale(f)); } // proxies from before the field: the raws' are rebuilt from their originals, the PNG's is left as it is - for f in [&arw_file, &dng_file, &png_file] { + for f in [arw_file, dng_file, png_file] { edit_smart_header(f, |h| { h.as_object_mut().unwrap().remove("source_version"); }); assert!(crate::smart::source_stale(f), "no field = version 0"); assert!(!crate::smart::is_stale(f), "the look is current"); } - let png_bytes = std::fs::read(&png_file).unwrap(); + let png_bytes = std::fs::read(png_file).unwrap(); for id in [arw, dng, png] { s.media.forget(id); } @@ -3379,28 +3359,26 @@ fn smart_previews_of_raws_from_an_older_decode_are_refreshed() { let r = s.execute("library.smartPreviews", &json!({})).unwrap(); assert_eq!((r["built"].as_u64(), r["refreshed"].as_u64()), (Some(3), Some(2)), "{r}"); assert_eq!(calls.load(Ordering::SeqCst), 2, "only the raws' originals are read"); - assert!(!crate::smart::source_stale(&arw_file) && !crate::smart::source_stale(&dng_file)); - assert!(std::fs::read(&png_file).unwrap() == png_bytes, "a PNG's proxy is never rebuilt for the raw decode"); + assert!(!crate::smart::source_stale(arw_file) && !crate::smart::source_stale(dng_file)); + assert!(std::fs::read(png_file).unwrap() == png_bytes, "a PNG's proxy is never rebuilt for the raw decode"); // the opening scan: a folder not checked at this decode version looks at the raws once, whatever their look - for f in [&arw_file, &dng_file] { + for f in [arw_file, dng_file] { edit_smart_header(f, |h| h["source_version"] = json!(0)); } - crate::smart::mark_look_checked(&dir).unwrap(); + crate::smart::mark_look_checked(dir).unwrap(); std::fs::write(dir.join("source-version"), b"0\n").unwrap(); - assert!(crate::smart::look_checked(&dir) && !crate::smart::source_checked(&dir)); + assert!(crate::smart::look_checked(dir) && !crate::smart::source_checked(dir)); for id in [arw, dng, png] { s.media.forget(id); } calls.store(0, Ordering::SeqCst); - crate::cmd::previews::refresh_stale_smart_previews(&mut s).unwrap().join().unwrap(); + crate::cmd::previews::refresh_stale_smart_previews(s).unwrap().join().unwrap(); assert_eq!(calls.load(Ordering::SeqCst), 2, "the two raws"); - assert!(!crate::smart::source_stale(&arw_file) && !crate::smart::source_stale(&dng_file)); - assert!(std::fs::read(&png_file).unwrap() == png_bytes); - assert!(crate::smart::source_checked(&dir) && crate::smart::look_checked(&dir)); - assert!(crate::cmd::previews::refresh_stale_smart_previews(&mut s).is_none(), "once per version"); - let _ = std::fs::remove_dir_all(&src); - let _ = std::fs::remove_dir_all(&lib); + assert!(!crate::smart::source_stale(arw_file) && !crate::smart::source_stale(dng_file)); + assert!(std::fs::read(png_file).unwrap() == png_bytes); + assert!(crate::smart::source_checked(dir) && crate::smart::look_checked(dir)); + assert!(crate::cmd::previews::refresh_stale_smart_previews(s).is_none(), "once per version"); } /// Opening refresh used `origin_ref`, which hard-codes `outliers: false`. A raw with Remove Hot @@ -3409,16 +3387,14 @@ fn smart_previews_of_raws_from_an_older_decode_are_refreshed() { #[test] fn refresh_of_a_raw_with_remove_hot_pixels_on_keeps_the_correction() { use std::sync::{Arc, Mutex}; - let src = temp_dir("smarthot-src"); - let lib = temp_dir("smarthot-lib"); - write_png(&src.join("a.png"), 3); + let storage = super::TestDir::new("smarthot"); + let raw_path = storage.join("a.dng"); + std::fs::write(&raw_path, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); let mut s = Session::new().with_fs(); - s.open_library(&lib, false).unwrap(); - s.execute("library.import", &json!({"paths": [src.join("a.png").to_string_lossy()]})).unwrap(); + s.open_library(storage.join("lib"), false).unwrap(); + s.execute("library.import", &json!({"paths": [raw_path.to_string_lossy()]})).unwrap(); let id = s.active().unwrap(); let mut raw = (**s.catalog.photo(id).unwrap()).clone(); - raw.format = "ARW".into(); - raw.kind = lightcraft_catalog::MediaKind::Raw; let mut develop = (*raw.develop).clone(); develop.detail.nr_outliers = true; raw.develop = std::sync::Arc::new(develop); @@ -3446,8 +3422,6 @@ fn refresh_of_a_raw_with_remove_hot_pixels_on_keeps_the_correction() { assert!(!seen.is_empty(), "the original was read"); assert!(seen.iter().all(|&o| o), "refresh decoded with Remove Hot Pixels on: {seen:?}"); assert!(!crate::smart::source_stale(&file)); - let _ = std::fs::remove_dir_all(&src); - let _ = std::fs::remove_dir_all(&lib); } /// Build Smart Previews used to take a cached proxy source (no camera profile) as a profile match @@ -3495,49 +3469,43 @@ fn build_smart_previews_refreshes_a_stale_proxy_once_the_original_is_back() { let _ = std::fs::remove_dir_all(&lib); } -/// A library with an ARW (fitted look), a DNG (none) and a PNG (the test loader decodes PNG pixels for the raws), -/// all three with current smart previews; the loader counts the originals it reads. +/// Two synthetic raws (one with a fitted look) and a PNG with current smart previews. struct SmartFixture { s: Session, - src: std::path::PathBuf, - lib: std::path::PathBuf, - dir: std::path::PathBuf, - files: [std::path::PathBuf; 3], + _storage: super::TestDir, + dir: PathBuf, + files: [PathBuf; 3], + ids: [PhotoId; 3], } impl SmartFixture { fn new(tag: &str) -> SmartFixture { - let src = temp_dir(&format!("{tag}-src")); - let lib = temp_dir(&format!("{tag}-lib")); - for (name, seed) in [("a.png", 3), ("b.png", 9), ("c.png", 5)] { - write_png(&src.join(name), seed); + let storage = super::TestDir::new(tag); + let src = storage.join("src"); + std::fs::create_dir(&src).unwrap(); + for name in ["a.dng", "b.dng"] { + let metadata = lightcraft_meta::Metadata { model: Some(name.into()), ..Default::default() }; + std::fs::write(src.join(name), crate::tests_xmp::synthetic_dng_with(None, metadata)).unwrap(); } + write_png(&src.join("c.png"), 5); let mut s = Session::new().with_fs(); - s.open_library(&lib, false).unwrap(); - let paths: Vec = ["a.png", "b.png", "c.png"].iter().map(|n| src.join(n).to_string_lossy().to_string()).collect(); + s.open_library(storage.join("lib"), false).unwrap(); + let names = ["a.dng", "b.dng", "c.png"]; + let paths = names.map(|name| src.join(name).to_string_lossy().into_owned()); s.execute("library.import", &json!({ "paths": paths })).unwrap(); - let find = |s: &Session, name: &str| s.catalog.photos().find(|p| p.file_name == name).unwrap().id; - let ids = [find(&s, "a.png"), find(&s, "b.png"), find(&s, "c.png")]; - for (id, format) in [(ids[0], "ARW"), (ids[1], "DNG")] { - let mut raw = (**s.catalog.photo(id).unwrap()).clone(); - raw.format = format.into(); - raw.kind = lightcraft_catalog::MediaKind::Raw; - s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id }).unwrap(); - s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(raw) }).unwrap(); - } + let ids = names.map(|name| s.catalog.photos().find(|p| p.file_name == name).unwrap().id); + // Treat the first raw as a fitted-look format while decoding real sensor pixels from its DNG. + let id = ids[0]; + let mut raw = (**s.catalog.photo(id).unwrap()).clone(); + raw.format = "ARW".into(); + s.catalog.apply(lightcraft_catalog::Op::RemovePhoto { id }).unwrap(); + s.catalog.apply(lightcraft_catalog::Op::AddPhoto { photo: Box::new(raw) }).unwrap(); s.execute("library.select", &json!({"ids": [ids[0].0, ids[1].0, ids[2].0], "active": ids[0].0})).unwrap(); let dir = s.media.smart_dir.clone().unwrap(); let files = ids.map(|id| crate::smart::sharded_file_path(&dir, s.catalog.photo(id).unwrap())); let r = s.execute("library.smartPreviews", &json!({})).unwrap(); assert_eq!((r["built"].as_u64(), r["refreshed"].as_u64()), (Some(3), Some(0)), "{r}"); - SmartFixture { s, src, lib, dir, files } - } -} - -impl Drop for SmartFixture { - fn drop(&mut self) { - let _ = std::fs::remove_dir_all(&self.src); - let _ = std::fs::remove_dir_all(&self.lib); + SmartFixture { s, _storage: storage, dir, files, ids } } } @@ -5874,3 +5842,58 @@ fn copy_dng_output_names(destination: &Path) -> Vec { files.sort(); files } + +#[test] +fn relink_updates_source_classification_and_keeps_offline_undo_redo() { + use crate::media::SourceLevel; + use lightcraft_catalog::MediaKind; + for raw_first in [false, true] { + let dir = super::TestDir::new(&format!("relink-kind-{raw_first}")); + let png = dir.join("rendered.png"); + let dng = dir.join("sensor.dng"); + write_png(&png, 30); + std::fs::write(&dng, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + let (original, target) = if raw_first { (&dng, &png) } else { (&png, &dng) }; + let library = dir.join("library"); + let mut s = Session::new().with_fs(); + s.open_library(&library, false).unwrap(); + s.execute("library.import", &json!({"paths": [original.to_string_lossy()]})).unwrap(); + let id = s.active().unwrap(); + s.execute("develop.set", &json!({"ids": [id.0], "control": "light.exposure", "value": 0.4})).unwrap(); + let before = s.catalog.photo(id).unwrap().clone(); + assert_eq!(s.execute("library.smartPreviews", &json!({"ids": [id.0]})).unwrap()["built"], 1); + s.execute("photo.relink", &json!({"id": id.0, "path": target.to_string_lossy()})).unwrap(); + let after = s.catalog.photo(id).unwrap().clone(); + assert_eq!(after.kind, if raw_first { MediaKind::Image } else { MediaKind::Raw }); + assert_eq!(after.format, if raw_first { "PNG" } else { "DNG" }); + assert_eq!(after.develop, before.develop, "relink preserves edits"); + assert_eq!(s.execute("library.smartPreviews", &json!({"ids": [id.0]})).unwrap()["built"], 1); + std::fs::rename(original, original.with_extension("offline")).unwrap(); + std::fs::rename(target, target.with_extension("offline")).unwrap(); + s.media.forget(id); + let p = s.catalog.photo(id).unwrap(); + let source = s.media.source_ref(p, SourceLevel::Preview).load_source().unwrap(); + assert!(source.from_proxy); + assert_eq!(source.info_or(crate::media::source_info(p)).raw, !raw_first); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap(), &before); + let p = s.catalog.photo(id).unwrap(); + let source = s.media.source_ref(p, SourceLevel::Preview).load_source().unwrap(); + assert_eq!(source.info_or(crate::media::source_info(p)).raw, raw_first); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.catalog.photo(id).unwrap(), &after); + let p = s.catalog.photo(id).unwrap(); + let source = s.media.source_ref(p, SourceLevel::Preview).load_source().unwrap(); + assert_eq!(source.info_or(crate::media::source_info(p)).raw, !raw_first); + // Finish the opening refresh before reopening can start an unowned marker writer. + if let Some(refresh) = crate::cmd::previews::refresh_stale_smart_previews(&mut s) { + refresh.join().unwrap(); + } + assert!(crate::smart::look_checked(s.media.smart_dir.as_ref().unwrap())); + s.persist().unwrap(); + drop(s); + let mut reopened = Session::new().with_fs(); + reopened.open_library(&library, false).unwrap(); + assert_eq!(reopened.catalog.photo(id).unwrap(), &after); + } +} diff --git a/crates/engine/src/tests/smart_interpretation.rs b/crates/engine/src/tests/smart_interpretation.rs new file mode 100644 index 00000000000..e02716dd762 --- /dev/null +++ b/crates/engine/src/tests/smart_interpretation.rs @@ -0,0 +1,441 @@ +//! Proxy pixels must keep the interpretation that decoded them, including across Undo and offline use. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, mpsc}; +use std::time::{Duration, Instant}; + +use lightcraft_catalog::{Op, Photo, PhotoId}; +use lightcraft_pipeline::SourceInfo; +use lightcraft_raster::Rgb32f; +use serde_json::{Value, json}; + +use crate::Session; +use crate::media::SourceLevel; + +struct Lib { + s: Session, + dir: super::TestDir, + file: PathBuf, + id: PhotoId, +} + +impl Lib { + fn new(name: &str, sensor: bool) -> Self { + let dir = super::TestDir::new(&format!("smart-interpretation-{name}")); + let file = dir.join("sensor.dng"); + std::fs::write(&file, crate::tests_xmp::synthetic_dng_with(None, Default::default())).unwrap(); + let mut s = Session::new().with_fs(); + s.open_library(dir.join("library"), false).unwrap(); + let r = s.execute("library.import", &json!({"paths": [file.to_string_lossy()]})).unwrap(); + let id = PhotoId(r["imported"][0].as_u64().unwrap()); + let mut x = Self { s, dir, file, id }; + if !sensor { + x.set_preview(true, false); + } + x + } + + fn photo(&self) -> Arc { + self.s.catalog.photo(self.id).unwrap().clone() + } + + fn smart_dir(&self) -> PathBuf { + self.s.media.smart_dir.clone().unwrap() + } + + fn set_preview(&mut self, preview: bool, undo: bool) { + let p = self.photo(); + let flag = preview.then(|| "previous decoder".into()); + let op = Op::SetContent { + id: p.id, + width: p.width, + height: p.height, + file_size: p.file_size, + content_hash: p.content_hash.clone(), + preview_checked: p.preview_stamp(&flag), + preview_only: flag, + }; + if undo { + self.s.commit("Source interpretation", op).unwrap(); + } else { + self.s.apply_system(op).unwrap(); + self.s.media.forget(p.id); + } + } + + fn build(&mut self) -> Value { + self.s.execute("library.smartPreviews", &json!({"id": self.id.0})).unwrap() + } + + fn status(&mut self) -> bool { + self.s.execute("photo.smartPreview", &json!({"id": self.id.0})).unwrap()["smartPreview"].as_bool().unwrap() + } + + fn offline_source(&mut self) -> Result { + let photo = self.photo(); + self.s.media.forget(self.id); + self.s.media.source_ref(&photo, SourceLevel::Preview).load_source() + } +} + +fn old_path(dir: &Path, photo: &Photo, flat: bool) -> PathBuf { + let hash = lightcraft_preview::Hasher128::new().str(&crate::media::content_key(photo)).finish(); + let name = format!("{:032x}.lcsp", hash.0); + if flat { dir.join(name) } else { dir.join(&name[..2]).join(name) } +} + +fn write_proxy(path: &Path, info: Option<&SourceInfo>, stale: bool) -> Vec { + let mut bytes = crate::smart::encode(&Rgb32f::filled(48, 32, [0.2, 0.4, 0.6]), info).unwrap(); + if stale { + let (start, end, mut header) = header(&bytes); + header["enc"] = json!(0); + bytes.splice(start..end, header.to_string().bytes()); + } + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, &bytes).unwrap(); + bytes +} + +fn header(bytes: &[u8]) -> (usize, usize, Value) { + let start = b"LCSP1\n".len(); + let end = start + bytes[start..].iter().position(|b| *b == b'\n').unwrap(); + (start, end, serde_json::from_slice(&bytes[start..end]).unwrap()) +} + +fn wait_build(s: &Session) { + let deadline = Instant::now() + Duration::from_secs(10); + while s.preview_build.as_ref().is_some_and(|state| state.running()) { + assert!(Instant::now() < deadline, "the proxy build finished"); + std::thread::sleep(Duration::from_millis(2)); + } +} + +#[test] +fn raw_smart_build_requires_source_facts() { + let mut x = Lib::new("missing-facts", true); + x.s.media.insert(x.id, SourceLevel::Preview, Arc::new(Rgb32f::filled(48, 32, [0.7; 3]))); + let r = x.build(); + assert_eq!(r["built"], 0, "unknown pixels must not be labelled sensor-derived: {r}"); + assert!(r["failed"][0][1].as_str().unwrap().contains("Reload"), "{r}"); + assert!(!x.status()); +} + +#[test] +fn stale_interpretation_mismatch_does_not_complete_the_refresh() { + let mut x = Lib::new("stale-mismatch", false); + let dir = x.smart_dir(); + let path = crate::smart::sharded_file_path(&dir, &x.photo()); + let bytes = write_proxy(&path, Some(&Default::default()), true); + let r = x.build(); + assert_eq!((r["built"].clone(), r["staleKept"].clone()), (json!(0), json!(0)), "{r}"); + assert!(r["failed"][0][1].as_str().unwrap().contains("Reload"), "{r}"); + let loader = x.s.media.file_loader.clone().unwrap(); + let activity = x.s.activity.clone(); + x.s.media.file_loader = Some(Arc::new(move |path, edge, options| { + assert!(activity.list().iter().any(|row| row.kind == "smartPreviews"), "the opening refresh holds an activity row"); + loader(path, edge, options) + })); + crate::cmd::previews::refresh_stale_smart_previews(&mut x.s).unwrap().join().unwrap(); + assert!(!crate::smart::look_checked(&dir), "a mismatch must not complete the opening refresh"); + assert_eq!(std::fs::read(&path).unwrap(), bytes); + x.s.execute("library.smartPreviews", &json!({"id": x.id.0, "background": true})).unwrap(); + wait_build(&x.s); + let progress = x.s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!(progress["failed"], 1); + assert!(progress["error"].as_str().unwrap().contains("Reload"), "{progress}"); +} + +#[test] +fn undo_during_a_build_cannot_overwrite_another_interpretation() { + let mut x = Lib::new("undo-worker", false); + let preview = crate::smart::sharded_file_path(&x.smart_dir(), &x.photo()); + let bytes = write_proxy(&preview, Some(&Default::default()), true); + x.set_preview(false, true); + let sensor = crate::smart::sharded_file_path(&x.smart_dir(), &x.photo()); + let (entered, receive_entered) = mpsc::channel(); + let (release, receive_release) = mpsc::channel(); + let receive_release = Mutex::new(receive_release); + x.s.media.file_loader = Some(Arc::new(move |_, _, _| { + entered.send(()).unwrap(); + receive_release.lock().unwrap().recv_timeout(Duration::from_secs(10)).unwrap(); + Ok((Rgb32f::filled(48, 32, [0.7; 3]), SourceInfo { raw: true, ..Default::default() })) + })); + x.s.execute("library.smartPreviews", &json!({"id": x.id.0, "background": true})).unwrap(); + receive_entered.recv_timeout(Duration::from_secs(10)).unwrap(); + assert!(x.s.activity.list().iter().any(|row| row.kind == "smartPreviews")); + x.s.execute("edit.undo", &json!({})).unwrap(); + assert!(x.photo().preview_only.is_some()); + release.send(()).unwrap(); + wait_build(&x.s); + assert_eq!(std::fs::read(&preview).unwrap(), bytes, "the old job only writes its captured sensor identity"); + assert!(crate::smart::load(&sensor).unwrap().info.unwrap().raw); + std::fs::remove_file(&x.file).unwrap(); + assert!(!x.offline_source().unwrap().info.unwrap().raw); + x.s.execute("edit.redo", &json!({})).unwrap(); + assert!(x.offline_source().unwrap().info.unwrap().raw); +} + +#[test] +fn relink_ignores_wrong_destination_pixels_and_preserves_undo_files() { + let mut x = Lib::new("relink-files", false); + let old = crate::smart::sharded_file_path(&x.smart_dir(), &x.photo()); + let old_bytes = write_proxy(&old, Some(&Default::default()), false); + let target = x.dir.join("destination.dng"); + std::fs::write(&target, crate::tests_xmp::synthetic_dng_with(None, lightcraft_meta::Metadata { iso: Some(200), ..Default::default() })).unwrap(); + let r = x.s.execute("library.import", &json!({"paths": [target.to_string_lossy()]})).unwrap(); + let destination = PhotoId(r["imported"][0].as_u64().unwrap()); + assert_ne!( + crate::media::content_key(&x.photo()), + crate::media::content_key(x.s.catalog.photo(destination).unwrap()), + "Relink changes content identities" + ); + let legacy = old_path(&x.smart_dir(), x.s.catalog.photo(destination).unwrap(), true); + let legacy_bytes = write_proxy(&legacy, Some(&Default::default()), false); + x.s.execute("photo.relink", &json!({"id": x.id.0, "path": target.to_string_lossy()})).unwrap(); + assert!(x.photo().develops_raw()); + assert!(!x.status(), "the destination's preview pixels cannot stand in for its sensor data"); + assert_eq!(x.build()["built"], 1); + let sensor = crate::smart::sharded_file_path(&x.smart_dir(), &x.photo()); + let sensor_bytes = std::fs::read(&sensor).unwrap(); + assert!(crate::smart::load(&sensor).unwrap().info.unwrap().raw); + assert_eq!(std::fs::read(&old).unwrap(), old_bytes); + assert_eq!(std::fs::read(&legacy).unwrap(), legacy_bytes); + std::fs::remove_file(&x.file).unwrap(); + std::fs::remove_file(&target).unwrap(); + // A later invalid op rolls the raw→preview edit back without deleting offline-only pixels. + let before = x.s.catalog.to_snapshot(); + assert!( + x.s.commit( + "Invalid interpretation edit", + Op::Batch { + ops: vec![ + Op::SetContent { + id: x.id, + width: 9, + height: 9, + file_size: 1, + content_hash: Some("changed".into()), + preview_only: Some("changed interpretation".into()), + preview_checked: "".into() + }, + Op::RemovePhoto { id: PhotoId(u64::MAX) }, + ] + } + ) + .is_err() + ); + assert_eq!(x.s.catalog.to_snapshot(), before); + assert_eq!(std::fs::read(&old).unwrap(), old_bytes); + assert_eq!(std::fs::read(&legacy).unwrap(), legacy_bytes); + assert_eq!(std::fs::read(&sensor).unwrap(), sensor_bytes); + assert!(x.offline_source().unwrap().info.unwrap().raw); + x.s.execute("edit.undo", &json!({})).unwrap(); + assert!(!x.offline_source().unwrap().info.unwrap().raw); + x.s.execute("edit.redo", &json!({})).unwrap(); + assert!(x.offline_source().unwrap().info.unwrap().raw); +} + +#[test] +fn rebuilding_preserves_content_only_legacy_bytes() { + for flat in [false, true] { + let mut x = Lib::new(&format!("rebuild-{flat}"), true); + let legacy = old_path(&x.smart_dir(), &x.photo(), flat); + let bytes = write_proxy(&legacy, Some(&SourceInfo { raw: true, ..Default::default() }), true); + assert_eq!(x.build()["built"], 1); + assert_eq!(std::fs::read(&legacy).unwrap(), bytes, "a rebuild cannot replace another interpretation's pixels"); + let current = crate::smart::sharded_file_path(&x.smart_dir(), &x.photo()); + assert!(crate::smart::load(¤t).unwrap().info.unwrap().raw); + assert!(!crate::smart::is_stale(¤t)); + } +} + +#[test] +fn build_repairs_or_rejects_undecodable_candidates() { + for offline in [false, true] { + for stale in [false, true] { + for fallback in [false, true] { + let mut x = Lib::new(&format!("corrupt-{offline}-{stale}-{fallback}"), true); + let photo = x.photo(); + let dir = x.smart_dir(); + let current = crate::smart::sharded_file_path(&dir, &photo); + let info = SourceInfo { raw: true, ..Default::default() }; + let mut bytes = write_proxy(¤t, Some(&info), stale); + let (_, end, head) = header(&bytes); + let tail = bytes.len() - head["tail"].as_u64().unwrap() as usize; + bytes[end + 3..tail - 2].fill(0); // SOI/EOI remain valid; actual JPEG decoding must reject it. + std::fs::write(¤t, bytes).unwrap(); + assert!(crate::smart::is_valid(¤t)); + assert!(crate::smart::load(¤t).is_err()); + if fallback { + write_proxy(&old_path(&dir, &photo, true), Some(&info), stale); + } + if offline { + std::fs::remove_file(&x.file).unwrap(); + } + let r = x.build(); + let usable = !offline || fallback; + assert_eq!(r["built"], usize::from(usable), "{offline}/{stale}/{fallback}: {r}"); + assert_eq!(r["failed"].as_array().unwrap().is_empty(), usable, "{r}"); + assert_eq!(r["staleKept"], usize::from(offline && stale && fallback), "{r}"); + assert_eq!(x.status(), usable); + assert_eq!(x.s.media.smart_availability.exists(&dir, &photo), usable); + assert_eq!(x.offline_source().is_ok(), usable); + } + } + } +} + +#[test] +fn damaged_candidates_fall_back_in_every_layout() { + for decode_failure in [false, true] { + for good_at in 1..4 { + let mut x = Lib::new(&format!("fallback-{decode_failure}-{good_at}"), true); + let photo = x.photo(); + let dir = x.smart_dir(); + let name = crate::smart::file_name(&photo); + let paths = [dir.join(&name[..2]).join(&name), dir.join(&name), old_path(&dir, &photo, false), old_path(&dir, &photo, true)]; + let info = SourceInfo { raw: true, ..Default::default() }; + for path in &paths[..good_at] { + let mut bytes = write_proxy(path, Some(&info), false); + if decode_failure { + let (_, end, head) = header(&bytes); + let tail = bytes.len() - head["tail"].as_u64().unwrap() as usize; + bytes[end + 3..tail - 2].fill(0); + } else { + bytes.truncate(10); + } + std::fs::write(path, bytes).unwrap(); + } + write_proxy(&paths[good_at], Some(&info), false); + std::fs::remove_file(&x.file).unwrap(); + assert!(x.status()); + assert!(x.s.media.smart_availability.exists(&dir, &photo)); + let source = x.offline_source().unwrap(); + assert!(source.from_proxy && source.info.unwrap().raw); + assert!((source.image.data[0][0] - 0.2).abs() < 0.02); + } + } +} + +#[test] +fn malformed_declared_facts_cannot_pass_status_build_or_loading() { + let cases = [ + (json!([]), vec![0]), + (json!([{"kind": 255, "w": 1, "h": 1, "len": 1}]), vec![0]), + (json!([{"kind": 0, "w": 0, "h": 1, "len": 0}]), vec![]), + (json!([{"kind": 0, "w": 2, "h": 2, "len": 1}]), vec![0]), + (json!([{"kind": 0, "w": usize::MAX, "h": 2, "len": 1}]), vec![0]), + (json!([{"kind": 0, "w": 2, "h": 2, "len": 4}]), vec![0; 3]), + ]; + for (i, (mattes, planes)) in cases.into_iter().enumerate() { + let mut x = Lib::new(&format!("malformed-tail-{i}"), true); + let photo = x.photo(); + let path = old_path(&x.smart_dir(), &photo, i % 2 == 0); + let bytes = write_proxy(&path, Some(&SourceInfo { raw: true, ..Default::default() }), false); + let (_, end, mut head) = header(&bytes); + let tail = bytes.len() - head["tail"].as_u64().unwrap() as usize; + let mut facts: Value = serde_json::from_slice(&bytes[tail + 4..]).unwrap(); + facts["mattes"] = mattes; + let facts = serde_json::to_vec(&facts).unwrap(); + head["tail"] = json!(4 + facts.len() + planes.len()); + let mut broken = format!("LCSP1\n{head}\n").into_bytes(); + broken.extend_from_slice(&bytes[end + 1..tail]); + broken.extend_from_slice(&(facts.len() as u32).to_le_bytes()); + broken.extend(facts); + broken.extend(planes); + std::fs::write(&path, &broken).unwrap(); + assert!(crate::smart::decode(&broken).is_err(), "malformed tail{i}"); + assert!(crate::smart::is_valid(&path), "JPEG framing alone cannot validate the tail"); + std::fs::remove_file(&x.file).unwrap(); + assert!(!x.status(), "malformed tail{i}"); + assert!(!x.s.media.smart_availability.exists(&x.smart_dir(), &photo)); + assert!(x.offline_source().is_err()); + assert_eq!(x.build()["built"], 0); + assert_eq!(std::fs::read(&path).unwrap(), broken); + } +} + +#[test] +fn discard_preserves_every_unselected_consumer() { + for preview_copy in [false, true] { + for legacy in [false, true] { + let mut x = Lib::new(&format!("discard-{preview_copy}-{legacy}"), true); + let r = x.s.execute("photo.virtualCopy", &json!({"id": x.id.0})).unwrap(); + let copy = PhotoId(r["ids"][0].as_u64().unwrap()); + let parent = x.id; + x.id = copy; + x.set_preview(preview_copy, false); + x.id = parent; + let photo = x.photo(); + let path = if legacy { old_path(&x.smart_dir(), &photo, true) } else { crate::smart::sharded_file_path(&x.smart_dir(), &photo) }; + let bytes = write_proxy(&path, Some(&SourceInfo { raw: true, ..Default::default() }), false); + std::fs::remove_file(&x.file).unwrap(); + x.s.execute("library.smartPreviews", &json!({"id": copy.0, "discard": true})).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), bytes, "an unselected sensor consumer still needs these pixels"); + assert!(x.offline_source().unwrap().info.unwrap().raw); + x.s.execute("library.smartPreviews", &json!({"ids": [parent.0, copy.0], "discard": true})).unwrap(); + assert!(!path.exists(), "selecting every consumer permits explicit deletion"); + } + } +} + +#[test] +fn proxy_operations_invalidate_fresh_background_availability() { + for background in [false, true] { + let mut x = Lib::new(&format!("cached-availability-{background}"), true); + let photo = x.photo(); + let dir = x.smart_dir(); + let (wake, receive) = mpsc::channel(); + x.s.media.smart_availability.run_in_background(Arc::new(move || { + let _ = wake.send(()); + })); + let availability = x.s.media.smart_availability.clone(); + assert!(!availability.exists(&dir, &photo)); + let deadline = Instant::now() + Duration::from_secs(5); + while !availability.checked_missing(&dir, &photo) { + let remaining = deadline.checked_duration_since(Instant::now()).expect("the missing proxies have been checked"); + receive.recv_timeout(remaining).unwrap(); + } + assert!(!availability.exists(&dir, &photo)); + for discard in [false, true] { + x.s.execute("library.smartPreviews", &json!({"id": x.id.0, "background": background, "discard": discard})).unwrap(); + wait_build(&x.s); + let deadline = Instant::now() + Duration::from_secs(5); + loop { + let exists = availability.exists(&dir, &photo); + let checked = if discard { availability.checked_missing(&dir, &photo) } else { exists }; + if checked { + assert_eq!(exists, !discard); + break; + } + let remaining = deadline.checked_duration_since(Instant::now()).expect("availability changed after write/discard"); + receive.recv_timeout(remaining).unwrap(); + } + } + } +} + +#[test] +fn an_unremovable_old_candidate_does_not_block_an_interpretation_edit() { + let mut x = Lib::new("unremovable-candidate", true); + let dir = x.smart_dir(); + let photo = x.photo(); + let sensor = crate::smart::sharded_file_path(&dir, &photo); + let sensor_bytes = write_proxy(&sensor, Some(&SourceInfo { raw: true, ..Default::default() }), false); + let flat = dir.join(crate::smart::file_name(&photo)); + std::fs::create_dir_all(&flat).unwrap(); + assert!(std::fs::remove_file(&flat).is_err(), "this candidate cannot be invalidated as a file"); + let mut preview = (*photo).clone(); + preview.preview_only = Some("previous decoder".into()); + let preview = crate::smart::sharded_file_path(&dir, &preview); + let preview_bytes = write_proxy(&preview, Some(&Default::default()), false); + std::fs::remove_file(&x.file).unwrap(); + x.set_preview(true, true); + assert!(x.photo().preview_only.is_some(), "classification edits do not depend on deleting proxy files"); + assert!(!x.offline_source().unwrap().info.unwrap().raw); + x.s.execute("edit.undo", &json!({})).unwrap(); + assert!(x.offline_source().unwrap().info.unwrap().raw); + assert_eq!(std::fs::read(&sensor).unwrap(), sensor_bytes); + assert_eq!(std::fs::read(&preview).unwrap(), preview_bytes); + assert!(flat.is_dir()); +} diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 287de18989b..16d445679c6 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -19,6 +19,8 @@ impl LightcraftApp { // worker fills: a sleeping NAS or a dropped share never stalls a frame let repaint = ctx.clone(); self.session.media.availability.run_in_background(std::sync::Arc::new(move || repaint.request_repaint())); + let repaint = ctx.clone(); + self.session.media.smart_availability.run_in_background(std::sync::Arc::new(move || repaint.request_repaint())); self.styled = true; self.font_language = self.ui.language; } else if self.font_language != self.ui.language { diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 91f0c6efd13..6fa693f878b 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -22,6 +22,38 @@ use crate::LightcraftApp; pub type ControlResponse = Value; +/// Read and decode status-query files on a tracked worker, then reply on completion. The +/// response belongs to the snapshotted library, never a different library opened meanwhile. +fn smart_preview_status(app: &mut LightcraftApp, params: &Value, reply: Sender) -> Outcome { + const LABEL: &str = "Smart Preview Status"; + let job = match lightcraft_engine::cmd::previews::smart_status_job(&app.session, params) { + Ok(job) => job, + Err(e) => return err(e.to_string()), + }; + let library = app.session.library_generation(); + let started = crate::tasks::spawn( + app, + LABEL, + Some("smartPreviews"), + move || lightcraft_engine::guard::catch(LABEL, job), + move |app, _, result| { + let response = if app.session.library_generation() != library { + failure("Smart Preview Status: another library was opened before the check ended") + } else { + match result { + Ok(value) => success(value), + Err(e) => failure(e), + } + }; + let _ = reply.send(response); + }, + ); + match started { + Ok(()) => Outcome::Later, + Err(e) => err(e), + } +} + pub struct ControlRequest { pub method: String, pub params: Value, @@ -360,6 +392,11 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest ctx.request_repaint(); return started; } + if id == "photo.smartPreview" { + let started = smart_preview_status(app, ¶ms, req.reply.clone()); + ctx.request_repaint(); + return started; + } let r = app.run(id, params); ctx.request_repaint(); wrap(r) diff --git a/crates/ui-egui/src/panels/right/info.rs b/crates/ui-egui/src/panels/right/info.rs index 2a63242ab78..bd7544aa9c6 100644 --- a/crates/ui-egui/src/panels/right/info.rs +++ b/crates/ui-egui/src/panels/right/info.rs @@ -1,5 +1,6 @@ use super::{Icon, LightcraftApp, PhotoId, Sense, Tokens, divider, header, json, padded, register, text_button, vec2}; +/// Draw editable metadata and cached original/proxy availability for the selected photo. pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { let Some(p) = app.session.catalog.photo(id).cloned() else { return }; header(ui, "Info"); @@ -203,11 +204,7 @@ pub(super) fn info(app: &mut LightcraftApp, ui: &mut egui::Ui, id: PhotoId) { if let lightcraft_catalog::Source::File { path } = &p.source { let avail = &app.session.media.availability; let online = !avail.is_offline(path); - let smart = app.session.media.smart_dir.as_ref().is_some_and(|d| { - let shard = lightcraft_engine::smart::sharded_file_path(d, &p); - let legacy = d.join(lightcraft_engine::smart::file_name(&p)); - avail.exists(&shard.to_string_lossy()) == Some(true) || avail.exists(&legacy.to_string_lossy()) == Some(true) - }); + let smart = app.session.media.smart_dir.as_ref().is_some_and(|d| app.session.media.smart_availability.exists(d, &p)); if !online || smart { let text = match (online, smart) { (false, true) => "Original offline · editing the smart preview", diff --git a/crates/ui-egui/src/tests/offline.rs b/crates/ui-egui/src/tests/offline.rs index 5327412d1bc..c7296b050e6 100644 --- a/crates/ui-egui/src/tests/offline.rs +++ b/crates/ui-egui/src/tests/offline.rs @@ -247,3 +247,32 @@ fn import_reads_files_off_the_ui_thread_and_can_be_cancelled() { assert_eq!(calls.on(ui_thread), 0, "files were never read on the UI thread"); let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn smart_preview_status_checks_files_off_the_ui_thread() { + let calls = Calls::default(); + let nas = Nas::asleep(); + let app = LightcraftApp::new(offline_library(&calls, &nas), Services { png: None, ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + h.step(); + let ui = std::thread::current().id(); + let reply = h.send("engine.execute", json!({"command": "photo.smartPreview", "params": {"id": 1}})).unwrap(); + frames_while_asleep(&mut h, &nas, 5, "Smart Preview Status"); + assert!(reply.try_recv().is_err(), "status waits for the original probe on its worker"); + assert!(h.app.session.activity.list().iter().any(|row| row.label == "Smart Preview Status")); + assert_eq!(calls.on(ui), 0); + nas.wake(); + let deadline = Instant::now() + Duration::from_secs(10); + let answer = loop { + h.step(); + if let Ok(answer) = reply.try_recv() { + break answer; + } + assert!(Instant::now() < deadline, "the status query answered"); + std::thread::sleep(Duration::from_millis(1)); + }; + assert_eq!(answer["ok"], true, "{answer}"); + assert_eq!(answer["result"], json!({"smartPreview": false, "originalOnline": false})); + assert_eq!(calls.on(ui), 0); + assert!(h.app.tasks.is_empty()); +} From 042600dca7757fc1d91013dc55e253d9e6e1a0a0 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 18:44:00 +0100 Subject: [PATCH 35/42] Smart Previews: preserve live consumers and newer proxy files --- crates/engine/src/cmd/previews.rs | 171 +++++++++++++++--- crates/engine/src/lib.rs | 9 + crates/engine/src/library.rs | 4 + crates/engine/src/media/quick.rs | 3 + crates/engine/src/smart.rs | 2 +- crates/engine/src/smart/tests.rs | 19 +- .../engine/src/tests/smart_interpretation.rs | 50 +++++ 7 files changed, 220 insertions(+), 38 deletions(-) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index fcb5f7ab59d..75c2a934c5f 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -48,6 +48,8 @@ pub struct PreviewBuild { pub order: Vec, pub focus: AtomicUsize, pub backward: AtomicBool, + #[cfg(not(target_arch = "wasm32"))] + pub(crate) discard_retention: Option>>, /// Test-only: the gate this build's lanes wait at before a photo's first render (see /// [`test_gate`]). Captured by `build` on the calling thread; production builds never have one. #[cfg(test)] @@ -669,11 +671,66 @@ struct SmartJob { path: crate::smart::PreviewPath, source: Option, ages: Ages, - /// Only identities that no unselected photo uses, in either folder layout. - discard_paths: Vec, availability: crate::smart::Availability, } +/// Shared with catalog edits for the lifetime of a discard. A worker holds this +/// lock only while checking and removing one path. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug)] +pub(crate) struct DiscardRetention { + dir: std::path::PathBuf, + selected: std::collections::HashSet, + candidates: std::collections::HashSet, + held_by: std::collections::HashMap>, + counts: std::collections::HashMap, +} + +#[cfg(not(target_arch = "wasm32"))] +impl DiscardRetention { + fn new( + dir: &std::path::Path, + selected: std::collections::HashSet, + jobs: &[SmartJob], + catalog: &lightcraft_catalog::Catalog, + ) -> Self { + let candidates = jobs.iter().flat_map(|job| job.path.candidates()).collect(); + let mut retention = Self { dir: dir.to_path_buf(), selected, candidates, held_by: Default::default(), counts: Default::default() }; + if !retention.candidates.is_empty() { + for p in catalog.photos() { + retention.update(p.id, Some(p)); + } + } + retention + } + + pub(crate) fn update(&mut self, id: lightcraft_catalog::PhotoId, photo: Option<&lightcraft_catalog::Photo>) { + if let Some(previous) = self.held_by.remove(&id) { + for path in previous { + if let std::collections::hash_map::Entry::Occupied(mut count) = self.counts.entry(path) { + *count.get_mut() -= 1; + if *count.get() == 0 { + count.remove(); + } + } + } + } + if self.selected.contains(&id) { + return; + } + if let Some(p) = photo.filter(|p| matches!(p.source, lightcraft_catalog::Source::File { .. })) { + let paths: Vec<_> = + crate::smart::PreviewPath::new(&self.dir, p).candidates().into_iter().filter(|p| self.candidates.contains(p)).collect(); + for path in &paths { + *self.counts.entry(path.clone()).or_default() += 1; + } + if !paths.is_empty() { + self.held_by.insert(id, paths); + } + } + } +} + /// DNG tone fits also go stale, although DNGs keep their own matrix and Kelvin white-balance scale. /// So do preview-only raws: their proxy is the embedded JPEG, read in the colour space the raw /// declares, which a look version bump can change too (#2654). @@ -758,12 +815,12 @@ fn original_only(source: crate::media::SourceRef) -> Option>, jobs: Vec, state: Option<(&PreviewBuild, &TaskGuard)>, ) -> std::result::Result { let mut n = SmartCounts::default(); - if !discard { + if discard.is_none() { // a chosen folder on another drive must be there: never recreate it on this one if custom { crate::smart::check_writable(dir)?; @@ -771,7 +828,7 @@ fn smart_run( std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; } } - for SmartJob { id, path, source, ages, discard_paths, availability } in jobs { + for SmartJob { id, path, source, ages, availability } in jobs { if state.is_some_and(|(st, _)| st.cancel.load(Ordering::Relaxed)) { break; } @@ -779,11 +836,29 @@ fn smart_run( let candidates = path.candidates(); // Read either the new shard or a pre-upgrade flat file, without making new work // depend on having the original online. - if discard { - for path in discard_paths { - if std::fs::remove_file(&path).is_ok() { - n.removed += 1; + if let Some(retention) = discard { + let mut errors = Vec::new(); + for path in &candidates { + let guard = retention.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if state.is_some_and(|(st, _)| st.cancel.load(Ordering::Relaxed)) { + break; + } + if guard.counts.contains_key(path) { + continue; + } + match std::fs::remove_file(path) { + Ok(()) => n.removed += 1, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => errors.push(format!("{}: {e}", path.display())), + } + } + if !errors.is_empty() { + let why = errors.join("\n"); + if let Some((st, _)) = state { + st.failed.fetch_add(1, Ordering::Relaxed); + *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(why.clone()); } + n.failed.push(json!([id.0, why])); } } else { let reusable = path.load_with_path().ok().map(|(path, _)| path); @@ -798,7 +873,14 @@ fn smart_run( let damaged = existing.exists(); let newer = valid && crate::smart::from_newer_build(&existing); let stale = valid && !newer && ages.stale(&existing); - if valid && !stale { + if crate::smart::from_newer_build(path) { + n.newer_kept += 1; + if valid { + n.built += 1; + } else if let Some((st, _)) = state { + st.skipped.fetch_add(1, Ordering::Relaxed); + } + } else if valid && !stale { n.built += 1; if newer { n.newer_kept += 1; @@ -913,38 +995,27 @@ fn smart(s: &mut Session, p: &Value) -> Result { } let mut jobs: Vec = Vec::new(); let selected: std::collections::HashSet<_> = ids.iter().copied().collect(); - let retained: std::collections::HashSet<_> = if discard { - s.catalog - .photos() - .filter(|p| !selected.contains(&p.id) && matches!(p.source, lightcraft_catalog::Source::File { .. })) - .flat_map(|p| crate::smart::PreviewPath::new(&dir, p).candidates()) - .collect() - } else { - Default::default() - }; for id in ids { let Some(ph) = s.catalog.photo(id).cloned() else { continue }; if !matches!(ph.source, lightcraft_catalog::Source::File { .. }) { continue; } let path = crate::smart::PreviewPath::new(&dir, &ph); - // Copies can share the current decoder identity as well as the content-only legacy - // identity. Deleting either would strand an unselected photo whose original is offline. - let discard_paths = if discard { path.candidates().into_iter().filter(|p| !retained.contains(p)).collect() } else { Vec::new() }; // Decode the original afresh, with the photo's hot-pixel setting. Cached sources may // carry an imported profile or predate the lens database captured by smart_run. let source = (!discard).then(|| s.media.origin_ref_of(&ph, crate::media::SourceLevel::Preview.max_edge())); - jobs.push(SmartJob { id, path, source, ages: Ages::of(&ph), discard_paths, availability: s.media.smart_availability.clone() }); + jobs.push(SmartJob { id, path, source, ages: Ages::of(&ph), availability: s.media.smart_availability.clone() }); } let custom = s.smart_previews_dir.is_some(); + let retention = discard.then(|| Arc::new(std::sync::Mutex::new(DiscardRetention::new(&dir, selected, &jobs, &s.catalog)))); if background { - let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() }); + let state = Arc::new(PreviewBuild { total: jobs.len(), what, discard_retention: retention.clone(), ..Default::default() }); let previous = s.preview_build.clone(); set_current(s, state.clone()); // (this build always has its row) let run = Running { task: Some(task_for(s, &state)), state: state.clone() }; let work = move || { - if let Err(e) = smart_run(&dir, custom, discard, jobs, run.task.as_ref().map(|task| (&*run.state, task))) { + if let Err(e) = smart_run(&dir, custom, retention.as_deref(), jobs, run.task.as_ref().map(|task| (&*run.state, task))) { log::warn!("{C}: {e}"); *run.state.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); } @@ -971,12 +1042,57 @@ fn smart(s: &mut Session, p: &Value) -> Result { } return Ok(state.json()); } - let r = smart_run(&dir, custom, discard, jobs, None).map_err(|e| bad(C, e))?; + let r = smart_run(&dir, custom, retention.as_deref(), jobs, None).map_err(|e| bad(C, e))?; Ok( json!({"built": r.built, "repaired": r.repaired, "refreshed": r.refreshed, "staleKept": r.stale_kept, "newerKept": r.newer_kept, "removed": r.removed, "failed": r.failed}), ) } +#[cfg(all(test, not(target_arch = "wasm32")))] +#[test] +fn pending_discard_retains_the_proxy_an_unselected_photo_regains_on_undo() { + use lightcraft_catalog::{MediaKind, Op, Photo, PhotoId, Source}; + let dir = crate::tests::TestDir::new("discard-retention"); + let mut s = Session::new(); + s.media.smart_dir = Some(dir.to_path_buf()); + let mut p = Photo::new(PhotoId(1), Source::File { path: "offline.dng".into() }, "offline.dng", "DNG", 8, 8, ""); + p.kind = MediaKind::Raw; + let path = crate::smart::sharded_file_path(&dir, &p); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let bytes = crate::smart::encode( + &lightcraft_raster::Rgb32f::filled(8, 8, [0.2; 3]), + Some(&lightcraft_pipeline::SourceInfo { raw: true, ..Default::default() }), + ) + .unwrap(); + std::fs::write(&path, &bytes).unwrap(); + let mut copy = p.clone(); + copy.id = PhotoId(2); + s.commit("Add", Op::Batch { ops: vec![Op::AddPhoto { photo: Box::new(p) }, Op::AddPhoto { photo: Box::new(copy.clone()) }] }).unwrap(); + s.commit( + "Change interpretation", + Op::SetContent { + id: copy.id, + width: copy.width, + height: copy.height, + file_size: copy.file_size, + content_hash: copy.content_hash, + preview_only: Some("decoder changed".into()), + preview_checked: String::new(), + }, + ) + .unwrap(); + let gate = SMART_WRITE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + smart(&mut s, &json!({"id": 1, "background": true, "discard": true})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + drop(gate); + let started = std::time::Instant::now(); + while s.preview_build.as_ref().unwrap().running() { + assert!(started.elapsed() < std::time::Duration::from_secs(10)); + std::thread::yield_now(); + } + assert_eq!(std::fs::read(&path).unwrap(), bytes); +} + /// Refresh existing proxies for the Compact encoding, preview-fitted look, and raw-source versions. /// Every file photo can need an encoding refresh. Vendor raws and DNGs can need a look refresh, /// and photos developed from sensor data can need a raw-source refresh. A worker checks the @@ -997,7 +1113,6 @@ pub(crate) fn refresh_stale_smart_previews(s: &mut Session) -> Option) { jobs.into_iter().filter(|job| job.path.needs_refresh(|path| !crate::smart::from_newer_build(path) && job.ages.stale(path))).collect(); if !stale.is_empty() { // `custom`: the folder is there already, and must not be recreated if it went away since - match smart_run(dir, true, false, stale, None) { + match smart_run(dir, true, None, stale, None) { Ok(n) if !n.failed.is_empty() => { log::warn!("smart previews: look refresh needs attention: {:?}", n.failed); return; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 5d6583ebe23..ac95304da24 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -848,6 +848,11 @@ impl Session { } } // (a batch that was only partly taken back changed the catalog all the same: what hangs on its photos goes too) + #[cfg(not(target_arch = "wasm32"))] + let retention = self.preview_build.as_ref().filter(|b| b.running()).and_then(|b| b.discard_retention.as_ref()); + #[cfg(not(target_arch = "wasm32"))] + let mut discard = + retention.filter(|_| !invalidated.is_empty()).map(|r| r.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); let applied = apply(&mut self.catalog, op); if applied.is_err() && !matches!(applied, Err(CatalogError::PartlyApplied { .. })) { return applied.map_err(Into::into); @@ -859,6 +864,10 @@ impl Session { self.reload_tickets.invalidate(id); } for id in invalidated { + #[cfg(not(target_arch = "wasm32"))] + if let Some(retention) = &mut discard { + retention.update(id, self.catalog.photo(id).map(|p| &**p)); + } if invalidate_reads { self.reload_tickets.invalidate(id); } diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index a742a32b796..03e28f6c7eb 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -639,6 +639,10 @@ impl Session { // never edited this session would look unchanged and show the old library's numbers. static LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); catalog.revision = LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1) << 32; + #[cfg(not(target_arch = "wasm32"))] + if let Some(discard) = self.preview_build.as_ref().filter(|b| b.discard_retention.is_some()) { + discard.cancel.store(true, std::sync::atomic::Ordering::Relaxed); + } self.catalog = catalog; // nor do tasks waiting in line carry over: they name the old library's photos and folders let dropped = self.activity.library_changed(); diff --git a/crates/engine/src/media/quick.rs b/crates/engine/src/media/quick.rs index 525b605065b..5359ec461a9 100644 --- a/crates/engine/src/media/quick.rs +++ b/crates/engine/src/media/quick.rs @@ -157,6 +157,9 @@ pub fn source_identity(p: &Photo) -> Hash128 { if decoder != 0 { k.str("decoder").u64(decoder); } + if let Some(raw) = crate::smart::raw_interpretation(p) { + k.str("raw-interpretation").u64(u64::from(raw)); + } let metadata = source_metadata_key(p); if metadata != 0 { k.u64(metadata); diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index bb9510ee138..78691cc6e2d 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -23,7 +23,7 @@ pub use availability::Availability; const MAGIC: &[u8] = b"LCSP1\n"; /// Raw proxies retain their sensor/preview interpretation; rendered-image identities stay unchanged. -fn raw_interpretation(p: &Photo) -> Option { +pub(crate) fn raw_interpretation(p: &Photo) -> Option { // Keep the existing ORF proxy policy until the shared-decoder migration. (p.kind == lightcraft_catalog::MediaKind::Raw && !p.format.eq_ignore_ascii_case("ORF")).then(|| p.develops_raw()) } diff --git a/crates/engine/src/smart/tests.rs b/crates/engine/src/smart/tests.rs index 5de6308fbaa..ebdc0eba747 100644 --- a/crates/engine/src/smart/tests.rs +++ b/crates/engine/src/smart/tests.rs @@ -472,7 +472,11 @@ fn raw_proxy_names_distinguish_sensor_and_preview_pixels() { let mut preview = sensor.clone(); preview.preview_only = Some("old decoder".into()); assert_eq!(crate::media::content_key(&sensor), crate::media::content_key(&preview)); - assert_ne!(file_name(&sensor), file_name(&preview), "{format}: the two interpretations must never overwrite each other"); + if format == "ORF" { + assert_eq!(file_name(&sensor), file_name(&preview), "ORF retains the legacy key until the decoder migration"); + } else { + assert_ne!(file_name(&sensor), file_name(&preview), "{format}: the two interpretations must never overwrite each other"); + } } } @@ -481,7 +485,7 @@ fn legacy_raw_proxies_require_matching_recorded_interpretation() { use lightcraft_catalog::{PhotoId, Source}; for expected in [false, true] { for recorded in [None, Some(false), Some(true)] { - let dir = temp(&format!("raw-legacy-{expected}-{recorded:?}")); + let dir = crate::tests::TestDir::new(&format!("raw-legacy-{expected}-{recorded:?}")); let mut photo = Photo::new(PhotoId(1), Source::File { path: dir.join("offline.dng").to_string_lossy().into() }, "offline.dng", "DNG", 8, 8, ""); photo.kind = lightcraft_catalog::MediaKind::Raw; @@ -493,11 +497,10 @@ fn legacy_raw_proxies_require_matching_recorded_interpretation() { std::fs::write(&old, &bytes).unwrap(); assert!(file_path(&dir, &photo).exists(), "retention still sees the legacy file"); let mut media = crate::media::MediaCache::default(); - media.smart_dir = Some(dir.clone()); + media.smart_dir = Some(dir.to_path_buf()); let source = media.source_ref(&photo, crate::media::SourceLevel::Preview).load_source(); assert_eq!(source.is_ok(), recorded == Some(expected), "expected={expected}, recorded={recorded:?}"); assert_eq!(std::fs::read(&old).unwrap(), bytes, "incompatible legacy data stays on disk"); - std::fs::remove_dir_all(dir).unwrap(); } } } @@ -505,7 +508,7 @@ fn legacy_raw_proxies_require_matching_recorded_interpretation() { #[test] fn ordinary_jpeg_legacy_proxy_without_facts_remains_usable() { use lightcraft_catalog::{PhotoId, Source}; - let dir = temp("jpeg-legacy-no-facts"); + let dir = crate::tests::TestDir::new("jpeg-legacy-no-facts"); let photo = Photo::new(PhotoId(1), Source::File { path: dir.join("offline.jpg").to_string_lossy().into() }, "offline.jpg", "JPEG", 8, 8, ""); let hash = lightcraft_preview::Hasher128::new().str(&crate::media::content_key(&photo)).finish(); let old = dir.join(format!("{:032x}.lcsp", hash.0)); @@ -514,11 +517,10 @@ fn ordinary_jpeg_legacy_proxy_without_facts_remains_usable() { assert_eq!(file_name(&photo), old.file_name().unwrap().to_string_lossy()); assert_eq!(file_path(&dir, &photo), old); let mut media = crate::media::MediaCache::default(); - media.smart_dir = Some(dir.clone()); + media.smart_dir = Some(dir.to_path_buf()); let source = media.source_ref(&photo, crate::media::SourceLevel::Preview).load_source().unwrap(); assert!(source.from_proxy); assert!(source.info.is_none()); - std::fs::remove_dir_all(dir).unwrap(); } #[test] @@ -556,7 +558,7 @@ fn a_scan_cannot_clear_pending_behind_a_newer_marker_for_another_database() { #[test] fn a_hostile_facts_length_cannot_establish_raw_compatibility() { use lightcraft_catalog::{MediaKind, PhotoId, Source}; - let dir = temp("facts-length"); + let dir = crate::tests::TestDir::new("facts-length"); let mut photo = Photo::new(PhotoId(1), Source::File { path: dir.join("missing.dng").to_string_lossy().into() }, "missing.dng", "DNG", 8, 8, ""); photo.kind = MediaKind::Raw; let path = sharded_file_path(&dir, &photo); @@ -570,7 +572,6 @@ fn a_hostile_facts_length_cannot_establish_raw_compatibility() { assert!(is_valid(&path), "the JPEG framing remains complete"); assert!(decode(&bytes).is_err()); assert!(PreviewPath::new(&dir, &photo).load_with_path().is_err()); - std::fs::remove_dir_all(dir).unwrap(); } #[test] diff --git a/crates/engine/src/tests/smart_interpretation.rs b/crates/engine/src/tests/smart_interpretation.rs index e02716dd762..10c08b079b6 100644 --- a/crates/engine/src/tests/smart_interpretation.rs +++ b/crates/engine/src/tests/smart_interpretation.rs @@ -145,6 +145,35 @@ fn stale_interpretation_mismatch_does_not_complete_the_refresh() { assert!(progress["error"].as_str().unwrap().contains("Reload"), "{progress}"); } +#[test] +fn a_newer_incompatible_proxy_at_the_write_destination_is_preserved() { + let mut x = Lib::new("newer-incompatible", true); + let path = crate::smart::sharded_file_path(&x.smart_dir(), &x.photo()); + let mut bytes = write_proxy(&path, Some(&SourceInfo { raw: false, ..Default::default() }), false); + let (start, end, mut h) = header(&bytes); + h["source_version"] = json!(crate::smart::SOURCE_VERSION + 1); + bytes.splice(start..end, h.to_string().bytes()); + std::fs::write(&path, &bytes).unwrap(); + assert!(crate::smart::from_newer_build(&path)); + let report = x.build(); + assert_eq!(report["built"], 0); + assert_eq!(report["newerKept"], 1); + assert_eq!(std::fs::read(&path).unwrap(), bytes); +} + +#[test] +fn an_offline_render_from_the_old_interpretation_does_not_reenter_the_cache() { + let mut x = Lib::new("stale-render", false); + let path = crate::smart::sharded_file_path(&x.smart_dir(), &x.photo()); + write_proxy(&path, Some(&SourceInfo { raw: false, ..Default::default() }), false); + std::fs::remove_file(&x.file).unwrap(); + let old = x.s.render_job(x.id, 48, 32, false, true).unwrap().run(); + assert!(old.loaded.as_ref().is_some_and(|s| s.from_proxy)); + x.set_preview(false, true); + x.s.accept(&old); + assert!(!x.s.media.has_source(x.id, old.level)); +} + #[test] fn undo_during_a_build_cannot_overwrite_another_interpretation() { let mut x = Lib::new("undo-worker", false); @@ -379,6 +408,27 @@ fn discard_preserves_every_unselected_consumer() { } } +#[test] +fn discard_reports_unremovable_candidates_even_when_it_removes_another() { + let mut x = Lib::new("discard-broken", true); + let photo = x.photo(); + let dir = x.smart_dir(); + let path = crate::smart::sharded_file_path(&dir, &photo); + write_proxy(&path, Some(&SourceInfo { raw: true, ..Default::default() }), false); + let blocked = old_path(&dir, &photo, true); + std::fs::create_dir(&blocked).unwrap(); + let options = json!({"id": x.id.0, "discard": true}); + let r = x.s.execute("library.smartPreviews", &options).unwrap(); + assert_eq!(r["removed"], 1); + assert!(r["failed"][0][1].as_str().unwrap().contains(blocked.to_string_lossy().as_ref())); + assert!(!path.exists()); + x.s.execute("library.smartPreviews", &json!({"id": x.id.0, "discard": true, "background": true})).unwrap(); + wait_build(&x.s); + let progress = x.s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!(progress["failed"], 1); + assert!(progress["error"].as_str().unwrap().contains(blocked.to_string_lossy().as_ref())); +} + #[test] fn proxy_operations_invalidate_fresh_background_availability() { for background in [false, true] { From 8602edefc2a633edfffac19c30587d30bfbb01cb Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 18:51:52 +0100 Subject: [PATCH 36/42] Report unreadable newer Smart Previews in background results --- crates/engine/src/cmd/previews.rs | 4 +++- crates/engine/src/tests/smart_interpretation.rs | 5 +++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 75c2a934c5f..cad94be97e5 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -878,7 +878,9 @@ fn smart_run( if valid { n.built += 1; } else if let Some((st, _)) = state { - st.skipped.fetch_add(1, Ordering::Relaxed); + st.failed.fetch_add(1, Ordering::Relaxed); + *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = + Some(format!("Kept the newer smart preview at {}. This build cannot read it.", path.display())); } } else if valid && !stale { n.built += 1; diff --git a/crates/engine/src/tests/smart_interpretation.rs b/crates/engine/src/tests/smart_interpretation.rs index 10c08b079b6..f9c8b812805 100644 --- a/crates/engine/src/tests/smart_interpretation.rs +++ b/crates/engine/src/tests/smart_interpretation.rs @@ -158,6 +158,11 @@ fn a_newer_incompatible_proxy_at_the_write_destination_is_preserved() { let report = x.build(); assert_eq!(report["built"], 0); assert_eq!(report["newerKept"], 1); + x.s.execute("library.smartPreviews", &json!({"id": x.id.0, "background": true})).unwrap(); + wait_build(&x.s); + let progress = x.s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!(progress["failed"], 1); + assert!(progress["error"].as_str().unwrap().contains("Kept the newer smart preview")); assert_eq!(std::fs::read(&path).unwrap(), bytes); } From ba34c18993d6c8f0e036e1ab4a20cbd11c56eab4 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:13:55 +0100 Subject: [PATCH 37/42] Format Smart Preview retention guard --- crates/engine/src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ac95304da24..df79f9eb327 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -851,8 +851,7 @@ impl Session { #[cfg(not(target_arch = "wasm32"))] let retention = self.preview_build.as_ref().filter(|b| b.running()).and_then(|b| b.discard_retention.as_ref()); #[cfg(not(target_arch = "wasm32"))] - let mut discard = - retention.filter(|_| !invalidated.is_empty()).map(|r| r.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + let mut discard = retention.filter(|_| !invalidated.is_empty()).map(|r| r.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); let applied = apply(&mut self.catalog, op); if applied.is_err() && !matches!(applied, Err(CatalogError::PartlyApplied { .. })) { return applied.map_err(Into::into); From 33198d1619c93b5d0792db4e21a1c46c7841f9db Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 19:19:31 +0100 Subject: [PATCH 38/42] Smart Previews: report unreadable proxies and synchronize discard cancellation --- crates/engine/src/cmd/previews.rs | 32 +++++++++---------- crates/engine/src/library.rs | 6 +++- .../engine/src/tests/smart_interpretation.rs | 3 ++ 3 files changed, 23 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index cad94be97e5..e0f0da62064 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -790,6 +790,17 @@ struct SmartCounts { failed: Vec, } +#[cfg(not(target_arch = "wasm32"))] +impl SmartCounts { + fn fail(&mut self, id: lightcraft_catalog::PhotoId, why: String, state: Option<(&PreviewBuild, &TaskGuard)>) { + if let Some((st, _)) = state { + st.failed.fetch_add(1, Ordering::Relaxed); + *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(why.clone()); + } + self.failed.push(json!([id.0, why])); + } +} + /// `source` if it reads the photo's original, else `None`. A source decoded from a smart preview /// (it now carries the proxy's stored facts), a proxy standing in for an offline original, and the /// proxy fallback of a file source are not the original: building or repairing a proxy from one @@ -853,12 +864,7 @@ fn smart_run( } } if !errors.is_empty() { - let why = errors.join("\n"); - if let Some((st, _)) = state { - st.failed.fetch_add(1, Ordering::Relaxed); - *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(why.clone()); - } - n.failed.push(json!([id.0, why])); + n.fail(id, errors.join("\n"), state); } } else { let reusable = path.load_with_path().ok().map(|(path, _)| path); @@ -877,10 +883,8 @@ fn smart_run( n.newer_kept += 1; if valid { n.built += 1; - } else if let Some((st, _)) = state { - st.failed.fetch_add(1, Ordering::Relaxed); - *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = - Some(format!("Kept the newer smart preview at {}. This build cannot read it.", path.display())); + } else { + n.fail(id, format!("Kept the newer smart preview at {}. This build cannot read it.", path.display()), state); } } else if valid && !stale { n.built += 1; @@ -946,13 +950,7 @@ fn smart_run( n.built += 1; n.stale_kept += 1; } - Err(e) => { - if let Some((st, _)) = state { - st.failed.fetch_add(1, Ordering::Relaxed); - *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e.clone()); - } - n.failed.push(json!([id.0, e])); - } + Err(e) => n.fail(id, e, state), } } } diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 03e28f6c7eb..48eaa82c022 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -640,7 +640,11 @@ impl Session { static LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); catalog.revision = LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1) << 32; #[cfg(not(target_arch = "wasm32"))] - if let Some(discard) = self.preview_build.as_ref().filter(|b| b.discard_retention.is_some()) { + if let Some(discard) = &self.preview_build + && let Some(retention) = &discard.discard_retention + { + // Serialize cancellation with the worker's check and unlink before switching catalogs. + let _guard = retention.lock().unwrap_or_else(std::sync::PoisonError::into_inner); discard.cancel.store(true, std::sync::atomic::Ordering::Relaxed); } self.catalog = catalog; diff --git a/crates/engine/src/tests/smart_interpretation.rs b/crates/engine/src/tests/smart_interpretation.rs index f9c8b812805..2f4cfafa3fb 100644 --- a/crates/engine/src/tests/smart_interpretation.rs +++ b/crates/engine/src/tests/smart_interpretation.rs @@ -158,6 +158,9 @@ fn a_newer_incompatible_proxy_at_the_write_destination_is_preserved() { let report = x.build(); assert_eq!(report["built"], 0); assert_eq!(report["newerKept"], 1); + assert!(report["failed"][0][1].as_str().unwrap().contains("Kept the newer smart preview")); + assert!(crate::cmd::previews::refresh_stale_smart_previews(&mut x.s).unwrap().join().is_ok()); + assert!(!crate::smart::look_checked(&x.smart_dir()), "an unreadable proxy leaves the refresh pending"); x.s.execute("library.smartPreviews", &json!({"id": x.id.0, "background": true})).unwrap(); wait_build(&x.s); let progress = x.s.execute("library.previewProgress", &json!({})).unwrap(); From 1014bcd6a22dde79ad646767491029cbbdc723a1 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 26 Nov 2026 20:22:04 +0100 Subject: [PATCH 39/42] Compile Smart Preview rebuild helpers only where used --- crates/engine/src/smart.rs | 2 ++ crates/engine/src/smart/availability.rs | 1 + 2 files changed, 3 insertions(+) diff --git a/crates/engine/src/smart.rs b/crates/engine/src/smart.rs index 78691cc6e2d..9defaab8034 100644 --- a/crates/engine/src/smart.rs +++ b/crates/engine/src/smart.rs @@ -78,6 +78,7 @@ impl PreviewPath { } /// Rebuilds write only their captured interpretation; older identities remain read-only. + #[cfg(any(test, not(target_arch = "wasm32")))] pub(crate) fn write_path(&self) -> &Path { &self.current } @@ -92,6 +93,7 @@ impl PreviewPath { } /// Existing but incompatible/damaged proxies must not make the opening refresh look complete. + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn needs_refresh(&self, is_stale: impl FnOnce(&Path) -> bool) -> bool { self.candidates().iter().any(|path| path.exists()) && self.load_with_path().map_or(true, |(path, _)| is_stale(&path)) } diff --git a/crates/engine/src/smart/availability.rs b/crates/engine/src/smart/availability.rs index 6bd67f79b9d..02669202477 100644 --- a/crates/engine/src/smart/availability.rs +++ b/crates/engine/src/smart/availability.rs @@ -40,6 +40,7 @@ impl Availability { } /// Writes and explicit discards invalidate every interpretation, including in-flight probes. + #[cfg(any(test, not(target_arch = "wasm32")))] pub(crate) fn invalidate(&self, paths: &[std::path::PathBuf]) { for path in paths { let path = path.to_string_lossy(); From 61a5c5792143bc4e48faba9dfa2e8833df37c6d3 Mon Sep 17 00:00:00 2001 From: pancake Date: Sat, 28 Nov 2026 00:45:09 +0100 Subject: [PATCH 40/42] Smart Previews: exercise lens provenance with compatible proxy jobs --- crates/engine/src/cmd/previews.rs | 89 ++++++++++++++++++------------- 1 file changed, 52 insertions(+), 37 deletions(-) diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index e0f0da62064..d54009cbf27 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -1417,9 +1417,11 @@ mod tests { #[cfg(all(test, not(target_arch = "wasm32")))] mod smart_provenance_tests { - use super::{Ages, smart_run}; + use super::{Ages, SmartJob, smart_run}; use crate::media::{SourceLevel, SourceRef}; + use crate::smart::PreviewPath; use lightcraft_catalog::{MediaKind, Photo, PhotoId, Source}; + use std::path::Path; use std::sync::Arc; fn temp(tag: &str) -> std::io::Result { @@ -1429,6 +1431,15 @@ mod smart_provenance_tests { Ok(dir) } + fn rendered_photo(dir: &Path, id: u64, name: &str) -> Photo { + let source = Source::File { path: dir.join(name).to_string_lossy().into_owned() }; + Photo::new(PhotoId(id), source, name, "JPEG", 32, 24, "") + } + + fn job(dir: &Path, photo: &Photo, source: SourceRef, ages: Ages) -> SmartJob { + SmartJob { id: photo.id, path: PreviewPath::new(dir, photo), source: Some(source), ages, availability: Default::default() } + } + #[test] fn damaged_shard_never_relabels_cached_legacy_fallback_and_repairs_from_online_original() { let dir = temp("legacy-fallback").unwrap(); @@ -1447,7 +1458,8 @@ mod smart_provenance_tests { std::fs::create_dir_all(shard.parent().unwrap()).unwrap(); let mut image = lightcraft_raster::Rgb32f::new(48, 32); image.data.fill([0.25, 0.3, 0.2]); - let bytes = crate::smart::encode(&image, None).unwrap(); + let facts = lightcraft_pipeline::SourceInfo { raw: true, ..Default::default() }; + let bytes = crate::smart::encode(&image, Some(&facts)).unwrap(); let start = b"LCSP1\n".len(); let nl = start + bytes[start..].iter().position(|b| *b == b'\n').unwrap(); let mut head: serde_json::Value = serde_json::from_slice(&bytes[start..nl]).unwrap(); @@ -1467,18 +1479,18 @@ mod smart_provenance_tests { let cached_missing = shard.to_string_lossy().into_owned(); session.media.availability.set_probe(Arc::new(move |path| path != cached_missing)); let source = session.media.source_ref(&photo, SourceLevel::Preview); - assert!(matches!(&source, SourceRef::File { fallback: Some(p), .. } if p == &legacy)); + assert!(matches!(&source, SourceRef::File { fallback: Some(p), .. } if p.candidates().contains(&legacy))); assert!(source.load_source().unwrap().from_proxy, "the renderer can still use the offline fallback"); - let counts = smart_run(&dir, false, false, vec![(photo.id, shard.clone(), Some(source), Ages::of(&photo))], None).unwrap(); - assert_eq!((counts.built, counts.repaired, counts.refreshed, counts.stale_kept, counts.failed.len()), (0, 0, 0, 0, 1)); + let counts = smart_run(&dir, false, None, vec![job(&dir, &photo, source, Ages::of(&photo))], None).unwrap(); + assert_eq!((counts.built, counts.repaired, counts.refreshed, counts.stale_kept, counts.failed.len()), (1, 0, 0, 1, 0)); assert_eq!(std::fs::read(&shard).unwrap(), b"broken", "a failed repair leaves its destination untouched"); assert_eq!(std::fs::read(&legacy).unwrap(), old); assert!(crate::smart::load(&legacy).unwrap().from_proxy); - session.media.file_loader = Some(Arc::new(move |_, _, _| Ok((image.clone(), Default::default())))); + session.media.file_loader = Some(Arc::new(move |_, _, _| Ok((image.clone(), facts.clone())))); let source = session.media.source_ref(&photo, SourceLevel::Preview); - let counts = smart_run(&dir, false, false, vec![(photo.id, shard.clone(), Some(source), Ages::of(&photo))], None).unwrap(); - assert_eq!((counts.built, counts.repaired, counts.refreshed, counts.failed.len()), (1, 1, 0, 0)); + let counts = smart_run(&dir, false, None, vec![job(&dir, &photo, source, Ages::of(&photo))], None).unwrap(); + assert_eq!((counts.built, counts.repaired, counts.refreshed, counts.failed.len()), (1, 0, 1, 0)); assert!(crate::smart::is_valid(&shard)); assert!(!crate::smart::is_stale_for(&shard, true)); assert_eq!(std::fs::read(&legacy).unwrap(), old, "repair does not overwrite the valid legacy copy"); @@ -1488,7 +1500,9 @@ mod smart_provenance_tests { #[test] fn missing_target_never_encodes_proxy_sources_but_keeps_valid_offline_proxies() { let dir = temp("missing-target").unwrap(); - let legacy = dir.join("legacy.lcsp"); + let cached = rendered_photo(&dir, 1, "cached.jpg"); + let cached_path = PreviewPath::new(&dir, &cached); + let legacy = dir.join(crate::smart::file_name(&cached)); let image = lightcraft_raster::Rgb32f::new(48, 32); let bytes = crate::smart::encode(&image, Some(&Default::default())).unwrap(); std::fs::write(&legacy, &bytes).unwrap(); @@ -1500,18 +1514,18 @@ mod smart_provenance_tests { SourceRef::Loaded(Box::new(reduced)), SourceRef::Loaded(Box::new(loaded.clone())), SourceRef::Fit { from: Box::new(loaded), max_edge: 24 }, - SourceRef::Smart { path: legacy.clone() }, + SourceRef::Smart { path: cached_path.clone() }, ]; + let ages = Ages { look: true, source: true }; for (i, source) in sources.into_iter().enumerate() { - let target = dir.join(format!("missing-{i}.lcsp")); - let counts = - smart_run(&dir, false, false, vec![(PhotoId(1), target.clone(), Some(source), Ages { look: true, source: true })], None).unwrap(); + let photo = rendered_photo(&dir, 2, &format!("missing-{i}.jpg")); + let target = crate::smart::sharded_file_path(&dir, &photo); + let counts = smart_run(&dir, false, None, vec![job(&dir, &photo, source, ages)], None).unwrap(); assert_eq!((counts.built, counts.repaired, counts.failed.len()), (0, 0, 1)); assert!(!target.exists()); } - let source = SourceRef::Smart { path: legacy.clone() }; - let counts = - smart_run(&dir, false, false, vec![(PhotoId(1), legacy.clone(), Some(source), Ages { look: true, source: true })], None).unwrap(); + let source = SourceRef::Smart { path: cached_path }; + let counts = smart_run(&dir, false, None, vec![job(&dir, &cached, source, ages)], None).unwrap(); assert_eq!((counts.built, counts.repaired, counts.failed.len()), (1, 0, 0)); assert_eq!(std::fs::read(&legacy).unwrap(), bytes); let _ = std::fs::remove_dir_all(&dir); @@ -1660,13 +1674,16 @@ mod smart_provenance_tests { let database = dir.join("lens.xml"); let image = lightcraft_raster::Rgb32f::new(32, 24); let old = crate::smart::encode_with_lens_key(&image, None, 0).unwrap(); + let photo = rendered_photo(&dir, 1, "original.jpg"); + let target = crate::smart::sharded_file_path(&dir, &photo); + std::fs::create_dir_all(target.parent().unwrap()).unwrap(); + let ages = Ages { look: true, source: true }; for replace in [false, true] { for existing in [None, Some(b"broken".to_vec()), Some(old.clone())] { std::fs::write(&database, DB).unwrap(); crate::lens_profiles::reload(); let before = crate::lens_profiles::cache_key(); assert_ne!(before, 0); - let target = dir.join("target.lcsp"); if let Some(bytes) = &existing { std::fs::write(&target, bytes).unwrap(); } else { @@ -1684,10 +1701,8 @@ mod smart_provenance_tests { } Ok((pixels.clone(), Default::default())) })); - let origin = Source::File { path: dir.join("original.arw").to_string_lossy().into_owned() }; - let source = session.media.origin_ref(&origin, SourceLevel::Preview.max_edge()); - let counts = - smart_run(&dir, false, false, vec![(PhotoId(1), target.clone(), Some(source), Ages { look: true, source: true })], None).unwrap(); + let source = session.media.origin_ref_of(&photo, SourceLevel::Preview.max_edge()); + let counts = smart_run(&dir, false, None, vec![job(&dir, &photo, source, ages)], None).unwrap(); assert_ne!(crate::lens_profiles::cache_key(), before); if let Some(bytes) = &existing { assert_eq!(std::fs::read(&target).unwrap(), *bytes, "a reload never replaces the previous destination"); @@ -1705,16 +1720,16 @@ mod smart_provenance_tests { std::fs::write(&database, DB).unwrap(); crate::lens_profiles::reload(); std::fs::write(&target, &old).unwrap(); - let source = session.media.origin_ref(&origin, SourceLevel::Preview.max_edge()); - super::refresh_stale(&dir, vec![(PhotoId(1), target.clone(), Some(source), Ages { look: true, source: true })]); + let source = session.media.origin_ref_of(&photo, SourceLevel::Preview.max_edge()); + super::refresh_stale(&dir, vec![job(&dir, &photo, source, ages)]); assert_eq!(std::fs::read(&target).unwrap(), old); assert!(!crate::smart::look_checked(&dir)); // A subsequent stable decode writes B's identity and can complete the scan. let pixels = image.clone(); session.media.file_loader = Some(Arc::new(move |_, _, _| Ok((pixels.clone(), Default::default())))); - let source = session.media.origin_ref(&origin, SourceLevel::Preview.max_edge()); - super::refresh_stale(&dir, vec![(PhotoId(1), target.clone(), Some(source), Ages { look: true, source: true })]); + let source = session.media.origin_ref_of(&photo, SourceLevel::Preview.max_edge()); + super::refresh_stale(&dir, vec![job(&dir, &photo, source, ages)]); assert!(!crate::smart::is_stale_for(&target, true)); assert!(crate::smart::look_checked(&dir)); // Reset the marker before the next race attempt. @@ -1727,11 +1742,15 @@ mod smart_provenance_tests { crate::lens_profiles::reload(); let key_a = crate::lens_profiles::cache_key(); crate::smart::mark_look_checked_with_lens_key(&dir, key_a).unwrap(); - let (first, second) = (dir.join("first.lcsp"), dir.join("second.lcsp")); + let first_photo = rendered_photo(&dir, 1, "first.jpg"); + let second_photo = rendered_photo(&dir, 2, "second.jpg"); + let first = crate::smart::sharded_file_path(&dir, &first_photo); + let second = crate::smart::sharded_file_path(&dir, &second_photo); let older = crate::smart::encode_with_lens_key(&image, None, 0).unwrap(); - std::fs::write(&first, &older).unwrap(); - std::fs::write(&second, &older).unwrap(); - let src = |session: &mut crate::Session| session.media.origin_ref(&Source::File { path: "test.arw".into() }, SourceLevel::Preview.max_edge()); + for path in [&first, &second] { + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, &older).unwrap(); + } let (db_path, pixels) = (database.clone(), image.clone()); let mut session = crate::Session::new(); session.media.file_loader = Some(Arc::new(move |_, _, _| { @@ -1739,14 +1758,10 @@ mod smart_provenance_tests { crate::lens_profiles::reload(); Ok((pixels.clone(), Default::default())) })); - let first_source = src(&mut session); + let first_source = session.media.origin_ref_of(&first_photo, SourceLevel::Preview.max_edge()); session.media.file_loader = Some(Arc::new(move |_, _, _| Ok((image.clone(), Default::default())))); - let second_source = src(&mut session); - let ages = Ages { look: true, source: true }; - super::refresh_stale( - &dir, - vec![(PhotoId(1), first.clone(), Some(first_source), ages), (PhotoId(2), second.clone(), Some(second_source.clone()), ages)], - ); + let second_source = session.media.origin_ref_of(&second_photo, SourceLevel::Preview.max_edge()); + super::refresh_stale(&dir, vec![job(&dir, &first_photo, first_source, ages), job(&dir, &second_photo, second_source.clone(), ages)]); assert_eq!(std::fs::read(&first).unwrap(), older, "a reload during decode preserves the first proxy"); assert_ne!(crate::lens_profiles::cache_key(), key_a); assert!(!crate::smart::is_stale_for(&second, true), "the next original was decoded with the new database"); @@ -1756,7 +1771,7 @@ mod smart_provenance_tests { assert_eq!(crate::lens_profiles::cache_key(), key_a); assert!(crate::smart::is_stale_for(&second, true)); assert!(!crate::smart::look_checked(&dir), "the aborted scan must invalidate A's old folder marker"); - super::refresh_stale(&dir, vec![(PhotoId(2), second.clone(), Some(second_source), ages)]); + super::refresh_stale(&dir, vec![job(&dir, &second_photo, second_source, ages)]); assert!(!crate::smart::is_stale_for(&second, true)); assert!(crate::smart::look_checked(&dir), "a stable scan makes the folder current again"); } From b0016147d551ea29c5fa50aaca98fc2db9c856e4 Mon Sep 17 00:00:00 2001 From: pancake Date: Sat, 28 Nov 2026 00:48:42 +0100 Subject: [PATCH 41/42] Smart Previews: verify raw facts from the fresh original --- crates/engine/src/media.rs | 2 +- crates/engine/src/tests/smart_interpretation.rs | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/media.rs b/crates/engine/src/media.rs index 389ffbf7df6..2b04ded2371 100644 --- a/crates/engine/src/media.rs +++ b/crates/engine/src/media.rs @@ -38,7 +38,7 @@ pub use cache::DenoiseIndex; #[cfg(test)] pub(crate) use cache::rendered_budget; pub(crate) use quick::decoder_key; - pub use quick::{QuickJob, QuickSource, content_key, lens_key, source_info}; +pub use quick::{QuickJob, QuickSource, content_key, lens_key, source_info}; pub use render::{RenderJob, RenderResult, ScreenFrame, develop, develop_reporting, fit_cached, fit_for_display}; #[cfg(test)] use settings_hash::SETTINGS_HASH_ENTRIES; diff --git a/crates/engine/src/tests/smart_interpretation.rs b/crates/engine/src/tests/smart_interpretation.rs index 2f4cfafa3fb..6b720a49131 100644 --- a/crates/engine/src/tests/smart_interpretation.rs +++ b/crates/engine/src/tests/smart_interpretation.rs @@ -111,13 +111,20 @@ fn wait_build(s: &Session) { } #[test] -fn raw_smart_build_requires_source_facts() { +fn raw_smart_build_requires_facts_from_the_fresh_original() { let mut x = Lib::new("missing-facts", true); + let original = x.s.media.file_loader.clone().unwrap(); x.s.media.insert(x.id, SourceLevel::Preview, Arc::new(Rgb32f::filled(48, 32, [0.7; 3]))); + x.s.media.file_loader = Some(Arc::new(|_, _, _| Ok((Rgb32f::filled(48, 32, [0.7; 3]), SourceInfo::default())))); let r = x.build(); - assert_eq!(r["built"], 0, "unknown pixels must not be labelled sensor-derived: {r}"); + assert_eq!(r["built"], 0, "unverified original pixels must not be labelled sensor-derived: {r}"); assert!(r["failed"][0][1].as_str().unwrap().contains("Reload"), "{r}"); assert!(!x.status()); + + x.s.media.file_loader = Some(original); + let r = x.build(); + assert_eq!(r["built"], 1, "a verified fresh decode can build despite the unfactored cache: {r}"); + assert!(x.status()); } #[test] From a1333f3b2ed233c6d9edffa7320562bb012a1ed5 Mon Sep 17 00:00:00 2001 From: pancake Date: Thu, 3 Dec 2026 14:31:29 +0100 Subject: [PATCH 42/42] Keep Smart Preview retention atomic with catalog changes --- crates/engine/src/lib.rs | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index df79f9eb327..151055e7557 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -847,15 +847,25 @@ impl Session { _ => {} } } - // (a batch that was only partly taken back changed the catalog all the same: what hangs on its photos goes too) - #[cfg(not(target_arch = "wasm32"))] - let retention = self.preview_build.as_ref().filter(|b| b.running()).and_then(|b| b.discard_retention.as_ref()); - #[cfg(not(target_arch = "wasm32"))] - let mut discard = retention.filter(|_| !invalidated.is_empty()).map(|r| r.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); - let applied = apply(&mut self.catalog, op); - if applied.is_err() && !matches!(applied, Err(CatalogError::PartlyApplied { .. })) { - return applied.map_err(Into::into); - } + let applied = { + // Hold the discard lock through the catalog change and its retention updates. + #[cfg(not(target_arch = "wasm32"))] + let retention = self.preview_build.as_ref().filter(|b| b.running()).and_then(|b| b.discard_retention.as_ref()); + #[cfg(not(target_arch = "wasm32"))] + let discard = retention.filter(|_| !invalidated.is_empty()).map(|r| r.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + let applied = apply(&mut self.catalog, op); + // A partially applied batch changed the catalog, so refresh its retention and caches too. + if applied.is_err() && !matches!(applied, Err(CatalogError::PartlyApplied { .. })) { + return applied.map_err(Into::into); + } + #[cfg(not(target_arch = "wasm32"))] + if let Some(mut retention) = discard { + for &id in &invalidated { + retention.update(id, self.catalog.photo(id).map(|p| &**p)); + } + } + applied + }; for id in denoise_changed { self.denoise_photo_changed(id); } @@ -863,10 +873,6 @@ impl Session { self.reload_tickets.invalidate(id); } for id in invalidated { - #[cfg(not(target_arch = "wasm32"))] - if let Some(retention) = &mut discard { - retention.update(id, self.catalog.photo(id).map(|p| &**p)); - } if invalidate_reads { self.reload_tickets.invalidate(id); }