diff --git a/crates/engine/src/camera_preview/tests.rs b/crates/engine/src/camera_preview/tests.rs index 4abd411397..e83e3215da 100644 --- a/crates/engine/src/camera_preview/tests.rs +++ b/crates/engine/src/camera_preview/tests.rs @@ -1106,6 +1106,109 @@ fn external_profile_geometry_preserves_oriented_default_crop_and_resolution() { } } +#[test] +fn configured_lens_geometry_reaches_pool_add_after_raw_decode() { + const DB: &str = r#" + NikonUncalibratedT1.5 + SyntheticSynthetic 18mmT1.5 + + "#; + const CHILD: &str = "LIGHTCRAFT_TEST_POOL_DECODE_GEOMETRY_CHILD"; + if std::env::var_os(CHILD).is_none() { + let dir = std::env::temp_dir().join(format!("lightcraft-pool-decode-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("synthetic.xml"), DB).unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "camera_preview::tests::configured_lens_geometry_reaches_pool_add_after_raw_decode", "--nocapture"]) + .env(CHILD, "1") + .env(crate::lens_profiles::ENV, &dir) + .env("LIGHTCRAFT_CONFIG_DIR", &dir) + .env("LIGHTCRAFT_CAMERA_PROFILES", &dir) + .output() + .unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + + // A complete, bounded uncompressed NEF: production decode reads a real Bayer strip, + // EXIF lens identity and an embedded JPEG. No corpus or injected RawImage is involved. + use lightcraft_tiff::{IfdBuilder, ImageData, TiffWriter, Value, tags}; + let (w, h) = (768, 512); + let scene = profile_geometry_scene(w, h); + let samples: Vec = scene + .data + .iter() + .enumerate() + .flat_map(|(i, p)| { + let channel = match (i / w % 2, i % w % 2) { + (0, 0) => 0, + (1, 1) => 2, + _ => 1, + }; + ((p[channel] * 16383.0).round() as u16).to_le_bytes() + }) + .collect(); + let mut mosaic = IfdBuilder::new(); + mosaic.set(tags::NEW_SUBFILE_TYPE, Value::Long(vec![0])); + mosaic.set(tags::IMAGE_WIDTH, Value::Long(vec![w as u32])); + mosaic.set(tags::IMAGE_LENGTH, Value::Long(vec![h as u32])); + mosaic.set(tags::BITS_PER_SAMPLE, Value::Short(vec![14])); + mosaic.set(tags::SAMPLES_PER_PIXEL, Value::Short(vec![1])); + mosaic.set(tags::COMPRESSION, Value::Short(vec![1])); + mosaic.set(tags::PHOTOMETRIC, Value::Short(vec![32803])); + mosaic.set(tags::CFA_REPEAT_PATTERN_DIM, Value::Short(vec![2, 2])); + mosaic.set(tags::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 1, 2])); + mosaic.set_image(ImageData::Strips { rows_per_strip: h as u32, strips: vec![samples] }); + let mut ifd = IfdBuilder::new(); + ifd.set(tags::MAKE, Value::Ascii("Nikon".into())); + ifd.set(tags::MODEL, Value::Ascii("Uncalibrated".into())); + ifd.add_sub_ifd(mosaic); + let mut exif = IfdBuilder::new(); + exif.set(tags::FOCAL_LENGTH, Value::Rational(vec![(18, 1)])); + exif.set(tags::LENS_MODEL, Value::Ascii("Synthetic 18mm".into())); + ifd.set_child(tags::EXIF_IFD, exif); + let shell = TiffWriter::default().write(&[ifd.clone()]).unwrap(); + let raw = lightcraft_raw::decode(&shell).expect("procedural NEF decodes through the production reader"); + assert_eq!(raw.format, RawFormat::Nef); + assert!(raw.opcodes.list3.is_empty()); + assert_eq!(raw.info().developed_size(), (w, h)); + let lens = crate::lens_profiles::for_raw(&raw.info(), || lightcraft_meta::extract(&shell)).expect("configured database resolves EXIF identity"); + let transform = lightcraft_raw::color::camera_transform(&raw, lightcraft_raw::color::as_shot_white_xy(&raw)); + assert!(transform.matrix_is_fallback); + let mut sensor = sensor_proxy(&raw, 2, 384).unwrap(); + sensor.map_in_place(|p| { + transform.matrix.apply_f32(std::array::from_fn(|i| p[i] * transform.wb[i] * 2f32.powf(transform.baseline_exposure as f32))) + }); + let mut target = profile_geometry_target(&sensor, &lens, Cr3Framing { scale: 0.95, offset: [0.006, -0.004] }); + target.map_in_place(|p| p.map(|v| v.powf(0.7))); + let to_srgb = lightcraft_color::SRGB.from_xyz().mul(&REC2020.to_xyz()); + let srgb = |v: f32| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }; + let pixels: Vec = target.data.iter().flat_map(|p| to_srgb.apply_f32(*p).map(|v| (srgb(v).clamp(0.0, 1.0) * 255.0).round() as u8)).collect(); + let image = lightcraft_codecs::EncodeImage::new(target.width as u32, target.height as u32, 3, lightcraft_codecs::Samples::U8(&pixels)); + let jpeg = lightcraft_codecs::encode_jpeg(&image, 98, lightcraft_codecs::ChromaSubsampling::S444, &Default::default()).unwrap(); + ifd.set(0x0201, Value::Long(vec![0])); + ifd.set(0x0202, Value::Long(vec![jpeg.len() as u32])); + let offset = TiffWriter::default().write(&[ifd.clone()]).unwrap().len(); + ifd.set(0x0201, Value::Long(vec![offset as u32])); + let mut file = TiffWriter::default().write(&[ifd]).unwrap(); + assert_eq!(file.len(), offset); + file.extend(jpeg); + let decoded = lightcraft_raw::decode(&file).unwrap(); + let corrected = profile_pairs(&decoded, &file, None, Some(&lens)).expect("corrected decoded NEF contributes colour pairs"); + let plain = profile_pairs(&decoded, &file, None, None).unwrap(); + assert_ne!(corrected, plain, "fixture distinguishes forwarding the resolved correction from dropping it"); + // Match the documented per-photo cap, then observe the result through Pool's public fit API. + let step = corrected.len().div_ceil(4000).max(1); + let expected: Vec<_> = corrected.into_iter().step_by(step).collect(); + let (matrix, hue_sat) = fit_profile(&expected).expect("synthetic scene spans enough colours for pooled calibration"); + let expected = crate::camera_profiles::CameraProfile::new("Uncalibrated", 1, expected.len(), matrix, hue_sat); + let mut pool = crate::camera_profiles::Pool::default(); + assert_eq!(pool.add(&file).unwrap(), Some("Uncalibrated".into())); + assert_eq!(pool.files(), vec![("Uncalibrated".into(), 1)]); + assert_eq!(pool.fit(1), vec![Ok(expected)], "Pool::add must forward the database correction after decoding the actual bytes"); +} + #[test] fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() { const DB: &str = r#" @@ -1124,6 +1227,8 @@ fn external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop() .args(["--exact", "camera_preview::tests::external_profile_geometry_reaches_file_and_pooled_pairs_in_the_default_crop", "--nocapture"]) .env(CHILD, "1") .env(crate::lens_profiles::ENV, &dir) + .env("LIGHTCRAFT_CONFIG_DIR", &dir) + .env("LIGHTCRAFT_CAMERA_PROFILES", &dir) .output() .unwrap(); std::fs::remove_dir_all(&dir).unwrap(); diff --git a/crates/engine/src/camera_profiles.rs b/crates/engine/src/camera_profiles.rs index 323a0e0c86..990b859d16 100644 --- a/crates/engine/src/camera_profiles.rs +++ b/crates/engine/src/camera_profiles.rs @@ -262,6 +262,39 @@ mod tests { CameraProfile::new("ILCE-7M4", 12, 3456, Mat3([[1.6, -0.5, -0.1], [-0.2, 1.3, -0.1], [-0.1, -0.2, 1.3]]), Some(table)) } + #[test] + fn public_cache_key_includes_the_configured_lens_database() { + const CHILD: &str = "LIGHTCRAFT_TEST_CAMERA_CACHE_KEY_CHILD"; + if std::env::var_os(CHILD).is_none() { + let dir = std::env::temp_dir().join(format!("lc-camera-key-wiring-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("lens.xml"), + r#"Test18mmT1.5 + "#, + ) + .unwrap(); + // Both OnceLocks and the configured camera-profile folder belong to the child only. + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "camera_profiles::tests::public_cache_key_includes_the_configured_lens_database", "--nocapture"]) + .env(CHILD, "1") + .env(crate::lens_profiles::ENV, &dir) + .env("LIGHTCRAFT_CONFIG_DIR", &dir) + .env("LIGHTCRAFT_CAMERA_PROFILES", &dir) + .output() + .unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + assert!(crate::lens_profiles::database().is_some(), "fixture database was loaded by the public loader"); + let lens_key = crate::lens_profiles::cache_key(); + assert_ne!(lens_key, 0); + let directory = dir(); + assert_eq!(cache_key(), cache_key_with_lens(directory.as_deref(), lens_key)); + assert_ne!(cache_key(), cache_key_with_lens(directory.as_deref(), 0), "public camera key must forward the loaded lens key"); + } + #[test] fn profiles_round_trip_and_reject_bad_files() { let dir = std::env::temp_dir().join(format!("lc-camera-profiles-{}", std::process::id())); diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index dc1f2c864a..a3be4dc255 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -354,8 +354,8 @@ struct SmartCounts { /// `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: refreshing a stale proxy from one of them -/// would stamp its older look as current. +/// proxy fallback of a file source are not the original: building or repairing a proxy from one +/// of them would stamp its older look as current. #[cfg(not(target_arch = "wasm32"))] fn original_only(source: crate::media::SourceRef) -> Option { use crate::media::SourceRef; @@ -364,6 +364,7 @@ fn original_only(source: crate::media::SourceRef) -> Option Some(SourceRef::Loaded(d)), + source @ SourceRef::Demo { .. } => Some(source), _ => None, } } @@ -410,9 +411,9 @@ fn smart_run( if damaged && !stale && crate::smart::is_valid(&path) { n.built += 1; } else { - // a stale proxy is rebuilt from the original only: never from itself (the file - // fallback or a source decoded from a proxy would stamp the old look as current) - let source = if stale { source.and_then(original_only) } else { source }; + // Every encode stamps current identities, including repairs and missing targets. + // Never relabel pixels from a proxy, even when the destination has no readable header. + let source = source.and_then(original_only); // 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 @@ -420,6 +421,9 @@ fn smart_run( .ok_or_else(|| "nothing to build from".to_string()) .and_then(|s| s.load_source()) .and_then(|src| { + if src.from_proxy || src.reduced { + return Err("smart previews need the original source".to_string()); + } let info = src.info_or(Default::default()); crate::smart::encode(&src.image, Some(&info)) }) @@ -737,3 +741,104 @@ mod tests { assert_eq!(r["failed"], json!(0)); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod smart_provenance_tests { + use super::smart_run; + use crate::media::{SourceLevel, SourceRef}; + use lightcraft_catalog::{MediaKind, Photo, PhotoId, Source}; + use std::sync::Arc; + + fn temp(tag: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("lc-smart-provenance-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn damaged_shard_never_relabels_cached_legacy_fallback_and_repairs_from_online_original() { + let dir = temp("legacy-fallback"); + let mut photo = Photo::new( + PhotoId(1), + Source::File { path: dir.join("offline.arw").to_string_lossy().into_owned() }, + "offline.arw", + "ARW", + 48, + 32, + "2026-11-02T00:00:00", + ); + photo.kind = MediaKind::Raw; + let shard = crate::smart::sharded_file_path(&dir, &photo); + let legacy = dir.join(crate::smart::file_name(&photo)); + 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 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(); + head["lens_db"] = serde_json::json!(crate::lens_profiles::cache_key().wrapping_add(1)); + let mut old = bytes[..start].to_vec(); + old.extend_from_slice(head.to_string().as_bytes()); + old.extend_from_slice(&bytes[nl..]); + std::fs::write(&legacy, &old).unwrap(); + std::fs::write(&shard, b"broken").unwrap(); + assert!(crate::smart::is_stale_for(&legacy, true)); + assert!(!crate::smart::is_stale_for(&shard, true), "a damaged header is not stale"); + + let mut session = crate::Session::new(); + session.media.smart_dir = Some(dir.clone()); + session.media.file_loader = Some(Arc::new(|_, _| Err("original is offline".into()))); + // Reproduce the UI cache selecting legacy while the worker sees the damaged shard. + 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!(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), true)], None).unwrap(); + assert_eq!((counts.built, counts.repaired, counts.refreshed, counts.stale_kept, counts.failed.len()), (0, 0, 0, 0, 1)); + 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())))); + let source = session.media.source_ref(&photo, SourceLevel::Preview); + let counts = smart_run(&dir, false, false, vec![(photo.id, shard.clone(), Some(source), true)], None).unwrap(); + assert_eq!((counts.built, counts.repaired, counts.refreshed, counts.failed.len()), (1, 1, 0, 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"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn missing_target_never_encodes_proxy_sources_but_keeps_valid_offline_proxies() { + let dir = temp("missing-target"); + let legacy = dir.join("legacy.lcsp"); + let image = lightcraft_raster::Rgb32f::new(48, 32); + let bytes = crate::smart::encode(&image, Some(&Default::default())).unwrap(); + std::fs::write(&legacy, &bytes).unwrap(); + let loaded = crate::smart::load(&legacy).unwrap(); + assert!(loaded.info.is_some(), "stored facts do not confer original provenance"); + let mut reduced = crate::media::DecodedSource::new(Arc::new(image.clone()), Some(Default::default())); + reduced.reduced = true; + let sources = [ + 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() }, + ]; + 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), true)], 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), true)], 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); + } +} diff --git a/crates/engine/src/lens_profiles.rs b/crates/engine/src/lens_profiles.rs index ba4cdf62e6..052c256939 100644 --- a/crates/engine/src/lens_profiles.rs +++ b/crates/engine/src/lens_profiles.rs @@ -173,6 +173,31 @@ mod tests { "#; + #[test] + fn public_cache_key_hashes_the_configured_database() { + const CHILD: &str = "LIGHTCRAFT_TEST_LENS_CACHE_KEY_CHILD"; + if std::env::var_os(CHILD).is_none() { + let dir = std::env::temp_dir().join(format!("lc-lens-key-wiring-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("lens.xml"), DB).unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "lens_profiles::tests::public_cache_key_hashes_the_configured_database", "--nocapture"]) + .env(CHILD, "1") + .env(ENV, &dir) + .env("LIGHTCRAFT_CAMERA_PROFILES", &dir) + .env("LIGHTCRAFT_CONFIG_DIR", &dir) + .output() + .unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + let loaded = database().expect("fixture database was loaded by the public loader"); + assert_eq!(loaded, &LensDb::parse(DB).unwrap()); + assert_ne!(cache_key(), 0, "configured nonempty database cannot use the no-database identity"); + assert_eq!(cache_key(), cache_key_for(Some(loaded)), "public lens key hashes the actual loaded snapshot"); + } + #[test] fn database_identity_tracks_loaded_geometry_not_xml_formatting() { let db = LensDb::parse(DB).unwrap(); diff --git a/crates/engine/src/smart/tests.rs b/crates/engine/src/smart/tests.rs index 84d7920c14..10b318a109 100644 --- a/crates/engine/src/smart/tests.rs +++ b/crates/engine/src/smart/tests.rs @@ -382,11 +382,18 @@ fn smart_preview_from_another_database_stays_decodable_offline() { let bytes = encode(&image, None).unwrap(); let nl = MAGIC.len() + bytes[MAGIC.len()..].iter().position(|b| *b == b'\n').unwrap(); let mut head: serde_json::Value = serde_json::from_slice(&bytes[MAGIC.len()..nl]).unwrap(); - head[LENS_FIELD] = serde_json::json!(123); - assert!(header_is_stale(&head, true, 456)); + head[LENS_FIELD] = serde_json::json!(crate::lens_profiles::cache_key().wrapping_add(1)); let mut changed = MAGIC.to_vec(); changed.extend_from_slice(head.to_string().as_bytes()); changed.extend_from_slice(&bytes[nl..]); - let (decoded, _, _) = decode(&changed).unwrap(); - assert_eq!((decoded.width, decoded.height), (image.width, image.height)); + let dir = temp("lens-database-offline"); + let path = dir.join("old.lcsp"); + std::fs::write(&path, &changed).unwrap(); + assert!(is_stale_for(&path, true), "the public disk check compares the current lens identity"); + assert!(!is_stale_for(&path, false), "non-fitted photos do not depend on the lens database"); + assert!(is_valid(&path), "staleness does not invalidate the offline copy"); + let decoded = load(&path).unwrap(); + assert!(decoded.from_proxy); + assert_eq!((decoded.image.width, decoded.image.height), (image.width, image.height)); + let _ = std::fs::remove_dir_all(&dir); }