diff --git a/apps/lightcraft-web/src/files.rs b/apps/lightcraft-web/src/files.rs index d0c9f348b37..37e82c3b6ed 100644 --- a/apps/lightcraft-web/src/files.rs +++ b/apps/lightcraft-web/src/files.rs @@ -190,6 +190,10 @@ impl Store for FilesStore { self.0.truncate(name, len as usize); Ok(()) } + /// The browser always runs the newest build, and its storage is small. + fn keeps_replaced_formats(&self) -> bool { + false + } fn describe(&self) -> String { "browser storage".into() } diff --git a/crates/catalog/examples/persist_bench.rs b/crates/catalog/examples/persist_bench.rs index 693e862d097..7013ae2d8ef 100644 --- a/crates/catalog/examples/persist_bench.rs +++ b/crates/catalog/examples/persist_bench.rs @@ -1,13 +1,16 @@ -//! Catalog persistence costs on large synthetic catalogs (issue #37): log append, compaction -//! (snapshot serialise / write+fsync / log reset), synchronous and on the background worker, load, -//! and a catalog clone. +//! Catalog persistence costs on large synthetic catalogs (issue #37): an import that compacts as +//! the app does (how often, and how much it writes in all), log append, compaction (snapshot +//! serialise / write+fsync / log reset), synchronous and on the background worker, load, and a +//! catalog clone. //! //! ```text //! cargo run --release -p lightcraft-catalog --example persist_bench -- [photos…] //! ``` //! //! `` is a scratch directory (wiped per size). Default sizes: 1000 10000 85000. 90 % of the -//! photos are Local browse records, the rest library photos with a few edits and history steps. +//! photos are Local browse records, the rest library photos with a few edits and history steps; +//! `PERSIST_BENCH_MIX=library` makes them all unedited JPEGs of a library, with a title; +//! `PERSIST_BENCH_MIX=edited` makes them all edited raws with 20 history steps each. //! Peak memory: run under `/usr/bin/time -l` (macOS) / `-v` (Linux) with one size; //! `PERSIST_BENCH_NO_LOAD=1` skips the final load, so the peak is building + compacting. @@ -21,7 +24,47 @@ fn ms(t: Instant) -> f64 { t.elapsed().as_secs_f64() * 1e3 } +/// `PERSIST_BENCH_MIX=library`: an imported JPEG nobody edited. +fn library_photo(c: &mut Catalog, i: u64) -> Photo { + let id = c.alloc_photo_id(); + let name = format!("IMG_{i:08}.jpg"); + let path = format!("/Volumes/Photos/Library/Archive/2019/2019-07 Summer/Trip to the coast/Day {:05}/extra/{name}", i / 500); + let mut p = Photo::new(id, Source::File { path }, &name, "JPEG", 4032, 3024, "2026-09-30T12:00:00"); + p.file_size = 3_400_000 + i; + p.captured = Some(format!("2019-07-{:02}T10:{:02}:{:02}", 1 + i % 28, i % 60, (i / 60) % 60)); + p.content_hash = Some(format!("{:032x}", i.wrapping_mul(0x9e37_79b9_7f4a_7c15))); + p.meta.title = format!("IMG_{i:07}"); + p +} + +/// `PERSIST_BENCH_MIX=edited`: a raw with 20 edits, each a history step with its own settings. +fn edited_photo(c: &mut Catalog, i: u64) -> Photo { + let mut p = library_photo(c, i); + p.kind = MediaKind::Raw; + p.format = "CR3".into(); + p.as_shot_wb = Some((5200.0, 3.0)); + let mut d = p.import_defaults(); + for step in 0..20u64 { + match step % 4 { + 0 => d.light.exposure = (i % 7) as f64 * 0.1 + step as f64 * 0.01, + 1 => d.light.contrast = step as f64, + 2 => d.wb.tint = (i % 11) as f64 + step as f64, + _ => d.detail.sharpen_amount = 40.0 + step as f64, + } + p.history.push(HistoryStep { label: "Edit".into(), settings: Arc::new(d.clone()) }); + } + p.develop = p.history.last().map(|s| s.settings.clone()).unwrap_or_default(); + p.edited = Some("2026-09-30T12:00:00".into()); + p.rating = (i % 6) as u8; + p +} + fn photo(c: &mut Catalog, i: u64) -> Photo { + match std::env::var("PERSIST_BENCH_MIX").as_deref() { + Ok("library") => return library_photo(c, i), + Ok("edited") => return edited_photo(c, i), + _ => {} + } let id = c.alloc_photo_id(); let mut p = Photo::new( id, @@ -61,6 +104,20 @@ fn photo(c: &mut Catalog, i: u64) -> Photo { p } +/// Log rating changes (2000 per append) until the journal asks for a compaction. +fn fill_until_due(j: &mut Journal, cat: &mut Catalog, ids: &[PhotoId]) -> std::result::Result<(), Box> { + while !j.wants_snapshot() { + let ops: Vec = (0..2000u64) + .map(|k| Op::SetRating { id: ids.get((k as usize) % ids.len().max(1)).copied().unwrap_or(PhotoId(1)), rating: ((j.seq() + k) % 6) as u8 }) + .collect(); + for op in &ops { + cat.apply(op.clone())?; + } + j.append(&ops)?; + } + Ok(()) +} + fn stats(mut v: Vec) -> String { v.sort_by(f64::total_cmp); let pick = |q: f64| v.get(((v.len() as f64 - 1.0) * q).round() as usize).copied().unwrap_or(0.0); @@ -78,17 +135,55 @@ fn main() -> std::result::Result<(), Box> { let _ = std::fs::remove_dir_all(&dir); let (mut j, _, _) = Journal::open(Box::new(FsStore::open(&dir)?))?; let mut cat = Catalog::new(); - // bulk-add (as one import would) and log it, so the first compaction is an import's + // an import: photos added one op each, the log compacted whenever the journal asks for + // it (as the app does; synchronously here, so the numbers don't depend on timing) + let t = Instant::now(); + let (mut compactions, mut written, mut log_written) = (0u64, 0u64, 0u64); for chunk in (0..n).collect::>().chunks(500) { let ops: Vec = chunk.iter().map(|i| Op::AddPhoto { photo: Box::new(photo(&mut cat, *i)) }).collect(); for op in &ops { cat.apply(op.clone())?; } + let before = j.log_bytes(); j.append(&ops)?; + log_written += j.log_bytes() - before; + if j.wants_snapshot() { + j.snapshot(&cat)?; + compactions += 1; + written += j.stats().last_snapshot.bytes; + } + } + let log_left = j.log_bytes(); + // (a last batch that reached a threshold was snapshotted already: not again) + if log_left > 0 { + j.snapshot(&cat)?; + written += j.stats().last_snapshot.bytes; + } + let import_ms = ms(t); + let size = j.snapshot_bytes(); + println!( + "== {n} photos ({} local): snapshot {:.1} MB ({:.0} B per photo)", + cat.photos().filter(|p| p.local).count(), + size as f64 / 1e6, + size as f64 / n.max(1) as f64 + ); + let last = if log_left > 0 { " (and a last one)" } else { "" }; + println!( + " import: {compactions} compactions{last} wrote {:.1} MB of snapshots ({:.1}x the final one) + {:.1} MB of log in {:.1} s; {:.1} MB of log left for the last", + written as f64 / 1e6, + written as f64 / size.max(1) as f64, + log_written as f64 / 1e6, + import_ms / 1e3, + log_left as f64 / 1e6 + ); + if std::env::var_os("PERSIST_BENCH_NO_LOAD").is_none() { + let t = Instant::now(); + let (_, loaded, _) = Journal::open(Box::new(FsStore::open(&dir)?))?; + println!(" open (the whole catalog from its snapshot): {:.1} ms", ms(t)); + if loaded.len() != cat.len() { + return Err("reloaded catalog differs".into()); + } } - j.snapshot(&cat)?; - let first = j.stats().last_snapshot; - println!("== {n} photos ({} local): snapshot {:.1} MB", cat.photos().filter(|p| p.local).count(), first.bytes as f64 / 1e6); let t = Instant::now(); let copy = cat.clone(); @@ -107,14 +202,10 @@ fn main() -> std::result::Result<(), Box> { } println!(" append (1 op, fsync): {}", stats(appends)); - // compactions at the default threshold crossing + // compactions when the journal asks for them let mut totals = Vec::new(); for _ in 0..3 { - while !j.wants_snapshot() { - let op = Op::SetRating { id: ids.first().copied().unwrap_or(PhotoId(1)), rating: (j.seq() % 6) as u8 }; - cat.apply(op.clone())?; - j.append(&[op])?; - } + fill_until_due(&mut j, &mut cat, &ids)?; j.snapshot(&cat)?; let s = j.stats().last_snapshot; println!( @@ -125,14 +216,10 @@ fn main() -> std::result::Result<(), Box> { } println!(" compaction total: {}", stats(totals)); - // the same at the threshold, written by the worker while single-op appends go on + // the same, written by the worker while single-op appends go on let mut blocking = Vec::new(); for _ in 0..3 { - while !j.wants_snapshot() { - let op = Op::SetRating { id: ids.first().copied().unwrap_or(PhotoId(1)), rating: (j.seq() % 6) as u8 }; - cat.apply(op.clone())?; - j.append(&[op])?; - } + fill_until_due(&mut j, &mut cat, &ids)?; let t = Instant::now(); j.snapshot_in_background(&cat)?; let start_ms = ms(t); @@ -158,6 +245,26 @@ fn main() -> std::result::Result<(), Box> { } println!(" background compaction blocking: {}", stats(blocking)); + // changes all over the library (a rating on every 50th photo), then one compaction + let spread: Vec = cat.photos().map(|p| p.id).step_by(50).collect(); + let ops: Vec = spread.iter().map(|id| Op::SetRating { id: *id, rating: 3 }).collect(); + for op in &ops { + cat.apply(op.clone())?; + } + j.append(&ops)?; + j.snapshot(&cat)?; + let s = j.stats().last_snapshot; + println!(" compaction after {} changes all over the library: wrote {:.1} MB in {:.1} ms", ops.len(), s.bytes as f64 / 1e6, s.total_ms); + // and after changes in one place (the first 1000 photos) + let ops: Vec = ids.iter().map(|id| Op::SetRating { id: *id, rating: 4 }).collect(); + for op in &ops { + cat.apply(op.clone())?; + } + j.append(&ops)?; + j.snapshot(&cat)?; + let s = j.stats().last_snapshot; + println!(" compaction after {} changes in one place: wrote {:.1} MB in {:.1} ms", ops.len(), s.bytes as f64 / 1e6, s.total_ms); + // forget the untouched Local records (folders last browsed long ago; every 7th folder // recently; every 50th Local record rated), then compact let folders: std::collections::BTreeSet = cat.photos().filter(|p| p.local).filter_map(|p| folder_of(p)).collect(); @@ -175,7 +282,7 @@ fn main() -> std::result::Result<(), Box> { } j.append(&ops)?; j.snapshot(&cat)?; - let before = j.stats().last_snapshot.bytes; + let before = j.snapshot_bytes(); let t = Instant::now(); let plan = cat.forget_local_plan("2026-10-05T00:00:00", DEFAULT_FORGET_DAYS, &|_| false); let plan_ms = ms(t); @@ -187,7 +294,7 @@ fn main() -> std::result::Result<(), Box> { j.append(&ops)?; let apply_ms = ms(t); j.snapshot(&cat)?; - let after = j.stats().last_snapshot.bytes; + let after = j.snapshot_bytes(); println!( " forget Local: {} of {} local records forgotten (kept: {} recent, {} touched, {} in use); plan {plan_ms:.1} ms, apply+append {apply_ms:.1} ms; snapshot {:.1} MB -> {:.1} MB", plan.evict.len(), @@ -205,11 +312,32 @@ fn main() -> std::result::Result<(), Box> { continue; } let t = Instant::now(); - let (_, loaded, _) = Journal::open(Box::new(FsStore::open(&dir)?))?; - println!(" open (load snapshot + replay): {:.1} ms", ms(t)); + let (mut j, mut loaded, _) = Journal::open(Box::new(FsStore::open(&dir)?))?; + let open_ms = ms(t); + println!(" open (after forgetting; load snapshot + replay): {open_ms:.1} ms"); if loaded.len() != cat.len() { return Err("reloaded catalog differs".into()); } + // a long log (never compacted here): what replaying it costs when the library is opened + let ids: Vec = loaded.photos().map(|p| p.id).take(1000).collect(); + const REPLAYED: u64 = 200_000; + for batch in 0..REPLAYED / 2000 { + let ops: Vec = (0..2000u64) + .map(|k| Op::SetRating { + id: ids.get((k as usize) % ids.len().max(1)).copied().unwrap_or(PhotoId(1)), + rating: ((batch + k) % 6) as u8, + }) + .collect(); + for op in &ops { + loaded.apply(op.clone())?; + } + j.append(&ops)?; + } + let log_mb = j.log_bytes() as f64 / 1e6; + drop(j); + let t = Instant::now(); + let (_, _, report) = Journal::open(Box::new(FsStore::open(&dir)?))?; + println!(" open with {} more log records ({log_mb:.1} MB): {:.1} ms ({:.1} ms more)", report.replayed, ms(t), ms(t) - open_ms); } let _ = std::fs::remove_dir_all(&dir); Ok(()) diff --git a/crates/catalog/proptest-regressions/tests_segments.txt b/crates/catalog/proptest-regressions/tests_segments.txt new file mode 100644 index 00000000000..bbc114778aa --- /dev/null +++ b/crates/catalog/proptest-regressions/tests_segments.txt @@ -0,0 +1,7 @@ +# Seeds for failure cases proptest has generated in the past. It is +# automatically read and these particular cases re-run before any +# novel cases are generated. +# +# It is recommended to check this file in to source control so that +# everyone who runs the test benefits from these saved cases. +cc 9f973b20fb5e7757eb3527f1d0e006379629e5bc8fb2b60cd1d5003295f9eeaf # shrinks to per = 1, steps = [(0, 0, 1), (5, 0, 1)] diff --git a/crates/catalog/src/develop_defaults.json b/crates/catalog/src/develop_defaults.json new file mode 100644 index 00000000000..90de5435385 --- /dev/null +++ b/crates/catalog/src/develop_defaults.json @@ -0,0 +1,229 @@ +{ + "version": 1, + "profile": { + "id": "lc.color", + "amount": 100.0, + "camera_local_tone": false + }, + "treatment": "color", + "wb": { + "mode": "asShot", + "temp": 6500.0, + "tint": 0.0, + "scale": "legacy" + }, + "light": { + "exposure": 0.0, + "contrast": 0.0, + "highlights": 0.0, + "shadows": 0.0, + "whites": 0.0, + "blacks": 0.0 + }, + "hdr": { + "enabled": false, + "max_ev": 3.0, + "sdr_brightness": 0.0, + "sdr_clarity": 0.0, + "sdr_contrast": 0.0, + "sdr_highlights": 0.0, + "sdr_shadows": 0.0, + "sdr_whites": 0.0 + }, + "curve": { + "highlights": 0.0, + "lights": 0.0, + "darks": 0.0, + "shadows": 0.0, + "split_shadows": 25.0, + "split_mid": 50.0, + "split_highlights": 75.0, + "master": [], + "red": [], + "green": [], + "blue": [], + "refine_saturation": 100.0 + }, + "color": { + "vibrance": 0.0, + "saturation": 0.0 + }, + "mixer": { + "red": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "orange": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "yellow": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "green": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "aqua": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "blue": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "purple": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "magenta": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + } + }, + "point_colors": [], + "bw_mix": { + "red": 0.0, + "orange": 0.0, + "yellow": 0.0, + "green": 0.0, + "aqua": 0.0, + "blue": 0.0, + "purple": 0.0, + "magenta": 0.0 + }, + "grading": { + "shadows": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "midtones": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "highlights": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "global": { + "hue": 0.0, + "sat": 0.0, + "lum": 0.0 + }, + "blending": 50.0, + "balance": 0.0 + }, + "effects": { + "texture": 0.0, + "clarity": 0.0, + "dehaze": 0.0 + }, + "vignette": { + "amount": 0.0, + "midpoint": 50.0, + "roundness": 0.0, + "feather": 50.0, + "highlights": 0.0, + "style": "highlightPriority" + }, + "grain": { + "amount": 0.0, + "size": 25.0, + "roughness": 50.0, + "seed": 0 + }, + "detail": { + "sharpen_amount": 0.0, + "sharpen_radius": 1.0, + "sharpen_detail": 25.0, + "sharpen_masking": 0.0, + "nr_luminance": 0.0, + "nr_detail": 50.0, + "nr_contrast": 0.0, + "nr_color": 0.0, + "nr_color_detail": 50.0, + "nr_color_smoothness": 50.0 + }, + "optics": { + "remove_ca": false, + "lens_profile": false, + "profile_distortion": 100.0, + "profile_vignetting": 100.0, + "defringe_purple_amount": 0.0, + "defringe_purple_hue_lo": 30.0, + "defringe_purple_hue_hi": 70.0, + "defringe_green_amount": 0.0, + "defringe_green_hue_lo": 40.0, + "defringe_green_hue_hi": 60.0, + "distortion": 0.0, + "vignetting": 0.0, + "vignetting_midpoint": 50.0, + "ca_red": 0.0, + "ca_blue": 0.0 + }, + "geometry": { + "upright": "off", + "guides": [], + "upright_transform": null, + "vertical": 0.0, + "horizontal": 0.0, + "rotate": 0.0, + "aspect": 0.0, + "scale": 100.0, + "offset_x": 0.0, + "offset_y": 0.0, + "constrain_crop": false + }, + "crop": { + "geometry": { + "rect": { + "x0": 0.0, + "y0": 0.0, + "x1": 1.0, + "y1": 1.0 + }, + "angle": 0.0 + }, + "aspect": null, + "flip_h": false, + "flip_v": false + }, + "orientation": "Normal", + "masks": [], + "spots": [], + "red_eye": [], + "lens_blur": { + "enabled": false, + "amount": 0.0, + "focal_distance": 0.0, + "focal_range": 0.0 + }, + "enhance": { + "denoise": 0.0, + "raw_details": false, + "super_resolution": false, + "denoise_on": null + }, + "calibration": { + "shadows_tint": 0.0, + "red_hue": 0.0, + "red_sat": 0.0, + "green_hue": 0.0, + "green_sat": 0.0, + "blue_hue": 0.0, + "blue_sat": 0.0 + }, + "disabled_sections": [] +} diff --git a/crates/catalog/src/fixtures/v10-catalog.log.jsonl b/crates/catalog/src/fixtures/v10-catalog.log.jsonl new file mode 100644 index 00000000000..289ad184945 --- /dev/null +++ b/crates/catalog/src/fixtures/v10-catalog.log.jsonl @@ -0,0 +1,7 @@ +{"seq":4,"crc":24908816,"op":{"op":"setDevelop","id":8,"settings":{"wb":{"temp":7000.0}},"label":"Temperature","edited":"2026-10-10T14:00:00"}} +{"seq":5,"crc":2749520832,"op":{"op":"pushHistory","id":8,"step":{"label":"Temperature","settings":{"wb":{"temp":7000.0}}}}} +{"seq":6,"crc":1078812333,"op":{"op":"setMeta","id":8,"meta":{"title":"Harbour","keywords":["boats"]}}} +{"seq":7,"crc":4123692544,"op":{"op":"setRating","id":9,"rating":3}} +{"seq":8,"crc":1378474312,"op":{"op":"setVersions","id":9,"versions":[{"name":"Rich","created":"2026-10-10T14:05:00","settings":{"crop":{"aspect":[3,2],"flip_h":true,"geometry":{"angle":1.5,"rect":{"x0":0.0,"x1":1.0,"y0":0.0,"y1":1.0}}},"curve":{"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}]},"disabled_sections":["detail","light"],"geometry":{"guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0]},"masks":[{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"end":{"x":0.5,"y":0.4},"kind":"linear","start":{"x":0.5,"y":0.0}}},{"invert":true,"name":"Sun","op":"add","shape":{"angle":0.0,"center":{"x":0.7,"y":0.2},"feather":50.0,"invert":false,"kind":"radial","rx":0.1,"ry":0.1}},{"invert":false,"op":"add","shape":{"hi":1.0,"hi_feather":0.0,"kind":"luminanceRange","lo":0.6,"lo_feather":0.1}}],"id":1,"invert":false,"name":"Sky","refine":30.0,"visible":true},{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"detail":[{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":128},{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":64}],"edge":2.0,"exclude":[{"x":0.1,"y":0.1}],"hint":[{"x":0.4,"y":0.6}],"kind":"object","seg":{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":256}}},{"invert":false,"op":"add","shape":{"kind":"prompt","text":"the red boat"}},{"invert":false,"op":"add","shape":{"kind":"colorRange","refine":40.0,"samples":[[0.5,0.1,0.2]]}},{"invert":false,"op":"add","shape":{"kind":"people","parts":["face"],"person":1}},{"invert":false,"op":"add","shape":{"kind":"subject"}}],"id":2,"invert":false,"name":"Boat","visible":true}],"point_colors":[{"chroma":0.1,"hue":0.0,"hue_range":50.0,"hue_shift":20.0,"lum":0.5,"lum_range":50.0,"lum_shift":0.0,"range":50.0,"sat_range":50.0,"sat_shift":0.0,"variance":0.0}],"profile":{"amount":150.0,"camera_local_tone":true,"id":"lc.mono"},"red_eye":[{"catchlight":{"x":0.1,"y":-0.1},"center":{"x":0.5,"y":0.4},"darken":50.0,"pet":false,"pupil_size":50.0,"rx":0.02,"ry":0.015}],"spots":[{"feather":50.0,"mode":"remove","opacity":100.0,"points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"source_offset":{"x":0.05,"y":0.0}}],"treatment":"bw","wb":{"tint":12.0}},"auto":false}]}} +{"seq":9,"crc":1772878675,"op":{"op":"setAsShotWb","id":8,"wb":[5200.0,8.0]}} +{"seq":10,"crc":4045689318,"op":{"op":"setDevelop","id":8,"settings":{"wb":{"scale":"kelvin","temp":5200.0,"tint":8.0}},"label":"White Balance","edited":"2026-10-11T09:00:00"}} diff --git a/crates/catalog/src/fixtures/v10-catalog.snap.json b/crates/catalog/src/fixtures/v10-catalog.snap.json new file mode 100644 index 00000000000..71a8b2b8325 --- /dev/null +++ b/crates/catalog/src/fixtures/v10-catalog.snap.json @@ -0,0 +1 @@ +{"format":"lightcraft-catalog","version":10,"seq":3,"defaults":{"bw_mix":{"aqua":0.0,"blue":0.0,"green":0.0,"magenta":0.0,"orange":0.0,"purple":0.0,"red":0.0,"yellow":0.0},"calibration":{"blue_hue":0.0,"blue_sat":0.0,"green_hue":0.0,"green_sat":0.0,"red_hue":0.0,"red_sat":0.0,"shadows_tint":0.0},"color":{"saturation":0.0,"vibrance":0.0},"crop":{"aspect":null,"flip_h":false,"flip_v":false,"geometry":{"angle":0.0,"rect":{"x0":0.0,"x1":1.0,"y0":0.0,"y1":1.0}}},"curve":{"blue":[],"darks":0.0,"green":[],"highlights":0.0,"lights":0.0,"master":[],"red":[],"refine_saturation":100.0,"shadows":0.0,"split_highlights":75.0,"split_mid":50.0,"split_shadows":25.0},"detail":{"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0,"nr_contrast":0.0,"nr_detail":50.0,"nr_luminance":0.0,"sharpen_amount":0.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"sharpen_radius":1.0},"disabled_sections":[],"effects":{"clarity":0.0,"dehaze":0.0,"texture":0.0},"enhance":{"denoise":0.0,"denoise_on":null,"raw_details":false,"super_resolution":false},"geometry":{"aspect":0.0,"constrain_crop":false,"guides":[],"horizontal":0.0,"offset_x":0.0,"offset_y":0.0,"rotate":0.0,"scale":100.0,"upright":"off","upright_transform":null,"vertical":0.0},"grading":{"balance":0.0,"blending":50.0,"global":{"hue":0.0,"lum":0.0,"sat":0.0},"highlights":{"hue":0.0,"lum":0.0,"sat":0.0},"midtones":{"hue":0.0,"lum":0.0,"sat":0.0},"shadows":{"hue":0.0,"lum":0.0,"sat":0.0}},"grain":{"amount":0.0,"roughness":50.0,"seed":0,"size":25.0},"hdr":{"enabled":false,"max_ev":3.0,"sdr_brightness":0.0,"sdr_clarity":0.0,"sdr_contrast":0.0,"sdr_highlights":0.0,"sdr_shadows":0.0,"sdr_whites":0.0},"lens_blur":{"amount":0.0,"enabled":false,"focal_distance":0.0,"focal_range":0.0},"light":{"blacks":0.0,"contrast":0.0,"exposure":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0},"masks":[],"mixer":{"aqua":{"hue":0.0,"lum":0.0,"sat":0.0},"blue":{"hue":0.0,"lum":0.0,"sat":0.0},"green":{"hue":0.0,"lum":0.0,"sat":0.0},"magenta":{"hue":0.0,"lum":0.0,"sat":0.0},"orange":{"hue":0.0,"lum":0.0,"sat":0.0},"purple":{"hue":0.0,"lum":0.0,"sat":0.0},"red":{"hue":0.0,"lum":0.0,"sat":0.0},"yellow":{"hue":0.0,"lum":0.0,"sat":0.0}},"optics":{"ca_blue":0.0,"ca_red":0.0,"defringe_green_amount":0.0,"defringe_green_hue_hi":60.0,"defringe_green_hue_lo":40.0,"defringe_purple_amount":0.0,"defringe_purple_hue_hi":70.0,"defringe_purple_hue_lo":30.0,"distortion":0.0,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"remove_ca":false,"vignetting":0.0,"vignetting_midpoint":50.0},"orientation":"Normal","point_colors":[],"profile":{"amount":100.0,"camera_local_tone":false,"id":"lc.color"},"red_eye":[],"spots":[],"treatment":"color","version":1,"vignette":{"amount":0.0,"feather":50.0,"highlights":0.0,"midpoint":50.0,"roundness":0.0,"style":"highlightPriority"},"wb":{"mode":"asShot","scale":"legacy","temp":6500.0,"tint":0.0}},"catalog":{"photos":{"7":{"id":7,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0007.jpg"},"file_name":"IMG_0007.jpg","kind":"raw","format":"JPEG","width":4032,"height":3024,"file_size":25000000,"captured":"2019-07-14T15:21:07","imported":"2026-10-10T12:00:00","meta":{"camera":"Camera Model X","lens":"24-70mm f/2.8","focal_mm":35.0,"aperture":4.0,"shutter":"1/250","iso":400,"location":"Old harbour","city":"Lisbon","state":"Lisboa","country":"Portugal","gps":[38.7,-9.1],"title":"Harbour","caption":"Boats at dusk","alt_text":"Three boats","extended_description":"Three boats moored at dusk","copyright":"(c) Someone","copyright_status":"copyrighted","usage_terms":"All rights reserved","copyright_url":"https://example.org/rights","creator":"Someone","keywords":["Places|Lisbon","boats"],"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.3,"y1":0.4},"kind":"Face","name":"Ana","description":null}]},"rating":4,"flag":"pick","label":"green","develop":{"crop":{"aspect":[3,2],"flip_h":true,"geometry":{"angle":1.5,"rect":{"x0":0.0,"x1":1.0,"y0":0.0,"y1":1.0}}},"curve":{"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}]},"disabled_sections":["detail","light"],"geometry":{"guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0]},"light":{"exposure":0.3},"masks":[{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"end":{"x":0.5,"y":0.4},"kind":"linear","start":{"x":0.5,"y":0.0}}},{"invert":true,"name":"Sun","op":"add","shape":{"angle":0.0,"center":{"x":0.7,"y":0.2},"feather":50.0,"invert":false,"kind":"radial","rx":0.1,"ry":0.1}},{"invert":false,"op":"add","shape":{"hi":1.0,"hi_feather":0.0,"kind":"luminanceRange","lo":0.6,"lo_feather":0.1}}],"id":1,"invert":false,"name":"Sky","refine":30.0,"visible":true},{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"detail":[{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":128},{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":64}],"edge":2.0,"exclude":[{"x":0.1,"y":0.1}],"hint":[{"x":0.4,"y":0.6}],"kind":"object","seg":{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":256}}},{"invert":false,"op":"add","shape":{"kind":"prompt","text":"the red boat"}},{"invert":false,"op":"add","shape":{"kind":"colorRange","refine":40.0,"samples":[[0.5,0.1,0.2]]}},{"invert":false,"op":"add","shape":{"kind":"people","parts":["face"],"person":1}},{"invert":false,"op":"add","shape":{"kind":"subject"}}],"id":2,"invert":false,"name":"Boat","visible":true}],"point_colors":[{"chroma":0.1,"hue":0.0,"hue_range":50.0,"hue_shift":20.0,"lum":0.5,"lum_range":50.0,"lum_shift":0.0,"range":50.0,"sat_range":50.0,"sat_shift":0.0,"variance":0.0}],"profile":{"amount":150.0,"camera_local_tone":true,"id":"lc.mono"},"red_eye":[{"catchlight":{"x":0.1,"y":-0.1},"center":{"x":0.5,"y":0.4},"darken":50.0,"pet":false,"pupil_size":50.0,"rx":0.02,"ry":0.015}],"spots":[{"feather":50.0,"mode":"remove","opacity":100.0,"points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"source_offset":{"x":0.05,"y":0.0}}],"treatment":"bw","wb":{"tint":12.0}},"edited":"2026-10-10T13:00:00","versions":[{"name":"Warm","created":"2026-10-10T12:30:00","settings":{"light":{"contrast":20.0}},"auto":true}],"history":[{"label":"Contrast","settings":{"light":{"contrast":20.0}}},{"label":"Exposure","settings":{"crop":{"aspect":[3,2],"flip_h":true,"geometry":{"angle":1.5,"rect":{"x0":0.0,"x1":1.0,"y0":0.0,"y1":1.0}}},"curve":{"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}]},"disabled_sections":["detail","light"],"geometry":{"guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0]},"light":{"exposure":0.3},"masks":[{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"end":{"x":0.5,"y":0.4},"kind":"linear","start":{"x":0.5,"y":0.0}}},{"invert":true,"name":"Sun","op":"add","shape":{"angle":0.0,"center":{"x":0.7,"y":0.2},"feather":50.0,"invert":false,"kind":"radial","rx":0.1,"ry":0.1}},{"invert":false,"op":"add","shape":{"hi":1.0,"hi_feather":0.0,"kind":"luminanceRange","lo":0.6,"lo_feather":0.1}}],"id":1,"invert":false,"name":"Sky","refine":30.0,"visible":true},{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"detail":[{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":128},{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":64}],"edge":2.0,"exclude":[{"x":0.1,"y":0.1}],"hint":[{"x":0.4,"y":0.6}],"kind":"object","seg":{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":256}}},{"invert":false,"op":"add","shape":{"kind":"prompt","text":"the red boat"}},{"invert":false,"op":"add","shape":{"kind":"colorRange","refine":40.0,"samples":[[0.5,0.1,0.2]]}},{"invert":false,"op":"add","shape":{"kind":"people","parts":["face"],"person":1}},{"invert":false,"op":"add","shape":{"kind":"subject"}}],"id":2,"invert":false,"name":"Boat","visible":true}],"point_colors":[{"chroma":0.1,"hue":0.0,"hue_range":50.0,"hue_shift":20.0,"lum":0.5,"lum_range":50.0,"lum_shift":0.0,"range":50.0,"sat_range":50.0,"sat_shift":0.0,"variance":0.0}],"profile":{"amount":150.0,"camera_local_tone":true,"id":"lc.mono"},"red_eye":[{"catchlight":{"x":0.1,"y":-0.1},"center":{"x":0.5,"y":0.4},"darken":50.0,"pet":false,"pupil_size":50.0,"rx":0.02,"ry":0.015}],"spots":[{"feather":50.0,"mode":"remove","opacity":100.0,"points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"source_offset":{"x":0.05,"y":0.0}}],"treatment":"bw","wb":{"tint":12.0}}}],"deleted":true,"local":true,"duration":12.5,"as_shot_wb":[5200.0,3.0],"content_hash":"00000000000000009e3779b97f4a7c15","embedded_lens":{"warp":null,"vignette":{"k":[0.0,0.0,0.0,0.0,0.0],"center":{"x":0.0,"y":0.0},"radius":0.0},"stages":[null,null,null]},"copy_of":3,"copy_name":"Copy 1","import_look":{"light":{"contrast":20.0}},"analysis":{"sharpness":71.0,"clipped":0.02,"group":4,"best":true},"preview_only":"unsupported raw variant","local_baseline":3735928559},"8":{"id":8,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0008.jpg"},"file_name":"IMG_0008.jpg","format":"JPEG","width":4032,"height":3024,"imported":"2026-10-10T12:00:00","develop":{}},"9":{"id":9,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0009.jpg"},"file_name":"IMG_0009.jpg","format":"JPEG","width":4032,"height":3024,"imported":"2026-10-10T12:00:00","develop":{"crop":{"aspect":[3,2],"flip_h":true,"geometry":{"angle":1.5,"rect":{"x0":0.0,"x1":1.0,"y0":0.0,"y1":1.0}}},"curve":{"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}]},"disabled_sections":["detail","light"],"geometry":{"guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0]},"masks":[{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"end":{"x":0.5,"y":0.4},"kind":"linear","start":{"x":0.5,"y":0.0}}},{"invert":true,"name":"Sun","op":"add","shape":{"angle":0.0,"center":{"x":0.7,"y":0.2},"feather":50.0,"invert":false,"kind":"radial","rx":0.1,"ry":0.1}},{"invert":false,"op":"add","shape":{"hi":1.0,"hi_feather":0.0,"kind":"luminanceRange","lo":0.6,"lo_feather":0.1}}],"id":1,"invert":false,"name":"Sky","refine":30.0,"visible":true},{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"detail":[{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":128},{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":64}],"edge":2.0,"exclude":[{"x":0.1,"y":0.1}],"hint":[{"x":0.4,"y":0.6}],"kind":"object","seg":{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":256}}},{"invert":false,"op":"add","shape":{"kind":"prompt","text":"the red boat"}},{"invert":false,"op":"add","shape":{"kind":"colorRange","refine":40.0,"samples":[[0.5,0.1,0.2]]}},{"invert":false,"op":"add","shape":{"kind":"people","parts":["face"],"person":1}},{"invert":false,"op":"add","shape":{"kind":"subject"}}],"id":2,"invert":false,"name":"Boat","visible":true}],"point_colors":[{"chroma":0.1,"hue":0.0,"hue_range":50.0,"hue_shift":20.0,"lum":0.5,"lum_range":50.0,"lum_shift":0.0,"range":50.0,"sat_range":50.0,"sat_shift":0.0,"variance":0.0}],"profile":{"amount":150.0,"camera_local_tone":true,"id":"lc.mono"},"red_eye":[{"catchlight":{"x":0.1,"y":-0.1},"center":{"x":0.5,"y":0.4},"darken":50.0,"pet":false,"pupil_size":50.0,"rx":0.02,"ry":0.015}],"spots":[{"feather":50.0,"mode":"remove","opacity":100.0,"points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"source_offset":{"x":0.05,"y":0.0}}],"treatment":"bw","wb":{"tint":12.0}},"local":true,"local_baseline":5167973575965256545}},"albums":{},"next_photo":10,"next_album":1,"next_stack":1}} diff --git a/crates/catalog/src/fixtures/v11-catalog.log.jsonl b/crates/catalog/src/fixtures/v11-catalog.log.jsonl new file mode 100644 index 00000000000..289ad184945 --- /dev/null +++ b/crates/catalog/src/fixtures/v11-catalog.log.jsonl @@ -0,0 +1,7 @@ +{"seq":4,"crc":24908816,"op":{"op":"setDevelop","id":8,"settings":{"wb":{"temp":7000.0}},"label":"Temperature","edited":"2026-10-10T14:00:00"}} +{"seq":5,"crc":2749520832,"op":{"op":"pushHistory","id":8,"step":{"label":"Temperature","settings":{"wb":{"temp":7000.0}}}}} +{"seq":6,"crc":1078812333,"op":{"op":"setMeta","id":8,"meta":{"title":"Harbour","keywords":["boats"]}}} +{"seq":7,"crc":4123692544,"op":{"op":"setRating","id":9,"rating":3}} +{"seq":8,"crc":1378474312,"op":{"op":"setVersions","id":9,"versions":[{"name":"Rich","created":"2026-10-10T14:05:00","settings":{"crop":{"aspect":[3,2],"flip_h":true,"geometry":{"angle":1.5,"rect":{"x0":0.0,"x1":1.0,"y0":0.0,"y1":1.0}}},"curve":{"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}]},"disabled_sections":["detail","light"],"geometry":{"guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0]},"masks":[{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"end":{"x":0.5,"y":0.4},"kind":"linear","start":{"x":0.5,"y":0.0}}},{"invert":true,"name":"Sun","op":"add","shape":{"angle":0.0,"center":{"x":0.7,"y":0.2},"feather":50.0,"invert":false,"kind":"radial","rx":0.1,"ry":0.1}},{"invert":false,"op":"add","shape":{"hi":1.0,"hi_feather":0.0,"kind":"luminanceRange","lo":0.6,"lo_feather":0.1}}],"id":1,"invert":false,"name":"Sky","refine":30.0,"visible":true},{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"detail":[{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":128},{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":64}],"edge":2.0,"exclude":[{"x":0.1,"y":0.1}],"hint":[{"x":0.4,"y":0.6}],"kind":"object","seg":{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":256}}},{"invert":false,"op":"add","shape":{"kind":"prompt","text":"the red boat"}},{"invert":false,"op":"add","shape":{"kind":"colorRange","refine":40.0,"samples":[[0.5,0.1,0.2]]}},{"invert":false,"op":"add","shape":{"kind":"people","parts":["face"],"person":1}},{"invert":false,"op":"add","shape":{"kind":"subject"}}],"id":2,"invert":false,"name":"Boat","visible":true}],"point_colors":[{"chroma":0.1,"hue":0.0,"hue_range":50.0,"hue_shift":20.0,"lum":0.5,"lum_range":50.0,"lum_shift":0.0,"range":50.0,"sat_range":50.0,"sat_shift":0.0,"variance":0.0}],"profile":{"amount":150.0,"camera_local_tone":true,"id":"lc.mono"},"red_eye":[{"catchlight":{"x":0.1,"y":-0.1},"center":{"x":0.5,"y":0.4},"darken":50.0,"pet":false,"pupil_size":50.0,"rx":0.02,"ry":0.015}],"spots":[{"feather":50.0,"mode":"remove","opacity":100.0,"points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"source_offset":{"x":0.05,"y":0.0}}],"treatment":"bw","wb":{"tint":12.0}},"auto":false}]}} +{"seq":9,"crc":1772878675,"op":{"op":"setAsShotWb","id":8,"wb":[5200.0,8.0]}} +{"seq":10,"crc":4045689318,"op":{"op":"setDevelop","id":8,"settings":{"wb":{"scale":"kelvin","temp":5200.0,"tint":8.0}},"label":"White Balance","edited":"2026-10-11T09:00:00"}} diff --git a/crates/catalog/src/fixtures/v11-catalog.snap.json b/crates/catalog/src/fixtures/v11-catalog.snap.json new file mode 100644 index 00000000000..1abf80f2188 --- /dev/null +++ b/crates/catalog/src/fixtures/v11-catalog.snap.json @@ -0,0 +1 @@ +{"format":"lightcraft-catalog","version":11,"seq":3,"defaults":{"bw_mix":{"aqua":0.0,"blue":0.0,"green":0.0,"magenta":0.0,"orange":0.0,"purple":0.0,"red":0.0,"yellow":0.0},"calibration":{"blue_hue":0.0,"blue_sat":0.0,"green_hue":0.0,"green_sat":0.0,"red_hue":0.0,"red_sat":0.0,"shadows_tint":0.0},"color":{"saturation":0.0,"vibrance":0.0},"crop":{"aspect":null,"flip_h":false,"flip_v":false,"geometry":{"angle":0.0,"rect":{"x0":0.0,"x1":1.0,"y0":0.0,"y1":1.0}}},"curve":{"blue":[],"darks":0.0,"green":[],"highlights":0.0,"lights":0.0,"master":[],"red":[],"refine_saturation":100.0,"shadows":0.0,"split_highlights":75.0,"split_mid":50.0,"split_shadows":25.0},"detail":{"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0,"nr_contrast":0.0,"nr_detail":50.0,"nr_luminance":0.0,"sharpen_amount":0.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"sharpen_radius":1.0},"disabled_sections":[],"effects":{"clarity":0.0,"dehaze":0.0,"texture":0.0},"enhance":{"denoise":0.0,"denoise_on":null,"raw_details":false,"super_resolution":false},"geometry":{"aspect":0.0,"constrain_crop":false,"guides":[],"horizontal":0.0,"offset_x":0.0,"offset_y":0.0,"rotate":0.0,"scale":100.0,"upright":"off","upright_transform":null,"vertical":0.0},"grading":{"balance":0.0,"blending":50.0,"global":{"hue":0.0,"lum":0.0,"sat":0.0},"highlights":{"hue":0.0,"lum":0.0,"sat":0.0},"midtones":{"hue":0.0,"lum":0.0,"sat":0.0},"shadows":{"hue":0.0,"lum":0.0,"sat":0.0}},"grain":{"amount":0.0,"roughness":50.0,"seed":0,"size":25.0},"hdr":{"enabled":false,"max_ev":3.0,"sdr_brightness":0.0,"sdr_clarity":0.0,"sdr_contrast":0.0,"sdr_highlights":0.0,"sdr_shadows":0.0,"sdr_whites":0.0},"lens_blur":{"amount":0.0,"enabled":false,"focal_distance":0.0,"focal_range":0.0},"light":{"blacks":0.0,"contrast":0.0,"exposure":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0},"masks":[],"mixer":{"aqua":{"hue":0.0,"lum":0.0,"sat":0.0},"blue":{"hue":0.0,"lum":0.0,"sat":0.0},"green":{"hue":0.0,"lum":0.0,"sat":0.0},"magenta":{"hue":0.0,"lum":0.0,"sat":0.0},"orange":{"hue":0.0,"lum":0.0,"sat":0.0},"purple":{"hue":0.0,"lum":0.0,"sat":0.0},"red":{"hue":0.0,"lum":0.0,"sat":0.0},"yellow":{"hue":0.0,"lum":0.0,"sat":0.0}},"optics":{"ca_blue":0.0,"ca_red":0.0,"defringe_green_amount":0.0,"defringe_green_hue_hi":60.0,"defringe_green_hue_lo":40.0,"defringe_purple_amount":0.0,"defringe_purple_hue_hi":70.0,"defringe_purple_hue_lo":30.0,"distortion":0.0,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"remove_ca":false,"vignetting":0.0,"vignetting_midpoint":50.0},"orientation":"Normal","point_colors":[],"profile":{"amount":100.0,"camera_local_tone":false,"id":"lc.color"},"red_eye":[],"spots":[],"treatment":"color","version":1,"vignette":{"amount":0.0,"feather":50.0,"highlights":0.0,"midpoint":50.0,"roundness":0.0,"style":"highlightPriority"},"wb":{"mode":"asShot","scale":"legacy","temp":6500.0,"tint":0.0}},"catalog":{"photos":{},"albums":{},"next_photo":10,"next_album":1,"next_stack":1},"segments":[{"name":"segments/7-3.json","first":7,"photos":3,"bytes":10481,"crc":2799158326}],"photos":3} diff --git a/crates/catalog/src/fixtures/v11-segments-7-3.json b/crates/catalog/src/fixtures/v11-segments-7-3.json new file mode 100644 index 00000000000..7b7286089b1 --- /dev/null +++ b/crates/catalog/src/fixtures/v11-segments-7-3.json @@ -0,0 +1 @@ +{"format":"lightcraft-catalog-segment","version":11,"photos":{"7":{"id":7,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0007.jpg"},"file_name":"IMG_0007.jpg","kind":"raw","format":"JPEG","width":4032,"height":3024,"file_size":25000000,"captured":"2019-07-14T15:21:07","imported":"2026-10-10T12:00:00","meta":{"camera":"Camera Model X","lens":"24-70mm f/2.8","focal_mm":35.0,"aperture":4.0,"shutter":"1/250","iso":400,"location":"Old harbour","city":"Lisbon","state":"Lisboa","country":"Portugal","gps":[38.7,-9.1],"title":"Harbour","caption":"Boats at dusk","alt_text":"Three boats","extended_description":"Three boats moored at dusk","copyright":"(c) Someone","copyright_status":"copyrighted","usage_terms":"All rights reserved","copyright_url":"https://example.org/rights","creator":"Someone","keywords":["Places|Lisbon","boats"],"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.3,"y1":0.4},"kind":"Face","name":"Ana","description":null}]},"rating":4,"flag":"pick","label":"green","develop":{"crop":{"aspect":[3,2],"flip_h":true,"geometry":{"angle":1.5,"rect":{"x0":0.0,"x1":1.0,"y0":0.0,"y1":1.0}}},"curve":{"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}]},"disabled_sections":["detail","light"],"geometry":{"guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0]},"light":{"exposure":0.3},"masks":[{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"end":{"x":0.5,"y":0.4},"kind":"linear","start":{"x":0.5,"y":0.0}}},{"invert":true,"name":"Sun","op":"add","shape":{"angle":0.0,"center":{"x":0.7,"y":0.2},"feather":50.0,"invert":false,"kind":"radial","rx":0.1,"ry":0.1}},{"invert":false,"op":"add","shape":{"hi":1.0,"hi_feather":0.0,"kind":"luminanceRange","lo":0.6,"lo_feather":0.1}}],"id":1,"invert":false,"name":"Sky","refine":30.0,"visible":true},{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"detail":[{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":128},{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":64}],"edge":2.0,"exclude":[{"x":0.1,"y":0.1}],"hint":[{"x":0.4,"y":0.6}],"kind":"object","seg":{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":256}}},{"invert":false,"op":"add","shape":{"kind":"prompt","text":"the red boat"}},{"invert":false,"op":"add","shape":{"kind":"colorRange","refine":40.0,"samples":[[0.5,0.1,0.2]]}},{"invert":false,"op":"add","shape":{"kind":"people","parts":["face"],"person":1}},{"invert":false,"op":"add","shape":{"kind":"subject"}}],"id":2,"invert":false,"name":"Boat","visible":true}],"point_colors":[{"chroma":0.1,"hue":0.0,"hue_range":50.0,"hue_shift":20.0,"lum":0.5,"lum_range":50.0,"lum_shift":0.0,"range":50.0,"sat_range":50.0,"sat_shift":0.0,"variance":0.0}],"profile":{"amount":150.0,"camera_local_tone":true,"id":"lc.mono"},"red_eye":[{"catchlight":{"x":0.1,"y":-0.1},"center":{"x":0.5,"y":0.4},"darken":50.0,"pet":false,"pupil_size":50.0,"rx":0.02,"ry":0.015}],"spots":[{"feather":50.0,"mode":"remove","opacity":100.0,"points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"source_offset":{"x":0.05,"y":0.0}}],"treatment":"bw","wb":{"tint":12.0}},"edited":"2026-10-10T13:00:00","versions":[{"name":"Warm","created":"2026-10-10T12:30:00","settings":{"light":{"contrast":20.0}},"auto":true}],"history":[{"label":"Contrast","settings":{"light":{"contrast":20.0}}},{"label":"Exposure","settings":{"crop":{"aspect":[3,2],"flip_h":true,"geometry":{"angle":1.5,"rect":{"x0":0.0,"x1":1.0,"y0":0.0,"y1":1.0}}},"curve":{"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}]},"disabled_sections":["detail","light"],"geometry":{"guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0]},"light":{"exposure":0.3},"masks":[{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"end":{"x":0.5,"y":0.4},"kind":"linear","start":{"x":0.5,"y":0.0}}},{"invert":true,"name":"Sun","op":"add","shape":{"angle":0.0,"center":{"x":0.7,"y":0.2},"feather":50.0,"invert":false,"kind":"radial","rx":0.1,"ry":0.1}},{"invert":false,"op":"add","shape":{"hi":1.0,"hi_feather":0.0,"kind":"luminanceRange","lo":0.6,"lo_feather":0.1}}],"id":1,"invert":false,"name":"Sky","refine":30.0,"visible":true},{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"detail":[{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":128},{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":64}],"edge":2.0,"exclude":[{"x":0.1,"y":0.1}],"hint":[{"x":0.4,"y":0.6}],"kind":"object","seg":{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":256}}},{"invert":false,"op":"add","shape":{"kind":"prompt","text":"the red boat"}},{"invert":false,"op":"add","shape":{"kind":"colorRange","refine":40.0,"samples":[[0.5,0.1,0.2]]}},{"invert":false,"op":"add","shape":{"kind":"people","parts":["face"],"person":1}},{"invert":false,"op":"add","shape":{"kind":"subject"}}],"id":2,"invert":false,"name":"Boat","visible":true}],"point_colors":[{"chroma":0.1,"hue":0.0,"hue_range":50.0,"hue_shift":20.0,"lum":0.5,"lum_range":50.0,"lum_shift":0.0,"range":50.0,"sat_range":50.0,"sat_shift":0.0,"variance":0.0}],"profile":{"amount":150.0,"camera_local_tone":true,"id":"lc.mono"},"red_eye":[{"catchlight":{"x":0.1,"y":-0.1},"center":{"x":0.5,"y":0.4},"darken":50.0,"pet":false,"pupil_size":50.0,"rx":0.02,"ry":0.015}],"spots":[{"feather":50.0,"mode":"remove","opacity":100.0,"points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"source_offset":{"x":0.05,"y":0.0}}],"treatment":"bw","wb":{"tint":12.0}}}],"deleted":true,"local":true,"duration":12.5,"as_shot_wb":[5200.0,3.0],"content_hash":"00000000000000009e3779b97f4a7c15","embedded_lens":{"warp":null,"vignette":{"k":[0.0,0.0,0.0,0.0,0.0],"center":{"x":0.0,"y":0.0},"radius":0.0},"stages":[null,null,null]},"copy_of":3,"copy_name":"Copy 1","import_look":{"light":{"contrast":20.0}},"analysis":{"sharpness":71.0,"clipped":0.02,"group":4,"best":true},"preview_only":"unsupported raw variant","local_baseline":3735928559},"8":{"id":8,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0008.jpg"},"file_name":"IMG_0008.jpg","format":"JPEG","width":4032,"height":3024,"imported":"2026-10-10T12:00:00","develop":{}},"9":{"id":9,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0009.jpg"},"file_name":"IMG_0009.jpg","format":"JPEG","width":4032,"height":3024,"imported":"2026-10-10T12:00:00","develop":{"crop":{"aspect":[3,2],"flip_h":true,"geometry":{"angle":1.5,"rect":{"x0":0.0,"x1":1.0,"y0":0.0,"y1":1.0}}},"curve":{"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}]},"disabled_sections":["detail","light"],"geometry":{"guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0]},"masks":[{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"end":{"x":0.5,"y":0.4},"kind":"linear","start":{"x":0.5,"y":0.0}}},{"invert":true,"name":"Sun","op":"add","shape":{"angle":0.0,"center":{"x":0.7,"y":0.2},"feather":50.0,"invert":false,"kind":"radial","rx":0.1,"ry":0.1}},{"invert":false,"op":"add","shape":{"hi":1.0,"hi_feather":0.0,"kind":"luminanceRange","lo":0.6,"lo_feather":0.1}}],"id":1,"invert":false,"name":"Sky","refine":30.0,"visible":true},{"adjust":{"amount":100.0,"blacks":0.0,"clarity":0.0,"color_hue":0.0,"color_sat":0.0,"contrast":0.0,"defringe":0.0,"dehaze":0.0,"exposure":0.0,"highlights":0.0,"hue":0.0,"moire":0.0,"noise":0.0,"saturation":0.0,"shadows":0.0,"sharpness":0.0,"temp":0.0,"texture":0.0,"tint":0.0,"whites":0.0},"components":[{"invert":false,"op":"add","shape":{"detail":[{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":128},{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":64}],"edge":2.0,"exclude":[{"x":0.1,"y":0.1}],"hint":[{"x":0.4,"y":0.6}],"kind":"object","seg":{"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7],"side":256}}},{"invert":false,"op":"add","shape":{"kind":"prompt","text":"the red boat"}},{"invert":false,"op":"add","shape":{"kind":"colorRange","refine":40.0,"samples":[[0.5,0.1,0.2]]}},{"invert":false,"op":"add","shape":{"kind":"people","parts":["face"],"person":1}},{"invert":false,"op":"add","shape":{"kind":"subject"}}],"id":2,"invert":false,"name":"Boat","visible":true}],"point_colors":[{"chroma":0.1,"hue":0.0,"hue_range":50.0,"hue_shift":20.0,"lum":0.5,"lum_range":50.0,"lum_shift":0.0,"range":50.0,"sat_range":50.0,"sat_shift":0.0,"variance":0.0}],"profile":{"amount":150.0,"camera_local_tone":true,"id":"lc.mono"},"red_eye":[{"catchlight":{"x":0.1,"y":-0.1},"center":{"x":0.5,"y":0.4},"darken":50.0,"pet":false,"pupil_size":50.0,"rx":0.02,"ry":0.015}],"spots":[{"feather":50.0,"mode":"remove","opacity":100.0,"points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"source_offset":{"x":0.05,"y":0.0}}],"treatment":"bw","wb":{"tint":12.0}},"local":true,"local_baseline":5167973575965256545}}} diff --git a/crates/catalog/src/fixtures/v6-catalog.log.jsonl b/crates/catalog/src/fixtures/v6-catalog.log.jsonl new file mode 100644 index 00000000000..de73d856c00 --- /dev/null +++ b/crates/catalog/src/fixtures/v6-catalog.log.jsonl @@ -0,0 +1,5 @@ +{"seq":4,"crc":2044174370,"op":{"op":"setDevelop","id":8,"settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"label":"Temperature","edited":"2026-10-10T14:00:00"}} +{"seq":5,"crc":1983535997,"op":{"op":"pushHistory","id":8,"step":{"label":"Temperature","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}}}} +{"seq":6,"crc":3297692306,"op":{"op":"setMeta","id":8,"meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"Harbour","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":["boats"]}}} +{"seq":7,"crc":4123692544,"op":{"op":"setRating","id":9,"rating":3}} +{"seq":8,"crc":1875893688,"op":{"op":"setVersions","id":9,"versions":[{"name":"Rich","created":"2026-10-10T14:05:00","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"auto":false}]}} diff --git a/crates/catalog/src/fixtures/v6-catalog.snap.json b/crates/catalog/src/fixtures/v6-catalog.snap.json new file mode 100644 index 00000000000..7908b5c43cb --- /dev/null +++ b/crates/catalog/src/fixtures/v6-catalog.snap.json @@ -0,0 +1 @@ +{"format":"lightcraft-catalog","version":6,"seq":3,"catalog":{"photos":{"7":{"id":7,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0007.jpg"},"file_name":"IMG_0007.jpg","kind":"raw","format":"JPEG","width":4032,"height":3024,"file_size":25000000,"captured":"2019-07-14T15:21:07","imported":"2026-10-10T12:00:00","meta":{"camera":"Camera Model X","lens":"24-70mm f/2.8","focal_mm":35.0,"aperture":4.0,"shutter":"1/250","iso":400,"location":"Old harbour","city":"Lisbon","state":"Lisboa","country":"Portugal","gps":[38.7,-9.1],"title":"Harbour","caption":"Boats at dusk","alt_text":"Three boats","extended_description":"Three boats moored at dusk","copyright":"(c) Someone","copyright_status":"copyrighted","usage_terms":"All rights reserved","copyright_url":"https://example.org/rights","creator":"Someone","keywords":["Places|Lisbon","boats"],"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.3,"y1":0.4},"kind":"Face","name":"Ana","description":null}]},"rating":4,"flag":"pick","label":"green","develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"edited":"2026-10-10T13:00:00","versions":[{"name":"Warm","created":"2026-10-10T12:30:00","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"auto":true}],"history":[{"label":"Contrast","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}},{"label":"Exposure","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]}}],"deleted":true,"local":true,"duration":12.5,"as_shot_wb":[5200.0,3.0],"content_hash":"00000000000000009e3779b97f4a7c15","embedded_lens":{"warp":null,"vignette":{"k":[0.0,0.0,0.0,0.0,0.0],"center":{"x":0.0,"y":0.0},"radius":0.0}},"copy_of":3,"copy_name":"Copy 1","import_look":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"analysis":{"sharpness":71.0,"clipped":0.02,"group":4,"best":true},"preview_only":"unsupported raw variant","local_baseline":3735928559},"8":{"id":8,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0008.jpg"},"file_name":"IMG_0008.jpg","kind":"image","format":"JPEG","width":4032,"height":3024,"file_size":0,"captured":null,"imported":"2026-10-10T12:00:00","meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":[]},"rating":0,"flag":"none","label":null,"develop":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"edited":null,"versions":[],"history":[],"deleted":false,"duration":null,"as_shot_wb":null},"9":{"id":9,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0009.jpg"},"file_name":"IMG_0009.jpg","kind":"image","format":"JPEG","width":4032,"height":3024,"file_size":0,"captured":null,"imported":"2026-10-10T12:00:00","meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":[]},"rating":0,"flag":"none","label":null,"develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"edited":null,"versions":[],"history":[],"deleted":false,"local":true,"duration":null,"as_shot_wb":null,"local_baseline":5167973575965256545}},"albums":{},"next_photo":10,"next_album":1,"next_stack":1}} diff --git a/crates/catalog/src/fixtures/v7-catalog.log.jsonl b/crates/catalog/src/fixtures/v7-catalog.log.jsonl new file mode 100644 index 00000000000..deb40d1c43b --- /dev/null +++ b/crates/catalog/src/fixtures/v7-catalog.log.jsonl @@ -0,0 +1,7 @@ +{"seq":4,"crc":2044174370,"op":{"op":"setDevelop","id":8,"settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"label":"Temperature","edited":"2026-10-10T14:00:00"}} +{"seq":5,"crc":1983535997,"op":{"op":"pushHistory","id":8,"step":{"label":"Temperature","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}}}} +{"seq":6,"crc":3297692306,"op":{"op":"setMeta","id":8,"meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"Harbour","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":["boats"]}}} +{"seq":7,"crc":4123692544,"op":{"op":"setRating","id":9,"rating":3}} +{"seq":8,"crc":1875893688,"op":{"op":"setVersions","id":9,"versions":[{"name":"Rich","created":"2026-10-10T14:05:00","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"auto":false}]}} +{"seq":9,"crc":1772878675,"op":{"op":"setAsShotWb","id":8,"wb":[5200.0,8.0]}} +{"seq":10,"crc":1072007694,"op":{"op":"setDevelop","id":8,"settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":5200.0,"tint":8.0,"scale":"kelvin"},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"label":"White Balance","edited":"2026-10-11T09:00:00"}} diff --git a/crates/catalog/src/fixtures/v7-catalog.snap.json b/crates/catalog/src/fixtures/v7-catalog.snap.json new file mode 100644 index 00000000000..1e523028981 --- /dev/null +++ b/crates/catalog/src/fixtures/v7-catalog.snap.json @@ -0,0 +1 @@ +{"format":"lightcraft-catalog","version":7,"seq":3,"catalog":{"photos":{"7":{"id":7,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0007.jpg"},"file_name":"IMG_0007.jpg","kind":"raw","format":"JPEG","width":4032,"height":3024,"file_size":25000000,"captured":"2019-07-14T15:21:07","imported":"2026-10-10T12:00:00","meta":{"camera":"Camera Model X","lens":"24-70mm f/2.8","focal_mm":35.0,"aperture":4.0,"shutter":"1/250","iso":400,"location":"Old harbour","city":"Lisbon","state":"Lisboa","country":"Portugal","gps":[38.7,-9.1],"title":"Harbour","caption":"Boats at dusk","alt_text":"Three boats","extended_description":"Three boats moored at dusk","copyright":"(c) Someone","copyright_status":"copyrighted","usage_terms":"All rights reserved","copyright_url":"https://example.org/rights","creator":"Someone","keywords":["Places|Lisbon","boats"],"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.3,"y1":0.4},"kind":"Face","name":"Ana","description":null}]},"rating":4,"flag":"pick","label":"green","develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"edited":"2026-10-10T13:00:00","versions":[{"name":"Warm","created":"2026-10-10T12:30:00","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"auto":true}],"history":[{"label":"Contrast","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}},{"label":"Exposure","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]}}],"deleted":true,"local":true,"duration":12.5,"as_shot_wb":[5200.0,3.0],"content_hash":"00000000000000009e3779b97f4a7c15","embedded_lens":{"warp":null,"vignette":{"k":[0.0,0.0,0.0,0.0,0.0],"center":{"x":0.0,"y":0.0},"radius":0.0},"stages":[null,null,null]},"copy_of":3,"copy_name":"Copy 1","import_look":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"analysis":{"sharpness":71.0,"clipped":0.02,"group":4,"best":true},"preview_only":"unsupported raw variant","local_baseline":3735928559},"8":{"id":8,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0008.jpg"},"file_name":"IMG_0008.jpg","kind":"image","format":"JPEG","width":4032,"height":3024,"file_size":0,"captured":null,"imported":"2026-10-10T12:00:00","meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":[]},"rating":0,"flag":"none","label":null,"develop":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"edited":null,"versions":[],"history":[],"deleted":false,"duration":null,"as_shot_wb":null},"9":{"id":9,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0009.jpg"},"file_name":"IMG_0009.jpg","kind":"image","format":"JPEG","width":4032,"height":3024,"file_size":0,"captured":null,"imported":"2026-10-10T12:00:00","meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":[]},"rating":0,"flag":"none","label":null,"develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"edited":null,"versions":[],"history":[],"deleted":false,"local":true,"duration":null,"as_shot_wb":null,"local_baseline":5167973575965256545}},"albums":{},"next_photo":10,"next_album":1,"next_stack":1}} diff --git a/crates/catalog/src/fixtures/v8-catalog.log.jsonl b/crates/catalog/src/fixtures/v8-catalog.log.jsonl new file mode 100644 index 00000000000..deb40d1c43b --- /dev/null +++ b/crates/catalog/src/fixtures/v8-catalog.log.jsonl @@ -0,0 +1,7 @@ +{"seq":4,"crc":2044174370,"op":{"op":"setDevelop","id":8,"settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"label":"Temperature","edited":"2026-10-10T14:00:00"}} +{"seq":5,"crc":1983535997,"op":{"op":"pushHistory","id":8,"step":{"label":"Temperature","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}}}} +{"seq":6,"crc":3297692306,"op":{"op":"setMeta","id":8,"meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"Harbour","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":["boats"]}}} +{"seq":7,"crc":4123692544,"op":{"op":"setRating","id":9,"rating":3}} +{"seq":8,"crc":1875893688,"op":{"op":"setVersions","id":9,"versions":[{"name":"Rich","created":"2026-10-10T14:05:00","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"auto":false}]}} +{"seq":9,"crc":1772878675,"op":{"op":"setAsShotWb","id":8,"wb":[5200.0,8.0]}} +{"seq":10,"crc":1072007694,"op":{"op":"setDevelop","id":8,"settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":5200.0,"tint":8.0,"scale":"kelvin"},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"label":"White Balance","edited":"2026-10-11T09:00:00"}} diff --git a/crates/catalog/src/fixtures/v8-catalog.snap.json b/crates/catalog/src/fixtures/v8-catalog.snap.json new file mode 100644 index 00000000000..7b2ad615251 --- /dev/null +++ b/crates/catalog/src/fixtures/v8-catalog.snap.json @@ -0,0 +1 @@ +{"format":"lightcraft-catalog","version":8,"seq":3,"catalog":{"photos":{"7":{"id":7,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0007.jpg"},"file_name":"IMG_0007.jpg","kind":"raw","format":"JPEG","width":4032,"height":3024,"file_size":25000000,"captured":"2019-07-14T15:21:07","imported":"2026-10-10T12:00:00","meta":{"camera":"Camera Model X","lens":"24-70mm f/2.8","focal_mm":35.0,"aperture":4.0,"shutter":"1/250","iso":400,"location":"Old harbour","city":"Lisbon","state":"Lisboa","country":"Portugal","gps":[38.7,-9.1],"title":"Harbour","caption":"Boats at dusk","alt_text":"Three boats","extended_description":"Three boats moored at dusk","copyright":"(c) Someone","copyright_status":"copyrighted","usage_terms":"All rights reserved","copyright_url":"https://example.org/rights","creator":"Someone","keywords":["Places|Lisbon","boats"],"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.3,"y1":0.4},"kind":"Face","name":"Ana","description":null}]},"rating":4,"flag":"pick","label":"green","develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"edited":"2026-10-10T13:00:00","versions":[{"name":"Warm","created":"2026-10-10T12:30:00","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"auto":true}],"history":[{"label":"Contrast","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}},{"label":"Exposure","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]}}],"deleted":true,"local":true,"duration":12.5,"as_shot_wb":[5200.0,3.0],"content_hash":"00000000000000009e3779b97f4a7c15","embedded_lens":{"warp":null,"vignette":{"k":[0.0,0.0,0.0,0.0,0.0],"center":{"x":0.0,"y":0.0},"radius":0.0},"stages":[null,null,null]},"copy_of":3,"copy_name":"Copy 1","import_look":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"analysis":{"sharpness":71.0,"clipped":0.02,"group":4,"best":true},"preview_only":"unsupported raw variant","local_baseline":3735928559},"8":{"id":8,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0008.jpg"},"file_name":"IMG_0008.jpg","kind":"image","format":"JPEG","width":4032,"height":3024,"file_size":0,"captured":null,"imported":"2026-10-10T12:00:00","meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":[]},"rating":0,"flag":"none","label":null,"develop":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"edited":null,"versions":[],"history":[],"deleted":false,"duration":null,"as_shot_wb":null},"9":{"id":9,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0009.jpg"},"file_name":"IMG_0009.jpg","kind":"image","format":"JPEG","width":4032,"height":3024,"file_size":0,"captured":null,"imported":"2026-10-10T12:00:00","meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":[]},"rating":0,"flag":"none","label":null,"develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"edited":null,"versions":[],"history":[],"deleted":false,"local":true,"duration":null,"as_shot_wb":null,"local_baseline":5167973575965256545}},"albums":{},"next_photo":10,"next_album":1,"next_stack":1}} diff --git a/crates/catalog/src/fixtures/v9-catalog.log.jsonl b/crates/catalog/src/fixtures/v9-catalog.log.jsonl new file mode 100644 index 00000000000..deb40d1c43b --- /dev/null +++ b/crates/catalog/src/fixtures/v9-catalog.log.jsonl @@ -0,0 +1,7 @@ +{"seq":4,"crc":2044174370,"op":{"op":"setDevelop","id":8,"settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"label":"Temperature","edited":"2026-10-10T14:00:00"}} +{"seq":5,"crc":1983535997,"op":{"op":"pushHistory","id":8,"step":{"label":"Temperature","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":7000.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}}}} +{"seq":6,"crc":3297692306,"op":{"op":"setMeta","id":8,"meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"Harbour","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":["boats"]}}} +{"seq":7,"crc":4123692544,"op":{"op":"setRating","id":9,"rating":3}} +{"seq":8,"crc":1875893688,"op":{"op":"setVersions","id":9,"versions":[{"name":"Rich","created":"2026-10-10T14:05:00","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"auto":false}]}} +{"seq":9,"crc":1772878675,"op":{"op":"setAsShotWb","id":8,"wb":[5200.0,8.0]}} +{"seq":10,"crc":1072007694,"op":{"op":"setDevelop","id":8,"settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":5200.0,"tint":8.0,"scale":"kelvin"},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"label":"White Balance","edited":"2026-10-11T09:00:00"}} diff --git a/crates/catalog/src/fixtures/v9-catalog.snap.json b/crates/catalog/src/fixtures/v9-catalog.snap.json new file mode 100644 index 00000000000..7ae0051621f --- /dev/null +++ b/crates/catalog/src/fixtures/v9-catalog.snap.json @@ -0,0 +1 @@ +{"format":"lightcraft-catalog","version":9,"seq":3,"catalog":{"photos":{"7":{"id":7,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0007.jpg"},"file_name":"IMG_0007.jpg","kind":"raw","format":"JPEG","width":4032,"height":3024,"file_size":25000000,"captured":"2019-07-14T15:21:07","imported":"2026-10-10T12:00:00","meta":{"camera":"Camera Model X","lens":"24-70mm f/2.8","focal_mm":35.0,"aperture":4.0,"shutter":"1/250","iso":400,"location":"Old harbour","city":"Lisbon","state":"Lisboa","country":"Portugal","gps":[38.7,-9.1],"title":"Harbour","caption":"Boats at dusk","alt_text":"Three boats","extended_description":"Three boats moored at dusk","copyright":"(c) Someone","copyright_status":"copyrighted","usage_terms":"All rights reserved","copyright_url":"https://example.org/rights","creator":"Someone","keywords":["Places|Lisbon","boats"],"regions":[{"rect":{"x0":0.1,"y0":0.2,"x1":0.3,"y1":0.4},"kind":"Face","name":"Ana","description":null}]},"rating":4,"flag":"pick","label":"green","develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"edited":"2026-10-10T13:00:00","versions":[{"name":"Warm","created":"2026-10-10T12:30:00","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"auto":true}],"history":[{"label":"Contrast","settings":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]}},{"label":"Exposure","settings":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.3,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]}}],"deleted":true,"local":true,"duration":12.5,"as_shot_wb":[5200.0,3.0],"content_hash":"00000000000000009e3779b97f4a7c15","embedded_lens":{"warp":null,"vignette":{"k":[0.0,0.0,0.0,0.0,0.0],"center":{"x":0.0,"y":0.0},"radius":0.0},"stages":[null,null,null]},"copy_of":3,"copy_name":"Copy 1","import_look":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":20.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"analysis":{"sharpness":71.0,"clipped":0.02,"group":4,"best":true},"preview_only":"unsupported raw variant","local_baseline":3735928559},"8":{"id":8,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0008.jpg"},"file_name":"IMG_0008.jpg","kind":"image","format":"JPEG","width":4032,"height":3024,"file_size":0,"captured":null,"imported":"2026-10-10T12:00:00","meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":[]},"rating":0,"flag":"none","label":null,"develop":{"version":1,"profile":{"id":"lc.color","amount":100.0},"treatment":"color","wb":{"mode":"asShot","temp":6500.0,"tint":0.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[],"red":[],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[],"upright_transform":null,"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":0.0},"aspect":null,"flip_h":false,"flip_v":false},"orientation":"Normal","masks":[],"spots":[],"red_eye":[],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":[]},"edited":null,"versions":[],"history":[],"deleted":false,"duration":null,"as_shot_wb":null},"9":{"id":9,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0009.jpg"},"file_name":"IMG_0009.jpg","kind":"image","format":"JPEG","width":4032,"height":3024,"file_size":0,"captured":null,"imported":"2026-10-10T12:00:00","meta":{"camera":"","lens":"","focal_mm":null,"aperture":null,"shutter":"","iso":null,"location":"","city":"","state":"","country":"","gps":null,"title":"","caption":"","alt_text":"","extended_description":"","copyright":"","creator":"","keywords":[]},"rating":0,"flag":"none","label":null,"develop":{"version":1,"profile":{"id":"lc.mono","amount":150.0,"camera_local_tone":true},"treatment":"bw","wb":{"mode":"asShot","temp":6500.0,"tint":12.0},"light":{"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0},"curve":{"highlights":0.0,"lights":0.0,"darks":0.0,"shadows":0.0,"split_shadows":25.0,"split_mid":50.0,"split_highlights":75.0,"master":[{"x":0.0,"y":0.0},{"x":0.4,"y":0.55},{"x":1.0,"y":1.0}],"red":[{"x":0.0,"y":0.1},{"x":1.0,"y":0.9}],"green":[],"blue":[],"refine_saturation":100.0},"color":{"vibrance":0.0,"saturation":0.0},"mixer":{"red":{"hue":0.0,"sat":0.0,"lum":0.0},"orange":{"hue":0.0,"sat":0.0,"lum":0.0},"yellow":{"hue":0.0,"sat":0.0,"lum":0.0},"green":{"hue":0.0,"sat":0.0,"lum":0.0},"aqua":{"hue":0.0,"sat":0.0,"lum":0.0},"blue":{"hue":0.0,"sat":0.0,"lum":0.0},"purple":{"hue":0.0,"sat":0.0,"lum":0.0},"magenta":{"hue":0.0,"sat":0.0,"lum":0.0}},"point_colors":[{"lum":0.5,"chroma":0.1,"hue":0.0,"hue_shift":20.0,"sat_shift":0.0,"lum_shift":0.0,"variance":0.0,"range":50.0,"hue_range":50.0,"sat_range":50.0,"lum_range":50.0}],"bw_mix":{"red":0.0,"orange":0.0,"yellow":0.0,"green":0.0,"aqua":0.0,"blue":0.0,"purple":0.0,"magenta":0.0},"grading":{"shadows":{"hue":0.0,"sat":0.0,"lum":0.0},"midtones":{"hue":0.0,"sat":0.0,"lum":0.0},"highlights":{"hue":0.0,"sat":0.0,"lum":0.0},"global":{"hue":0.0,"sat":0.0,"lum":0.0},"blending":50.0,"balance":0.0},"effects":{"texture":0.0,"clarity":0.0,"dehaze":0.0},"vignette":{"amount":0.0,"midpoint":50.0,"roundness":0.0,"feather":50.0,"highlights":0.0,"style":"highlightPriority"},"grain":{"amount":0.0,"size":25.0,"roughness":50.0,"seed":0},"detail":{"sharpen_amount":0.0,"sharpen_radius":1.0,"sharpen_detail":25.0,"sharpen_masking":0.0,"nr_luminance":0.0,"nr_detail":50.0,"nr_contrast":0.0,"nr_color":0.0,"nr_color_detail":50.0,"nr_color_smoothness":50.0},"optics":{"remove_ca":false,"lens_profile":false,"profile_distortion":100.0,"profile_vignetting":100.0,"defringe_purple_amount":0.0,"defringe_purple_hue_lo":30.0,"defringe_purple_hue_hi":70.0,"defringe_green_amount":0.0,"defringe_green_hue_lo":40.0,"defringe_green_hue_hi":60.0,"distortion":0.0,"vignetting":0.0,"vignetting_midpoint":50.0,"ca_red":0.0,"ca_blue":0.0},"geometry":{"upright":"off","guides":[[{"x":0.1,"y":0.1},{"x":0.1,"y":0.9}],[{"x":0.9,"y":0.1},{"x":0.8,"y":0.9}]],"upright_transform":[1.0,0.01,0.0,-0.01,1.0,0.0,0.0,0.002,1.0],"vertical":0.0,"horizontal":0.0,"rotate":0.0,"aspect":0.0,"scale":100.0,"offset_x":0.0,"offset_y":0.0,"constrain_crop":false},"crop":{"geometry":{"rect":{"x0":0.0,"y0":0.0,"x1":1.0,"y1":1.0},"angle":1.5},"aspect":[3,2],"flip_h":true,"flip_v":false},"orientation":"Normal","masks":[{"id":1,"name":"Sky","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"linear","start":{"x":0.5,"y":0.0},"end":{"x":0.5,"y":0.4}}},{"name":"Sun","op":"add","invert":true,"shape":{"kind":"radial","center":{"x":0.7,"y":0.2},"rx":0.1,"ry":0.1,"angle":0.0,"feather":50.0,"invert":false}},{"op":"add","invert":false,"shape":{"kind":"luminanceRange","lo":0.6,"hi":1.0,"lo_feather":0.1,"hi_feather":0.0}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0},"refine":30.0},{"id":2,"name":"Boat","visible":true,"invert":false,"components":[{"op":"add","invert":false,"shape":{"kind":"object","hint":[{"x":0.4,"y":0.6}],"exclude":[{"x":0.1,"y":0.1}],"seg":{"side":256,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},"detail":[{"side":128,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]},{"side":64,"data":"eJxjYAAAAAEAAQ==","rect":[0.1,0.2,0.6,0.7]}],"edge":2.0}},{"op":"add","invert":false,"shape":{"kind":"prompt","text":"the red boat"}},{"op":"add","invert":false,"shape":{"kind":"colorRange","samples":[[0.5,0.1,0.2]],"refine":40.0}},{"op":"add","invert":false,"shape":{"kind":"people","person":1,"parts":["face"]}},{"op":"add","invert":false,"shape":{"kind":"subject"}}],"adjust":{"temp":0.0,"tint":0.0,"exposure":0.0,"contrast":0.0,"highlights":0.0,"shadows":0.0,"whites":0.0,"blacks":0.0,"texture":0.0,"clarity":0.0,"dehaze":0.0,"hue":0.0,"saturation":0.0,"sharpness":0.0,"noise":0.0,"moire":0.0,"defringe":0.0,"color_hue":0.0,"color_sat":0.0,"amount":100.0}}],"spots":[{"mode":"remove","points":[{"x":0.3,"y":0.3},{"x":0.32,"y":0.31}],"size":0.02,"feather":50.0,"opacity":100.0,"source_offset":{"x":0.05,"y":0.0}}],"red_eye":[{"center":{"x":0.5,"y":0.4},"rx":0.02,"ry":0.015,"pupil_size":50.0,"darken":50.0,"pet":false,"catchlight":{"x":0.1,"y":-0.1}}],"lens_blur":{"enabled":false,"amount":0.0,"focal_distance":0.0,"focal_range":0.0},"enhance":{"denoise":0.0,"raw_details":false,"super_resolution":false},"calibration":{"shadows_tint":0.0,"red_hue":0.0,"red_sat":0.0,"green_hue":0.0,"green_sat":0.0,"blue_hue":0.0,"blue_sat":0.0},"disabled_sections":["detail","light"]},"edited":null,"versions":[],"history":[],"deleted":false,"local":true,"duration":null,"as_shot_wb":null,"local_baseline":5167973575965256545}},"albums":{},"next_photo":10,"next_album":1,"next_stack":1}} diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index edcfae22ae2..4fb3cfd0e7d 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -1,9 +1,11 @@ //! Crash-safe catalog persistence: an append-only op log plus periodic snapshots. //! //! Files (in a [`Store`]): -//! - `catalog.snap` — `{"format":"lightcraft-catalog","version":V,"seq":N,"catalog":{…}}`, the -//! state after op `N` in catalog format `V` ([`VERSION`]); replaced atomically (temp + fsync + -//! rename). +//! - `catalog.snap` — `{"format":"lightcraft-catalog","version":V,"seq":N,"defaults":{…}, +//! "catalog":{…},"segments":[…]}`, the state after op `N` in catalog format `V` ([`VERSION`]); replaced +//! atomically (temp + fsync + rename). The catalog's photos are in the segment files it lists +//! (`segments/….json`, see [`crate::segments`]), or in `catalog.snap` itself where the store has +//! no segments; //! - `catalog.log` — JSON lines, one per op applied after the snapshot: //! `{"seq":N,"crc":C,"op":{…}}` where `C` is the CRC-32 of the op's JSON text. Appends are //! fsynced before [`Journal::append`] returns. @@ -32,65 +34,209 @@ //! `<= N` are skipped as stale; //! - after the log rewrite: the new snapshot + exactly the records `> N`. //! +//! **When to compact** ([`SnapshotPolicy`]): a snapshot rewrites the segments whose photos +//! changed (the whole catalog where there are no segments), so it is due when the log is long and +//! has grown to a share of what the snapshot would rewrite, not after a fixed number of changes. +//! Writing then stays proportional to what changed: changes within a few segments are compacted +//! every 2000 records however large the library, changes all over it less often. +//! +//! Closing a library compacts its log too, unless that would rewrite a lot and the log is still +//! short ([`Journal::wants_snapshot_on_close`]): a log is never left long from one session to the +//! next. +//! //! At most one snapshot is in flight; a synchronous [`Journal::snapshot`] and dropping the journal //! first wait for it, so an older snapshot can never replace a newer one. //! //! # Format versions //! //! The snapshot's `version` is the catalog format, and it covers the log beside it: the log has -//! no header of its own, and is only ever appended to under a snapshot of this build's format. +//! no header of its own, and is only ever appended to under a snapshot that states the defaults +//! its records leave out (this build's format, or one from 10 on with this build's defaults). //! -//! | Version | Written by | Adds | -//! |---|---|---| -//! | (none) | early builds: a log without a snapshot | | -//! | 1 | up to v0.2.0 | | -//! | 2 | after v0.2.0 | `Op::SetBrowsed`, `Catalog.browsed`, `Photo.local_baseline` | -//! | 3 | albums by hand | `Op::SetAlbumOrder`, `Album.order` | -//! | 4 | Reload reads lens data | `Op::SetEmbeddedLens` | -//! | 5 | the keyword list | `Op::SetKeyword`, `Catalog.keyword_list` | -//! | 6 | folder labels | `Op::SetFolderRecord`, `Catalog.folder_records` | -//! | 7 | Kelvin white balance for raws whose camera has matrices (#730) | `Op::SetAsShotWb`, `WhiteBalance.scale` | -//! | 8 | History cursor: Go to History Step adds no step | `Op::SetHistoryCursor`, `Photo.history_cursor` | -//! | 9 | preview-only recheck | `Photo.preview_checked`, `Op::SetContent.preview_checked` | +//! Every format, what it adds and which build wrote it first is one row of [`FORMATS`]: the +//! newest row is [`VERSION`], what this build writes. //! //! Rules: -//! - **Bump [`VERSION`]** (and add a row above) in the change that adds an [`Op`] variant or a -//! serialized field to the catalog, a photo, an album, a stack or develop settings that an older -//! build would misread or silently drop. New fields must deserialize from older data -//! (`#[serde(default)]`), so newer builds keep reading every older format. +//! - **Add a row to [`FORMATS`]** in the change that adds an [`Op`] variant or a serialized field +//! to the catalog, a photo, an album, a stack or develop settings that an older build would +//! misread or silently drop. New fields must deserialize from older data (`#[serde(default)]`), +//! so newer builds keep reading every older format. The row says whether it adds an op +//! ([`NEW_OP`]) or only fields ([`FIELDS`]); a row's description is free to name an op either +//! way (a field an op carries), since nothing reads its words. +//! - **A number means one format, and is final only on `main`.** Two changes written at the same +//! time both take the next number; the one that lands second takes the number after it (and +//! renames its fixture). A number that is spoken for but not in this build yet can have its +//! row all the same ([`Format::here`] set to `false`), so nothing else takes it. +//! - **Every format from 6 on has a fixture**: a small library written by the build of that +//! format (`fixtures/v-catalog.*`; `tests_stored::write_this_formats_fixture` writes this +//! build's), which every later build must open as it was (`tests_format_version`). //! - **Opening an older format upgrades it**: right after loading, [`Journal::open`] writes a //! snapshot in this build's format (also for a new library), before anything is appended — so a //! library is never a mix, and older builds refuse it from then on instead of reading part of it. //! [`LoadReport::upgraded_from`] says when that happened. +//! - **An upgrade keeps what it replaces**: older builds can't read the upgraded library, so the +//! files it was are first kept beside it as `catalog.snap.v-` and +//! `catalog.log.v-` (`seq`: the last change they hold), byte for byte +//! ([`LoadReport::kept`]; a damaged log is kept under its own name instead). Put back under +//! their own names, they are the library as the older build left it. They stay unless the +//! library on disk is known to be in its old format still: an upgrade that did not happen +//! leaves no copy, and one that was written keeps its copy whatever fails after it. Nothing +//! removes them afterwards: they are the user's to delete. (Not where the store says there is +//! no going back, [`Store::keeps_replaced_formats`].) +//! - **A library that can't be upgraded is not opened**, where appending to it as it is would +//! not be safe: one that states no defaults for develop settings (formats before 10) or other +//! ones than this build's ([`crate::stored`]), since a record written by this build leaves +//! out what equals this build's defaults. It is left as it was, and the error says why. (A +//! library that states this build's defaults opens as it is, and the next open tries again.) //! - **A newer format is refused, untouched**: a snapshot whose `version` is above [`VERSION`], //! or a log record whose CRC matches (so it is exactly what was written) but whose op doesn't //! parse, fails [`Journal::open`] with [`CatalogError::Newer`] before any file is modified — it //! is never mistaken for a torn tail or damage. (Builds up to v0.2.0 refuse a v2 snapshot with //! "unsupported format".) +use crate::segments::{self, Photos, Segment}; use crate::store::Store; -use crate::{Catalog, CatalogError, Op, Result}; +use crate::{Catalog, CatalogError, Op, PhotoId, Result}; pub const SNAPSHOT: &str = "catalog.snap"; pub const LOG: &str = "catalog.log"; +pub use crate::segments::{SEGMENT_DIR, SEGMENT_PREFIX, SEGMENT_SUFFIX, segment_file}; const FORMAT: &str = "lightcraft-catalog"; -/// 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 = 9; +/// One catalog format: a number in `catalog.snap` that says how the library beside it is written. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Format { + pub version: u32, + /// What it came with. + pub written_by: &'static str, + /// What it adds to the format before it. + pub adds: &'static str, + /// It adds an [`Op`] variant ([`NEW_OP`]), not only fields ([`FIELDS`]): the newest of these is the newest op's + /// format (the guard test `op_variants_are_versioned` holds that against the ops themselves). + pub adds_op: bool, + /// This build reads and writes what the format adds. `false`: the number is spoken for by a + /// change that is not in this build yet (see the module docs → *Format versions*). + pub here: bool, +} + +/// A row of [`FORMATS`] that adds an [`Op`] variant ([`Format::adds_op`]). +pub const NEW_OP: bool = true; +/// A row of [`FORMATS`] that adds fields, or a way of storing records, but no op. +pub const FIELDS: bool = false; + +const fn format(version: u32, written_by: &'static str, adds_op: bool, adds: &'static str) -> Format { + Format { version, written_by, adds, adds_op, here: true } +} + +/// The newest format in `formats` that this build has and that adds an op, by each row's flag. +pub fn newest_op_format(formats: &[Format]) -> Option<&Format> { + formats.iter().rev().find(|f| f.here && f.adds_op) +} + +/// Every catalog format, oldest first. (Before them: early builds wrote a log without a snapshot.) +pub const FORMATS: &[Format] = &[ + format(1, "up to v0.2.0", FIELDS, ""), + format(2, "after v0.2.0", NEW_OP, "`Op::SetBrowsed`, `Catalog.browsed`, `Photo.local_baseline`"), + format(3, "albums by hand", NEW_OP, "`Op::SetAlbumOrder`, `Album.order`"), + format(4, "Reload reads lens data", NEW_OP, "`Op::SetEmbeddedLens`"), + format(5, "the keyword list", NEW_OP, "`Op::SetKeyword`, `Catalog.keyword_list`"), + format(6, "folder labels", NEW_OP, "`Op::SetFolderRecord`, `Catalog.folder_records`"), + format(7, "Kelvin white balance (#730)", NEW_OP, "`Op::SetAsShotWb`, `WhiteBalance.scale`"), + format(8, "the History cursor", NEW_OP, "`Op::SetHistoryCursor`, `Photo.history_cursor`"), + format(9, "preview-only recheck (#974)", FIELDS, "`Photo.preview_checked`, `Op::SetContent`'s `preview_checked`"), + format(10, "compact records", FIELDS, "the stored form (`crate::stored`): unset fields and default develop settings are left out"), + format(11, "the snapshot in segments", FIELDS, "`catalog.snap` lists segment files that hold the photos (`crate::segments`)"), +]; + +/// The catalog format this build writes (and the newest it reads): the newest of [`FORMATS`]. +pub const VERSION: u32 = newest(FORMATS); + +const fn newest(formats: &[Format]) -> u32 { + match formats.last() { + Some(f) => f.version, + None => 0, + } +} /// When [`Journal::wants_snapshot`] says it's time to compact the log. +/// +/// The log is worth compacting once it is long (`max_records` or `max_bytes`) **and** has grown +/// to `1 / snapshot_share` of what the snapshot would rewrite (the segments whose photos changed +/// and `catalog.snap`; the whole catalog where there are no segments); or, whatever that is, once +/// it reaches `log_cap_bytes` (what opening the library has to replay stays bounded). #[derive(Clone, Copy, Debug)] pub struct SnapshotPolicy { pub max_records: u64, pub max_bytes: u64, + /// The log must also have reached this share of what the snapshot would rewrite: 4 = a + /// quarter of it. 0: no such condition (a long log is compacted whatever that costs). + pub snapshot_share: u64, + /// A log this large is compacted in any case. + pub log_cap_bytes: u64, + /// Closing the library compacts whatever log there is while that rewrites at most this much + /// (it is quick, and the next open has nothing to replay). More is rewritten on close only + /// once the log is long (`max_records` or `max_bytes`): a log never grows past that from one + /// session to the next, so what a damaged record in it can cost stays what it was. + pub close_bytes: u64, + /// Photos per segment (see [`crate::segments`]): a segment that changed is written in pieces + /// of this many once it holds more than twice as many. + pub segment_photos: usize, + /// And about this many bytes: where records are large (edited photos with their history), a + /// segment holds fewer photos, down to 64. 0: any size. + pub segment_bytes: u64, + /// What a snapshot costs besides what it writes: it looks through every photo for the ones + /// that changed, which counts as rewriting `1 / scan_share` of the catalog (16: a library of + /// millions of photos is not compacted every 2000 changes of an import). 0: nothing. + pub scan_share: u64, } impl Default for SnapshotPolicy { fn default() -> Self { - SnapshotPolicy { max_records: 2000, max_bytes: 16 << 20 } + SnapshotPolicy { + max_records: 2000, + max_bytes: 16 << 20, + snapshot_share: 4, + log_cap_bytes: 256 << 20, + close_bytes: 64 << 20, + // (measured: docs/catalog-persistence.md, "Segment size") + segment_photos: 4096, + segment_bytes: 2 << 20, + scan_share: 16, + } + } +} + +impl SnapshotPolicy { + /// Whether a log of `records` records and `bytes` bytes is due for compaction into a snapshot + /// that would rewrite `rewrite_bytes`. + pub fn due(&self, records: u64, bytes: u64, rewrite_bytes: u64) -> bool { + if bytes >= self.log_cap_bytes { + return true; + } + let share = match self.snapshot_share { + 0 => true, + n => bytes >= rewrite_bytes / n, + }; + self.long(records, bytes) && share + } + + /// A log of this length is long (`max_records` or `max_bytes`), whatever the snapshot's size. + pub fn long(&self, records: u64, bytes: u64) -> bool { + records >= self.max_records || bytes >= self.max_bytes } } +/// How much an upgrade to this build's format is needed (see [`Journal::upgrade`]). +#[derive(Clone, Copy, PartialEq, Eq)] +enum Upgrade { + /// The library may go on as it is if it can't be upgraded now. + May, + /// The library can't be used as it is. + Must, + /// As [`Upgrade::Must`], for a library whose log was damaged: the snapshot must also have + /// replaced that log. + Repair, +} + /// What happened while loading. #[derive(Clone, Debug, Default, PartialEq)] pub struct LoadReport { @@ -116,6 +262,13 @@ pub struct LoadReport { pub upgraded_from: Option, /// What [`Catalog::repair`] changed in a damaged snapshot (empty for a sound one). pub repaired: Vec, + /// The files that upgrade replaced, kept beside the library under these names (the snapshot, + /// then the log; a file there was none of has no copy). + pub kept: Vec, + /// The library stated other defaults for develop settings than this build has (it was written + /// by a build with other ones): its records were read over its own defaults, and it was + /// rewritten with this build's. + pub other_defaults: bool, } /// Where persistence time goes (reported by `library.info` → `persistence`; printed to stderr @@ -142,15 +295,20 @@ pub struct PersistStats { pub snapshot_running: bool, /// Background snapshots that failed (the log was kept whole; retried later). pub failed_snapshots: u64, + /// Segment files the snapshot lists, and the size of the snapshot with them. + pub segments: u64, + pub snapshot_bytes: u64, } /// One snapshot (compaction), by stage. #[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct SnapshotTiming { - /// Serialising the catalog to JSON, streamed into the temp file (buffered writes included). + /// Writing the segments that changed (serialised, fsynced and, when a one-file library is + /// split, read back). pub serialize_ms: f64, - /// Flushing, `sync_all` and the atomic rename of `catalog.snap`. + /// Writing `catalog.snap` (serialised, `sync_all`, the atomic rename) and removing the + /// segment files it no longer lists. pub write_sync_ms: f64, /// Resetting `catalog.log` (an atomic rewrite to empty, or to the records appended while a /// background snapshot ran; fsynced). @@ -161,8 +319,10 @@ pub struct SnapshotTiming { pub blocking_ms: f64, /// Written by a worker thread. pub background: bool, - /// Size of `catalog.snap`. + /// Bytes written: `catalog.snap` and the segments that changed. pub bytes: u64, + /// Segments written. + pub segments: u64, /// Log records the snapshot compacted. pub records: u64, } @@ -179,9 +339,29 @@ fn ms_since(t: web_time::Instant) -> f64 { pub struct Journal { store: Box, + /// The library is in an older format still: its upgrade was put off (its files could not be + /// kept, or the new snapshot not written) and is tried at the next open. No compaction writes + /// the new format meanwhile: that would be an upgrade with no way back kept. + upgrade_deferred: Option, /// `seq` of the last durable op. seq: u64, snapshot_seq: u64, + /// Size of `catalog.snap` and its segments together (0: none yet), and of `catalog.snap`. + snapshot_bytes: u64, + head_bytes: u64, + /// The segments `catalog.snap` lists, and the photos they hold (see [`crate::segments`]). + segments: Vec, + baseline: Photos, + /// `catalog.snap` itself holds photos: a one-file library (formats up to 10, or written + /// where there are no segments). + inline_photos: bool, + /// The snapshot read when the library was opened listed segments (see + /// [`Journal::remove_unlisted_segments`]). + opened_with_segments: bool, + /// The segments (by index) that hold photos changed since the snapshot, and their bytes: an + /// estimate, for when to compact. What a snapshot rewrites is decided from the photos. + touched: std::collections::BTreeSet, + touched_bytes: u64, log_records: u64, log_bytes: u64, pub policy: SnapshotPolicy, @@ -207,7 +387,11 @@ struct Pending { started: web_time::Instant, /// Time the caller spent starting it. start_ms: f64, - worker: std::thread::JoinHandle>, + /// Photos changed by the ops appended since it started. + touched: Vec, + /// Returns how it went, with the photos on disk then: the ones it wrote, or after a failure + /// the ones that were there before. + worker: std::thread::JoinHandle<(std::io::Result, Photos)>, } fn io(e: std::io::Error) -> CatalogError { @@ -275,37 +459,134 @@ fn resync(line: &[u8], last: u64) -> Option<(usize, (u64, Op))> { }) } -/// Write `catalog.snap` for the state after op `seq`, streaming the JSON into the store (no -/// whole-file string). The bytes are exactly -/// `{"format":"lightcraft-catalog","version":1,"seq":N,"catalog":}\n`, -/// as before streaming. Fills in the serialise / write+sync times and the size. -fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io::Result { +/// What a snapshot is written of, and against. +struct Job<'a> { + /// The snapshot is of the state after this op. + seq: u64, + catalog: &'a Catalog, + /// The segments on disk and the photos they hold. + segments: &'a [Segment], + baseline: &'a Photos, + /// How large segments are to be. + size: segments::Size, + /// The library is in one file: read the segments it is split into back before committing. + verify: bool, +} + +/// A snapshot that was written. +struct Saved { + timing: SnapshotTiming, + /// The segments it lists. + segments: Vec, + /// Size of `catalog.snap`. + head_bytes: u64, + /// `catalog.snap` holds the photos itself (the store has no segments). + inline_photos: bool, + /// The stretches of ids whose photos it wrote (see [`segments::refresh`]). + changed: Vec<(std::ops::Bound, std::ops::Bound)>, +} + +/// The ops' photos whose records change (not the ones an album or stack merely names). +fn changed_photos(op: &Op, out: &mut impl FnMut(PhotoId)) { + match op { + Op::Batch { ops } => ops.iter().for_each(|o| changed_photos(o, out)), + Op::AddAlbum { .. } | Op::SetAlbumPhotos { .. } | Op::SetAlbumCover { .. } | Op::AddStack { .. } | Op::SetStack { .. } => {} + other => other.photo_ids(out), + } +} + +/// Write the snapshot of `job`: the segments whose photos changed, then `catalog.snap`, which +/// lists the segments and is the commit (replaced atomically); then the segment files it no +/// longer lists are removed. Where the store has no segments, `catalog.snap` holds the photos +/// itself. An error leaves the snapshot before this one as it was. +fn write_snapshot(store: &mut dyn Store, job: &Job<'_>) -> std::io::Result { let t0 = web_time::Instant::now(); - let mut serialize_ms = 0.0; - let bytes = store.write_atomic_with(SNAPSHOT, &mut |w| { + let segmented = store.segmented(); + let written = if segmented { + let on_disk = + segments::OnDisk { version: VERSION, seq: job.seq, segments: job.segments, baseline: job.baseline, size: job.size, verify: job.verify }; + Some(segments::write(store, job.catalog.photo_map(), &on_disk)?) + } else { + None + }; + // Every segment written is still there: a program that opened the library without its lock + // doesn't know them, and committing a snapshot that lists a file that is gone would leave a + // library that doesn't open. + if let Some(w) = &written + && !segments::present(store, &w.new) + { + segments::discard(store, &w.new); + return Err(std::io::Error::other("a segment was removed while the snapshot was being written (is the library open in another program?)")); + } + let serialize_ms = ms_since(t0); + let head; + let (body, listed): (&Catalog, &[Segment]) = match &written { + Some(w) => { + head = job.catalog.without_photos(); + (&head, &w.segments) + } + None => (job.catalog, &[]), + }; + let seq = job.seq; + let head_bytes = store.write_atomic_with(SNAPSHOT, &mut |w| { use std::io::Write; - let t = web_time::Instant::now(); // serde_json emits many tiny writes: buffer them in a concrete writer (inlined), so only // 1 MiB chunks go through the store's `dyn Write` let mut b = std::io::BufWriter::with_capacity(1 << 20, w); - write!(b, "{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":{seq},\"catalog\":")?; - serde_json::to_writer(&mut b, catalog).map_err(std::io::Error::other)?; - b.write_all(b"}\n")?; - b.flush()?; - serialize_ms = ms_since(t); - Ok(()) - })?; - Ok(SnapshotTiming { serialize_ms, write_sync_ms: (ms_since(t0) - serialize_ms).max(0.0), bytes, ..Default::default() }) + write!(b, "{}", snapshot_head(seq))?; + serde_json::to_writer(&mut b, body).map_err(std::io::Error::other)?; + b.write_all(b",\"segments\":")?; + serde_json::to_writer(&mut b, listed).map_err(std::io::Error::other)?; + writeln!(b, ",\"photos\":{}}}", job.catalog.len())?; + b.flush() + }); + let head_bytes = match head_bytes { + Ok(n) => n, + Err(e) => { + // Not committed: the segments written for it are no snapshot's. (Unless the + // `catalog.snap` in the store lists them after all, or can't be read to say: a + // replace that failed after it took effect. Then they stay.) + if let Some(w) = &written + && !may_list(store, &w.new) + { + segments::discard(store, &w.new); + } + return Err(e); + } + }; + // committed: what the snapshot before listed and this one doesn't is no longer needed + match &written { + Some(w) => segments::discard(store, &w.obsolete), + None => segments::discard(store, &job.segments.iter().map(|s| s.name.clone()).collect::>()), + } + let (segments, count, bytes, changed) = written.map_or((Vec::new(), 0, 0, Vec::new()), |w| (w.segments, w.written, w.bytes, w.changed)); + let timing = SnapshotTiming { + serialize_ms, + write_sync_ms: (ms_since(t0) - serialize_ms).max(0.0), + bytes: head_bytes + bytes, + segments: count, + ..Default::default() + }; + Ok(Saved { timing, segments, head_bytes, inline_photos: !segmented && !job.catalog.is_empty(), changed }) } /// The highest `seq` a snapshot may hold; beyond it the counter is treated as corrupt, far from overflow. const MAX_SEQ: u64 = u64::MAX / 2; +/// How `catalog.snap` starts for the state after op `seq`, up to the catalog itself: what it is, +/// and what a record's missing develop settings read as ([`crate::stored`]). +fn snapshot_head(seq: u64) -> String { + format!("{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":{seq},\"defaults\":{},\"catalog\":", crate::stored::base().0) +} + /// Just the identification of `catalog.snap` (read before the catalog itself). #[derive(serde::Deserialize)] struct SnapHeader { format: String, version: u32, + /// What a record's missing develop settings read as (from format 10 on). + #[serde(default)] + defaults: Option, } /// The whole `catalog.snap` (after [`SnapHeader`] was checked; `format` and `version` are ignored). @@ -313,45 +594,149 @@ struct SnapHeader { struct SnapFile { seq: u64, catalog: Catalog, + /// The segments that hold the catalog's photos (none: `catalog` holds them itself). + #[serde(default)] + segments: Vec, + /// How many photos the catalog has (format 11 on): a list of segments that doesn't add up to + /// this is not the one that was written. + #[serde(default)] + photos: Option, +} + +/// Just the segments `catalog.snap` lists. +#[derive(serde::Deserialize)] +struct SnapSegments { + #[serde(default)] + segments: Vec, +} + +/// The segments the `catalog.snap` in the store lists (none when there is no such file); `None` +/// when it can't be read to say. +fn listed_on_disk(store: &mut dyn Store) -> Option> { + match store.read(SNAPSHOT) { + Ok(Some(bytes)) => serde_json::from_slice::(&bytes).ok().map(|snap| snap.segments), + Ok(None) => Some(Vec::new()), + Err(_) => None, + } +} + +/// Whether the `catalog.snap` in the store lists any of `names`, or can't be read to say. +fn may_list(store: &mut dyn Store, names: &[String]) -> bool { + listed_on_disk(store).is_none_or(|listed| listed.iter().any(|s| names.contains(&s.name))) +} + +/// Whether `log` starts with the catalog's first change: then it holds the whole catalog. +fn log_from_the_start(log: Option<&[u8]>) -> bool { + let first = log.unwrap_or_default().split(|b| *b == b'\n').find(|l| !l.iter().all(u8::is_ascii_whitespace)); + first.and_then(|l| std::str::from_utf8(l).ok()).and_then(|l| decode_record(l.trim_end_matches('\r'))).is_some_and(|(seq, _)| seq == 1) } impl Journal { /// Open (or create) the catalog in `store`: load the snapshot, replay the log, repair a torn - /// tail. Fails only if the snapshot itself is unreadable (then nothing is modified). + /// tail. Fails if the snapshot is unreadable or a newer LightCraft's (then nothing is + /// modified), or if the library is in an older format and can't be brought to this build's + /// where it must be (see the module docs → *Format versions*). pub fn open(mut store: Box) -> Result<(Journal, Catalog, LoadReport)> { let mut report = LoadReport::default(); let snap = store.read(SNAPSHOT).map_err(io)?; let log = store.read(LOG).map_err(io)?; report.created = snap.is_none() && log.is_none(); - let (mut catalog, snapshot_seq, snapshot_version) = match snap { + // Segment files without the snapshot that lists them (a folder copied or synced in part, + // a `catalog.snap` that was removed): they hold the photos, and opening this as a new + // library would abandon them. Not so when the log holds every change from the first: a + // library that never had a snapshot, whose first one got as far as writing segments. + if snap.is_none() + && store.segmented() + && !log_from_the_start(log.as_deref()) + && let n @ 1.. = segments::files(store.as_mut()).map_err(io)? + { + return Err(CatalogError::Corrupt(format!( + "{SNAPSHOT} is missing, but {n} segment file(s) of a catalog are here ({SEGMENT_PREFIX}…{SEGMENT_SUFFIX})" + ))); + } + let head_bytes = snap.as_ref().map_or(0, |b| b.len() as u64); + let mut listed = Vec::new(); + let mut stated = None; + // (dropped once the snapshot, its segments and the log are read: their records are read + // over the library's own defaults where those are not this build's) + let mut reading = None; + // (the snapshot says what its records' missing develop settings read as: from format 10) + let mut states_defaults = false; + let (mut catalog, snapshot_seq, snapshot_version) = match &snap { Some(bytes) => { // the header first: a newer snapshot may not parse as this version's catalog - let h: SnapHeader = serde_json::from_slice(&bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; + let h: SnapHeader = serde_json::from_slice(bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; if h.format != FORMAT { return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: not a LightCraft catalog (format {:?})", h.format))); } if h.version > VERSION { return Err(newer(format!("{SNAPSHOT} is catalog format v{}", h.version))); } - let s: SnapFile = serde_json::from_slice(&bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; + states_defaults = h.defaults.is_some(); + if let Some(theirs) = h.defaults.filter(|theirs| !crate::stored::reads_the_same(theirs)) { + log::info!("catalog: the library was written with other develop defaults; reading it over its own"); + report.other_defaults = true; + reading = Some(crate::stored::reading_over(Some(std::sync::Arc::new(theirs)))); + } + let s: SnapFile = serde_json::from_slice(bytes).map_err(|e| CatalogError::Corrupt(format!("{SNAPSHOT}: {e}")))?; // a seq this high can't come from real use; the next record's seq would wrap if s.seq > MAX_SEQ { return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: seq {} is out of range", s.seq))); } - let mut catalog = s.catalog; - report.repaired = catalog.repair(); - for r in &report.repaired { - log::warn!("{SNAPSHOT}: {r}"); - } - (catalog, s.seq, Some(h.version)) + listed = s.segments; + stated = s.photos; + (s.catalog, s.seq, Some(h.version)) } None => (Catalog::new(), 0, None), }; report.snapshot_seq = snapshot_seq; + // the photos: in `catalog.snap` itself (a one-file library), or in the segments it lists + let inline_photos = !catalog.is_empty(); + let mut baseline = Photos::new(); + if !listed.is_empty() { + if inline_photos { + return Err(CatalogError::Corrupt(format!("{SNAPSHOT}: holds photos and lists segments"))); + } + let readers = segments::readers(store.as_ref(), listed.len()); + let photos = segments::load(store.as_mut(), readers, &listed).map_err(|e| match e.kind() { + std::io::ErrorKind::InvalidData => CatalogError::Corrupt(e.to_string()), + _ => io(e), + })?; + if store.segmented() && !report.other_defaults { + // (shared with the catalog: pointers, not copies. Not where the segments were + // written with other defaults: none of them is what this build would write, so + // none is what the next snapshot may keep.) + baseline = photos.clone(); + } + catalog.set_photos(photos); + } + if stated.is_some_and(|n| n != catalog.len() as u64) { + return Err(CatalogError::Corrupt(format!( + "{SNAPSHOT}: its segments hold {} photos where it states {}", + catalog.len(), + stated.unwrap_or(0) + ))); + } + // (once the photos are in: on a library in segments `catalog.snap` holds none, and its + // stacks would read as stacks of missing photos) + report.repaired = catalog.repair(); + for r in &report.repaired { + log::warn!("{SNAPSHOT}: {r}"); + } + let snapshot_bytes = head_bytes + listed.iter().map(|s| s.bytes).sum::(); let mut j = Journal { store, + upgrade_deferred: None, seq: snapshot_seq, snapshot_seq, + snapshot_bytes, + head_bytes, + opened_with_segments: !listed.is_empty(), + segments: listed, + baseline, + inline_photos, + touched: std::collections::BTreeSet::new(), + touched_bytes: 0, log_records: 0, log_bytes: 0, policy: SnapshotPolicy::default(), @@ -400,6 +785,7 @@ impl Journal { report.stale += 1; } Some((seq, op)) if j.seq.checked_add(1) == Some(seq) => { + j.touch(std::slice::from_ref(&op)); if catalog.apply(op).is_err() { report.failed += 1; } else { @@ -430,12 +816,27 @@ impl Journal { needs_newline = !has_nl; } + drop(reading); + // An older (or snapshot-less) library is brought to this build's format before anything + // 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)); + // (what this open has written the library anew with: this build's format and defaults) + let mut rewritten = false; if let Some(at) = damaged_at { let name = format!("{LOG}.damaged-{}", j.seq); j.store.write_atomic(&name, &log).map_err(io)?; log::warn!("catalog log damaged at byte {at}; kept as {name}; state recovered up to op {}", j.seq); report.damaged = Some(name); - j.snapshot(&catalog)?; + match older { + // (its log goes either way: the snapshot it was is kept like any other upgrade's) + Some(from) => { + report.kept = j.upgrade(&catalog, from, snap.as_deref(), &[], Upgrade::Repair)?.unwrap_or_default(); + report.upgraded_from = Some(from); + } + None => j.snapshot(&catalog)?, + } + rewritten = true; } else { if good_end < log.len() { report.torn_bytes = (log.len() - good_end) as u64; @@ -449,29 +850,129 @@ impl Journal { j.log_bytes = good_end as u64; } } - // Bring an older (or new, or snapshot-less) library to this version's format before - // anything is appended: a snapshot in this format makes older builds refuse the library - // instead of misreading ops or dropping fields they don't know. if report.created { // tiny: written directly, not counted as a compaction - let empty = format!("{{\"format\":\"{FORMAT}\",\"version\":{VERSION},\"seq\":0,\"catalog\":{}}}\n", catalog.to_snapshot()); - if let Err(e) = j.store.write_atomic(SNAPSHOT, empty.as_bytes()) { - log::warn!("catalog: can't write the new library's snapshot: {e}"); + let empty = format!("{}{}}}\n", snapshot_head(0), catalog.to_snapshot()); + // (A new library that can't be written is not one to work in: what would be added to + // its log leaves out defaults that nothing states.) + j.store + .write_atomic(SNAPSHOT, empty.as_bytes()) + .map_err(|e| CatalogError::Io(format!("can't write the new library's {SNAPSHOT}: {e}")))?; + j.head_bytes = empty.len() as u64; + j.snapshot_bytes = j.head_bytes; + } else if let (Some(from), false) = (older, rewritten) { + // A library that states its defaults and has this build's may go on as it is when it + // can't be upgraded now (the next open tries again): what is appended to it reads the + // same in every build that reads it. One that states none (formats before 10), or + // other ones, must not be appended to as it is: a record written from here on leaves + // out what equals this build's defaults. + let how = if report.other_defaults || !states_defaults { Upgrade::Must } else { Upgrade::May }; + if let Some(kept) = j.upgrade(&catalog, from, snap.as_deref(), &log, how)? { + rewritten = true; + report.upgraded_from = Some(from); + report.kept = kept; + } else { + j.upgrade_deferred = Some(from); + } + } + if report.other_defaults && !rewritten { + // The same format, other defaults: the library must state this build's before + // anything is appended. Nothing is kept for that: any build reads a library over + // the defaults it states. + j.snapshot(&catalog)?; + } + + catalog.revision = 0; + Ok((j, catalog, report)) + } + + /// Bring a library in format `from` to this build's: keep the files it was (`snap` and `log`, + /// see [`Journal::keep_replaced`]), then write the snapshot. `Some`: upgraded, with the names + /// of the files kept. `None` (only with [`Upgrade::May`]): not upgraded, and as it was, with + /// nothing kept. Otherwise that is an error: the library can't be used as it is. + /// + /// The kept files stay unless the library on disk is known to be in its old format still: + /// also when the snapshot was committed and something after it failed (emptying the log), + /// and when what is on disk can't be read to say. + fn upgrade(&mut self, catalog: &Catalog, from: u32, snap: Option<&[u8]>, log: &[u8], how: Upgrade) -> Result>> { + let refused = |what: &str, e: String| CatalogError::Io(format!("the library is in an older format (v{from}) and {what}: {e}")); + let kept = match self.keep_replaced(from, snap, log) { + Ok(kept) => kept, + Err(e) if how == Upgrade::May => { + // not upgraded without its way back: it opens as it is; retried on next open + log::warn!("catalog: can't keep the format v{from} files, so the library is not upgraded: {e}"); + return Ok(None); } - } else if report.damaged.is_none() && snapshot_version != Some(VERSION) { - report.upgraded_from = Some(snapshot_version.unwrap_or(0)); - match j.snapshot(&catalog) { - Ok(()) => { - if let Some(v) = report.upgraded_from { - log::info!("catalog: upgraded from format v{v} to v{VERSION}"); + Err(e) => return Err(refused("its files can't be kept before it is upgraded", e.to_string())), + }; + if let Err(e) = self.snapshot(catalog) { + match self.on_disk_version() { + // Committed all the same (the log could not be emptied): the library is upgraded, + // and its way back stays. Its log's records are in the snapshot and are passed + // over when it is read. Not so a damaged log, which would be appended to after + // its damage: the next open has to deal with it first. + Some(Some(VERSION)) if how != Upgrade::Repair => log::warn!("catalog: upgraded to format v{VERSION}, but: {e}"), + Some(Some(VERSION)) => return Err(refused("was upgraded, but its damaged log is still in place", e.to_string())), + // what is on disk can't be read to say: the way back stays + None => return Err(refused("it can't be told whether its upgrade was written", e.to_string())), + // Nothing lost: the old files are intact and still load. No copy of them stays: + // there is nothing to go back from. + Some(_) => { + self.forget_kept(&kept); + if how != Upgrade::May { + return Err(refused("can't be upgraded", e.to_string())); } + log::warn!("catalog: can't write the format v{VERSION} snapshot: {e}"); + return Ok(None); } - // nothing lost: the old files are intact and still load; retried on next open - Err(e) => log::warn!("catalog: can't write the format v{VERSION} snapshot: {e}"), } } - catalog.revision = 0; - Ok((j, catalog, report)) + log::info!("catalog: upgraded from format v{from} to v{VERSION}; the files it was are kept as {kept:?}"); + Ok(Some(kept)) + } + + /// The format of the snapshot in the store: `Some(None)` where there is none, `None` where + /// it can't be read to say. + fn on_disk_version(&mut self) -> Option> { + match self.store.read(SNAPSHOT) { + Ok(None) => Some(None), + Ok(Some(bytes)) => serde_json::from_slice::(&bytes).ok().map(|h| Some(h.version)), + Err(_) => None, + } + } + + /// Keep the files of a library in format `from` before an upgrade replaces them: `snap` and + /// `log` as they were read, under names that say their format and the last change they hold. + /// Returns the names (none where the store keeps none). All or nothing: on an error, what was + /// written is removed again. + fn keep_replaced(&mut self, from: u32, snap: Option<&[u8]>, log: &[u8]) -> std::io::Result> { + // (A library in one file: what it was is its snapshot and its log. One in segments would + // need its segments kept as well; no format before this build's has any.) + if !self.store.keeps_replaced_formats() || self.opened_with_segments { + return Ok(Vec::new()); + } + let seq = self.seq; + let files = [(SNAPSHOT, snap), (LOG, (!log.is_empty()).then_some(log))]; + let mut kept = Vec::new(); + for (name, bytes) in files { + let Some(bytes) = bytes else { continue }; + let name = format!("{name}.v{from}-{seq}"); + if let Err(e) = self.store.write_atomic(&name, bytes) { + self.forget_kept(&kept); + return Err(e); + } + kept.push(name); + } + Ok(kept) + } + + /// Remove kept files that keep nothing (the upgrade they were for did not happen). + fn forget_kept(&mut self, kept: &[String]) { + for name in kept { + if let Err(e) = self.store.remove(name) { + log::warn!("catalog: can't remove {name}: {e}"); + } + } } /// Append ops (already applied to the live catalog) durably, in order. @@ -504,7 +1005,9 @@ impl Journal { if let Some(p) = self.pending.as_mut() { p.tail.extend_from_slice(buf.as_bytes()); p.tail_records += ops.len() as u64; + ops.iter().for_each(|op| changed_photos(op, &mut |id| p.touched.push(id))); } + self.touch(ops); self.seq = seq; self.log_records += ops.len() as u64; self.log_bytes += buf.len() as u64; @@ -533,18 +1036,60 @@ impl Journal { if let Err(e) = self.wait() { log::warn!("catalog: background snapshot failed ({e}); writing one now"); } + // A library whose upgrade was put off still has its old files: keep them before the new + // format replaces them. If they can't be kept the library stays as it is. + let mut kept_now = Vec::new(); + if let Some(from) = self.upgrade_deferred { + let kept = (|| { + let snap = self.store.read(SNAPSHOT)?; + let log = self.store.read(LOG)?.unwrap_or_default(); + self.keep_replaced(from, snap.as_deref(), &log) + })(); + match kept { + Ok(kept) => kept_now = kept, + Err(e) if unlogged == 0 => { + return Err(CatalogError::Io(format!("the upgrade was put off (the files of format v{from} can't be kept): {e}"))); + } + // (changes that are in no log would be lost: saved all the same) + Err(e) => log::warn!("catalog: can't keep the format v{from} files: {e}"), + } + } let t0 = web_time::Instant::now(); let seq = self.seq.checked_add(unlogged).ok_or_else(|| CatalogError::Corrupt(format!("{SNAPSHOT}: op counter overflow")))?; - let mut timing = match write_snapshot(self.store.as_mut(), seq, catalog) { - Ok(t) => t, + let job = + Job { seq, catalog, segments: &self.segments, baseline: &self.baseline, size: self.segment_size(catalog), verify: self.inline_photos }; + let saved = match write_snapshot(self.store.as_mut(), &job) { + Ok(saved) => saved, Err(e) => { // nothing lost (the log is whole); don't retry on every append self.stats.failed_snapshots += 1; - self.retry_at_records = self.log_records + self.policy.max_records; + // The new snapshot may have been committed all the same (the failure came after + // its rename): then the upgrade is done and its way back stays. Only a disk that + // still reads the old format has nothing to go back from; one that can't be read + // keeps them. + match self.on_disk_version() { + // (committed all the same, but its folder was not synced: `seq` is not advanced, so the + // ops stay queued and are numbered again after the old seq; skipped as stale if + // the snapshot survived a crash, replayed if not) + Some(Some(VERSION)) => self.upgrade_deferred = None, + None => {} + Some(_) => self.forget_kept(&kept_now), + } + self.retry_at_records = self.log_records.saturating_add(self.policy.max_records); return Err(io(e)); } }; // the snapshot is durable: it holds every op up to `seq` + self.upgrade_deferred = None; + let mut timing = saved.timing; + // what is on disk now: as before, but for the stretches this snapshot wrote + let mut on_disk = std::mem::take(&mut self.baseline); + if self.store.segmented() { + segments::refresh(&mut on_disk, catalog.photo_map(), &saved.changed); + } else { + on_disk.clear(); + } + self.adopt(saved, on_disk); self.seq = seq; self.snapshot_seq = seq; let t2 = web_time::Instant::now(); @@ -567,23 +1112,47 @@ impl Journal { /// `catalog` must reflect every appended op. Appends go on meanwhile; [`Journal::poll`] /// finishes the compaction. No-op while a snapshot is already in flight. pub fn snapshot_in_background(&mut self, catalog: &Catalog) -> Result<()> { - if self.pending.is_some() { + if self.pending.is_some() || self.upgrade_deferred.is_some() { return Ok(()); } let t0 = web_time::Instant::now(); let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) }; let copy = catalog.clone(); let seq = self.seq; - let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || write_snapshot(writer.as_mut(), seq, ©)); + // The worker takes what is on disk with it (the segment list and the photos they hold) + // and gives back what is on disk when it is done. Nothing else writes snapshots meanwhile. + let listed = self.segments.clone(); + let baseline = std::mem::take(&mut self.baseline); + let (size, verify) = (self.segment_size(catalog), self.inline_photos); + let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || { + let job = Job { seq, catalog: ©, segments: &listed, baseline: &baseline, size, verify }; + match write_snapshot(writer.as_mut(), &job) { + Ok(saved) => { + let on_disk = if writer.segmented() { copy.into_photo_map() } else { Photos::new() }; + (Ok(saved), on_disk) + } + Err(e) => (Err(e), baseline), + } + }); let worker = match spawned { Ok(w) => w, Err(e) => { + // (what is on disk went with the thread that didn't start: the snapshot written + // now takes nothing on disk for granted and writes every segment) log::warn!("catalog: can't start a snapshot thread ({e}); writing it now"); return self.snapshot(catalog); } }; - self.pending = - Some(Pending { seq, tail: Vec::new(), tail_records: 0, records: self.log_records, started: t0, start_ms: ms_since(t0), worker }); + self.pending = Some(Pending { + seq, + tail: Vec::new(), + tail_records: 0, + records: self.log_records, + started: t0, + start_ms: ms_since(t0), + touched: Vec::new(), + worker, + }); Ok(()) } @@ -619,13 +1188,16 @@ impl Journal { fn finish(&mut self) -> Result<()> { let Some(p) = self.pending.take() else { return Ok(()) }; let t0 = web_time::Instant::now(); - let written = p.worker.join().unwrap_or_else(|_| Err(std::io::Error::other("snapshot thread panicked"))); - let mut timing = match written { - Ok(t) => t, + // (a worker that panicked took what is on disk with it: the next snapshot takes nothing + // on disk for granted and writes every segment) + let (written, on_disk) = p.worker.join().unwrap_or_else(|_| (Err(std::io::Error::other("snapshot thread panicked")), Photos::new())); + let saved = match written { + Ok(saved) => saved, Err(e) => { // the log still holds every record: nothing lost, retry later + self.baseline = on_disk; self.stats.failed_snapshots += 1; - self.retry_at_records = self.log_records + self.policy.max_records; + self.retry_at_records = self.log_records.saturating_add(self.policy.max_records); log::error!("catalog: background snapshot failed: {e}"); return Err(io(e)); } @@ -633,10 +1205,13 @@ impl Journal { // `catalog.snap` (op `p.seq`) is durable; the log's records `<= p.seq` are now stale. // Keep exactly the ones appended since (a crash before this rewrite skips the stale ones). let t1 = web_time::Instant::now(); + let mut timing = saved.timing; + self.adopt(saved, on_disk); self.snapshot_seq = p.seq; + p.touched.iter().for_each(|id| self.touch_photo(*id)); if let Err(e) = self.store.write_atomic(LOG, &p.tail) { // the log stays whole (stale records are skipped on load); compact again later - self.retry_at_records = self.log_records + self.policy.max_records; + self.retry_at_records = self.log_records.saturating_add(self.policy.max_records); log::error!("catalog: can't trim the log after a snapshot: {e}"); return Err(io(e)); } @@ -653,6 +1228,56 @@ impl Journal { Ok(()) } + /// How large the segments of a snapshot of `catalog` are to be. + fn segment_size(&self, catalog: &Catalog) -> segments::Size { + // (for photos in no segment yet: what a record takes on average in the snapshot there is) + let photos = self.snapshot_bytes.saturating_sub(if self.inline_photos { 0 } else { self.head_bytes }); + let record_bytes = photos.checked_div(catalog.len() as u64).unwrap_or(0); + segments::Size { per: self.policy.segment_photos, bytes: self.policy.segment_bytes, record_bytes } + } + + /// A snapshot was committed: what is on disk now. + fn adopt(&mut self, saved: Saved, on_disk: Photos) { + self.head_bytes = saved.head_bytes; + self.snapshot_bytes = saved.head_bytes + saved.segments.iter().map(|s| s.bytes).sum::(); + self.segments = saved.segments; + self.baseline = on_disk; + self.inline_photos = saved.inline_photos; + self.touched.clear(); + self.touched_bytes = 0; + } + + /// Note the segments of the photos `ops` change (for [`Journal::wants_snapshot`]). + fn touch(&mut self, ops: &[Op]) { + if self.segments.is_empty() { + return; + } + let mut ids = Vec::new(); + ops.iter().for_each(|op| changed_photos(op, &mut |id| ids.push(id))); + ids.into_iter().for_each(|id| self.touch_photo(id)); + } + + fn touch_photo(&mut self, id: PhotoId) { + if let Some(k) = segments::segment_of(&self.segments, id) + && self.touched.insert(k) + { + self.touched_bytes += self.segments.get(k).map_or(0, |s| s.bytes); + } + } + + /// What a snapshot would rewrite now, in bytes: `catalog.snap` and the segments that hold + /// changed photos; all of it where there are no segments (yet). + fn rewrite_bytes(&self) -> u64 { + if self.inline_photos || !self.store.segmented() { + return self.snapshot_bytes; + } + let scan = match self.policy.scan_share { + 0 => 0, + n => self.snapshot_bytes / n, + }; + self.head_bytes + self.touched_bytes + scan + } + fn record_snapshot(&mut self, t: SnapshotTiming) { self.stats.snapshots += 1; self.stats.last_snapshot = t; @@ -660,9 +1285,10 @@ impl Journal { self.stats.max_blocking_ms = self.stats.max_blocking_ms.max(t.blocking_ms); if profiling() { eprintln!( - "catalog: {}snapshot of {} records, {} B: serialize {:.1} ms, write+sync {:.1} ms, log reset {:.1} ms, total {:.1} ms, blocking {:.1} ms", + "catalog: {}snapshot of {} records, {} segment(s), {} B written: segments {:.1} ms, catalog.snap {:.1} ms, log reset {:.1} ms, total {:.1} ms, blocking {:.1} ms", if t.background { "background " } else { "" }, t.records, + t.segments, t.bytes, t.serialize_ms, t.write_sync_ms, @@ -675,14 +1301,63 @@ impl Journal { /// Where persistence time went so far. pub fn stats(&self) -> PersistStats { - PersistStats { snapshot_running: self.pending.is_some(), ..self.stats } + PersistStats { + snapshot_running: self.pending.is_some(), + segments: self.segments.len() as u64, + snapshot_bytes: self.snapshot_bytes, + ..self.stats + } } /// The log is long enough to be worth compacting. pub fn wants_snapshot(&self) -> bool { self.pending.is_none() + && self.upgrade_deferred.is_none() && self.log_records >= self.retry_at_records - && (self.log_records >= self.policy.max_records || self.log_bytes >= self.policy.max_bytes) + && self.policy.due(self.log_records, self.log_bytes, self.rewrite_bytes()) + } + + /// Whether closing the library should compact the log: there is one, and compacting it + /// rewrites little enough to do in passing ([`SnapshotPolicy::close_bytes`]) or the log is + /// long ([`SnapshotPolicy::long`]; during a session it may grow further, to its share of what + /// would be rewritten, but it isn't left that long between sessions). Nothing is lost either + /// way: what isn't compacted stays in the log and is replayed on open. + pub fn wants_snapshot_on_close(&self) -> bool { + self.log_records > 0 + && self.upgrade_deferred.is_none() + && (self.rewrite_bytes() <= self.policy.close_bytes || self.policy.long(self.log_records, self.log_bytes)) + } + + /// Size of the snapshot as last written or loaded: `catalog.snap` and its segments (0: none + /// yet). + pub fn snapshot_bytes(&self) -> u64 { + self.snapshot_bytes + } + + /// The segments `catalog.snap` lists. + pub fn segments(&self) -> &[Segment] { + &self.segments + } + + /// Remove the segment files the snapshot doesn't list: what a crash left between writing + /// segments and committing the snapshot, or between the commit and removing the old ones. + /// + /// Only for a caller that has the library to itself (it holds the library's lock): to anyone + /// else, the segments another program is writing for its next snapshot look the same. And + /// only when the library was opened from a snapshot that lists segments: files beside a + /// one-file `catalog.snap` (an older one put back over a newer folder) may be all there is of + /// the newer catalog, and are left alone for as long as this journal is open. + /// + /// What "the snapshot lists" is read from `catalog.snap` as it is on disk, together with what + /// this journal takes it to list (the two differ after a snapshot whose outcome it never + /// learned); if the file can't be read, nothing is removed. + pub fn remove_unlisted_segments(&mut self) { + if self.pending.is_some() || !self.store.segmented() || !self.opened_with_segments || self.segments.is_empty() { + return; + } + let Some(mut listed) = listed_on_disk(self.store.as_mut()) else { return }; + listed.extend(self.segments.iter().cloned()); + segments::discard_unlisted(self.store.as_mut(), &listed); } pub fn seq(&self) -> u64 { @@ -708,7 +1383,7 @@ impl Drop for Journal { /// records in it are skipped as stale on the next load. fn drop(&mut self) { if let Some(p) = self.pending.take() - && let Ok(Err(e)) = p.worker.join() + && let Ok((Err(e), _)) = p.worker.join() { log::error!("catalog: background snapshot failed: {e}"); } diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 1776c895c1e..d0d243b61a2 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -24,8 +24,10 @@ pub mod model; pub mod query; pub mod rules; pub mod safe_file; +pub mod segments; pub mod stacks; pub mod store; +mod stored; pub mod tally; use std::collections::BTreeMap; @@ -41,6 +43,7 @@ pub use lock::{LibraryLock, LockError, LockOwner}; pub use model::*; pub use query::{DateGroup, Filter, Person, RatingOp, Sort, SortKey, mix64}; pub use rules::{Match, Rule, RuleSet}; +pub use segments::Segment; use serde::{Deserialize, Serialize}; pub use store::{FsStore, MemStore, Store}; @@ -77,6 +80,7 @@ pub const HISTORY_LIMIT: usize = 200; #[serde(tag = "op", rename_all = "camelCase")] pub enum Op { AddPhoto { + #[serde(serialize_with = "stored::photo")] photo: Box, }, RemovePhoto { @@ -96,12 +100,14 @@ pub enum Op { }, SetDevelop { id: PhotoId, + #[serde(serialize_with = "stored::settings", deserialize_with = "stored::read_settings")] settings: Arc, label: String, edited: Option, }, SetMeta { id: PhotoId, + #[serde(serialize_with = "stored::meta")] meta: Box, }, SetDeleted { @@ -115,16 +121,19 @@ pub enum Op { }, SetVersions { id: PhotoId, + #[serde(serialize_with = "stored::versions")] versions: Vec, }, SetHistory { id: PhotoId, + #[serde(serialize_with = "stored::history")] history: Vec, }, /// Append one History entry (dropping the oldest beyond [`HISTORY_LIMIT`]). Logged instead of /// a full `SetHistory` so each edit costs one step in the op log. PushHistory { id: PhotoId, + #[serde(serialize_with = "stored::step")] step: HistoryStep, }, /// Move the History cursor (see [`Photo::history_cursor`]) without changing the steps. @@ -264,6 +273,7 @@ pub enum Op { #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct Catalog { + #[serde(serialize_with = "stored::photos")] photos: BTreeMap>, albums: BTreeMap, next_photo: u64, @@ -1006,6 +1016,59 @@ impl Catalog { // ---- persistence + /// The photos by id (what the journal saves in segments). + pub(crate) fn photo_map(&self) -> &BTreeMap> { + &self.photos + } + + /// Everything but the photos: what `catalog.snap` holds of a catalog whose photos are in + /// segments. + pub(crate) fn without_photos(&self) -> Catalog { + // every field by name: a new one doesn't compile until it is saved here too + let Catalog { + photos: _, + albums, + next_photo, + next_album, + stacks, + next_stack, + label_names, + browsed, + keyword_list, + folder_records, + revision, + changes: _, + index: _, + } = self; + Catalog { + photos: BTreeMap::new(), + albums: albums.clone(), + next_photo: *next_photo, + next_album: *next_album, + stacks: stacks.clone(), + next_stack: *next_stack, + label_names: label_names.clone(), + browsed: browsed.clone(), + keyword_list: keyword_list.clone(), + folder_records: folder_records.clone(), + revision: *revision, + // (what the latest ops touched is this session's to remember: not saved) + changes: Changes::default(), + // (lookups worked out from the rest: not saved) + index: index::Indexes::default(), + } + } + + /// The catalog's photos, for the journal to keep as what is on disk. + pub(crate) fn into_photo_map(self) -> BTreeMap> { + self.photos + } + + /// Give a catalog read without its photos the photos read from its segments. + pub(crate) fn set_photos(&mut self, photos: BTreeMap>) { + self.photos = photos; + } + /// Full snapshot as JSON. pub fn to_snapshot(&self) -> String { serde_json::to_string(self).unwrap_or_default() @@ -1160,8 +1223,14 @@ mod tests_local; #[cfg(test)] mod tests_lock; #[cfg(test)] +mod tests_policy; +#[cfg(test)] mod tests_repair; #[cfg(test)] mod tests_scale; #[cfg(test)] +mod tests_segments; +#[cfg(test)] +mod tests_stored; +#[cfg(test)] mod tests_torn_append; diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index 6ac3544ee7e..522242bf908 100644 --- a/crates/catalog/src/model.rs +++ b/crates/catalog/src/model.rs @@ -210,6 +210,7 @@ pub struct Meta { pub struct Version { pub name: String, pub created: String, + #[serde(deserialize_with = "crate::stored::read_settings")] pub settings: Arc, #[serde(default)] pub auto: bool, @@ -218,6 +219,7 @@ pub struct Version { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HistoryStep { pub label: String, + #[serde(deserialize_with = "crate::stored::read_settings")] pub settings: Arc, } @@ -245,6 +247,7 @@ pub struct Photo { pub flag: Flag, #[serde(default)] pub label: Option, + #[serde(deserialize_with = "crate::stored::read_settings")] pub develop: Arc, #[serde(default)] pub edited: Option, @@ -287,7 +290,7 @@ pub struct Photo { /// The settings import gave the photo when a user default (a raw/JPEG default preset, see /// the engine's import defaults) changed them from [`Photo::camera_defaults`]. They count as /// unedited, and Reset returns to them. - #[serde(default, skip_serializing_if = "Option::is_none")] + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::stored::read_optional_settings")] pub import_look: Option>, /// Assisted culling scores (`None` until analysed). #[serde(default, skip_serializing_if = "Option::is_none")] diff --git a/crates/catalog/src/segments.rs b/crates/catalog/src/segments.rs new file mode 100644 index 00000000000..d48239ee3e4 --- /dev/null +++ b/crates/catalog/src/segments.rs @@ -0,0 +1,595 @@ +//! The snapshot's photos in segment files (catalog format 11). +//! +//! `catalog.snap` holds everything about the catalog but its photos, and lists the **segments** +//! that hold those: files `segments/-.json` in the library folder, each a run of +//! photos in id order, +//! +//! ```text +//! {"format":"lightcraft-catalog-segment","version":11,"photos":{"":{…},…}} +//! ``` +//! +//! with its size and CRC-32 in the list. A compaction writes only the segments whose photos +//! changed since the last one, so its cost follows what changed, not the size of the library; +//! and opening a library reads its segments on several threads. +//! +//! **Which segments changed** is not worked out from the ops. The journal keeps the photos as the +//! segments on disk hold them (the *baseline*: shared pointers, not copies); a photo is the same +//! as on disk while the catalog still points to the same one. Changing a photo copies it (it is +//! shared with the baseline), so a segment is rewritten exactly when one of its photos was +//! changed, added or removed, whatever did it. +//! +//! **Where photos go.** Segment `k` holds the ids from its `first` up to the next segment's. +//! A segment whose photos changed is written again under a new name, in pieces of +//! [`crate::SnapshotPolicy::segment_photos`] once it holds more than twice that; one left without +//! photos is dropped. Photos added after a full last segment start new ones (an import leaves the +//! existing segments alone). Ids need not be dense: segments go by how many photos there are. +//! +//! **Crash safety.** Segments are written under names no snapshot lists yet, each fsynced; then +//! `catalog.snap` is replaced atomically, which is the commit; then the files it no longer lists +//! are removed. A crash before the commit leaves the old snapshot with all its segments; after +//! it, the new one with all of its. Segment files nothing lists are removed when the library is +//! opened. +//! +//! **A damaged segment** (wrong size or CRC, unreadable, photos it shouldn't hold) fails the open +//! with an error naming the file, and nothing is modified. +//! +//! **Stores without segments** ([`Store::segmented`] is false: the browser's) keep the photos in +//! `catalog.snap` itself, as formats up to 10 did. Either layout is read wherever it is found. + +use std::collections::BTreeMap; +use std::ops::Bound; +use std::sync::Arc; + +use serde::{Deserialize, Serialize}; + +use crate::store::Store; +use crate::{Photo, PhotoId}; + +/// The folder in the library that holds the segment files. +pub const SEGMENT_DIR: &str = "segments"; +/// Segment files are named `segments/-.json`: every one starts with this, and +/// ends with [`SEGMENT_SUFFIX`]. +pub const SEGMENT_PREFIX: &str = "segments/"; +/// Segments are JSON, and say so. +pub const SEGMENT_SUFFIX: &str = ".json"; + +/// The name of the segment file `.json` in the segments folder (`stem`: `-`). +pub fn segment_file(stem: &str) -> String { + format!("{SEGMENT_PREFIX}{stem}{SEGMENT_SUFFIX}") +} +const SEGMENT_FORMAT: &str = "lightcraft-catalog-segment"; +/// Segments read at once when a library is opened. +const LOAD_THREADS: usize = 8; + +pub(crate) type Photos = BTreeMap>; + +/// One segment, as `catalog.snap` lists it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Segment { + /// The file's name in the library folder. + pub name: String, + /// The segment holds the ids from this one up to the next segment's `first`. + pub first: PhotoId, + /// How many photos it holds. + pub photos: u64, + /// The file's size and CRC-32. + pub bytes: u64, + pub crc: u32, +} + +fn corrupt(what: String) -> std::io::Error { + std::io::Error::new(std::io::ErrorKind::InvalidData, what) +} + +/// The ids of segment `k` of `segments`: from its `first` (the first segment: from the lowest +/// id) up to the next segment's. +fn range(segments: &[Segment], k: usize) -> (Bound, Bound) { + let lo = match (k, segments.get(k)) { + (0, _) | (_, None) => Bound::Unbounded, + (_, Some(s)) => Bound::Included(s.first), + }; + let hi = segments.get(k + 1).map_or(Bound::Unbounded, |next| Bound::Excluded(next.first)); + (lo, hi) +} + +/// A run of photos to write as one segment. +struct Piece { + first: PhotoId, + /// The last id it holds. + last: PhotoId, + photos: u64, +} + +/// What a snapshot does with one stretch of the catalog. +enum Step { + /// The segment's photos are what its file holds. + Keep(Segment), + Write(Piece), + /// The ids of a stretch whose photos are not what the segments held (it is written in + /// pieces, or holds no photo any more). + Changed(Bound, Bound), +} + +/// How many photos go into a segment. +#[derive(Clone, Copy)] +pub(crate) struct Size { + /// At most this many ([`crate::SnapshotPolicy::segment_photos`]). + pub per: usize, + /// And about this many bytes ([`crate::SnapshotPolicy::segment_bytes`]; 0: any). + pub bytes: u64, + /// What a photo's record takes on average, as far as known (0: not known), for photos that + /// are in no segment yet. + pub record_bytes: u64, +} + +impl Size { + /// Photos per segment where a record takes `record_bytes`: the fewer the larger the records + /// (edited photos with their history), down to 64, so that a segment is about + /// [`Size::bytes`] whatever it holds. + fn photos(&self, record_bytes: u64) -> usize { + let per = self.per.max(1); + match self.bytes.checked_div(record_bytes) { + Some(n) if self.bytes > 0 => usize::try_from(n).unwrap_or(per).max(64).min(per), + _ => per, + } + } +} + +/// `now` cut into pieces of `per` photos (one piece while there are at most twice that). The +/// first piece starts at `first` when that is lower than its first photo. +fn pieces<'a>(now: impl Iterator, first: Option, per: usize, out: &mut Vec) { + let ids: Vec = now.copied().collect(); + let per = per.max(1); + let size = if ids.len() > per.saturating_mul(2) { per } else { ids.len().max(1) }; + for (k, chunk) in ids.chunks(size).enumerate() { + let (Some(lo), Some(hi)) = (chunk.first(), chunk.last()) else { continue }; + let start = match first { + Some(f) if k == 0 => f.min(*lo), + _ => *lo, + }; + out.push(Step::Write(Piece { first: start, last: *hi, photos: chunk.len() as u64 })); + } +} + +/// What a snapshot of `photos` writes, given the `segments` on disk and the photos they hold +/// (`baseline`). +fn plan(segments: &[Segment], baseline: &Photos, photos: &Photos, size: &Size) -> Vec { + let mut steps = Vec::new(); + if segments.is_empty() { + steps.push(Step::Changed(Bound::Unbounded, Bound::Unbounded)); + pieces(photos.keys(), None, size.photos(size.record_bytes), &mut steps); + return steps; + } + for (k, segment) in segments.iter().enumerate() { + // by the size of this segment's own records + let per = size.photos(segment.bytes.checked_div(segment.photos).unwrap_or(0)); + let (lo, mut hi) = range(segments, k); + // photos added after a full last segment start segments of their own + let mut after = None; + if k + 1 == segments.len() + && segment.photos >= per as u64 + && let Some((last, _)) = span(baseline, lo, hi).next_back() + { + hi = Bound::Included(*last); + after = Some(*last); + } + let (mut was, mut now) = (span(baseline, lo, hi), span(photos, lo, hi)); + let same = loop { + match (was.next(), now.next()) { + (None, None) => break true, + (Some((a, p)), Some((b, q))) if a == b && Arc::ptr_eq(p, q) => {} + _ => break false, + } + }; + // (a segment the baseline has no photos for is not known to be on disk as it should be) + if same && span(baseline, lo, hi).next().is_some() { + steps.push(Step::Keep(segment.clone())); + } else { + steps.push(Step::Changed(lo, hi)); + pieces(span(photos, lo, hi).map(|(id, _)| id), Some(segment.first), per, &mut steps); + } + if let Some(last) = after + && span(photos, Bound::Excluded(last), Bound::Unbounded).next().is_some() + { + steps.push(Step::Changed(Bound::Excluded(last), Bound::Unbounded)); + pieces(span(photos, Bound::Excluded(last), Bound::Unbounded).map(|(id, _)| id), None, per, &mut steps); + } + } + steps +} + +/// Counts and checksums what is written through it. +struct Summed { + inner: W, + crc: crc32fast::Hasher, +} + +impl std::io::Write for Summed { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + let n = self.inner.write(buf)?; + if let Some(written) = buf.get(..n) { + self.crc.update(written); + } + Ok(n) + } + fn flush(&mut self) -> std::io::Result<()> { + self.inner.flush() + } +} + +/// A name for a new segment that no file in `taken` has. +fn fresh_name(first: PhotoId, seq: u64, taken: &std::collections::BTreeSet) -> String { + let mut name = segment_file(&format!("{}-{seq}", first.0)); + let mut n = 1u32; + while taken.contains(&name) { + name = segment_file(&format!("{}-{seq}-{n}", first.0)); + n = n.saturating_add(1); + } + name +} + +/// Only names this module gives: nothing outside the library folder, no other file of it. +fn valid_name(name: &str) -> bool { + name.strip_prefix(SEGMENT_PREFIX) + .and_then(|rest| rest.strip_suffix(SEGMENT_SUFFIX)) + .is_some_and(|stem| !stem.is_empty() && stem.len() <= 64 && stem.bytes().all(|b| b.is_ascii_digit() || b == b'-')) +} + +/// The photos with ids from `lo` to `hi` (none when the bounds are the wrong way round, which +/// `BTreeMap::range` would not take). +fn span(photos: &Photos, lo: Bound, hi: Bound) -> std::collections::btree_map::Range<'_, PhotoId, Arc> { + let ordered = match (lo, hi) { + (Bound::Included(a), Bound::Included(b)) => a <= b, + (Bound::Included(a) | Bound::Excluded(a), Bound::Excluded(b)) | (Bound::Excluded(a), Bound::Included(b)) => a < b, + (Bound::Unbounded, _) | (_, Bound::Unbounded) => true, + }; + if ordered { photos.range((lo, hi)) } else { photos.range(PhotoId(0)..PhotoId(0)) } +} + +fn write_segment(store: &mut dyn Store, name: &str, version: u32, piece: &Piece, photos: &Photos) -> std::io::Result { + let mut crc = 0; + let bytes = store.write_new_with(name, &mut |w| { + use std::io::Write; + let mut b = Summed { inner: std::io::BufWriter::with_capacity(1 << 20, w), crc: crc32fast::Hasher::new() }; + write!(b, "{{\"format\":\"{SEGMENT_FORMAT}\",\"version\":{version},\"photos\":")?; + let run = span(photos, Bound::Included(piece.first), Bound::Included(piece.last)); + serde_json::to_writer(&mut b, &crate::stored::PhotoRange(run)).map_err(std::io::Error::other)?; + b.write_all(b"}\n")?; + b.flush()?; + crc = b.crc.clone().finalize(); + Ok(()) + })?; + Ok(Segment { name: name.to_string(), first: piece.first, photos: piece.photos, bytes, crc }) +} + +/// Write `pieces` (each with its place in the list and its file name), on several threads when +/// the store gives further handles (see [`readers`]): a segment is its own file, and most of +/// writing one is waiting for it to reach the disk. One result per piece, in order. +fn write_pieces(store: &mut dyn Store, version: u32, pieces: &[(usize, String, Piece)], photos: &Photos) -> Vec> { + let handles = readers(store, pieces.len()); + if handles.len() < 2 { + return pieces.iter().map(|(_, name, piece)| write_segment(store, name, version, piece, photos)).collect(); + } + let next = std::sync::atomic::AtomicUsize::new(0); + let done: std::sync::Mutex)>> = std::sync::Mutex::new(Vec::new()); + let work = |store: &mut dyn Store| { + loop { + let k = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let Some((_, name, piece)) = pieces.get(k) else { break }; + let written = write_segment(store, name, version, piece, photos); + done.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((k, written)); + } + }; + together(handles, store, &work); + let mut results: Vec>> = Vec::new(); + results.resize_with(pieces.len(), || None); + for (k, written) in done.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner) { + if let Some(slot) = results.get_mut(k) { + *slot = Some(written); + } + } + results + .into_iter() + .zip(pieces) + .map(|(r, (_, name, _))| r.unwrap_or_else(|| Err(std::io::Error::other(format!("{name} could not be written"))))) + .collect() +} + +/// Run `work` on a thread per handle and on this one (with `store`), until all return. A thread +/// that can't be started just isn't one of them, and one that panics leaves what it was doing +/// undone (the callers find that out from what is missing): neither is a panic here. +fn together(handles: Vec>, store: &mut dyn Store, work: &(dyn Fn(&mut dyn Store) + Sync)) { + std::thread::scope(|scope| { + let threads: Vec<_> = handles + .into_iter() + .filter_map(|mut handle| { + std::thread::Builder::new().name("catalog-segments".into()).spawn_scoped(scope, move || work(handle.as_mut())).ok() + }) + .collect(); + work(store); + for thread in threads { + let _ = thread.join(); + } + }); +} + +/// The segments of a snapshot, written and kept. +pub(crate) struct Written { + /// The snapshot's segments, in order. + pub segments: Vec, + /// How many of them were written now, and their bytes. + pub written: u64, + pub bytes: u64, + /// Files the snapshot before this one listed and this one doesn't: to remove once this one + /// is committed. + pub obsolete: Vec, + /// Files written now: to remove if this snapshot is not committed after all. + pub new: Vec, + /// The stretches of ids whose photos changed (see [`refresh`]). + pub changed: Vec<(Bound, Bound)>, +} + +/// Bring `baseline` (the photos the segments held) up to a snapshot of `photos` that was +/// committed: in the stretches that changed, it holds what `photos` holds. Costs what changed, +/// not a copy of every photo's pointer. +pub(crate) fn refresh(baseline: &mut Photos, photos: &Photos, changed: &[(Bound, Bound)]) { + for (lo, hi) in changed { + let gone: Vec = span(baseline, *lo, *hi).map(|(id, _)| *id).collect(); + for id in gone { + baseline.remove(&id); + } + baseline.extend(span(photos, *lo, *hi).map(|(id, p)| (*id, p.clone()))); + } +} + +/// What a snapshot's segments are written against. +#[derive(Clone, Copy)] +pub(crate) struct OnDisk<'a> { + /// The catalog format and the op the snapshot is of (they name the files). + pub version: u32, + pub seq: u64, + /// The segments the current snapshot lists, and the photos they hold. + pub segments: &'a [Segment], + pub baseline: &'a Photos, + /// How large segments are to be. + pub size: Size, + /// Read every segment written back and compare it with the photos before returning (when a + /// one-file library is split: its one file is replaced only by segments known to hold the + /// same). + pub verify: bool, +} + +/// Write the segments of `photos` that differ from what `segments` hold (`baseline`), under +/// names no file has. Nothing is listed anywhere yet: the caller commits by writing +/// `catalog.snap` with [`Written::segments`], or removes [`Written::new`]. +pub(crate) fn write(store: &mut dyn Store, photos: &Photos, on_disk: &OnDisk<'_>) -> std::io::Result { + let OnDisk { version, seq, segments, baseline, size, verify } = *on_disk; + // names no file has: not the listed segments', and not those of files nothing lists (left by + // a snapshot that was not committed, or whose outcome this journal never learned) + let mut taken: std::collections::BTreeSet = segments.iter().map(|s| s.name.clone()).collect(); + // (a folder that can't be listed is a snapshot that can't be written, not an empty folder) + let held = store.list()?; + // a store that lists nothing though it holds the catalog can't say which names are free: + // then what is written here is not removed on failure either (it may not be new) + let knows_its_files = !held.is_empty(); + taken.extend(held.into_iter().filter(|n| valid_name(n))); + let mut out = Written { segments: Vec::new(), written: 0, bytes: 0, obsolete: Vec::new(), new: Vec::new(), changed: Vec::new() }; + // the snapshot's segments in order: the ones kept, and a place for each one to write + let mut listed: Vec> = Vec::new(); + let mut pieces: Vec<(usize, String, Piece)> = Vec::new(); + for step in plan(segments, baseline, photos, &size) { + match step { + Step::Keep(segment) => listed.push(Some(segment)), + Step::Changed(lo, hi) => out.changed.push((lo, hi)), + Step::Write(piece) => { + let name = fresh_name(piece.first, seq, &taken); + taken.insert(name.clone()); + out.new.push(name.clone()); + pieces.push((listed.len(), name, piece)); + listed.push(None); + } + } + } + let result = (|| { + for ((slot, _, _), segment) in pieces.iter().zip(write_pieces(store, version, &pieces, photos)) { + let segment = segment?; + out.written += 1; + out.bytes += segment.bytes; + if let Some(place) = listed.get_mut(*slot) { + *place = Some(segment); + } + } + out.segments = listed.into_iter().flatten().collect(); + // the new files are in the folder for good before anything lists them + store.sync()?; + check_list(&out.segments).map_err(corrupt)?; + if out.segments.iter().map(|s| s.photos).sum::() != photos.len() as u64 { + return Err(corrupt("the segments don't hold every photo".into())); + } + if verify { + // one segment at a time (not a second copy of every photo in memory at once) + for (k, segment) in out.segments.iter().enumerate() { + let read = read_segment(store, &out.segments, k)?; + let (lo, hi) = range(&out.segments, k); + let mut held = span(photos, lo, hi); + let same = read.iter().all(|(a, p)| { + held.next() + .is_some_and(|(b, q)| a == b && p == q && serde_json::to_string(p.as_ref()).ok() == serde_json::to_string(q.as_ref()).ok()) + }) && held.next().is_none(); + if !same { + return Err(corrupt(format!("{} doesn't read back as the catalog's photos", segment.name))); + } + } + } + Ok(()) + })(); + if let Err(e) = result { + if knows_its_files { + discard(store, &out.new); + } + return Err(e); + } + let kept: std::collections::BTreeSet<&str> = out.segments.iter().map(|s| s.name.as_str()).collect(); + out.obsolete = segments.iter().filter(|s| !kept.contains(s.name.as_str())).map(|s| s.name.clone()).collect(); + Ok(out) +} + +/// Remove segment files (ones that are not, or no longer, listed). Failing to is not an error: +/// what stays is removed when the library is next opened. +pub(crate) fn discard(store: &mut dyn Store, names: &[String]) { + for name in names { + if valid_name(name.strip_suffix(".tmp").unwrap_or(name)) + && let Err(e) = store.remove(name) + { + if e.kind() == std::io::ErrorKind::Unsupported { + // said once: such a store keeps every segment file it was ever given + static SAID: std::sync::Once = std::sync::Once::new(); + SAID.call_once(|| log::warn!("catalog: this store can't remove files; segment files that are no longer used stay in it")); + } else { + log::warn!("catalog: can't remove {name}: {e}"); + } + } + } +} + +/// How many segment files the store holds. A store that can't be listed is an error, not "none" +/// (it may hold a catalog's photos). +pub(crate) fn files(store: &mut dyn Store) -> std::io::Result { + Ok(store.list()?.iter().filter(|n| valid_name(n)).count()) +} + +/// Whether the files `names` are all in the store (true where it can't say: it lists nothing). +pub(crate) fn present(store: &mut dyn Store, names: &[String]) -> bool { + match store.list() { + Ok(held) if !held.is_empty() => { + let held: std::collections::BTreeSet<&str> = held.iter().map(String::as_str).collect(); + names.iter().all(|n| held.contains(n.as_str())) + } + _ => true, + } +} + +/// Remove the segment files in the library folder that `segments` doesn't list. +pub(crate) fn discard_unlisted(store: &mut dyn Store, segments: &[Segment]) { + let listed: std::collections::BTreeSet<&str> = segments.iter().map(|s| s.name.as_str()).collect(); + let unlisted: Vec = match store.list() { + // (and what a crash left of one being written: `.tmp`) + Ok(names) => names.into_iter().filter(|n| valid_name(n.strip_suffix(".tmp").unwrap_or(n)) && !listed.contains(n.as_str())).collect(), + Err(e) => { + log::warn!("catalog: can't list the library's files: {e}"); + return; + } + }; + discard(store, &unlisted); +} + +/// A segment list a snapshot may state: this module's file names, each once, in id order. +fn check_list(segments: &[Segment]) -> Result<(), String> { + let mut names = std::collections::BTreeSet::new(); + let mut last: Option = None; + for s in segments { + if !valid_name(&s.name) { + return Err(format!("{:?} is not a segment file", s.name)); + } + if !names.insert(s.name.as_str()) { + return Err(format!("{} is listed twice", s.name)); + } + if last.is_some_and(|l| s.first <= l) { + return Err(format!("{} is out of order", s.name)); + } + last = Some(s.first); + } + Ok(()) +} + +#[derive(Deserialize)] +struct SegmentFile { + format: String, + photos: Photos, +} + +/// Read and check one segment. +fn read_segment(store: &mut dyn Store, segments: &[Segment], k: usize) -> std::io::Result { + let Some(segment) = segments.get(k) else { return Ok(Photos::new()) }; + let name = &segment.name; + let bytes = + store.read(name).map_err(|e| std::io::Error::new(e.kind(), format!("{name}: {e}")))?.ok_or_else(|| corrupt(format!("{name} is missing")))?; + if bytes.len() as u64 != segment.bytes || crc32fast::hash(&bytes) != segment.crc { + return Err(corrupt(format!("{name} is damaged ({} bytes where the snapshot lists {})", bytes.len(), segment.bytes))); + } + let file: SegmentFile = serde_json::from_slice(&bytes).map_err(|e| corrupt(format!("{name}: {e}")))?; + if file.format != SEGMENT_FORMAT { + return Err(corrupt(format!("{name} is not a catalog segment (format {:?})", file.format))); + } + if file.photos.len() as u64 != segment.photos { + return Err(corrupt(format!("{name} holds {} photos where the snapshot lists {}", file.photos.len(), segment.photos))); + } + let next = segments.get(k + 1).map(|s| s.first); + if file.photos.keys().any(|id| *id < segment.first || next.is_some_and(|n| *id >= n)) { + return Err(corrupt(format!("{name} holds photos of another segment"))); + } + Ok(file.photos) +} + +/// Further handles on `store` to read `count` segments with at once (none when it gives none: +/// see [`Store::background_writer`]). +pub(crate) fn readers(store: &dyn Store, count: usize) -> Vec> { + let wanted = std::thread::available_parallelism().map_or(1, |n| n.get()).min(LOAD_THREADS).min(count / 2); + let mut handles = Vec::new(); + while handles.len() < wanted { + let Some(h) = store.background_writer() else { break }; + handles.push(h); + } + handles +} + +/// Read the photos of `segments`: on the threads of `handles` (see [`readers`]) when there are +/// two or more, else one after the other. Any segment that can't be read as listed is an error +/// naming it. +pub(crate) fn load(store: &mut dyn Store, handles: Vec>, segments: &[Segment]) -> std::io::Result { + check_list(segments).map_err(corrupt)?; + let mut parts: Vec>> = Vec::new(); + parts.resize_with(segments.len(), || None); + if handles.len() < 2 { + for (k, part) in parts.iter_mut().enumerate() { + *part = Some(read_segment(store, segments, k)); + } + } else { + let next = std::sync::atomic::AtomicUsize::new(0); + let done: std::sync::Mutex)>> = std::sync::Mutex::new(Vec::new()); + // (the library's own defaults, where its records are read over them: on every thread) + let over = crate::stored::reading_now(); + let work = |store: &mut dyn Store| { + let _over = crate::stored::reading_over(over.clone()); + loop { + let k = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if k >= segments.len() { + break; + } + let part = read_segment(store, segments, k); + done.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((k, part)); + } + }; + together(handles, store, &work); + for (k, part) in done.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner) { + if let Some(slot) = parts.get_mut(k) { + *slot = Some(part); + } + } + } + let mut photos = Photos::new(); + for (segment, part) in segments.iter().zip(parts) { + // (a thread that died leaves its segment unread) + let mut part = part.unwrap_or_else(|| Err(corrupt(format!("{} could not be read", segment.name))))?; + photos.append(&mut part); + } + Ok(photos) +} + +/// The index in `segments` of the segment that holds (or would hold) photo `id`. +pub(crate) fn segment_of(segments: &[Segment], id: PhotoId) -> Option { + if segments.is_empty() { + return None; + } + Some(segments.partition_point(|s| s.first <= id).saturating_sub(1)) +} diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index 2f3dc4912b4..a95747d1bd0 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -1,4 +1,4 @@ -//! Byte storage for the catalog files (`catalog.snap`, `catalog.log`). +//! Byte storage for the catalog files (`catalog.snap`, its segments in `segments/`, `catalog.log`). //! //! [`FsStore`] is the native implementation (a library directory); [`MemStore`] keeps files in //! memory (tests, ephemeral sessions) and lets tests simulate crashes by editing the bytes. A web @@ -28,6 +28,17 @@ pub trait Store: Send { self.write_atomic(name, &buf)?; Ok(buf.len() as u64) } + /// Write a file that doesn't exist yet, streamed like [`Store::write_atomic_with`]: its + /// content is durable when this returns, but its place in the folder need not be before + /// [`Store::sync`]. For writing several new files that only count once something else names + /// them (a snapshot's segments): one sync of the folder for all of them. + fn write_new_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result { + self.write_atomic_with(name, fill) + } + /// Make the files written with [`Store::write_new_with`] durable in the folder. + fn sync(&mut self) -> io::Result<()> { + Ok(()) + } /// Append and make durable (fsync) before returning. On an error, part of `data` may have /// been written (a full disk, a dropped network share): the journal cuts the file back to its /// previous length with [`Store::truncate`] before appending again. @@ -35,6 +46,29 @@ pub trait Store: Send { /// Cut a file to `len` bytes (drop a torn tail before appending again). A missing file is /// left missing. fn truncate(&mut self, name: &str, len: u64) -> io::Result<()>; + /// Remove a file (a missing one is not an error). The default can't: such a store keeps what + /// it was asked to remove. + fn remove(&mut self, name: &str) -> io::Result<()> { + let _ = name; + Err(io::Error::new(io::ErrorKind::Unsupported, "this store can't remove files")) + } + /// Whether the files an upgrade to a newer catalog format replaces are kept beside the + /// library (see [`crate::journal`] → *Format versions*): the way back to the build that wrote + /// them. `false` where there is no such build to go back to (the browser always runs the + /// newest one) and room is short. + fn keeps_replaced_formats(&self) -> bool { + true + } + /// The names of the files it holds. The default knows none. + fn list(&mut self) -> io::Result> { + Ok(Vec::new()) + } + /// Whether the catalog's photos can be kept in segment files of their own (see + /// [`crate::segments`]): the store can hold any number of files, list them and remove them. + /// The default can't, and its catalog stays in one file. + fn segmented(&self) -> bool { + false + } /// Human-readable location (diagnostics). fn describe(&self) -> String; /// Another handle on the same files that a worker thread can write `catalog.snap` through @@ -64,15 +98,85 @@ impl FsStore { fn path(&self, name: &str) -> PathBuf { self.dir.join(name) } + /// The folder a file is in: the library's, or the one its name states (`segments/…`). + fn folder_of(&self, name: &str) -> PathBuf { + self.path(name).parent().map_or_else(|| self.dir.clone(), Path::to_path_buf) + } + /// Make the folder's entries durable. Where a folder can't be opened to be synced (Windows, + /// where `rename` is journaled by NTFS anyway) nothing is asked of it; on POSIX a failure is + /// the caller's to know. + fn sync_folder_checked(folder: &Path) -> io::Result<()> { + #[cfg(windows)] + { + let _ = folder; + Ok(()) + } + #[cfg(not(windows))] + { + match std::fs::File::open(folder) { + Ok(d) => d.sync_all().or_else(ignore_unsyncable), + // (no such folder: nothing in it to make durable) + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), + Err(e) => ignore_unsyncable(e), + } + } + } + /// [`Self::sync_folder_checked`] where a failure changes nothing for the caller (the file is + /// written and renamed already; the entry's durability is best effort there). + fn sync_folder(folder: &Path) { + let _ = Self::sync_folder_checked(folder); + } fn sync_dir(&self) { - // Makes the rename durable on POSIX; opening a directory fails on Windows (where - // `rename` is already journaled by NTFS), so errors are ignored. - if let Ok(d) = std::fs::File::open(&self.dir) { - let _ = d.sync_all(); + Self::sync_folder(&self.dir); + } + /// Make sure the folder the file `name` goes into is there (the segments folder is made with + /// its first file). It has to be a folder of the library's own: a file of that name, or a + /// link to a folder elsewhere, is an error that says so. + fn folder_for(&self, name: &str) -> io::Result { + let folder = self.folder_of(name); + if folder == self.dir { + return Ok(folder); + } + match std::fs::symlink_metadata(&folder) { + Ok(m) if m.is_dir() => Ok(folder), + Ok(_) => Err(io::Error::other(format!("{} is not a folder", folder.display()))), + Err(e) if e.kind() == io::ErrorKind::NotFound => { + std::fs::create_dir_all(&folder).map_err(|e| io::Error::new(e.kind(), format!("{}: {e}", folder.display())))?; + // (the new folder's entry in the library folder must survive a crash too: once per library) + Self::sync_folder(&self.dir); + Ok(folder) + } + Err(e) => Err(io::Error::new(e.kind(), format!("{}: {e}", folder.display()))), } } } +/// A folder sync that failed because this file system can't sync folders (network and FUSE file +/// systems answer EINVAL, ENOTSUP or EBADF to fsync on a directory) is "can't be synced here", +/// as on Windows; anything else is a real I/O error. +#[cfg(not(windows))] +fn ignore_unsyncable(e: io::Error) -> io::Result<()> { + if unsyncable(&e) { Ok(()) } else { Err(e) } +} + +#[cfg(not(windows))] +fn unsyncable(e: &io::Error) -> bool { + use io::ErrorKind::{InvalidInput, NotFound, Unsupported}; + // (EBADF 9 and EINVAL 22 everywhere; "not supported" is a platform's own number: on Linux 95, + // on the BSDs and macOS 45, and on macOS also the kernel's EOPNOTSUPP 102, which is ENETRESET + // on Linux and must fail there) + let platform: &[i32] = if cfg!(any(target_os = "linux", target_os = "android")) { + &[95] + } else if cfg!(target_vendor = "apple") { + &[45, 102] + } else if cfg!(any(target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", target_os = "dragonfly")) { + &[45] + } else { + &[] + }; + matches!(e.kind(), InvalidInput | Unsupported | NotFound) || e.raw_os_error().is_some_and(|c| matches!(c, 9 | 22) || platform.contains(&c)) +} + /// A new staging file at `tmp`: whatever is already there (a leftover from a crashed save, or a link) is removed first /// (a link itself, never what it points to), then the file is created exclusively, so a write never follows a link /// planted at that name into another file (issue #1502). @@ -98,22 +202,42 @@ impl Store for FsStore { self.appender = None; } let tmp = self.path(&format!("{name}.tmp")); + let folder = self.folder_for(name)?; { let mut f = create_staging(&tmp)?; f.write_all(data)?; f.sync_all()?; } std::fs::rename(&tmp, self.path(name))?; - self.sync_dir(); + // (renamed already: a folder that can't be synced is no reason to say nothing was written) + Self::sync_folder(&folder); Ok(()) } fn write_atomic_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result { + let n = self.write_new_with(name, fill)?; + Self::sync_folder_checked(&self.folder_of(name))?; + Ok(n) + } + + fn sync(&mut self) -> io::Result<()> { + // (as `sync_dir`: where a folder can't be opened, renames are journaled anyway). The + // files written with `write_new_with` are the segments, in their folder; the library + // folder too, for that folder itself when it is new. + // A failure is the snapshot's: `catalog.snap` must not name segments whose entries may + // not survive a crash. + Self::sync_folder_checked(&self.dir.join(crate::segments::SEGMENT_DIR))?; + Self::sync_folder_checked(&self.dir) + } + + fn write_new_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result { use std::io::Write; if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } let tmp = self.path(&format!("{name}.tmp")); + // (a file in a folder of the library: the folder is made when its first file is) + self.folder_for(name)?; let written = (|| { let mut w = Counter { inner: io::BufWriter::with_capacity(1 << 20, create_staging(&tmp)?), n: 0 }; fill(&mut w)?; @@ -130,7 +254,6 @@ impl Store for FsStore { } }; std::fs::rename(&tmp, self.path(name))?; - self.sync_dir(); Ok(n) } @@ -169,6 +292,59 @@ impl Store for FsStore { f.sync_all() } + fn remove(&mut self, name: &str) -> io::Result<()> { + if self.appender.as_ref().is_some_and(|(n, _)| n == name) { + self.appender = None; + } + match std::fs::remove_file(self.path(name)) { + Ok(()) => Ok(()), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e), + } + } + + fn list(&mut self) -> io::Result> { + let mut names = Vec::new(); + for entry in std::fs::read_dir(&self.dir)? { + let entry = entry?; + if entry.file_type().is_ok_and(|t| t.is_file()) + && let Ok(name) = entry.file_name().into_string() + { + names.push(name); + } + } + // and the segments, by the names the catalog gives them (`segments/…`): in a folder of + // the library's own (a file of that name, or a link to a folder elsewhere, is an error: + // what is listed here may be removed) + let folder = self.dir.join(crate::segments::SEGMENT_DIR); + let named = |e: io::Error| io::Error::new(e.kind(), format!("{}: {e}", folder.display())); + match std::fs::symlink_metadata(&folder) { + Ok(m) if !m.is_dir() => return Err(io::Error::other(format!("{} is not a folder", folder.display()))), + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(names), + Err(e) => return Err(named(e)), + } + match std::fs::read_dir(&folder) { + Ok(entries) => { + for entry in entries { + let entry = entry?; + if entry.file_type().is_ok_and(|t| t.is_file()) + && let Ok(name) = entry.file_name().into_string() + { + names.push(format!("{}{name}", crate::segments::SEGMENT_PREFIX)); + } + } + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(named(e)), + } + Ok(names) + } + + fn segmented(&self) -> bool { + true + } + fn describe(&self) -> String { self.dir.display().to_string() } @@ -202,6 +378,9 @@ pub struct MemStore { pub files: Arc>>>, /// Offer a [`Store::background_writer`] (off by default: snapshots stay synchronous). pub background: bool, + /// Keep the catalog in one file, like a store that can't hold segments (see + /// [`Store::segmented`]; off by default). + pub single_file: bool, } impl MemStore { @@ -234,6 +413,16 @@ impl Store for MemStore { } Ok(()) } + fn remove(&mut self, name: &str) -> io::Result<()> { + self.files.lock().unwrap_or_else(|e| e.into_inner()).remove(name); + Ok(()) + } + fn list(&mut self) -> io::Result> { + Ok(self.files.lock().unwrap_or_else(|e| e.into_inner()).keys().cloned().collect()) + } + fn segmented(&self) -> bool { + !self.single_file + } fn describe(&self) -> String { "memory".into() } @@ -267,3 +456,31 @@ mod tests_staging { let _ = std::fs::remove_dir_all(&dir); } } + +#[cfg(all(test, not(windows)))] +mod tests_sync_errors { + use super::unsyncable; + use std::io::{Error, ErrorKind}; + + /// A file system that can't sync a folder (EINVAL, ENOTSUP, EBADF) does not fail a save; a + /// real I/O error (EIO, ENOSPC) does. + #[test] + fn only_real_io_errors_fail_a_folder_sync() { + for code in [9, 22] { + assert!(unsyncable(&Error::from_raw_os_error(code)), "{code}"); + } + #[cfg(target_os = "linux")] + { + assert!(unsyncable(&Error::from_raw_os_error(95))); + assert!(!unsyncable(&Error::from_raw_os_error(102)), "ENETRESET on Linux"); + } + #[cfg(target_vendor = "apple")] + for code in [45, 102] { + assert!(unsyncable(&Error::from_raw_os_error(code)), "{code}"); + } + assert!(unsyncable(&Error::from(ErrorKind::Unsupported)) && unsyncable(&Error::from(ErrorKind::InvalidInput))); + for code in [5, 28] { + assert!(!unsyncable(&Error::from_raw_os_error(code)), "{code}"); + } + } +} diff --git a/crates/catalog/src/stored.rs b/crates/catalog/src/stored.rs new file mode 100644 index 00000000000..6e1ea94bea4 --- /dev/null +++ b/crates/catalog/src/stored.rs @@ -0,0 +1,1056 @@ +//! The stored form of catalog records: what `catalog.snap` and `catalog.log` hold. +//! +//! A [`Photo`] has a **public form** (its `Serialize`: every field stated; what `catalog.query` +//! returns and what the Local browse fingerprint, [`Photo::fingerprint`], is made from) and this +//! **stored form**, which states only what was set: +//! +//! - fields of a photo and of its [`Meta`] that are empty, zero or unset are left out; +//! - develop settings (the photo's, and those of its history steps, versions and import look) are +//! stored as their difference from [`DevelopSettings::default`]: `{}` for an unedited photo. +//! +//! Most photos of a library are never edited or described, and their records were mostly +//! defaults: about 3.4 kB each, of which 2.6 kB the default develop settings. Reading needs +//! nothing of its own: both forms are read by the types' `Deserialize`, where a missing field +//! takes its default, so libraries with full records (catalog formats up to 6) load as they are. +//! +//! **Settings are never stored in a form that reads back differently.** A value is left out only +//! where leaving it out of the defaults reads back as the defaults. That is not so for `process`, +//! whose missing value means the first process, not the default one; nor for single fields of a +//! value that is read all or nothing (the crop's rectangle), which is left out as a whole or not +//! at all. And each difference is read back and compared before it is written; settings that +//! would not survive are stored in full. +//! +//! **A library says what its missing values read as.** A value equal to the default is not in +//! the file, so a default that changed in the code would change every photo relying on it. So +//! `catalog.snap` states them itself (`"defaults"`: [`base`], the settings a record with nothing +//! stated reads as in the build that wrote it), and they cover the log beside it. A build whose +//! own differ ([`reads_the_same`]) reads the library's settings over the library's defaults, not +//! over its own ([`reading_over`]), and then rewrites the library with its own. A build that only +//! has more settings than the library states reads it as it is: a setting the library never +//! heard of takes this build's default. +//! +//! That works where a setting is a value in a struct, which every setting is (a test reads every +//! one both ways), and because the library states every setting, also those the settings' own +//! JSON leaves out at their default ([`UNWRITTEN`]). What a missing value reads as in this build +//! is pinned by a test as well (`develop_defaults.json`), so a changed default is seen when it +//! is made; a setting that is removed or renamed needs a loader of its own. + +use std::collections::BTreeMap; +use std::sync::{Arc, OnceLock}; + +use lightcraft_develop::DevelopSettings; +use serde::ser::{SerializeMap, SerializeSeq}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde_json::Value; + +use crate::{ColorLabel, CopyrightStatus, Flag, HistoryStep, MediaKind, Meta, Photo, PhotoId, Source, Version}; + +// ---- develop settings + +/// What the stored form of settings is measured against. +struct Defaults { + settings: DevelopSettings, + /// The default settings, section by section (their top-level fields). + sections: BTreeMap, + /// The stored form of the defaults themselves: the values that must always be stated. + /// `None`: the defaults can't be told from their JSON at all, and settings are stored in full. + stored: Option, +} + +/// One top-level field of the default settings. +struct Section { + /// As JSON text: a section that serialises to the same text is the default one. + text: String, + value: Value, + rule: Rule, +} + +/// Whether a value of the settings may be left out when it equals the default. +#[derive(Default)] +struct Rule { + /// Leaving it out of the defaults (the whole value, when it is an object) reads back as the + /// defaults. + elide: bool, + /// An object's fields. + fields: BTreeMap, +} + +impl Rule { + /// The rule for the value at `path` of `full`, the JSON of `settings`. + fn of(full: &Value, settings: &DevelopSettings, path: &mut Vec) -> Rule { + let mut without = full.clone(); + let elide = !path.is_empty() && remove_at(&mut without, path) && reads_exactly_as(&without, settings); + let mut fields = BTreeMap::new(); + if let Some(Value::Object(m)) = path.iter().try_fold(full, |v, k| v.get(k)) { + for k in m.keys() { + path.push(k.clone()); + fields.insert(k.clone(), Rule::of(full, settings, path)); + path.pop(); + } + } + Rule { elide, fields } + } +} + +fn defaults() -> &'static Defaults { + static DEFAULTS: OnceLock = OnceLock::new(); + DEFAULTS.get_or_init(|| { + let settings = DevelopSettings::default(); + let full = serde_json::to_value(&settings).unwrap_or(Value::Null); + let Rule { mut fields, .. } = Rule::of(&full, &settings, &mut Vec::new()); + // each section's text as the settings serialise it (a `Value`'s text orders keys differently) + let texts = settings.serialize(Sections { d: None, text: Vec::new() }).map(|c| c.texts).unwrap_or_default(); + let mut sections = BTreeMap::new(); + if let Value::Object(m) = full { + for (key, value) in m { + if let (Some(rule), Some(text)) = (fields.remove(&key), texts.get(&key)) { + sections.insert(key, Section { text: text.clone(), value, rule }); + } + } + } + let mut d = Defaults { settings, sections, stored: None }; + d.stored = difference(&d.settings, &d).filter(|stored| reads_exactly_as(stored, &d.settings)); + if d.stored.is_none() { + // the values depend on each other in a way this can't see: leave nothing out + log::error!("catalog: develop defaults don't read back from their stored form; settings are stored in full"); + d.sections.clear(); + } + d + }) +} + +// ---- what a library's missing values read as + +/// The settings a record with nothing stated (`{}`) reads as in this build, as `catalog.snap` +/// states them (`"defaults"`): the JSON text, and its value. +/// +/// Every setting is stated, also the ones the settings' own JSON leaves out at their default +/// ([`UNWRITTEN`]): a record never states those at their default either, so a default of theirs +/// that changed would otherwise go unseen. +pub(crate) fn base() -> &'static (String, Value) { + static BASE: OnceLock<(String, Value)> = OnceLock::new(); + BASE.get_or_init(|| { + let settings = serde_json::from_str::("{}").unwrap_or_default(); + let mut v = serde_json::to_value(&settings).unwrap_or(Value::Null); + for (path, read) in UNWRITTEN { + state(&mut v, path, read(&settings)); + } + (v.to_string(), v) + }) +} + +/// A setting's value in `settings`, as JSON. +type Stated = fn(&DevelopSettings) -> Value; + +/// The settings whose JSON is left out at their default (`skip_serializing_if`), and what each +/// is: [`base`] states them all the same. A test holds that these are all of them, but for the +/// rendering process: a record without one is on the first process in every build (a missing +/// process never means "the default one"), so there is no default of it to state. +pub(crate) const UNWRITTEN: [(&[&str], Stated); 4] = [ + (&["wb", "scale"], |s| serde_json::to_value(s.wb.scale).unwrap_or(Value::Null)), + (&["hdr"], |s| serde_json::to_value(s.hdr).unwrap_or(Value::Null)), + (&["profile", "camera_local_tone"], |s| Value::Bool(s.profile.camera_local_tone)), + (&["enhance", "denoise_on"], |s| serde_json::to_value(s.enhance.denoise_on).unwrap_or(Value::Null)), +]; + +/// Put `value` at `path` of `v` (through objects that are there). +fn state(v: &mut Value, path: &[&str], value: Value) { + let Some((last, parents)) = path.split_last() else { return }; + let mut at = v; + for k in parents { + let Some(next) = at.get_mut(*k) else { return }; + at = next; + } + if let Some(m) = at.as_object_mut() { + m.insert((*last).to_string(), value); + } +} + +/// Whether a library that states `theirs` as its defaults reads the same over this build's: +/// every setting both know has the same default. A setting only this build knows takes this +/// build's default (the library never heard of it); one only the library knows is not read by +/// this build, whatever it is read over. +pub(crate) fn reads_the_same(theirs: &Value) -> bool { + fn agree(theirs: &Value, ours: &Value) -> bool { + match (theirs, ours) { + (Value::Object(t), Value::Object(o)) => t.iter().all(|(k, x)| o.get(k).is_none_or(|y| agree(x, y))), + _ => same(theirs, ours), + } + } + agree(theirs, &base().1) +} + +thread_local! { + /// The defaults of the library being read on this thread, where they are not this build's. + static READING_OVER: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + +/// While it lives, settings read on this thread are read over these defaults (see +/// [`reading_over`]). +pub(crate) struct ReadingOver(Option>); + +impl Drop for ReadingOver { + fn drop(&mut self) { + let before = self.0.take(); + // (a thread shutting down has nothing left to read) + let _ = READING_OVER.try_with(|over| *over.borrow_mut() = before); + } +} + +/// Read the settings of a library that states `defaults` as its own: until the returned guard +/// is dropped, a value a record leaves out on this thread reads as the library's, not as this +/// build's. `None`: as this build's (the usual case, and what reading costs nothing for). +pub(crate) fn reading_over(defaults: Option>) -> ReadingOver { + ReadingOver(READING_OVER.try_with(|over| over.replace(defaults)).unwrap_or(None)) +} + +/// The defaults settings are being read over on this thread ([`reading_over`]), to read the +/// same library on other threads as well. +pub(crate) fn reading_now() -> Option> { + READING_OVER.try_with(|over| over.borrow().clone()).unwrap_or(None) +} + +/// Give `v` every value of `defaults` it leaves out, object by object: the reverse of [`strip`]. +fn fill(v: &mut Value, defaults: &Value) { + let (Value::Object(m), Value::Object(d)) = (v, defaults) else { return }; + for (k, x) in d { + match m.get_mut(k) { + Some(mine) => fill(mine, x), + None => { + m.insert(k.clone(), x.clone()); + } + } + } +} + +/// `deserialize_with` for settings in a saved record: over the defaults of the library being +/// read, where those are not this build's ([`reading_over`]). +pub(crate) fn read_settings<'de, D: Deserializer<'de>>(d: D) -> Result, D::Error> { + let Some(defaults) = reading_now() else { return Arc::::deserialize(d) }; + let mut v = Value::deserialize(d)?; + fill(&mut v, &defaults); + DevelopSettings::deserialize(v).map(Arc::new).map_err(serde::de::Error::custom) +} + +/// [`read_settings`] for settings that may not be there. +pub(crate) fn read_optional_settings<'de, D: Deserializer<'de>>(d: D) -> Result>, D::Error> { + #[derive(Deserialize)] + struct Read(#[serde(deserialize_with = "read_settings")] Arc); + Ok(Option::::deserialize(d)?.map(|r| r.0)) +} + +/// Remove the value at `path`; whether there was one. +fn remove_at(v: &mut Value, path: &[String]) -> bool { + let Some((last, parents)) = path.split_last() else { return false }; + let mut at = v; + for k in parents { + let Some(next) = at.get_mut(k) else { return false }; + at = next; + } + at.as_object_mut().is_some_and(|m| m.remove(last).is_some()) +} + +/// The same JSON value, also telling `-0.0` from `0.0` (which `Value`'s own comparison doesn't). +fn same(a: &Value, b: &Value) -> bool { + match (a, b) { + (Value::Number(x), Value::Number(y)) => match (x.as_f64(), y.as_f64()) { + (Some(p), Some(q)) if x.is_f64() || y.is_f64() => x.is_f64() == y.is_f64() && p.to_bits() == q.to_bits(), + _ => x == y, + }, + (Value::Array(x), Value::Array(y)) => x.len() == y.len() && x.iter().zip(y).all(|(p, q)| same(p, q)), + (Value::Object(x), Value::Object(y)) => x.len() == y.len() && x.iter().all(|(k, p)| y.get(k).is_some_and(|q| same(p, q))), + _ => a == b, + } +} + +/// Remove from `v` every value that is the one `base` (the defaults) has there, where `rule` +/// lets it be left out; objects are gone through field by field. An object that differs stays, +/// even when nothing of it is left. +fn strip(v: &mut Value, base: &Value, rule: &Rule) { + let (Value::Object(m), Value::Object(b)) = (v, base) else { return }; + m.retain(|k, x| { + let (Some(d), Some(r)) = (b.get(k), rule.fields.get(k)) else { return true }; + if r.elide && same(x, d) { + return false; + } + strip(x, d, r); + true + }); +} + +/// `v` reads as `settings`. (`==` takes -0.0 for 0.0: what is left out is chosen by [`same`] +/// and by JSON text, which don't, so a zero's sign is never what differs here.) +fn reads_as(v: &Value, settings: &DevelopSettings) -> bool { + DevelopSettings::deserialize(v).is_ok_and(|read| read == *settings) +} + +/// `v` reads as `settings` down to their JSON text. Costs a serialisation each: for working out +/// the rules once, not for every write. +fn reads_exactly_as(v: &Value, settings: &DevelopSettings) -> bool { + DevelopSettings::deserialize(v).is_ok_and(|read| read == *settings && serde_json::to_string(&read).ok() == serde_json::to_string(settings).ok()) +} + +/// Whether any number in `v` is -0.0. +fn has_negative_zero(v: &T) -> bool { + let mut scan = NegativeZero(false); + // (an error only says the walk stopped: when in doubt, it has one) + v.serialize(&mut scan).is_err() || scan.0 +} + +/// Walks a value for [`has_negative_zero`] (no text, no allocation). +struct NegativeZero(bool); + +impl NegativeZero { + fn see(&mut self, x: f64) { + self.0 |= x == 0.0 && x.is_sign_negative(); + } +} + +impl Serializer for &mut NegativeZero { + type Ok = (); + type Error = std::fmt::Error; + type SerializeSeq = Self; + type SerializeTuple = Self; + type SerializeTupleStruct = Self; + type SerializeTupleVariant = Self; + type SerializeMap = Self; + type SerializeStruct = Self; + type SerializeStructVariant = Self; + + fn serialize_f32(self, v: f32) -> Result<(), Self::Error> { + self.see(f64::from(v)); + Ok(()) + } + fn serialize_f64(self, v: f64) -> Result<(), Self::Error> { + self.see(v); + Ok(()) + } + fn serialize_bool(self, _: bool) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_i8(self, _: i8) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_i16(self, _: i16) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_i32(self, _: i32) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_i64(self, _: i64) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_u8(self, _: u8) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_u16(self, _: u16) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_u32(self, _: u32) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_u64(self, _: u64) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_char(self, _: char) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_str(self, _: &str) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_bytes(self, _: &[u8]) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_none(self) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_some(self, v: &T) -> Result<(), Self::Error> { + v.serialize(self) + } + fn serialize_unit(self) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_unit_struct(self, _: &'static str) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_newtype_struct(self, _: &'static str, v: &T) -> Result<(), Self::Error> { + v.serialize(self) + } + fn serialize_newtype_variant(self, _: &'static str, _: u32, _: &'static str, v: &T) -> Result<(), Self::Error> { + v.serialize(self) + } + fn serialize_seq(self, _: Option) -> Result { + Ok(self) + } + fn serialize_tuple(self, _: usize) -> Result { + Ok(self) + } + fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result { + Ok(self) + } + fn serialize_tuple_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result { + Ok(self) + } + fn serialize_map(self, _: Option) -> Result { + Ok(self) + } + fn serialize_struct(self, _: &'static str, _: usize) -> Result { + Ok(self) + } + fn serialize_struct_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result { + Ok(self) + } +} + +impl serde::ser::SerializeSeq for &mut NegativeZero { + type Ok = (); + type Error = std::fmt::Error; + fn serialize_element(&mut self, v: &T) -> Result<(), Self::Error> { + v.serialize(&mut **self) + } + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +impl serde::ser::SerializeTuple for &mut NegativeZero { + type Ok = (); + type Error = std::fmt::Error; + fn serialize_element(&mut self, v: &T) -> Result<(), Self::Error> { + v.serialize(&mut **self) + } + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +impl serde::ser::SerializeTupleStruct for &mut NegativeZero { + type Ok = (); + type Error = std::fmt::Error; + fn serialize_field(&mut self, v: &T) -> Result<(), Self::Error> { + v.serialize(&mut **self) + } + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +impl serde::ser::SerializeTupleVariant for &mut NegativeZero { + type Ok = (); + type Error = std::fmt::Error; + fn serialize_field(&mut self, v: &T) -> Result<(), Self::Error> { + v.serialize(&mut **self) + } + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +impl SerializeMap for &mut NegativeZero { + type Ok = (); + type Error = std::fmt::Error; + fn serialize_key(&mut self, _: &T) -> Result<(), Self::Error> { + Ok(()) + } + fn serialize_value(&mut self, v: &T) -> Result<(), Self::Error> { + v.serialize(&mut **self) + } + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +impl serde::ser::SerializeStruct for &mut NegativeZero { + type Ok = (); + type Error = std::fmt::Error; + fn serialize_field(&mut self, _: &'static str, v: &T) -> Result<(), Self::Error> { + v.serialize(&mut **self) + } + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +impl serde::ser::SerializeStructVariant for &mut NegativeZero { + type Ok = (); + type Error = std::fmt::Error; + fn serialize_field(&mut self, _: &'static str, v: &T) -> Result<(), Self::Error> { + v.serialize(&mut **self) + } + fn end(self) -> Result<(), Self::Error> { + Ok(()) + } +} + +/// The stored form of `settings`: its difference from the defaults, or `None` when that would +/// not read back as `settings` (then they are stored in full). +fn difference(settings: &DevelopSettings, d: &Defaults) -> Option { + let v = Value::Object(settings.serialize(Sections { d: Some(d), text: Vec::new() }).ok()?.differing); + reads_as(&v, settings).then_some(v) +} + +/// Collects the sections of settings that differ from the defaults, each as what differs in it. +/// Settings are a struct of sections; most sections of most photos are the default ones, and +/// those are recognised by their JSON text, without building a value for them. +/// +/// Without defaults to compare with (`d` is `None`: while they are being worked out), collects +/// every section's JSON text instead. +struct Sections<'d> { + d: Option<&'d Defaults>, + /// Scratch space for a section's JSON text. + text: Vec, +} + +#[derive(Default)] +struct Collected { + /// The sections that differ from the defaults, as what differs in them. + differing: serde_json::Map, + /// Every section's JSON text (only without defaults to compare with). + texts: BTreeMap, +} + +struct SectionFields<'d> { + d: Option<&'d Defaults>, + text: Vec, + out: Collected, +} + +impl serde::ser::SerializeStruct for SectionFields<'_> { + type Ok = Collected; + type Error = serde_json::Error; + + fn serialize_field(&mut self, key: &'static str, value: &T) -> Result<(), Self::Error> { + let Some(d) = self.d else { + self.out.texts.insert(key.to_owned(), serde_json::to_string(value)?); + return Ok(()); + }; + let Some(section) = d.sections.get(key) else { + // not among the defaults (left out of them: the rendering process, HDR…): as it is + self.out.differing.insert(key.to_owned(), serde_json::to_value(value)?); + return Ok(()); + }; + self.text.clear(); + serde_json::to_writer(&mut self.text, value)?; + if section.rule.elide && self.text == section.text.as_bytes() { + return Ok(()); + } + let mut v = serde_json::to_value(value)?; + strip(&mut v, §ion.value, §ion.rule); + self.out.differing.insert(key.to_owned(), v); + Ok(()) + } + + fn end(self) -> Result { + Ok(self.out) + } +} + +/// Only a struct has sections. +fn not_a_struct() -> Result { + Err(serde::ser::Error::custom("settings are not a struct")) +} + +type No = serde::ser::Impossible; + +impl<'d> Serializer for Sections<'d> { + type Ok = Collected; + type Error = serde_json::Error; + type SerializeSeq = No; + type SerializeTuple = No; + type SerializeTupleStruct = No; + type SerializeTupleVariant = No; + type SerializeMap = No; + type SerializeStruct = SectionFields<'d>; + type SerializeStructVariant = No; + + fn serialize_struct(self, _: &'static str, _: usize) -> Result { + Ok(SectionFields { d: self.d, text: self.text, out: Collected::default() }) + } + + fn serialize_bool(self, _: bool) -> Result { + not_a_struct() + } + fn serialize_i8(self, _: i8) -> Result { + not_a_struct() + } + fn serialize_i16(self, _: i16) -> Result { + not_a_struct() + } + fn serialize_i32(self, _: i32) -> Result { + not_a_struct() + } + fn serialize_i64(self, _: i64) -> Result { + not_a_struct() + } + fn serialize_u8(self, _: u8) -> Result { + not_a_struct() + } + fn serialize_u16(self, _: u16) -> Result { + not_a_struct() + } + fn serialize_u32(self, _: u32) -> Result { + not_a_struct() + } + fn serialize_u64(self, _: u64) -> Result { + not_a_struct() + } + fn serialize_f32(self, _: f32) -> Result { + not_a_struct() + } + fn serialize_f64(self, _: f64) -> Result { + not_a_struct() + } + fn serialize_char(self, _: char) -> Result { + not_a_struct() + } + fn serialize_str(self, _: &str) -> Result { + not_a_struct() + } + fn serialize_bytes(self, _: &[u8]) -> Result { + not_a_struct() + } + fn serialize_none(self) -> Result { + not_a_struct() + } + fn serialize_some(self, _: &T) -> Result { + not_a_struct() + } + fn serialize_unit(self) -> Result { + not_a_struct() + } + fn serialize_unit_struct(self, _: &'static str) -> Result { + not_a_struct() + } + fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Result { + not_a_struct() + } + fn serialize_newtype_struct(self, _: &'static str, _: &T) -> Result { + not_a_struct() + } + fn serialize_newtype_variant(self, _: &'static str, _: u32, _: &'static str, _: &T) -> Result { + not_a_struct() + } + fn serialize_seq(self, _: Option) -> Result { + not_a_struct() + } + fn serialize_tuple(self, _: usize) -> Result { + not_a_struct() + } + fn serialize_tuple_struct(self, _: &'static str, _: usize) -> Result { + not_a_struct() + } + fn serialize_tuple_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result { + not_a_struct() + } + fn serialize_map(self, _: Option) -> Result { + not_a_struct() + } + fn serialize_struct_variant(self, _: &'static str, _: u32, _: &'static str, _: usize) -> Result { + not_a_struct() + } +} + +/// Develop settings in their stored form. +struct StoredSettings<'a>(&'a DevelopSettings); + +impl Serialize for StoredSettings<'_> { + fn serialize(&self, s: S) -> Result { + let d = defaults(); + // `==` takes -0.0 for 0.0, which their JSON (and so a photo's fingerprint and the preview + // cache key made from it) tells apart: settings with a negative zero are never taken for + // other settings equal to them + let negative_zero = std::cell::OnceCell::new(); + let no_negative_zero = || !*negative_zero.get_or_init(|| has_negative_zero(self.0)); + let exactly = |other: &DevelopSettings| *self.0 == *other && no_negative_zero(); + if exactly(&d.settings) + && let Some(stored) = &d.stored + { + return stored.serialize(s); + } + // Photos that were never edited often share their settings (a camera's import defaults): + // the last difference worked out is kept for the next settings equal to those. + thread_local! { + static LAST: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + } + // (a serializer can only be used once: it goes in and out of the closure in a cell) + let s = std::cell::Cell::new(Some(s)); + let stored = LAST.try_with(|last| { + let mut last = last.try_borrow_mut().ok()?; + if !last.as_ref().is_some_and(|(of, _)| exactly(of)) { + let v = difference(self.0, d)?; + if !no_negative_zero() { + // (not kept: it can't be taken for equal settings later) + return Some(v.serialize(s.take()?)); + } + *last = Some((self.0.clone(), v)); + } + let (_, v) = last.as_ref()?; + Some(v.serialize(s.take()?)) + }); + match (stored, s.take()) { + (Ok(Some(done)), _) => done, + // no difference that reads back, or the cache can't be used (a thread shutting down) + (_, Some(s)) => match difference(self.0, d) { + Some(v) => v.serialize(s), + None => self.0.serialize(s), + }, + (_, None) => Err(serde::ser::Error::custom("develop settings: the serializer was lost")), + } + } +} + +/// `serialize_with` for settings in an [`crate::Op`]. +pub(crate) fn settings(v: &Arc, s: S) -> Result { + StoredSettings(v).serialize(s) +} + +#[derive(Serialize)] +struct StoredStep<'a> { + label: &'a str, + settings: StoredSettings<'a>, +} + +impl<'a> StoredStep<'a> { + fn of(step: &'a HistoryStep) -> Self { + let HistoryStep { label, settings } = step; + StoredStep { label, settings: StoredSettings(settings) } + } +} + +#[derive(Serialize)] +struct StoredVersion<'a> { + name: &'a str, + created: &'a str, + settings: StoredSettings<'a>, + auto: bool, +} + +impl<'a> StoredVersion<'a> { + fn of(version: &'a Version) -> Self { + let Version { name, created, settings, auto } = version; + StoredVersion { name, created, settings: StoredSettings(settings), auto: *auto } + } +} + +/// A list in its stored form. +struct StoredList<'a, T, R>(&'a [T], fn(&'a T) -> R); + +impl Serialize for StoredList<'_, T, R> { + fn serialize(&self, s: S) -> Result { + let mut seq = s.serialize_seq(Some(self.0.len()))?; + for item in self.0 { + seq.serialize_element(&(self.1)(item))?; + } + seq.end() + } +} + +/// `serialize_with` for a history step in an [`crate::Op`]. +pub(crate) fn step(v: &HistoryStep, s: S) -> Result { + StoredStep::of(v).serialize(s) +} + +/// `serialize_with` for a history in an [`crate::Op`]. +pub(crate) fn history(v: &[HistoryStep], s: S) -> Result { + StoredList(v, StoredStep::of).serialize(s) +} + +/// `serialize_with` for versions in an [`crate::Op`]. +pub(crate) fn versions(v: &[Version], s: S) -> Result { + StoredList(v, StoredVersion::of).serialize(s) +} + +// ---- metadata + +fn no(v: &T) -> bool { + *v == T::default() +} + +/// [`Meta`] in its stored form: the fields that say something. +struct StoredMeta<'a>(&'a Meta); + +impl StoredMeta<'_> { + fn is_empty(&self) -> bool { + *self.0 == Meta::default() + } +} + +impl Serialize for StoredMeta<'_> { + fn serialize(&self, s: S) -> Result { + #[derive(Serialize)] + struct Fields<'a> { + #[serde(skip_serializing_if = "str::is_empty")] + camera: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + lens: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + focal_mm: Option, + #[serde(skip_serializing_if = "Option::is_none")] + aperture: Option, + #[serde(skip_serializing_if = "str::is_empty")] + shutter: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + iso: Option, + #[serde(skip_serializing_if = "str::is_empty")] + location: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + city: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + state: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + country: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + gps: Option<(f64, f64)>, + #[serde(skip_serializing_if = "str::is_empty")] + title: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + caption: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + alt_text: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + extended_description: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + copyright: &'a str, + #[serde(skip_serializing_if = "CopyrightStatus::is_unknown")] + copyright_status: CopyrightStatus, + #[serde(skip_serializing_if = "str::is_empty")] + usage_terms: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + copyright_url: &'a str, + #[serde(skip_serializing_if = "str::is_empty")] + creator: &'a str, + #[serde(skip_serializing_if = "<[String]>::is_empty")] + keywords: &'a [String], + #[serde(skip_serializing_if = "<[lightcraft_meta::Region]>::is_empty")] + regions: &'a [lightcraft_meta::Region], + #[serde(skip_serializing_if = "Option::is_none")] + focus: &'a Option, + } + // every field by name: a new one doesn't compile until it has a stored form + let Meta { + camera, + lens, + focal_mm, + aperture, + shutter, + iso, + location, + city, + state, + country, + gps, + title, + caption, + alt_text, + extended_description, + copyright, + copyright_status, + usage_terms, + copyright_url, + creator, + keywords, + regions, + focus, + } = self.0; + Fields { + camera, + lens, + focal_mm: *focal_mm, + aperture: *aperture, + shutter, + iso: *iso, + location, + city, + state, + country, + gps: *gps, + title, + caption, + alt_text, + extended_description, + copyright, + copyright_status: *copyright_status, + usage_terms, + copyright_url, + creator, + keywords, + regions, + focus, + } + .serialize(s) + } +} + +/// `serialize_with` for metadata in an [`crate::Op`]. +pub(crate) fn meta(v: &Meta, s: S) -> Result { + StoredMeta(v).serialize(s) +} + +// ---- photos + +/// A [`Photo`] in its stored form. +struct StoredPhoto<'a>(&'a Photo); + +impl Serialize for StoredPhoto<'_> { + fn serialize(&self, s: S) -> Result { + #[derive(Serialize)] + struct Fields<'a, H: Serialize, V: Serialize> { + id: PhotoId, + source: &'a Source, + file_name: &'a str, + #[serde(skip_serializing_if = "no")] + kind: MediaKind, + format: &'a str, + width: u32, + height: u32, + #[serde(skip_serializing_if = "no")] + file_size: u64, + #[serde(skip_serializing_if = "Option::is_none")] + captured: Option<&'a str>, + imported: &'a str, + #[serde(skip_serializing_if = "StoredMeta::is_empty")] + meta: StoredMeta<'a>, + #[serde(skip_serializing_if = "no")] + rating: u8, + #[serde(skip_serializing_if = "no")] + flag: Flag, + #[serde(skip_serializing_if = "Option::is_none")] + label: Option, + develop: StoredSettings<'a>, + #[serde(skip_serializing_if = "Option::is_none")] + edited: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + versions: Option, + #[serde(skip_serializing_if = "Option::is_none")] + history: Option, + #[serde(skip_serializing_if = "Option::is_none")] + history_cursor: Option, + #[serde(skip_serializing_if = "no")] + deleted: bool, + #[serde(skip_serializing_if = "no")] + local: bool, + #[serde(skip_serializing_if = "Option::is_none")] + duration: Option, + #[serde(skip_serializing_if = "Option::is_none")] + as_shot_wb: Option<(f64, f64)>, + #[serde(skip_serializing_if = "Option::is_none")] + content_hash: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + embedded_lens: &'a Option, + #[serde(skip_serializing_if = "Option::is_none")] + copy_of: Option, + #[serde(skip_serializing_if = "Option::is_none")] + copy_name: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + import_look: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + analysis: &'a Option, + #[serde(skip_serializing_if = "Option::is_none")] + preview_only: Option<&'a str>, + #[serde(skip_serializing_if = "str::is_empty")] + preview_checked: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + local_baseline: Option, + } + // every field by name: a new one doesn't compile until it has a stored form + let Photo { + id, + source, + file_name, + kind, + format, + width, + height, + file_size, + captured, + imported, + meta, + rating, + flag, + label, + develop, + edited, + versions, + history, + history_cursor, + deleted, + local, + duration, + as_shot_wb, + content_hash, + embedded_lens, + copy_of, + copy_name, + import_look, + analysis, + preview_only, + preview_checked, + local_baseline, + } = self.0; + Fields { + id: *id, + source, + file_name, + kind: *kind, + format, + width: *width, + height: *height, + file_size: *file_size, + captured: captured.as_deref(), + imported, + meta: StoredMeta(meta), + rating: *rating, + flag: *flag, + label: *label, + develop: StoredSettings(develop), + edited: edited.as_deref(), + versions: (!versions.is_empty()).then_some(StoredList(versions.as_slice(), StoredVersion::of)), + history: (!history.is_empty()).then_some(StoredList(history.as_slice(), StoredStep::of)), + history_cursor: *history_cursor, + deleted: *deleted, + local: *local, + duration: *duration, + as_shot_wb: *as_shot_wb, + content_hash: content_hash.as_deref(), + embedded_lens, + copy_of: *copy_of, + copy_name: copy_name.as_deref(), + import_look: import_look.as_deref().map(StoredSettings), + analysis, + preview_only: preview_only.as_deref(), + preview_checked, + local_baseline: *local_baseline, + } + .serialize(s) + } +} + +/// `serialize_with` for the photo of an [`crate::Op`]. +pub(crate) fn photo(v: &Photo, s: S) -> Result { + StoredPhoto(v).serialize(s) +} + +/// `serialize_with` for the catalog's photos. +pub(crate) fn photos(v: &BTreeMap>, s: S) -> Result { + let mut map = s.serialize_map(Some(v.len()))?; + for (id, p) in v { + map.serialize_entry(id, &StoredPhoto(p))?; + } + map.end() +} + +/// A run of the catalog's photos in their stored form (a segment's). +pub(crate) struct PhotoRange<'a>(pub std::collections::btree_map::Range<'a, PhotoId, Arc>); + +impl Serialize for PhotoRange<'_> { + fn serialize(&self, s: S) -> Result { + let mut map = s.serialize_map(None)?; + for (id, p) in self.0.clone() { + map.serialize_entry(id, &StoredPhoto(p))?; + } + map.end() + } +} diff --git a/crates/catalog/src/tests_background.rs b/crates/catalog/src/tests_background.rs index 5235c3e1712..3b34335d9e3 100644 --- a/crates/catalog/src/tests_background.rs +++ b/crates/catalog/src/tests_background.rs @@ -72,6 +72,16 @@ impl Store for Gated { fn describe(&self) -> String { "gated".into() } + // (a folder's layout: the photos in segments) + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.files.remove(name) + } + fn list(&mut self) -> std::io::Result> { + self.files.list() + } + fn segmented(&self) -> bool { + true + } fn background_writer(&self) -> Option> { Some(Box::new(self.clone())) } @@ -168,7 +178,7 @@ fn background_snapshot_keeps_edits_made_while_it_runs() { fn failed_background_snapshot_loses_nothing_and_retries_later() { let g = Gated::new(); let (mut j, mut live, _) = Journal::open(Box::new(g.clone())).unwrap(); - j.policy = SnapshotPolicy { max_records: 10, max_bytes: u64::MAX }; + j.policy = SnapshotPolicy { max_records: 10, max_bytes: u64::MAX, snapshot_share: 0, ..Default::default() }; for k in 0..12 { edit(&mut j, &mut live, k); } diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index e31d7fe0c49..2c1e72fea9c 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -1,7 +1,7 @@ //! Issue #102: catalog format versions. Older formats load and are upgraded; a newer format is //! refused with a clear error and left untouched (never read in part, truncated or set aside). -use crate::journal::{LOG, SNAPSHOT, VERSION, encode_record}; +use crate::journal::{FORMATS, LOG, SNAPSHOT, VERSION, encode_record}; use crate::*; fn photo(c: &mut Catalog) -> Op { @@ -238,8 +238,324 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`. - const NEWEST_FIELDS: u32 = 9; + // (formats 9 to 11 added no op: 9 added fields, 10 changed how records are stored, + // `crate::stored`, and 11 where, `crate::segments`) 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"); + // the newest format in this build that adds an op is the newest op's, and says so + let adds_an_op = crate::journal::newest_op_format(FORMATS).expect("a format adds an op"); + assert_eq!(adds_an_op.version, newest, "the newest op's format is the newest row of FORMATS that adds one: {adds_an_op:?}"); + assert!(adds_an_op.adds.contains("Op::SetHistoryCursor"), "{adds_an_op:?}"); +} + +/// A format that only adds a field may name the op that carries it ("`Op::SetContent`'s `preview_checked`", as #974 +/// does): which formats add an op is each row's own flag ([`crate::journal::Format::adds_op`]), never its wording. +#[test] +fn a_format_that_only_adds_a_field_may_name_an_op() { + use crate::journal::{Format, newest_op_format}; + let row = |version, adds, adds_op| Format { version, written_by: "a build", adds, adds_op, here: true }; + let formats = [row(1, "", false), row(2, "`Op::SetBrowsed`", true), row(3, "`Op::SetContent`'s `preview_checked`", false)]; + assert_eq!(newest_op_format(&formats).map(|f| f.version), Some(2), "format 3 adds a field, whatever it names"); +} + +/// Given the list of catalog formats, then each row that says it adds an op names the op it adds: the flag and the +/// words don't part. +#[test] +fn a_format_that_adds_an_op_names_it() { + for f in FORMATS.iter().filter(|f| f.adds_op) { + assert!(f.adds.contains("`Op::"), "format {} adds an op: its row names it ({:?})", f.version, f.adds); + } +} + +/// Given the list of catalog formats, then each number is there once, in order and without a +/// gap, and the newest one is what this build writes: a number never means two formats. +#[test] +fn a_format_number_means_one_format() { + let numbers: Vec = FORMATS.iter().map(|f| f.version).collect(); + assert_eq!(numbers, (1..=VERSION).collect::>()); + assert!(FORMATS.last().unwrap().here, "this build writes the newest format"); +} + +/// The library a format's fixture holds (`fixtures/v-…`, written by the build of format `N`): +/// its files, by their names in the library. +fn fixture(version: u32) -> Option> { + match version { + 6 => Some(vec![(SNAPSHOT, include_str!("fixtures/v6-catalog.snap.json")), (LOG, include_str!("fixtures/v6-catalog.log.jsonl"))]), + 7 => Some(vec![(SNAPSHOT, include_str!("fixtures/v7-catalog.snap.json")), (LOG, include_str!("fixtures/v7-catalog.log.jsonl"))]), + 8 => Some(vec![(SNAPSHOT, include_str!("fixtures/v8-catalog.snap.json")), (LOG, include_str!("fixtures/v8-catalog.log.jsonl"))]), + 9 => Some(vec![(SNAPSHOT, include_str!("fixtures/v9-catalog.snap.json")), (LOG, include_str!("fixtures/v9-catalog.log.jsonl"))]), + 10 => Some(vec![(SNAPSHOT, include_str!("fixtures/v10-catalog.snap.json")), (LOG, include_str!("fixtures/v10-catalog.log.jsonl"))]), + // (in segments, which is what format 11 adds) + 11 => Some(vec![ + (SNAPSHOT, include_str!("fixtures/v11-catalog.snap.json")), + (LOG, include_str!("fixtures/v11-catalog.log.jsonl")), + ("segments/7-3.json", include_str!("fixtures/v11-segments-7-3.json")), + ]), + _ => None, + } +} + +/// A fixture's files in a store. +fn store_of(files: &[(&'static str, &'static str)]) -> MemStore { + let m = MemStore::new(); + for (name, content) in files { + m.set(name, content.as_bytes().to_vec()); + } + m +} + +/// Given a library written by the build of each format from 6 on (its fixture), when this build +/// opens it, then it reads as that library and is left in this build's format. A format whose +/// change is not in this build yet has no fixture here; every other one must have its own. +#[test] +fn every_format_has_a_fixture_that_opens_as_it_was() { + for f in FORMATS.iter().filter(|f| f.version >= 6) { + let expected = crate::tests_stored::fixture_library(f.version); + let Some(files) = fixture(f.version) else { + assert!(!f.here, "format {} has no fixture (tests_stored::write_this_formats_fixture writes it)", f.version); + continue; + }; + assert!(f.here, "format {} has a fixture: it is in this build", f.version); + let snap = files.iter().find(|(name, _)| *name == SNAPSHOT).map(|(_, snap)| *snap).expect("a snapshot"); + assert!(snap.starts_with(&format!("{{\"format\":\"lightcraft-catalog\",\"version\":{},", f.version)), "v{}", f.version); + let m = store_of(&files); + let (_, mut loaded, r) = Journal::open(Box::new(m.clone())).unwrap(); + loaded.revision = expected.revision; + assert_eq!(loaded, expected, "v{}", f.version); + assert_eq!((r.failed, r.upgraded_from), (0, (f.version != VERSION).then_some(f.version)), "v{}", f.version); + assert_eq!(snapshot_version(&m), u64::from(VERSION), "v{}", f.version); + } + // the format that put the photos in segments has a fixture that is in segments + let v11 = fixture(11).unwrap(); + assert!(v11.iter().any(|(name, _)| name.starts_with(crate::journal::SEGMENT_PREFIX)) && v11[0].1.contains("\"photos\":{}")); +} + +// ---- an upgrade keeps what it replaces + +/// A store whose writes of some files fail. +struct Refusing { + files: MemStore, + refuse: fn(&str) -> bool, +} + +impl Store for Refusing { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.files.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + if (self.refuse)(name) { + return Err(std::io::Error::other("disk full")); + } + self.files.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.files.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.files.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.files.remove(name) + } + fn describe(&self) -> String { + "refusing".into() + } +} + +/// A format 6 library (the fixture) in a store. +fn v6_library() -> (MemStore, Vec, Vec) { + let m = store_of(&fixture(6).unwrap()); + let (snap, log) = (m.get(SNAPSHOT).unwrap(), m.get(LOG).unwrap()); + (m, snap, log) +} + +/// Given a library in an older format, when it is opened (which rewrites it in this build's +/// format, and older builds can't read that), then the files it was are kept beside it, byte for +/// byte, under names that say their format and the change they end at; the report names them; +/// and put back under their own names they are the library as it was. +#[test] +fn an_upgrade_keeps_the_files_it_replaces() { + let (m, snap, log) = v6_library(); + let (_, upgraded, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(r.upgraded_from, Some(6)); + assert_eq!(r.kept, ["catalog.snap.v6-8", "catalog.log.v6-8"]); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap.clone()), Some(log.clone()))); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + + // the way back: the kept files under their own names + let back = MemStore::new(); + back.set(SNAPSHOT, m.get("catalog.snap.v6-8").unwrap()); + back.set(LOG, m.get("catalog.log.v6-8").unwrap()); + assert_eq!(snapshot_version(&back), 6); + let (_, mut as_it_was, _) = Journal::open(Box::new(back)).unwrap(); + as_it_was.revision = upgraded.revision; + assert_eq!(as_it_was, upgraded); +} + +/// Given a library that is in this build's format already, or a new one, when it is opened, +/// then nothing is kept: there is nothing an older build could have read. +#[test] +fn nothing_is_kept_without_an_upgrade() { + let m = MemStore::new(); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(r.created && r.kept.is_empty()); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(r.kept.is_empty() && r.upgraded_from.is_none()); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [SNAPSHOT]); +} + +/// Given a library from before snapshots (only a log), when it is opened, then the log is kept +/// (as format 0: there was no number yet) and no snapshot is made up for it. +#[test] +fn an_upgrade_of_a_log_only_library_keeps_the_log() { + let mut c = Catalog::new(); + let op = photo(&mut c); + let log = format!("{}\n", encode_record(1, &op)).into_bytes(); + let m = MemStore::new(); + m.set(LOG, log.clone()); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!((r.upgraded_from, r.kept.as_slice()), (Some(0), ["catalog.log.v0-1".to_string()].as_slice())); + assert_eq!(m.get("catalog.log.v0-1"), Some(log)); + assert_eq!(m.get("catalog.snap.v0-1"), None); +} + +/// Given an older library whose files can't be kept (the disk is full), when it is opened, then +/// it is refused, and says why: it is not upgraded without its way back, and it is not worked in +/// as it is (it states no defaults for the records this build would add). Its files stay as they +/// were, nothing half kept is left, and it opens once there is room. +#[test] +fn a_library_that_cannot_be_kept_is_not_opened() { + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.log.v") }; + let e = Journal::open(Box::new(store)).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("older format (v6)") && why.contains("can't be kept")), "{e}"); + assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log))); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [LOG, SNAPSHOT], "nothing half kept"); + + let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, Some(6), 2)); +} + +/// Given an older library whose upgrade can't be written, when it is opened, then it is refused +/// and is as it was, with no copy of it left lying about: there is nothing to go back from. +#[test] +fn a_failed_upgrade_leaves_no_copy() { + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT }; + let e = Journal::open(Box::new(store)).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("can't be upgraded")), "{e}"); + assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(log))); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [LOG, SNAPSHOT]); +} + +/// Given an older library whose upgrade is written but whose log then can't be emptied, when it +/// is opened, then it is upgraded all the same (the log's changes are in the snapshot, and are +/// passed over when it is read), and the files it was are kept: its way back is not thrown away +/// because something failed after the upgrade. +#[test] +fn an_upgrade_that_is_written_keeps_its_copies_whatever_fails_after() { + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == LOG }; + let (_, c, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from), (3, Some(6))); + assert_eq!(r.kept, ["catalog.snap.v6-8", "catalog.log.v6-8"]); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log.clone()))); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + // the log it could not empty is all in the snapshot + assert_eq!(m.get(LOG), Some(log)); + let (_, mut again, r) = Journal::open(Box::new(m)).unwrap(); + again.revision = c.revision; + assert_eq!((again, r.replayed, r.upgraded_from), (c, 0, None)); +} + +/// Given an older library whose log is damaged, when it is opened (which saves what could be +/// read in this build's format), then that is an upgrade like any other: the snapshot it was is +/// kept beside the damaged log. +#[test] +fn a_damaged_older_library_keeps_its_snapshot() { + let (m, snap, log) = v6_library(); + // a record in the middle that is not what was written, with good ones after it + let mut lines: Vec = String::from_utf8(log).unwrap().lines().map(str::to_string).collect(); + lines[1] = lines[1].replacen("\"crc\":", "\"crc\":1", 1); + let damaged = format!("{}\n", lines.join("\n")).into_bytes(); + m.set(LOG, damaged.clone()); + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + let kept_log = r.damaged.clone().expect("damaged"); + assert_eq!((r.upgraded_from, r.kept.as_slice()), (Some(6), ["catalog.snap.v6-4".to_string()].as_slice()), "{r:?}"); + assert_eq!((m.get("catalog.snap.v6-4"), m.get(&kept_log)), (Some(snap), Some(damaged))); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); +} + +/// Given an older library whose log is damaged, when the upgrade is written but the damaged log +/// can't be replaced, then the library is refused (working in it would add changes after the +/// damage, where the next open would not read them), with the snapshot it was kept; and it +/// opens, repaired, once the log can be written. +#[test] +fn a_damaged_older_library_is_not_worked_in_with_its_damaged_log_in_place() { + let (m, snap, log) = v6_library(); + let mut lines: Vec = String::from_utf8(log).unwrap().lines().map(str::to_string).collect(); + lines[1] = lines[1].replacen("\"crc\":", "\"crc\":1", 1); + m.set(LOG, format!("{}\n", lines.join("\n")).into_bytes()); + let store = Refusing { files: m.clone(), refuse: |name| name == LOG }; + let e = Journal::open(Box::new(store)).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("damaged log")), "{e}"); + assert_eq!(m.get("catalog.snap.v6-4"), Some(snap), "its way back stays"); + + let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(c.photos().count(), 3); + assert!(r.damaged.is_some() && m.get(LOG).unwrap().is_empty(), "{r:?}"); +} + +/// Given an older library whose upgrade fails in a way that leaves it unknown whether it was +/// written (the snapshot can't be read afterwards), then the files it was are kept: the way +/// back is given up only when the library is known to be as it was. +#[test] +fn an_upgrade_that_cannot_be_checked_keeps_its_copies() { + /// Fails the write of the snapshot, and every read of it after that. + struct Blind { + files: MemStore, + failed: bool, + } + impl Store for Blind { + fn read(&mut self, name: &str) -> std::io::Result>> { + if self.failed && name == SNAPSHOT { + return Err(std::io::Error::other("unreadable")); + } + self.files.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + if name == SNAPSHOT { + self.failed = true; + return Err(std::io::Error::other("the share went away")); + } + self.files.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.files.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.files.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.files.remove(name) + } + fn describe(&self) -> String { + "blind".into() + } + } + let (m, snap, log) = v6_library(); + let e = Journal::open(Box::new(Blind { files: m.clone(), failed: false })).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("can't be told")), "{e}"); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log))); +} + +/// Given a place a new library can't be written to, when one is opened there, then it is +/// refused and nothing is left: a library without its first snapshot would be a log that states +/// no defaults for its records. +#[test] +fn a_new_library_that_cannot_be_written_is_not_opened() { + let m = MemStore::new(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT }; + let e = Journal::open(Box::new(store)).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("new library")), "{e}"); + assert!(m.files.lock().unwrap().is_empty()); } diff --git a/crates/catalog/src/tests_journal.rs b/crates/catalog/src/tests_journal.rs index 26b4e902ab6..f2ccec07d1a 100644 --- a/crates/catalog/src/tests_journal.rs +++ b/crates/catalog/src/tests_journal.rs @@ -286,33 +286,42 @@ fn fs_store_roundtrip() { let _ = std::fs::remove_dir_all(&dir); } -/// The streamed snapshot is byte-for-byte the format written before streaming (issue #37), so -/// existing libraries load and older builds can read new snapshots; FsStore and MemStore agree. +/// Where a store has no segments, the streamed snapshot is the one-file form written since +/// streaming (issue #37) with the (empty) list of segments after it, so a one-file library of +/// any format loads; where it has segments (a folder), such a file loads too and is rewritten +/// with its photos in segments. #[test] fn streamed_snapshot_keeps_the_on_disk_format() { - let (m, _, full) = sample_catalog_with_log(); + let (segmented, _, full) = sample_catalog_with_log(); + let m = MemStore { single_file: true, files: segmented.files.clone(), ..Default::default() }; let (mut j, c, _) = open(&m); assert_eq!(c.to_snapshot(), full.to_snapshot()); j.snapshot(&c).unwrap(); - let legacy = format!( - "{{\"format\":\"lightcraft-catalog\",\"version\":{},\"seq\":{},\"catalog\":{}}}\n", - crate::journal::VERSION, - j.seq(), - c.to_snapshot() - ); - assert_eq!(String::from_utf8(m.get(SNAPSHOT).unwrap()).unwrap(), legacy); - assert_eq!(j.stats().last_snapshot.bytes, legacy.len() as u64); + let legacy = |version: u32| { + format!( + "{{\"format\":\"lightcraft-catalog\",\"version\":{version},\"seq\":{},\"defaults\":{},\"catalog\":{}}}\n", + j.seq(), + crate::stored::base().0, + c.to_snapshot() + ) + }; + let one_file = legacy(crate::journal::VERSION).replace("}\n", &format!(",\"segments\":[],\"photos\":{}}}\n", c.len())); + assert_eq!(String::from_utf8(m.get(SNAPSHOT).unwrap()).unwrap(), one_file); + assert_eq!(j.stats().last_snapshot.bytes, one_file.len() as u64); let dir = std::env::temp_dir().join(format!("lc-journal-stream-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - // an old-style snapshot (written by a build before streaming) loads, and is rewritten the same - std::fs::write(dir.join(SNAPSHOT), legacy.as_bytes()).unwrap(); - let (mut fj, fc, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); - assert_eq!((fc.to_snapshot(), r.snapshot_seq), (c.to_snapshot(), j.seq())); - fj.snapshot(&fc).unwrap(); - assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), legacy.as_bytes()); + // an old-style snapshot (written by a build before segments) loads, and is rewritten in them + std::fs::write(dir.join(SNAPSHOT), legacy(7).as_bytes()).unwrap(); + let (fj, fc, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + assert_eq!((fc.to_snapshot(), r.snapshot_seq, r.upgraded_from), (c.to_snapshot(), j.seq(), Some(7))); + assert_eq!(fj.segments().len(), 1); + let name = fj.segments()[0].name.clone(); + assert_eq!(std::fs::metadata(dir.join(&name)).unwrap().len(), fj.segments()[0].bytes); drop(fj); + let (_, again, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + assert_eq!((again.to_snapshot(), r.upgraded_from), (c.to_snapshot(), None)); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/catalog/src/tests_policy.rs b/crates/catalog/src/tests_policy.rs new file mode 100644 index 00000000000..3f59b157f61 --- /dev/null +++ b/crates/catalog/src/tests_policy.rs @@ -0,0 +1,161 @@ +//! When the log is compacted into a snapshot ([`SnapshotPolicy`]): once it has grown to a share +//! of what the snapshot would rewrite, so the cost of saving follows what changed, not the +//! library's size. These are about a store without segments (the browser's), where a snapshot +//! rewrites the whole catalog; `tests_segments` has the same rule where it rewrites segments. + +use crate::journal::SNAPSHOT; +use crate::*; + +fn add(c: &mut Catalog) -> Op { + let id = c.alloc_photo_id(); + let op = Op::AddPhoto { + photo: Box::new(Photo::new( + id, + Source::File { path: format!("/pictures/2019/trip/IMG_{:06}.jpg", id.0) }, + "IMG.jpg", + "JPEG", + 4032, + 3024, + "2026-10-10T12:00:00", + )), + }; + c.apply(op.clone()).unwrap(); + op +} + +fn rate(c: &mut Catalog, k: u64) -> Op { + // (whatever ids the catalog gave its photos) + let id = c.photos().nth((k % 50) as usize).map(|p| p.id).unwrap(); + let op = Op::SetRating { id, rating: (k % 6) as u8 }; + c.apply(op.clone()).unwrap(); + op +} + +/// A library of `n` photos, saved and compacted. +fn library(n: u64) -> (MemStore, Journal, Catalog) { + let m = MemStore { single_file: true, ..Default::default() }; + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + let ops: Vec = (0..n).map(|_| add(&mut c)).collect(); + j.append(&ops).unwrap(); + j.snapshot(&c).unwrap(); + (m, j, c) +} + +/// Given a small library, when 2000 changes were logged, then the log is compacted, as it always was. +#[test] +fn a_small_library_compacts_after_2000_changes() { + let (_m, mut j, mut c) = library(50); + for k in 0..1999 { + let op = rate(&mut c, k); + j.append(&[op]).unwrap(); + assert!(!j.wants_snapshot(), "after {} changes", k + 1); + } + let op = rate(&mut c, 1999); + j.append(&[op]).unwrap(); + assert!(j.wants_snapshot()); +} + +/// Given a large library, when 2000 small changes were logged, then the snapshot is not rewritten +/// for them; it is once the log has grown to a quarter of the snapshot. +#[test] +fn a_large_library_compacts_when_the_log_is_a_quarter_of_the_snapshot() { + let (_m, mut j, mut c) = library(20_000); + let snapshot = j.snapshot_bytes(); + assert!(snapshot > 2_000_000, "{snapshot}"); + let mut k = 0; + while j.log_bytes() < snapshot / 4 { + assert!(!j.wants_snapshot(), "{} records, {} of {snapshot} bytes", j.log_records(), j.log_bytes()); + let ops: Vec = (0..500).map(|i| rate(&mut c, k + i)).collect(); + j.append(&ops).unwrap(); + k += 500; + } + assert!(j.log_records() > 4000, "{}", j.log_records()); + assert!(j.wants_snapshot()); + j.snapshot(&c).unwrap(); + assert!(!j.wants_snapshot()); +} + +/// The size the rule goes by is the snapshot's, also right after the library was opened. +#[test] +fn the_snapshot_size_is_known_after_reopening() { + let (m, j, _c) = library(2000); + let written = j.snapshot_bytes(); + assert_eq!(written, m.get(SNAPSHOT).unwrap().len() as u64); + drop(j); + let (j, _, _) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(j.snapshot_bytes(), written); + // a new library's first snapshot counts too + let (j, _, _) = Journal::open(Box::new(MemStore { single_file: true, ..Default::default() })).unwrap(); + assert!(j.snapshot_bytes() > 0); +} + +/// However large the snapshot, a log is never left to grow past the cap: opening the library +/// replays all of it. +#[test] +fn a_log_at_the_cap_is_compacted_whatever_the_snapshot_size() { + let p = SnapshotPolicy::default(); + let huge = 100 << 30; + assert!(!p.due(1_000_000, p.log_cap_bytes - 1, huge)); + assert!(p.due(1_000_000, p.log_cap_bytes, huge)); + // and a short log is left alone whatever its share of a tiny snapshot + assert!(!p.due(10, 4096, 100)); + // without a share, length alone decides (as before format 10) + let q = SnapshotPolicy { snapshot_share: 0, ..p }; + assert!(q.due(2000, 1, huge) && !q.due(1999, 1, huge)); +} + +/// Given an import of many photos, when the log is compacted whenever it is due, then all the +/// snapshots written together are a few times the final one, not one per 2000 photos. +#[test] +fn an_import_rewrites_the_snapshot_a_bounded_number_of_times() { + let m = MemStore { single_file: true, ..Default::default() }; + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + let (mut compactions, mut written) = (0u64, 0u64); + for _ in 0..80 { + let ops: Vec = (0..500).map(|_| add(&mut c)).collect(); + j.append(&ops).unwrap(); + if j.wants_snapshot() { + j.snapshot(&c).unwrap(); + compactions += 1; + written += j.snapshot_bytes(); + } + } + j.snapshot(&c).unwrap(); + let last = j.snapshot_bytes(); + // 40,000 photos: every 2000 records would be 20 compactions writing ~10x the final snapshot + assert!(compactions <= 12, "{compactions} compactions"); + assert!(written <= 5 * last, "{written} bytes of snapshots for a final one of {last}"); + drop(j); + let (_, loaded, _) = Journal::open(Box::new(m)).unwrap(); + assert_eq!(loaded.len(), 40_000); +} + +/// Given a small library with changes, when it is closed, then its log is compacted (the next +/// open replays nothing); with no changes there is nothing to write. +#[test] +fn closing_a_small_library_compacts_its_log() { + let (_m, mut j, mut c) = library(50); + assert!(!j.wants_snapshot_on_close(), "nothing changed"); + let op = rate(&mut c, 1); + j.append(&[op]).unwrap(); + assert!(j.wants_snapshot_on_close()); +} + +/// Given a library whose snapshot is large, when it is closed after a few changes, then the +/// snapshot is not rewritten for them. It is once the log is long (2000 changes), though that +/// is not yet its share of the snapshot: a log isn't left long from one session to the next, +/// so a damaged record in it never costs more changes than it used to. +#[test] +fn closing_a_large_library_keeps_a_short_log_and_compacts_a_long_one() { + let (_m, mut j, mut c) = library(20_000); + j.policy.close_bytes = j.snapshot_bytes() - 1; + for k in 0..1999 { + let op = rate(&mut c, k); + j.append(&[op]).unwrap(); + } + assert!(!j.wants_snapshot_on_close(), "{} changes", j.log_records()); + let op = rate(&mut c, 1999); + j.append(&[op]).unwrap(); + assert!(j.wants_snapshot_on_close()); + assert!(!j.wants_snapshot(), "during the session the log may still grow to its share of the snapshot"); +} diff --git a/crates/catalog/src/tests_segments.rs b/crates/catalog/src/tests_segments.rs new file mode 100644 index 00000000000..9618a8e785b --- /dev/null +++ b/crates/catalog/src/tests_segments.rs @@ -0,0 +1,1410 @@ +//! The snapshot in segments (catalog format 11): photos are saved in segment files listed by +//! `catalog.snap`, and a compaction rewrites only the segments whose photos changed. + +use std::collections::BTreeSet; +use std::sync::{Arc, Mutex}; + +use serde_json::Value; + +use crate::journal::{LOG, SEGMENT_PREFIX, SNAPSHOT, VERSION, segment_file}; +use crate::*; + +fn photo(id: u64) -> Photo { + Photo::new( + PhotoId(id), + Source::File { path: format!("/pictures/2019/trip/IMG_{id:06}.jpg") }, + &format!("IMG_{id:06}.jpg"), + "JPEG", + 4032, + 3024, + "2026-10-10T12:00:00", + ) +} + +/// Apply and log. +fn run(j: &mut Journal, c: &mut Catalog, ops: Vec) { + for op in &ops { + c.apply(op.clone()).unwrap(); + } + j.append(&ops).unwrap(); +} + +fn add(ids: impl IntoIterator) -> Vec { + ids.into_iter().map(|id| Op::AddPhoto { photo: Box::new(photo(id)) }).collect() +} + +/// A library of photos `1..=n` in segments of `per` photos, saved and compacted. +fn library(n: u64, per: usize) -> (MemStore, Journal, Catalog) { + let m = MemStore::new(); + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + j.policy.segment_photos = per; + run(&mut j, &mut c, add(1..=n)); + let album = c.alloc_album_id(); + run(&mut j, &mut c, vec![Op::AddAlbum { album: Album::new(album, "Keepers") }]); + j.snapshot(&c).unwrap(); + (m, j, c) +} + +fn segment_files(m: &MemStore) -> BTreeSet { + // (also what is left of one being written: `.tmp`) + m.files.lock().unwrap().keys().filter(|k| k.starts_with(SEGMENT_PREFIX) && (k.ends_with(".json") || k.ends_with(".json.tmp"))).cloned().collect() +} + +fn manifest(m: &MemStore) -> Value { + serde_json::from_slice(&m.get(SNAPSHOT).unwrap()).unwrap() +} + +fn listed(m: &MemStore) -> BTreeSet { + manifest(m)["segments"].as_array().unwrap().iter().map(|s| s["name"].as_str().unwrap().to_string()).collect() +} + +/// The catalog as opening the files gives it, compared as public JSON too. +fn reopen(m: &MemStore) -> Catalog { + let (_, c, _) = Journal::open(Box::new(m.clone())).unwrap(); + c +} + +fn assert_same(a: &Catalog, b: &Catalog) { + assert_eq!(a.to_snapshot(), b.to_snapshot()); + let public = |c: &Catalog| c.photos().map(|p| serde_json::to_string(p.as_ref()).unwrap()).collect::>(); + assert_eq!(public(a), public(b)); +} + +/// A copy of the files as a crash at this moment would leave them. +fn crash_copy(m: &MemStore) -> MemStore { + let copy = MemStore::new(); + *copy.files.lock().unwrap() = m.files.lock().unwrap().clone(); + copy +} + +/// Given a library, when it is saved, then its photos are in segment files that `catalog.snap` +/// lists (and holds none itself), and opening it gives the same catalog. +#[test] +fn photos_are_saved_in_segments_listed_by_the_snapshot() { + let (m, j, c) = library(10, 4); + let head = manifest(&m); + assert_eq!(head["version"].as_u64(), Some(u64::from(VERSION))); + assert_eq!(head["catalog"]["photos"], serde_json::json!({})); + assert_eq!(head["catalog"]["albums"].as_object().unwrap().len(), 1); + let segments = head["segments"].as_array().unwrap(); + assert_eq!(segments.iter().map(|s| s["photos"].as_u64().unwrap()).collect::>(), [4, 4, 2]); + assert_eq!(segments.iter().map(|s| s["first"].as_u64().unwrap()).collect::>(), [1, 5, 9]); + assert_eq!(listed(&m), segment_files(&m)); + for s in segments { + let bytes = m.get(s["name"].as_str().unwrap()).unwrap(); + assert_eq!(bytes.len() as u64, s["bytes"].as_u64().unwrap()); + assert_eq!(u64::from(crc32fast::hash(&bytes)), s["crc"].as_u64().unwrap()); + // a segment is JSON a person can read: its photos by id + let v: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(v["photos"].as_object().unwrap().len() as u64, s["photos"].as_u64().unwrap()); + } + assert_eq!(j.snapshot_bytes(), m.get(SNAPSHOT).unwrap().len() as u64 + segments.iter().map(|s| s["bytes"].as_u64().unwrap()).sum::()); + assert_same(&reopen(&m), &c); +} + +/// Given a saved library, when one photo changes and the log is compacted, then only that +/// photo's segment is rewritten: the other segment files are the same files. +#[test] +fn a_compaction_rewrites_only_the_segments_that_changed() { + let (m, mut j, mut c) = library(12, 4); + let before = listed(&m); + let files_before = m.files.lock().unwrap().clone(); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(6), rating: 5 }]); + j.snapshot(&c).unwrap(); + let after = listed(&m); + assert_eq!(before.intersection(&after).count(), 2, "{before:?} -> {after:?}"); + for name in before.intersection(&after) { + assert_eq!(m.get(name), files_before.get(name).cloned()); + } + assert_eq!(j.stats().last_snapshot.segments, 1); + // the replaced segment's old file is gone + assert_eq!(segment_files(&m), after); + assert_same(&reopen(&m), &c); +} + +/// Given a saved library, when nothing about its photos changed (an album was renamed), then +/// a compaction writes no segment at all. +#[test] +fn a_change_that_touches_no_photo_rewrites_no_segment() { + let (m, mut j, mut c) = library(12, 4); + let before = listed(&m); + let album = c.albums().next().unwrap().id; + run(&mut j, &mut c, vec![Op::RenameAlbum { id: album, name: "Best".into() }]); + j.snapshot(&c).unwrap(); + assert_eq!(listed(&m), before); + assert_eq!(j.stats().last_snapshot.segments, 0); + assert_same(&reopen(&m), &c); +} + +/// Given a saved library, when photos are imported, then they go into new segments at the end +/// and the segments of the photos that were there are left alone. +#[test] +fn an_import_adds_segments_and_leaves_the_others() { + let (m, mut j, mut c) = library(8, 4); + let before = listed(&m); + run(&mut j, &mut c, add(9..=20)); + j.snapshot(&c).unwrap(); + let after = listed(&m); + assert!(before.is_subset(&after), "{before:?} -> {after:?}"); + let counts: Vec = manifest(&m)["segments"].as_array().unwrap().iter().map(|s| s["photos"].as_u64().unwrap()).collect(); + assert_eq!(counts.iter().sum::(), 20); + assert!(counts.iter().all(|n| *n <= 8), "{counts:?}"); + assert_same(&reopen(&m), &c); +} + +/// A segment that grew past twice its size is split; one that lost all its photos is dropped. +#[test] +fn segments_split_when_they_grow_and_go_when_they_empty() { + let (m, mut j, mut c) = library(4, 4); + // ids between the existing ones' segment boundaries can't happen with counted ids, but a + // segment also grows when it is the last one: 4 photos -> 13 + run(&mut j, &mut c, add(5..=13)); + j.snapshot(&c).unwrap(); + let counts: Vec = manifest(&m)["segments"].as_array().unwrap().iter().map(|s| s["photos"].as_u64().unwrap()).collect(); + assert_eq!(counts, [4, 4, 4, 1]); + assert_same(&reopen(&m), &c); + + run(&mut j, &mut c, (5..=8).map(|id| Op::RemovePhoto { id: PhotoId(id) }).collect()); + j.snapshot(&c).unwrap(); + let firsts: Vec = manifest(&m)["segments"].as_array().unwrap().iter().map(|s| s["first"].as_u64().unwrap()).collect(); + assert_eq!(firsts, [1, 9, 13]); + assert_eq!(segment_files(&m), listed(&m)); + let back = reopen(&m); + assert_same(&back, &c); + assert!(back.photo(PhotoId(6)).is_none()); + + // everything removed: no segments, and the library still opens + run(&mut j, &mut c, [1, 2, 3, 4, 9, 10, 11, 12, 13].map(|id| Op::RemovePhoto { id: PhotoId(id) }).to_vec()); + j.snapshot(&c).unwrap(); + assert!(segment_files(&m).is_empty() && listed(&m).is_empty()); + assert_eq!(reopen(&m).len(), 0); +} + +/// Photo ids far apart (random ids) are grouped by how many there are, not by their value. +#[test] +fn widely_spaced_ids_fill_segments_like_any_others() { + let m = MemStore::new(); + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + j.policy.segment_photos = 4; + let ids: Vec = (1..=10u64).map(|k| k.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> 11).collect(); + run(&mut j, &mut c, add(ids.clone())); + j.snapshot(&c).unwrap(); + assert_eq!(listed(&m).len(), 3); + // one more, in the middle of the id range: its segment only + let before = listed(&m); + let mut sorted = ids.clone(); + sorted.sort_unstable(); + run(&mut j, &mut c, add([sorted[5] + 1])); + j.snapshot(&c).unwrap(); + assert_eq!(before.intersection(&listed(&m)).count(), 2); + assert_same(&reopen(&m), &c); +} + +/// A store whose every change is preceded by a copy of its files: what a crash just before +/// that change would leave. +#[derive(Clone, Default)] +struct Filmed { + files: MemStore, + frames: Arc>>, + filming: Arc>, +} + +impl Filmed { + fn frame(&self) { + if *self.filming.lock().unwrap() { + self.frames.lock().unwrap().push(crash_copy(&self.files)); + } + } +} + +impl Store for Filmed { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.files.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.frame(); + self.files.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.frame(); + self.files.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.frame(); + self.files.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.frame(); + self.files.remove(name) + } + fn list(&mut self) -> std::io::Result> { + self.files.list() + } + fn segmented(&self) -> bool { + true + } + fn describe(&self) -> String { + "filmed".into() + } +} + +/// Given a compaction that rewrites, adds and drops segments, when the program crashes before +/// any one of its writes, then opening the library gives every change made so far, and leaves +/// no segment file behind that the snapshot doesn't list. +#[test] +fn a_crash_at_any_point_of_a_compaction_loses_nothing() { + let store = Filmed::default(); + let (mut j, mut c, _) = Journal::open(Box::new(store.clone())).unwrap(); + j.policy.segment_photos = 4; + run(&mut j, &mut c, add(1..=12)); + j.snapshot(&c).unwrap(); + run( + &mut j, + &mut c, + vec![ + Op::SetRating { id: PhotoId(2), rating: 3 }, + Op::RemovePhoto { id: PhotoId(5) }, + Op::RemovePhoto { id: PhotoId(6) }, + Op::RemovePhoto { id: PhotoId(7) }, + Op::RemovePhoto { id: PhotoId(8) }, + ], + ); + run(&mut j, &mut c, add(13..=24)); + let expected = c.clone(); + + *store.filming.lock().unwrap() = true; + j.snapshot(&c).unwrap(); + *store.filming.lock().unwrap() = false; + let mut frames = std::mem::take(&mut *store.frames.lock().unwrap()); + frames.push(crash_copy(&store.files)); + assert!(frames.len() >= 6, "{} writes", frames.len()); + for (k, frame) in frames.iter().enumerate() { + let (mut j2, back, report) = Journal::open(Box::new(frame.clone())).unwrap(); + assert_eq!((report.failed, report.damaged.clone()), (0, None), "crash before write {k}"); + assert_eq!(back.to_snapshot(), expected.to_snapshot(), "crash before write {k}"); + j2.remove_unlisted_segments(); + assert_eq!(segment_files(frame), listed(frame), "crash before write {k}: a segment file nothing lists"); + // and the library goes on from there + drop(j2); + let (mut j3, mut c3, _) = Journal::open(Box::new(frame.clone())).unwrap(); + run(&mut j3, &mut c3, vec![Op::SetRating { id: PhotoId(1), rating: 1 }]); + j3.snapshot(&c3).unwrap(); + assert_eq!(reopen(frame).to_snapshot(), c3.to_snapshot(), "crash before write {k}"); + } +} + +/// The same while the snapshot is written by the worker thread and changes go on. +#[test] +fn a_background_compaction_writes_segments_and_keeps_later_changes() { + let m = MemStore { background: true, ..Default::default() }; + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + j.policy.segment_photos = 4; + run(&mut j, &mut c, add(1..=12)); + j.snapshot(&c).unwrap(); + let before = listed(&m); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(10), rating: 4 }]); + j.snapshot_in_background(&c).unwrap(); + // changes while it is being written: to a segment it rewrites, and to one it doesn't + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(11), rating: 2 }, Op::SetRating { id: PhotoId(1), rating: 2 }]); + assert_same(&reopen(&crash_copy(&m)), &c); + j.wait().unwrap(); + assert_eq!(before.intersection(&listed(&m)).count(), 2); + assert_same(&reopen(&m), &c); + // the next compaction rewrites the segments of what changed meanwhile + j.snapshot(&c).unwrap(); + assert_eq!(j.stats().last_snapshot.segments, 2); + assert_eq!(segment_files(&m), listed(&m)); + assert_same(&reopen(&m), &c); +} + +/// Segments are read on several threads when the store allows it; the result is the same. +#[test] +fn segments_load_the_same_in_parallel() { + let (m, _j, c) = library(200, 8); + assert!(listed(&m).len() >= 20); + let parallel = MemStore { background: true, ..crash_copy(&m) }; + assert_same(&reopen(¶llel), &c); + assert_same(&reopen(&m), &c); +} + +/// Given a segment file that is damaged, cut short or gone, when the library is opened, then +/// it says which file, and changes nothing. +#[test] +fn a_damaged_segment_is_reported_and_nothing_is_changed() { + let (m, mut j, mut c) = library(12, 4); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(1), rating: 1 }]); + drop(j); + let name = listed(&m).into_iter().nth(1).unwrap(); + let damage: [(&str, fn(Vec) -> Option>); 5] = [ + // still JSON, the same length and the same photos: only the checksum can tell + ("one digit changed", |mut b| { + let at = b.windows(4).position(|w| w == b"4032").unwrap(); + b[at] = b'5'; + Some(b) + }), + ("flipped", |mut b| { + let at = b.len() / 2; + b[at] ^= 0x20; + Some(b) + }), + ("cut short", |mut b| { + b.truncate(b.len() / 2); + Some(b) + }), + ("empty", |_| Some(Vec::new())), + ("gone", |_| None), + ]; + for (what, f) in damage { + let bad = crash_copy(&m); + match f(bad.get(&name).unwrap()) { + Some(b) => bad.set(&name, b), + None => { + bad.files.lock().unwrap().remove(&name); + } + } + let files = bad.files.lock().unwrap().clone(); + let e = Journal::open(Box::new(bad.clone())).map(|_| ()).unwrap_err(); + assert!(matches!(&e, CatalogError::Corrupt(msg) if msg.contains(&name)), "{what}: {e}"); + assert_eq!(*bad.files.lock().unwrap(), files, "{what}: files were changed"); + } +} + +/// A snapshot that lists segments it shouldn't (a name outside the library, the same file +/// twice, photos outside a segment's range, a wrong count) is refused, not followed. +#[test] +fn a_snapshot_with_a_bad_segment_list_is_refused() { + let (m, j, _c) = library(12, 4); + drop(j); + let edits: [(&str, fn(&mut Value)); 6] = [ + ("a path", |v| v["segments"][0]["name"] = "../catalog.seg-1-1".into()), + ("another file", |v| v["segments"][0]["name"] = "prefs.json".into()), + ("twice", |v| v["segments"][1] = v["segments"][0].clone()), + ("out of order", |v| v["segments"].as_array_mut().unwrap().swap(0, 2)), + ("wrong range", |v| v["segments"][1]["first"] = 6.into()), + ("wrong count", |v| v["segments"][0]["photos"] = 3.into()), + ]; + for (what, edit) in edits { + let bad = crash_copy(&m); + let mut v = manifest(&bad); + edit(&mut v); + bad.set(SNAPSHOT, serde_json::to_vec(&v).unwrap()); + let files = bad.files.lock().unwrap().clone(); + let e = Journal::open(Box::new(bad.clone())).map(|_| ()).unwrap_err(); + assert!(matches!(e, CatalogError::Corrupt(_)), "{what}: {e}"); + assert_eq!(*bad.files.lock().unwrap(), files, "{what}: files were changed"); + } + // absurd numbers are an error too, not an allocation + let bad = crash_copy(&m); + let mut v = manifest(&bad); + v["segments"][0]["photos"] = u64::MAX.into(); + v["segments"][0]["bytes"] = u64::MAX.into(); + bad.set(SNAPSHOT, serde_json::to_vec(&v).unwrap()); + assert!(Journal::open(Box::new(bad)).is_err()); +} + +/// Segment files that the snapshot doesn't list (left by a crash) are removed when the opener, +/// holding the library to itself, asks for it; opening alone removes nothing (to a second +/// program, the segments the first is writing for its next snapshot look the same). Other files +/// in the folder are never touched. +#[test] +fn unlisted_segment_files_are_removed_on_request_only() { + let (m, j, c) = library(8, 4); + drop(j); + m.set(&segment_file("99-99"), b"left by a crash".to_vec()); + m.set(&format!("{}.tmp", segment_file("99-100")), b"half written".to_vec()); + m.set("presets.json", b"[]".to_vec()); + m.set("segments/notes.txt", b"mine".to_vec()); + let (mut j, back, _) = Journal::open(Box::new(m.clone())).unwrap(); + assert_same(&back, &c); + assert_eq!(segment_files(&m).len(), listed(&m).len() + 2, "opening removed files"); + j.remove_unlisted_segments(); + assert_eq!(segment_files(&m), listed(&m)); + assert_eq!(m.get("presets.json").as_deref(), Some(&b"[]"[..])); + assert_eq!(m.get("segments/notes.txt").as_deref(), Some(&b"mine"[..])); +} + +/// Given segment files without the snapshot that lists them (a folder copied or synced in part, +/// a `catalog.snap` that was removed), when the folder is opened, then it is refused and nothing +/// is touched: the photos are in those files, and a new empty library must not replace them. +#[test] +fn segments_without_their_snapshot_are_not_a_new_library() { + let (m, j, _c) = library(12, 4); + drop(j); + for with_log in [true, false] { + let lost = crash_copy(&m); + lost.files.lock().unwrap().remove(SNAPSHOT); + if !with_log { + lost.files.lock().unwrap().remove(LOG); + } + let files = lost.files.lock().unwrap().clone(); + let e = Journal::open(Box::new(lost.clone())).map(|_| ()).unwrap_err(); + assert!(matches!(&e, CatalogError::Corrupt(msg) if msg.contains(SNAPSHOT) && msg.contains("3 segment")), "{e}"); + assert_eq!(*lost.files.lock().unwrap(), files); + } +} + +/// Given a library that so far is only a log (it never had a snapshot), when its first snapshot +/// gets as far as writing segments and no further (the write of `catalog.snap` fails, or the +/// program stops there), then nothing of it is lost and it opens once the snapshot can be +/// written: the log holds every change from the first, so the segment files are not "photos +/// without their snapshot". +#[test] +fn a_log_only_library_survives_a_first_snapshot_that_did_not_finish() { + let ops = add(1..=5); + let log: String = ops.iter().enumerate().map(|(k, op)| crate::journal::encode_record(k as u64 + 1, op) + "\n").collect(); + let mut expected = Catalog::new(); + for op in ops { + expected.apply(op).unwrap(); + } + // the write of `catalog.snap` fails: the library is not worked in as it is (a log states no + // defaults for what would be added to it), and is left as it was, with no segment + let store = Watched::default(); + store.files.set(LOG, log.clone().into_bytes()); + *store.fail.lock().unwrap() = Some(SNAPSHOT.into()); + let e = Journal::open(Box::new(store.clone())).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("can't be upgraded")), "{e}"); + assert!(segment_files(&store.files).is_empty() && store.files.get(SNAPSHOT).is_none()); + assert_eq!(store.files.get(LOG), Some(log.clone().into_bytes())); + *store.fail.lock().unwrap() = None; + let (_, c, r) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!((c.to_snapshot(), r.replayed, r.upgraded_from), (expected.to_snapshot(), 5, Some(0))); + + // the program stopped between the segments and `catalog.snap`: the log and a segment file + let m = MemStore::new(); + m.set(LOG, log.into_bytes()); + m.set(&segment_file("1-5"), b"written, never listed".to_vec()); + let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!((c.to_snapshot(), r.upgraded_from), (expected.to_snapshot(), Some(0))); + assert!(!listed(&m).contains(&segment_file("1-5")), "written over a file that was there"); + assert_same(&reopen(&m), &expected); + + // a log that doesn't start at the first change is no such library: refused + let (m, mut j, mut c) = library(12, 4); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(1), rating: 1 }]); + drop(j); + m.files.lock().unwrap().remove(SNAPSHOT); + assert!(matches!(Journal::open(Box::new(m)).map(|_| ()), Err(CatalogError::Corrupt(_)))); +} + +/// Given a snapshot whose `catalog.snap` was replaced although the store reported an error (so +/// the journal still takes the old segments to be the listed ones), when unlisted segments are +/// removed, then the ones the file on disk lists stay, and the library opens. +#[test] +fn cleaning_up_goes_by_the_snapshot_on_disk() { + let (m, j, _c) = library(12, 4); + drop(j); + let store = Lying { files: m.clone(), lie: Arc::new(Mutex::new(false)) }; + let (mut j, mut c, _) = Journal::open(Box::new(store.clone())).unwrap(); + j.policy.segment_photos = 4; + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(3), rating: 5 }]); + *store.lie.lock().unwrap() = true; + assert!(j.snapshot(&c).is_err()); + *store.lie.lock().unwrap() = false; + assert_same(&reopen(&crash_copy(&m)), &c); + j.remove_unlisted_segments(); + assert_same(&reopen(&crash_copy(&m)), &c); + j.snapshot(&c).unwrap(); + assert_same(&reopen(&m), &c); +} + +/// A store whose replace of `catalog.snap` takes effect and then reports an error. +#[derive(Clone)] +struct Lying { + files: MemStore, + lie: Arc>, +} + +impl Store for Lying { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.files.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.files.write_atomic(name, data)?; + if name == SNAPSHOT && *self.lie.lock().unwrap() { + return Err(std::io::Error::other("the connection dropped")); + } + Ok(()) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.files.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.files.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.files.remove(name) + } + fn list(&mut self) -> std::io::Result> { + self.files.list() + } + fn segmented(&self) -> bool { + true + } + fn describe(&self) -> String { + "lying".into() + } +} + +/// Given an older one-file `catalog.snap` put back over a folder that has segments (a restored +/// backup), when it is opened, then the one file is what opens, and the segment files, which may +/// be all there is of the newer catalog, are left alone in that session: also when the opener +/// asks for unlisted ones to be removed, and though the one file is split into segments of its +/// own. (They go when the library, by then in segments, is next opened and cleaned.) +#[test] +fn segments_beside_a_one_file_snapshot_are_left_alone() { + let (m, j, _c) = library(12, 4); + drop(j); + let newer = segment_files(&m); + let newer_bytes: Vec> = newer.iter().map(|n| m.get(n).unwrap()).collect(); + let old = include_str!("fixtures/v10-catalog.snap.json"); + m.set(SNAPSHOT, old.as_bytes().to_vec()); + m.set(LOG, Vec::new()); + let (mut j, back, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!((back.len(), r.upgraded_from), (3, Some(10))); + j.remove_unlisted_segments(); + for (name, bytes) in newer.iter().zip(&newer_bytes) { + assert_eq!(m.get(name).as_ref(), Some(bytes), "{name}"); + } + // the split wrote segments of its own, under names none of those files has + assert!(listed(&m).is_disjoint(&newer)); + drop(j); + let (mut j, back, _) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(back.len(), 3); + j.remove_unlisted_segments(); + assert_eq!(segment_files(&m), listed(&m)); +} + +/// A snapshot whose list of segments doesn't add up to the photos it states (an entry removed) +/// is refused: opening it would be a library that silently lost photos. +#[test] +fn a_segment_list_that_does_not_hold_every_photo_is_refused() { + let (m, j, _c) = library(12, 4); + drop(j); + assert_eq!(manifest(&m)["photos"].as_u64(), Some(12)); + let mut v = manifest(&m); + v["segments"].as_array_mut().unwrap().pop(); + m.set(SNAPSHOT, serde_json::to_vec(&v).unwrap()); + let files = m.files.lock().unwrap().clone(); + let e = Journal::open(Box::new(m.clone())).map(|_| ()).unwrap_err(); + assert!(matches!(&e, CatalogError::Corrupt(msg) if msg.contains("8 photos") && msg.contains("12")), "{e}"); + assert_eq!(*m.files.lock().unwrap(), files); + + // and a snapshot that holds photos itself and lists segments too + let (m, j, _c) = library(12, 4); + drop(j); + let mut v = manifest(&m); + v["catalog"]["photos"] = serde_json::json!({"99": serde_json::to_value(photo(99)).unwrap()}); + v["photos"] = 13.into(); + m.set(SNAPSHOT, serde_json::to_vec(&v).unwrap()); + assert!(matches!(Journal::open(Box::new(m)).map(|_| ()), Err(CatalogError::Corrupt(_)))); +} + +/// Given a library that was closed and opened again, when one photo changes and the log is +/// compacted, then only that photo's segment is rewritten: what is on disk is known from +/// opening it, not only from having written it. +#[test] +fn a_compaction_after_reopening_rewrites_only_what_changed() { + let (m, j, _c) = library(12, 4); + drop(j); + let before = listed(&m); + let files_before = m.files.lock().unwrap().clone(); + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + j.policy.segment_photos = 4; + assert_eq!(j.snapshot_bytes(), m.get(SNAPSHOT).unwrap().len() as u64 + j.segments().iter().map(|s| s.bytes).sum::()); + assert_eq!(j.stats().segments, 3); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(10), rating: 5 }]); + j.snapshot(&c).unwrap(); + assert_eq!(j.stats().last_snapshot.segments, 1); + let after = listed(&m); + assert_eq!(before.intersection(&after).count(), 2); + for name in before.intersection(&after) { + assert_eq!(m.get(name), files_before.get(name).cloned()); + } + let rewritten = after.difference(&before).next().unwrap(); + assert_eq!(j.stats().last_snapshot.bytes, (m.get(SNAPSHOT).unwrap().len() + m.get(rewritten).unwrap().len()) as u64); + assert_same(&reopen(&m), &c); +} + +/// A log replayed when the library is opened counts towards the next compaction like one +/// written in this session: 2000 changes within one segment, then a restart, and it is due. +#[test] +fn a_replayed_log_is_due_for_compaction_like_any_other() { + let (m, mut j, mut c) = library(20_000, 500); + let ops: Vec = (0..2000u64).map(|k| Op::SetRating { id: PhotoId(1 + k % 400), rating: 1 + (k % 5) as u8 }).collect(); + run(&mut j, &mut c, ops); + assert!(j.wants_snapshot()); + drop(j); + let (j, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(r.replayed, 2000); + assert!(j.wants_snapshot()); +} + +/// Where photos go when segments change: a last segment that isn't full takes the photos added +/// after it; a segment is split only past twice its size; a segment keeps its place in the id +/// range when its first photo is removed; and a segment is never written over a file that is +/// there. +#[test] +fn segments_are_laid_out_as_documented() { + let firsts = |m: &MemStore| manifest(m)["segments"].as_array().unwrap().iter().map(|s| s["first"].as_u64().unwrap()).collect::>(); + let counts = |m: &MemStore| manifest(m)["segments"].as_array().unwrap().iter().map(|s| s["photos"].as_u64().unwrap()).collect::>(); + // a last segment of 2 (of 4) takes the next photos + let (m, mut j, mut c) = library(10, 4); + run(&mut j, &mut c, add(11..=12)); + j.snapshot(&c).unwrap(); + assert_eq!((firsts(&m), counts(&m)), (vec![1, 5, 9], vec![4, 4, 4])); + // now full: the next ones start a segment + run(&mut j, &mut c, add(13..=13)); + j.snapshot(&c).unwrap(); + assert_eq!((firsts(&m), counts(&m)), (vec![1, 5, 9, 13], vec![4, 4, 4, 1])); + + // a segment grows to twice its size before it is split (ids with room between them) + let m = MemStore::new(); + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + j.policy.segment_photos = 4; + run(&mut j, &mut c, add((1..=10).map(|k| k * 10))); + j.snapshot(&c).unwrap(); + assert_eq!((firsts(&m), counts(&m)), (vec![10, 50, 90], vec![4, 4, 2])); + run(&mut j, &mut c, add(51..=54)); + j.snapshot(&c).unwrap(); + assert_eq!((firsts(&m), counts(&m)), (vec![10, 50, 90], vec![4, 8, 2])); + run(&mut j, &mut c, add(55..=55)); + j.snapshot(&c).unwrap(); + assert_eq!((firsts(&m), counts(&m)), (vec![10, 50, 54, 80, 90], vec![4, 4, 4, 1, 2])); + assert_same(&reopen(&m), &c); + + // the first photo of a segment removed: the segment still starts where it did + let (m, mut j, mut c) = library(12, 4); + run(&mut j, &mut c, vec![Op::RemovePhoto { id: PhotoId(5) }]); + j.snapshot(&c).unwrap(); + assert_eq!((firsts(&m), counts(&m)), (vec![1, 5, 9], vec![4, 3, 4])); + + // two snapshots at the same op (the second of a catalog that differs): the segment written + // second is a new file, not the first one written over + let (m, mut j, c) = library(12, 4); + let first = listed(&m); + let mut other = c.clone(); + other.apply(Op::SetRating { id: PhotoId(2), rating: 5 }).unwrap(); + j.snapshot(&other).unwrap(); + let second = listed(&m); + assert_eq!(first.intersection(&second).count(), 2); + assert!(second.difference(&first).all(|n| !first.contains(n))); + assert_same(&reopen(&m), &other); +} + +/// A store that records the names it is asked to read or remove, fails writing the segments +/// whose name it is told to, and gives further handles (so segments are written and read on +/// several threads). +#[derive(Clone, Default)] +struct Watched { + files: MemStore, + asked: Arc>>, + fail: Arc>>, +} + +impl Store for Watched { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.asked.lock().unwrap().insert(name.to_string()); + self.files.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + if self.fail.lock().unwrap().as_deref().is_some_and(|f| name.starts_with(f)) { + return Err(std::io::Error::other("disk full")); + } + self.files.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.files.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.files.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.asked.lock().unwrap().insert(name.to_string()); + self.files.remove(name) + } + fn list(&mut self) -> std::io::Result> { + self.files.list() + } + fn segmented(&self) -> bool { + true + } + fn describe(&self) -> String { + "watched".into() + } + fn background_writer(&self) -> Option> { + Some(Box::new(self.clone())) + } +} + +/// Many segments are written on several threads; the result is the same, and when one of them +/// can't be written the snapshot fails as a whole: nothing of it stays, and the library is what +/// it was, with its log. +#[test] +fn segments_are_written_on_several_threads_or_not_at_all() { + let store = Watched::default(); + let (mut j, mut c, _) = Journal::open(Box::new(store.clone())).unwrap(); + j.policy.segment_photos = 4; + run(&mut j, &mut c, add(1..=80)); + j.snapshot(&c).unwrap(); + assert_eq!(j.stats().last_snapshot.segments, 20); + assert_eq!( + manifest(&store.files)["segments"].as_array().unwrap().iter().map(|s| s["first"].as_u64().unwrap()).collect::>(), + (0..20).map(|k| 1 + 4 * k).collect::>() + ); + assert_same(&reopen(&store.files), &c); + + // every segment changes; the one starting at photo 41 can't be written + let before = store.files.files.lock().unwrap().clone(); + run(&mut j, &mut c, (1..=80).map(|id| Op::SetRating { id: PhotoId(id), rating: 3 }).collect()); + let logged = store.files.get(LOG).unwrap(); + *store.fail.lock().unwrap() = Some(format!("{SEGMENT_PREFIX}41-")); + assert!(j.snapshot(&c).is_err()); + let mut after = store.files.files.lock().unwrap().clone(); + assert_eq!(after.remove(LOG), Some(logged)); + let mut expected = before.clone(); + expected.remove(LOG); + assert_eq!(after, expected, "a failed snapshot left or changed files"); + assert_same(&reopen(&store.files), &c); + // and it works again once the disk does + *store.fail.lock().unwrap() = None; + j.snapshot(&c).unwrap(); + assert_eq!(j.stats().last_snapshot.segments, 20); + assert_same(&reopen(&store.files), &c); +} + +/// A snapshot naming files that aren't segments is refused before any of them is read, and +/// nothing is ever removed under such a name. +#[test] +fn only_segment_files_are_ever_read_or_removed() { + for name in [ + "../segments/1-1.json", + "segments/../../x.json", + "segments/1-1.json/../../x", + "segments/sub/1-1.json", + "prefs.json", + "catalog.log", + "segments/.json", + "segments/1-1", + "segments/1-1.json.tmp", + "segments/١-1.json", + "catalog.seg-1-1", + ] { + let store = Watched::default(); + let (mut j, mut c, _) = Journal::open(Box::new(store.clone())).unwrap(); + j.policy.segment_photos = 4; + run(&mut j, &mut c, add(1..=12)); + j.snapshot(&c).unwrap(); + drop(j); + let mut v = manifest(&store.files); + let real = v["segments"][0]["name"].as_str().unwrap().to_string(); + v["segments"][0]["name"] = name.into(); + store.files.set(SNAPSHOT, serde_json::to_vec(&v).unwrap()); + // (what the name points at exists: the refusal is not for want of a file) + store.files.set(name, store.files.get(&real).unwrap()); + store.asked.lock().unwrap().clear(); + let e = Journal::open(Box::new(store.clone())).map(|_| ()).unwrap_err(); + assert!(matches!(&e, CatalogError::Corrupt(msg) if msg.contains("not a segment file")), "{name}: {e}"); + let asked = store.asked.lock().unwrap().clone(); + assert_eq!(asked.into_iter().collect::>(), [LOG, SNAPSHOT], "{name}"); + } + // the same file twice, and segments out of order, are refused as such + for (what, edit) in [ + ("twice", (|v| v["segments"][1] = v["segments"][0].clone()) as fn(&mut Value)), + ("out of order", |v| v["segments"].as_array_mut().unwrap().swap(0, 2)), + ] { + let (m, j, _c) = library(12, 4); + drop(j); + let mut v = manifest(&m); + edit(&mut v); + m.set(SNAPSHOT, serde_json::to_vec(&v).unwrap()); + let e = Journal::open(Box::new(m)).map(|_| ()).unwrap_err(); + assert!(matches!(&e, CatalogError::Corrupt(msg) if msg.contains(what)), "{what}: {e}"); + } +} + +/// Given a library saved in one file (format 10: `fixtures/v10-catalog.*`, written by that build, +/// with a log of later changes), when it is opened, then it reads as it was and is rewritten in +/// segments. +#[test] +fn a_v9_library_loads_and_is_split_into_segments() { + let old = include_str!("fixtures/v10-catalog.snap.json"); + let log = include_str!("fixtures/v10-catalog.log.jsonl"); + assert!(old.starts_with(r#"{"format":"lightcraft-catalog","version":10,"#)); + // what the format 10 build reads from these files: the single-file loader, unchanged + let v: Value = serde_json::from_str(old).unwrap(); + let mut expected = Catalog::from_snapshot(&v["catalog"].to_string()).unwrap(); + expected.replay(&log.lines().map(|l| serde_json::from_str::(l).unwrap()["op"].to_string() + "\n").collect::()).unwrap(); + assert_eq!(expected.len(), 3); + + let m = MemStore::new(); + m.set(SNAPSHOT, old.as_bytes().to_vec()); + m.set(LOG, log.as_bytes().to_vec()); + let (j, loaded, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!((r.replayed, r.failed, r.upgraded_from), (log.lines().count(), 0, Some(10))); + assert_same(&loaded, &expected); + assert_eq!(manifest(&m)["version"].as_u64(), Some(u64::from(VERSION))); + assert_eq!(manifest(&m)["catalog"]["photos"], serde_json::json!({})); + assert_eq!(listed(&m).len(), 1); + assert_eq!(segment_files(&m), listed(&m)); + assert!(m.get(LOG).unwrap().is_empty()); + drop(j); + let (_, again, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(r.upgraded_from, None); + assert_same(&again, &expected); +} + +/// A store whose segment files come back different from what was written. +#[derive(Clone, Default)] +struct Garbling { + files: MemStore, + garble: Arc>, + /// `catalog.snap` is written, and then the write is said to have failed. + fail_after_snap: Arc>, +} + +impl Store for Garbling { + fn read(&mut self, name: &str) -> std::io::Result>> { + let mut b = self.files.read(name)?; + if *self.garble.lock().unwrap() + && name.starts_with(SEGMENT_PREFIX) + && let Some(b) = b.as_mut() + && let Some(at) = b.iter().position(|x| *x == b'4') + { + // a digit of a number: still JSON, still the same length + b[at] = b'5'; + } + Ok(b) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.files.write_atomic(name, data)?; + if name == SNAPSHOT && *self.fail_after_snap.lock().unwrap() { + return Err(std::io::Error::other("folder not synced")); + } + Ok(()) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.files.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.files.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.files.remove(name) + } + fn list(&mut self) -> std::io::Result> { + self.files.list() + } + fn segmented(&self) -> bool { + true + } + fn describe(&self) -> String { + "garbling".into() + } +} + +/// Given a one-file library, when the segments written for it don't read back as the photos +/// that were loaded, then the one file is kept as it is: the library opens from it as before, +/// nothing of the failed attempt is left, and the split is tried again at the next open. +#[test] +fn a_split_that_does_not_read_back_keeps_the_one_file() { + let old = include_str!("fixtures/v10-catalog.snap.json"); + let log = include_str!("fixtures/v10-catalog.log.jsonl"); + let store = Garbling::default(); + store.files.set(SNAPSHOT, old.as_bytes().to_vec()); + store.files.set(LOG, log.as_bytes().to_vec()); + *store.garble.lock().unwrap() = true; + let (mut j, mut loaded, r) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!((r.replayed, r.upgraded_from), (log.lines().count(), None), "not upgraded"); + assert_eq!(store.files.get(SNAPSHOT).unwrap(), old.as_bytes()); + assert_eq!(store.files.get(LOG).unwrap(), log.as_bytes()); + assert!(segment_files(&store.files).is_empty()); + // the library is usable meanwhile, and its changes are saved + run(&mut j, &mut loaded, vec![Op::SetRating { id: PhotoId(8), rating: 2 }]); + // and no compaction writes the new format meanwhile (that would be an upgrade with nothing + // kept to go back to) + let snapshot = store.files.get(SNAPSHOT).unwrap(); + assert!(!j.wants_snapshot() && !j.wants_snapshot_on_close()); + j.snapshot_in_background(&loaded).unwrap(); + assert_eq!(store.files.get(SNAPSHOT).unwrap(), snapshot); + *store.garble.lock().unwrap() = false; + let (_, again, r) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!(r.upgraded_from, Some(10)); + assert_same(&again, &loaded); + assert_eq!(segment_files(&store.files), listed(&store.files)); +} + +/// Given a library whose upgrade was put off, when it is compacted by hand, then it is upgraded +/// and the files it was are kept (no upgrade without a way back), and it is no longer put off. +#[test] +fn a_compaction_by_hand_of_a_library_put_off_keeps_the_old_files() { + let old = include_str!("fixtures/v10-catalog.snap.json"); + let log = include_str!("fixtures/v10-catalog.log.jsonl"); + let store = Garbling::default(); + store.files.set(SNAPSHOT, old.as_bytes().to_vec()); + store.files.set(LOG, log.as_bytes().to_vec()); + *store.garble.lock().unwrap() = true; + let (mut j, loaded, r) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!(r.upgraded_from, None); + *store.garble.lock().unwrap() = false; + let seq = j.seq(); + j.snapshot(&loaded).unwrap(); + assert_eq!(store.files.get(&format!("{SNAPSHOT}.v10-{seq}")).as_deref(), Some(old.as_bytes())); + assert_eq!(store.files.get(&format!("{LOG}.v10-{seq}")).as_deref(), Some(log.as_bytes())); + // the upgrade has happened: it is no longer put off, so a change is compacted on close + let mut loaded = loaded; + run(&mut j, &mut loaded, vec![Op::SetRating { id: PhotoId(8), rating: 3 }]); + assert!(j.wants_snapshot_on_close(), "still put off after the compaction by hand"); + drop(j); + // and it opens as the new format, with nothing to upgrade again + let (_, again, r) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!(r.upgraded_from, None); + assert_same(&again, &loaded); +} + +/// Given a library whose upgrade was put off, when it has changes and is closed, then closing does +/// not compact it into the new format (nothing would be kept to go back to), and it opens again +/// as it was, its changes replayed from the log. +#[test] +fn closing_a_library_put_off_does_not_upgrade_it() { + let old = include_str!("fixtures/v10-catalog.snap.json"); + let log = include_str!("fixtures/v10-catalog.log.jsonl"); + let store = Garbling::default(); + store.files.set(SNAPSHOT, old.as_bytes().to_vec()); + store.files.set(LOG, log.as_bytes().to_vec()); + *store.garble.lock().unwrap() = true; + let (mut j, mut loaded, r) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!(r.upgraded_from, None); + run(&mut j, &mut loaded, vec![Op::SetRating { id: PhotoId(8), rating: 3 }]); + assert!(!j.wants_snapshot_on_close()); + drop(j); + let (_, again, r) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!(r.upgraded_from, None); + assert_same(&again, &loaded); +} + +/// Given a library put off whose compaction commits the new snapshot but then reports a failure +/// (the rename took effect), then the files it was are kept, not removed as if nothing happened. +#[test] +fn a_compaction_that_failed_after_its_commit_keeps_the_old_files() { + let old = include_str!("fixtures/v10-catalog.snap.json"); + let log = include_str!("fixtures/v10-catalog.log.jsonl"); + let store = Garbling::default(); + store.files.set(SNAPSHOT, old.as_bytes().to_vec()); + store.files.set(LOG, log.as_bytes().to_vec()); + *store.garble.lock().unwrap() = true; + let (mut j, loaded, _) = Journal::open(Box::new(store.clone())).unwrap(); + *store.garble.lock().unwrap() = false; + *store.fail_after_snap.lock().unwrap() = true; + let kept_seq = j.seq(); + assert!(j.snapshot_with_unlogged(&loaded, 2).is_err()); + assert_eq!(store.files.get(&format!("{SNAPSHOT}.v10-{kept_seq}")).as_deref(), Some(old.as_bytes()), "the way back stays"); +} + +/// A store without segments (the browser's): the photos stay in `catalog.snap`, and the +/// library moves to segments when it is opened where they are possible, and back. +#[test] +fn a_store_without_segments_keeps_one_file() { + let m = MemStore { single_file: true, ..Default::default() }; + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + j.policy.segment_photos = 4; + run(&mut j, &mut c, add(1..=10)); + j.snapshot(&c).unwrap(); + assert_eq!(manifest(&m)["catalog"]["photos"].as_object().unwrap().len(), 10); + assert!(manifest(&m)["segments"].as_array().is_none_or(|s| s.is_empty()) && segment_files(&m).is_empty()); + assert_same(&reopen(&m), &c); + drop(j); + + // the same files where segments are possible + let desktop = MemStore { single_file: false, ..crash_copy(&m) }; + let (mut j, mut c2, _) = Journal::open(Box::new(desktop.clone())).unwrap(); + assert_same(&c2, &c); + j.policy.segment_photos = 4; + run(&mut j, &mut c2, vec![Op::SetRating { id: PhotoId(3), rating: 3 }]); + j.snapshot(&c2).unwrap(); + assert_eq!(manifest(&desktop)["catalog"]["photos"], serde_json::json!({})); + assert_eq!(listed(&desktop).len(), 3); + assert_same(&reopen(&desktop), &c2); + drop(j); + + // and back: a store without segments that holds the segment files reads them and returns + // to one file + let back = MemStore { single_file: true, ..crash_copy(&desktop) }; + let (mut j, mut c3, _) = Journal::open(Box::new(back.clone())).unwrap(); + assert_same(&c3, &c2); + run(&mut j, &mut c3, vec![Op::SetRating { id: PhotoId(4), rating: 4 }]); + j.snapshot(&c3).unwrap(); + assert_eq!(manifest(&back)["catalog"]["photos"].as_object().unwrap().len(), 10); + assert_same(&reopen(&back), &c3); +} + +/// When to compact goes by what a compaction would rewrite: changes within one segment are +/// compacted after 2000 of them, however large the library; changes spread over the whole +/// library wait until the log is a quarter of the segments they touch. +#[test] +fn compaction_is_due_by_what_it_would_rewrite() { + let (_m, mut j, mut c) = library(20_000, 500); + assert!(j.snapshot_bytes() > 2_000_000); + // 2000 changes to photos of one segment + for k in 0..2000u64 { + assert!(!j.wants_snapshot(), "after {k} changes"); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(1 + k % 400), rating: (k % 6) as u8 }]); + } + assert!(j.wants_snapshot()); + j.snapshot(&c).unwrap(); + assert_eq!(j.stats().last_snapshot.segments, 1); + + // 2000 changes spread over every segment: not yet + let ops: Vec = (0..2000u64).map(|k| Op::SetRating { id: PhotoId(1 + k * 10), rating: 1 + (k % 5) as u8 }).collect(); + run(&mut j, &mut c, ops); + assert!(!j.wants_snapshot(), "{} records, {} bytes of log for {} bytes of snapshot", j.log_records(), j.log_bytes(), j.snapshot_bytes()); + // closing a library compacts a long log all the same (it isn't left long between sessions) + assert!(j.wants_snapshot_on_close()); + while !j.wants_snapshot() { + let ops: Vec = (0..2000u64).map(|k| Op::SetRating { id: PhotoId(1 + k * 10), rating: (k % 6) as u8 }).collect(); + run(&mut j, &mut c, ops); + } + assert!(j.log_bytes() >= j.snapshot_bytes() / 5, "{} of {}", j.log_bytes(), j.snapshot_bytes()); +} + +/// An import of many photos writes, in all its compactions together, little more than the +/// final catalog. +#[test] +fn an_import_writes_little_more_than_the_catalog() { + let m = MemStore::new(); + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + j.policy.segment_photos = 1000; + let mut written = 0; + let mut next = 1; + for _ in 0..80 { + run(&mut j, &mut c, add(next..next + 500)); + next += 500; + if j.wants_snapshot() { + j.snapshot(&c).unwrap(); + written += j.stats().last_snapshot.bytes; + } + } + j.snapshot(&c).unwrap(); + written += j.stats().last_snapshot.bytes; + assert!(written <= j.snapshot_bytes() * 5 / 2, "{written} bytes written for a catalog of {}", j.snapshot_bytes()); + assert_eq!(reopen(&m).len(), 40_000); +} + +proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(96))] + + /// Whatever is done to a library (photos added at the end, in gaps and below the first + /// one, removed, changed; snapshots in the foreground and by the worker; closing and + /// opening), opening its files gives the catalog as it is, and a snapshot taken right + /// after another has nothing to write: what the journal takes to be on disk is on disk. + #[test] + fn segments_hold_the_catalog_whatever_is_done( + per in 1usize..6, + steps in proptest::collection::vec((0u8..10, 0u64..40, 1u64..6), 1..60), + ) { + let m = MemStore { background: true, ..Default::default() }; + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + j.policy.segment_photos = per; + let mut next = 1000u64; + for (what, pick, n) in steps { + let ids: Vec = c.photos().map(|p| p.id).collect(); + let some = |k: u64| ids.get((k as usize) % ids.len().max(1)).copied(); + match what { + // an import at the end + 0 | 1 => { + run(&mut j, &mut c, add(next..next + n)); + next += n + pick % 3; + } + // photos between and below the ones there are + 2 => { + let id = 1 + pick * 23 % 990; + if c.photo(PhotoId(id)).is_none() { + run(&mut j, &mut c, add([id])); + } + } + 3 => { + if let Some(id) = some(pick) { + run(&mut j, &mut c, vec![Op::RemovePhoto { id }]); + } + } + // a run of photos removed + 4 => { + let gone: Vec = ids.iter().skip(pick as usize % ids.len().max(1)).take(n as usize * 2).map(|id| Op::RemovePhoto { id: *id }).collect(); + run(&mut j, &mut c, gone); + } + 5 | 6 => { + if let Some(id) = some(pick) { + run(&mut j, &mut c, vec![Op::SetRating { id, rating: (n % 6) as u8 }]); + } + } + 7 => { + j.snapshot(&c).unwrap(); + proptest::prop_assert_eq!(reopen(&m).to_snapshot(), c.to_snapshot()); + j.snapshot(&c).unwrap(); + proptest::prop_assert_eq!(j.stats().last_snapshot.segments, 0); + } + 8 => { + j.snapshot_in_background(&c).unwrap(); + if pick % 2 == 0 + && let Some(id) = some(pick) + { + run(&mut j, &mut c, vec![Op::SetRating { id, rating: (n % 6) as u8 }]); + } + j.wait().unwrap(); + } + _ => { + drop(j); + let (j2, c2, _) = Journal::open(Box::new(m.clone())).unwrap(); + proptest::prop_assert_eq!(c2.to_snapshot(), c.to_snapshot()); + j = j2; + c = c2; + j.policy.segment_photos = per; + j.remove_unlisted_segments(); + } + } + proptest::prop_assert_eq!(reopen(&crash_copy(&m)).to_snapshot(), c.to_snapshot()); + } + j.wait().unwrap(); + j.snapshot(&c).unwrap(); + proptest::prop_assert_eq!(reopen(&m).to_snapshot(), c.to_snapshot()); + j.snapshot(&c).unwrap(); + proptest::prop_assert_eq!(j.stats().last_snapshot.segments, 0); + proptest::prop_assert_eq!(segment_files(&m), listed(&m)); + // every photo is in the one segment whose stretch of ids holds it + let firsts: Vec = j.segments().iter().map(|s| s.first.0).collect(); + proptest::prop_assert!(firsts.windows(2).all(|w| w[0] < w[1])); + proptest::prop_assert_eq!(j.segments().iter().map(|s| s.photos).sum::(), c.len() as u64); + } +} + +/// Segments are sized by what they hold, not only by how many photos: where records are large +/// (long captions here; edited photos with their history in a real library), a segment holds +/// fewer of them, so that a change to one photo rewrites about as much either way. +#[test] +fn large_records_go_into_segments_of_fewer_photos() { + let m = MemStore::new(); + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + j.policy.segment_photos = 2000; + j.policy.segment_bytes = 256 << 10; + let heavy: Vec = (1..=1000u64) + .map(|id| { + let mut p = photo(id); + p.meta.caption = "a caption ".repeat(200); + Op::AddPhoto { photo: Box::new(p) } + }) + .collect(); + run(&mut j, &mut c, heavy); + // a first snapshot, of photos whose size isn't known yet: by count + j.snapshot(&c).unwrap(); + assert_eq!(j.segments().len(), 1); + // once it is, a segment that changes is cut to size, and so are photos added later + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(1), rating: 1 }]); + let more: Vec = (1001..=1400u64) + .map(|id| { + let mut p = photo(id); + p.meta.caption = "a caption ".repeat(200); + Op::AddPhoto { photo: Box::new(p) } + }) + .collect(); + run(&mut j, &mut c, more); + j.snapshot(&c).unwrap(); + let sizes: Vec<(u64, u64)> = j.segments().iter().map(|s| (s.photos, s.bytes)).collect(); + assert!(sizes.len() >= 8, "{sizes:?}"); + assert!(sizes.iter().all(|(photos, bytes)| *photos <= 260 && *bytes <= 600 << 10), "{sizes:?}"); + assert_same(&reopen(&m), &c); + + // small records: by count, as before + let (_m, j, _c) = library(1000, 300); + assert_eq!(j.segments().iter().map(|s| s.photos).collect::>(), [300, 300, 300, 100]); +} + +/// Given a library in segments that states other defaults for develop settings than this build +/// has (an Exposure of +1), when it is opened, on one thread or several, then every photo has +/// that Exposure, not this build's; and every segment is rewritten with this build's defaults, +/// stating the Exposure, before anything is added: none of the old ones is kept, and the library +/// opens the same again. +#[test] +fn a_library_in_segments_with_other_defaults_reads_as_it_was_written() { + let (m, j, _) = library(200, 8); + drop(j); + let before = listed(&m); + assert!(before.len() >= 20); + // as a build with other defaults wrote it: the same records, other stated defaults + let mut theirs = stored::base().1.clone(); + theirs["light"]["exposure"] = 1.0.into(); + let snap = String::from_utf8(m.get(SNAPSHOT).unwrap()).unwrap(); + let stated = format!("\"defaults\":{},", stored::base().0); + assert!(snap.contains(&stated)); + m.set(SNAPSHOT, snap.replace(&stated, &format!("\"defaults\":{theirs},")).into_bytes()); + + for background in [false, true] { + let m = MemStore { background, ..crash_copy(&m) }; + let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(r.other_defaults && r.upgraded_from.is_none(), "{r:?}"); + assert_eq!(c.len(), 200); + assert!(c.photos().all(|p| p.develop.light.exposure == 1.0), "background: {background}"); + + let after = listed(&m); + assert!(after.is_disjoint(&before), "every segment rewritten"); + assert_eq!(segment_files(&m), after, "the old ones are gone"); + assert_eq!(manifest(&m)["defaults"], stored::base().1); + let segment = String::from_utf8(m.get(after.iter().next().unwrap()).unwrap()).unwrap(); + // (stated first; a new photo's settings also state the rendering process it is on) + assert!(segment.contains(r#""develop":{"light":{"exposure":1.0}"#), "{}", &segment[..segment.len().min(400)]); + let (_, again, r) = Journal::open(Box::new(m)).unwrap(); + assert!(!r.other_defaults); + assert_same(&again, &c); + } +} + +/// The sizes a library gets unless told otherwise: segments of about 2 MB, and of at most 4096 +/// photos where records are small. (Measured: `docs/catalog-persistence.md`, "Segment size". +/// Larger ones rewrite more for the same edits; much smaller ones are many files to make +/// durable when everything changed.) +#[test] +fn a_segment_is_about_two_megabytes_and_at_most_4096_photos() { + // small records: by count + let m = MemStore::new(); + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + run(&mut j, &mut c, add(1..=10_000)); + j.snapshot(&c).unwrap(); + assert_eq!(j.segments().iter().map(|s| s.photos).collect::>(), [4096, 4096, 1808]); + assert!(j.segments().iter().all(|s| s.bytes <= 2 << 20), "{:?}", j.segments().iter().map(|s| s.bytes).collect::>()); + assert_same(&reopen(&m), &c); + + // large records: by size, once it is known + let m = MemStore::new(); + let (mut j, mut c, _) = Journal::open(Box::new(m.clone())).unwrap(); + let heavy: Vec = (1..=3000u64) + .map(|id| { + let mut p = photo(id); + p.meta.caption = "a caption ".repeat(200); + Op::AddPhoto { photo: Box::new(p) } + }) + .collect(); + run(&mut j, &mut c, heavy); + j.snapshot(&c).unwrap(); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(1), rating: 1 }]); + j.snapshot(&c).unwrap(); + let sizes: Vec<(u64, u64)> = j.segments().iter().map(|s| (s.photos, s.bytes)).collect(); + assert!(sizes.len() >= 3, "{sizes:?}"); + assert!(sizes.iter().all(|(photos, bytes)| *photos < 4096 && *bytes <= 5 << 19), "{sizes:?}"); + assert_same(&reopen(&m), &c); +} + +/// In a library folder the segments are files `segments/-.json`: a folder of +/// their own beside `catalog.snap`, made with the first of them; what is left of one being +/// written, and files nothing lists, are cleared out of it on request; other files are not. +#[test] +fn segments_are_json_files_in_a_folder_of_their_own() { + let dir = std::env::temp_dir().join(format!("lc-segments-folder-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let names = |d: &std::path::Path| { + let mut v: Vec = std::fs::read_dir(d).map(|r| r.map(|e| e.unwrap().file_name().into_string().unwrap()).collect()).unwrap_or_default(); + v.sort(); + v + }; + let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + assert!(!dir.join("segments").exists(), "an empty library has none"); + j.policy.segment_photos = 4; + run(&mut j, &mut c, add(1..=12)); + j.snapshot(&c).unwrap(); + assert_eq!(names(&dir), ["catalog.log", "catalog.snap", "segments"]); + assert_eq!(names(&dir.join("segments")), ["1-12.json", "5-12.json", "9-12.json"]); + assert_eq!(j.segments().iter().map(|s| s.name.as_str()).collect::>(), ["segments/1-12.json", "segments/5-12.json", "segments/9-12.json"]); + let text = std::fs::read_to_string(dir.join("segments/5-12.json")).unwrap(); + assert!(serde_json::from_str::(&text).unwrap()["photos"]["6"]["file_name"].is_string()); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(6), rating: 5 }]); + j.snapshot(&c).unwrap(); + assert_eq!(names(&dir.join("segments")), ["1-12.json", "5-13.json", "9-12.json"]); + drop(j); + // left by a crash, and a file that is somebody else's + for (name, bytes) in [("77-1.json", "x"), ("77-2.json.tmp", "x"), ("notes.txt", "mine")] { + std::fs::write(dir.join("segments").join(name), bytes).unwrap(); + } + let (mut j, back, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + assert_same(&back, &c); + j.remove_unlisted_segments(); + assert_eq!(names(&dir.join("segments")), ["1-12.json", "5-13.json", "9-12.json", "notes.txt"]); + drop(j); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The segments folder has to be a folder of the library's own. A file of that name, or a link +/// to a folder elsewhere, is an error that names it (and nothing in the folder linked to is +/// listed, read or removed); a folder that can't be read is an error too, never "no segments". +#[test] +fn a_segments_folder_that_is_not_one_is_an_error_that_says_so() { + let temp = |name: &str| { + let dir = std::env::temp_dir().join(format!("lc-segments-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + }; + // a file named `segments`: the snapshot fails and says why; the changes stay in the log + let dir = temp("file"); + std::fs::write(dir.join("segments"), b"not a folder").unwrap(); + // (no library is started in a folder like that: it says what is in the way) + let e = Journal::open(Box::new(FsStore::open(&dir).unwrap())).map(|_| ()).unwrap_err(); + assert!(e.to_string().contains("segments") && e.to_string().contains("not a folder"), "{e}"); + std::fs::remove_file(dir.join("segments")).unwrap(); + drop(Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap()); + std::fs::write(dir.join("segments"), b"not a folder").unwrap(); + let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + run(&mut j, &mut c, add(1..=12)); + let e = j.snapshot(&c).unwrap_err(); + assert!(e.to_string().contains("segments") && e.to_string().contains("not a folder"), "{e}"); + drop(j); + assert_eq!(std::fs::read(dir.join("segments")).unwrap(), b"not a folder"); + assert_eq!(Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap().1.len(), 12); + let _ = std::fs::remove_dir_all(&dir); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + // a link to a folder elsewhere: what is in there is not the library's + let (dir, elsewhere) = (temp("link"), temp("elsewhere")); + std::fs::write(elsewhere.join("2024-10.json"), b"somebody's").unwrap(); + drop(Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap()); + std::os::unix::fs::symlink(&elsewhere, dir.join("segments")).unwrap(); + let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + run(&mut j, &mut c, add(1..=12)); + assert!(j.snapshot(&c).unwrap_err().to_string().contains("not a folder")); + j.remove_unlisted_segments(); + drop(j); + assert_eq!(std::fs::read(elsewhere.join("2024-10.json")).unwrap(), b"somebody's"); + for d in [dir, elsewhere] { + let _ = std::fs::remove_dir_all(d); + } + + // segments that can't be listed, and no snapshot: refused, not opened as a new library + let dir = temp("unreadable"); + let (mut j, mut c, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + j.policy.segment_photos = 4; + run(&mut j, &mut c, add(1..=12)); + j.snapshot(&c).unwrap(); + drop(j); + std::fs::remove_file(dir.join(SNAPSHOT)).unwrap(); + std::fs::remove_file(dir.join(LOG)).unwrap(); + std::fs::set_permissions(dir.join("segments"), std::fs::Permissions::from_mode(0o300)).unwrap(); + let refused = Journal::open(Box::new(FsStore::open(&dir).unwrap())).map(|_| ()); + std::fs::set_permissions(dir.join("segments"), std::fs::Permissions::from_mode(0o700)).unwrap(); + // (a process that may read anything, as root in a container, lists it: then it is refused for the segments it holds) + assert!(refused.is_err(), "opened as a new library"); + assert!(!dir.join(SNAPSHOT).exists()); + let _ = std::fs::remove_dir_all(&dir); + } +} + +/// The plain write of the store (a whole file given at once) puts a segment in its folder too. +#[test] +fn every_way_of_writing_a_segment_makes_its_folder() { + let dir = std::env::temp_dir().join(format!("lc-segments-plain-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut store = FsStore::open(&dir).unwrap(); + store.write_atomic(&segment_file("1-1"), b"{}").unwrap(); + assert_eq!(std::fs::read(dir.join("segments/1-1.json")).unwrap(), b"{}"); + assert_eq!(store.list().unwrap(), ["segments/1-1.json"]); + store.remove(&segment_file("1-1")).unwrap(); + assert!(store.list().unwrap().is_empty()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/catalog/src/tests_stored.rs b/crates/catalog/src/tests_stored.rs new file mode 100644 index 00000000000..45b20f4cb27 --- /dev/null +++ b/crates/catalog/src/tests_stored.rs @@ -0,0 +1,1047 @@ +//! The stored form of catalog records ([`crate::stored`]): what is saved is only what was set, +//! and a saved library reads back exactly as it was. + +use std::sync::Arc; + +use lightcraft_develop::DevelopSettings; +use serde::Serialize; +use serde_json::Value; + +use crate::journal::{LOG, SNAPSHOT, VERSION, encode_record}; +use crate::*; + +// ---- fixtures (also used, as they are, to write `fixtures/v6.*` with the format 6 build) + +/// Settings with nothing stated, as every saved library reads them: every value its default, +/// on the first rendering process (new photos get the latest one, see +/// `the_rendering_process_survives`). The fixtures start from these, so they stay what the +/// format 6 build wrote when a new process becomes the default. +fn base() -> DevelopSettings { + serde_json::from_str("{}").unwrap() +} + +fn plain(id: u64) -> Photo { + let mut p = Photo::new( + PhotoId(id), + Source::File { path: format!("/pictures/2019/trip/IMG_{id:04}.jpg") }, + &format!("IMG_{id:04}.jpg"), + "JPEG", + 4032, + 3024, + "2026-10-10T12:00:00", + ); + p.develop = Arc::new(base()); + p +} + +fn edited(d: impl FnOnce(&mut DevelopSettings)) -> Arc { + let mut s = base(); + d(&mut s); + Arc::new(s) +} + +/// Settings with lists, choices and optional values: masks of several kinds, curve points, +/// guides, an Upright transform, a locked crop aspect, spots, red eye, point colours. +fn rich() -> DevelopSettings { + use lightcraft_develop::{Mask, MaskComponent, MaskOp, MaskShape, PointColor, RedEye, SegMask, Spot}; + use lightcraft_geom::{Homography, Point}; + let at = |x: f64, y: f64| Point { x, y }; + let seg = |side: u32| SegMask { side, data: "eJxjYAAAAAEAAQ==".into(), rect: Some([0.1, 0.2, 0.6, 0.7]) }; + let component = |shape: MaskShape| MaskComponent { name: None, op: MaskOp::default(), invert: false, shape }; + let mut s = DevelopSettings { treatment: lightcraft_develop::Treatment::Bw, ..base() }; + s.profile.id = "lc.mono".into(); + s.profile.amount = 150.0; + s.profile.camera_local_tone = true; + s.wb.tint = 12.0; + s.curve.master = vec![at(0.0, 0.0), at(0.4, 0.55), at(1.0, 1.0)]; + s.curve.red = vec![at(0.0, 0.1), at(1.0, 0.9)]; + s.point_colors = vec![PointColor { hue_shift: 20.0, ..Default::default() }]; + s.geometry.guides = vec![(at(0.1, 0.1), at(0.1, 0.9)), (at(0.9, 0.1), at(0.8, 0.9))]; + s.geometry.upright_transform = Some(Homography([1.0, 0.01, 0.0, -0.01, 1.0, 0.0, 0.0, 0.002, 1.0])); + s.crop.aspect = Some((3, 2)); + s.crop.flip_h = true; + s.crop.geometry.angle = 1.5; + s.spots = vec![Spot { points: vec![at(0.3, 0.3), at(0.32, 0.31)], source_offset: Some(at(0.05, 0.0)), ..Default::default() }]; + s.red_eye = vec![RedEye { center: at(0.5, 0.4), catchlight: Some(at(0.1, -0.1)), ..Default::default() }]; + s.masks = vec![ + Mask { + id: 1, + name: "Sky".into(), + components: vec![ + component(MaskShape::Linear { start: at(0.5, 0.0), end: at(0.5, 0.4) }), + MaskComponent { + name: Some("Sun".into()), + invert: true, + ..component(MaskShape::Radial { center: at(0.7, 0.2), rx: 0.1, ry: 0.1, angle: 0.0, feather: 50.0, invert: false }) + }, + component(MaskShape::LuminanceRange { lo: 0.6, hi: 1.0, lo_feather: 0.1, hi_feather: 0.0 }), + ], + refine: 30.0, + ..Default::default() + }, + Mask { + id: 2, + name: "Boat".into(), + components: vec![ + component(MaskShape::Object { + hint: vec![at(0.4, 0.6)], + exclude: vec![at(0.1, 0.1)], + seg: Some(seg(256)), + detail: vec![seg(128), seg(64)], + edge: 2.0, + }), + component(MaskShape::Prompt { text: "the red boat".into(), seg: None, detail: Vec::new(), edge: 0.0 }), + component(MaskShape::ColorRange { samples: vec![[0.5, 0.1, 0.2]], refine: 40.0 }), + component(MaskShape::People { person: 1, parts: vec!["face".into()] }), + component(MaskShape::Subject), + ], + ..Default::default() + }, + ]; + s.disabled_sections = vec!["detail".into(), "light".into()]; + s +} + +/// A photo with every field set to something other than what [`plain`] has. +fn full() -> Photo { + let look = edited(|s| s.light.contrast = 20.0); + let now = Arc::new(DevelopSettings { light: lightcraft_develop::Light { exposure: 0.3, ..Default::default() }, ..rich() }); + let mut p = plain(7); + p.kind = MediaKind::Raw; + p.file_size = 25_000_000; + p.captured = Some("2019-07-14T15:21:07".into()); + p.meta = Meta { + camera: "Camera Model X".into(), + lens: "24-70mm f/2.8".into(), + focal_mm: Some(35.0), + aperture: Some(4.0), + shutter: "1/250".into(), + iso: Some(400), + location: "Old harbour".into(), + city: "Lisbon".into(), + state: "Lisboa".into(), + country: "Portugal".into(), + gps: Some((38.7, -9.1)), + title: "Harbour".into(), + caption: "Boats at dusk".into(), + alt_text: "Three boats".into(), + extended_description: "Three boats moored at dusk".into(), + copyright: "(c) Someone".into(), + copyright_status: CopyrightStatus::Copyrighted, + usage_terms: "All rights reserved".into(), + copyright_url: "https://example.org/rights".into(), + creator: "Someone".into(), + keywords: vec!["Places|Lisbon".into(), "boats".into()], + regions: vec![lightcraft_meta::Region { + rect: lightcraft_meta::Rect { x0: 0.1, y0: 0.2, x1: 0.3, y1: 0.4 }, + kind: lightcraft_meta::RegionKind::Face, + name: Some("Ana".into()), + description: None, + }], + // (no format with a fixture had it; see `fields_since_the_fixtures_survive_the_stored_form`) + focus: None, + }; + p.rating = 4; + p.flag = Flag::Pick; + p.label = Some(ColorLabel::Green); + p.develop = now.clone(); + p.edited = Some("2026-10-10T13:00:00".into()); + p.versions = vec![Version { name: "Warm".into(), created: "2026-10-10T12:30:00".into(), settings: look.clone(), auto: true }]; + p.history = vec![HistoryStep { label: "Contrast".into(), settings: look.clone() }, HistoryStep { label: "Exposure".into(), settings: now }]; + p.deleted = true; + p.local = true; + p.duration = Some(12.5); + p.as_shot_wb = Some((5200.0, 3.0)); + p.content_hash = Some("00000000000000009e3779b97f4a7c15".into()); + p.embedded_lens = Some(lightcraft_develop::EmbeddedLens { vignette: Some(Default::default()), ..Default::default() }); + p.copy_of = Some(PhotoId(3)); + p.copy_name = Some("Copy 1".into()); + p.import_look = Some(look); + p.analysis = Some(Analysis { sharpness: 71.0, clipped: 0.02, group: Some(4), best: true }); + p.preview_only = Some("unsupported raw variant".into()); + p.local_baseline = Some(0xdead_beef); + p +} + +/// Changes made after the snapshot of the format 6 fixture (they are its log). +fn later_ops() -> Vec { + let warm = edited(|s| s.wb.temp += 500.0); + vec![ + Op::SetDevelop { id: PhotoId(8), settings: warm.clone(), label: "Temperature".into(), edited: Some("2026-10-10T14:00:00".into()) }, + Op::PushHistory { id: PhotoId(8), step: HistoryStep { label: "Temperature".into(), settings: warm } }, + Op::SetMeta { id: PhotoId(8), meta: Box::new(Meta { title: "Harbour".into(), keywords: vec!["boats".into()], ..Default::default() }) }, + Op::SetRating { id: PhotoId(9), rating: 3 }, + Op::SetVersions { + id: PhotoId(9), + versions: vec![Version { name: "Rich".into(), created: "2026-10-10T14:05:00".into(), settings: Arc::new(rich()), auto: false }], + }, + ] +} + +/// What a fixture of format 7 on holds besides: a camera's as-shot white balance read later, and +/// settings on the Kelvin scale (the format's `Op::SetAsShotWb` and `WhiteBalance.scale`). +fn kelvin_ops() -> Vec { + let kelvin = edited(|s| { + s.wb.scale = lightcraft_develop::WbScale::Kelvin; + s.wb.temp = 5200.0; + s.wb.tint = 8.0; + }); + vec![ + Op::SetAsShotWb { id: PhotoId(8), wb: Some((5200.0, 8.0)) }, + Op::SetDevelop { id: PhotoId(8), settings: kelvin, label: "White Balance".into(), edited: Some("2026-10-11T09:00:00".into()) }, + ] +} + +/// The changes a fixture's log holds: [`later_ops`], and from format 7 on [`kelvin_ops`]. +fn fixture_ops(version: u32) -> Vec { + let mut ops = later_ops(); + if version >= 7 { + ops.extend(kelvin_ops()); + } + ops +} + +// ---- end of fixtures + +fn catalog_of(photos: impl IntoIterator) -> Catalog { + let mut c = Catalog::new(); + for p in photos { + c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + c +} + +/// The stored record of the catalog's only photo, as JSON. +fn record(c: &Catalog) -> Value { + let v: Value = serde_json::from_str(&c.to_snapshot()).unwrap(); + v["photos"].as_object().unwrap().values().next().unwrap().clone() +} + +/// The catalog saved and read again (counting changes like the one it was read from). Every +/// photo must also read back with the same public JSON, which tells apart what `==` doesn't +/// (-0.0 and 0.0) and is what a photo's fingerprint and its preview-cache key are made from. +fn reopened(c: &Catalog) -> Catalog { + let mut r = Catalog::from_snapshot(&c.to_snapshot()).unwrap(); + r.revision = c.revision; + // and it reads the same over the defaults a library states (the path a library written with + // other defaults takes) as it does plainly: every setting is a value in a struct + { + let _over = stored::reading_over(Some(Arc::new(stored::base().1.clone()))); + let mut filled = Catalog::from_snapshot(&c.to_snapshot()).unwrap(); + filled.revision = c.revision; + assert_eq!(filled, r, "read over the library's defaults"); + } + for (a, b) in c.photos().zip(r.photos()) { + assert_eq!(serde_json::to_string(a.as_ref()).unwrap(), serde_json::to_string(b.as_ref()).unwrap()); + assert_eq!((a.fingerprint(), a.develop.hash64()), (b.fingerprint(), b.develop.hash64())); + } + r +} + +/// Given a photo nobody edited or described, when the library is saved, then its record holds +/// what identifies the file and nothing else. +#[test] +fn an_untouched_photo_is_stored_without_defaults() { + let c = catalog_of([plain(1)]); + let r = record(&c); + let keys: Vec<&str> = r.as_object().unwrap().keys().map(String::as_str).collect(); + assert_eq!(keys, ["develop", "file_name", "format", "height", "id", "imported", "source", "width"]); + assert_eq!(r["develop"], serde_json::json!({})); + assert_eq!(reopened(&c), c); +} + +/// The stored form leaves out a photo's fields that are unset, so libraries depend on what +/// "unset" reads as. If this fails because the record of an untouched photo changed, or one of +/// these defaults did: that is a new catalog format ([`journal::VERSION`]) whose loader gives +/// the photos of older libraries the old value. +#[test] +fn the_record_of_an_untouched_photo_is_pinned() { + let c = catalog_of([plain(1)]); + assert_eq!( + stored_text(&c), + r#"{"id":1,"source":{"type":"file","path":"/pictures/2019/trip/IMG_0001.jpg"},"file_name":"IMG_0001.jpg","format":"JPEG","width":4032,"height":3024,"imported":"2026-10-10T12:00:00","develop":{}}"# + ); + let unset = plain(1); + assert_eq!( + (unset.kind, unset.flag, unset.rating, unset.file_size, unset.deleted, unset.local), + (MediaKind::Image, Flag::None, 0, 0, false, false) + ); + assert_eq!((MediaKind::default(), Flag::default(), CopyrightStatus::default()), (MediaKind::Image, Flag::None, CopyrightStatus::Unknown)); + assert_eq!(Meta::default().copyright_status, CopyrightStatus::Unknown); +} + +/// The stored record of the catalog's only photo (id 1), as it is written. +fn stored_text(c: &Catalog) -> String { + let snapshot = c.to_snapshot(); + let start = snapshot.find(r#""1":{"#).unwrap() + 4; + let end = snapshot.find(r#"},"albums""#).unwrap(); + snapshot[start..end].to_string() +} + +/// Given a photo with a title only, then the stored metadata is the title only. +#[test] +fn metadata_is_stored_field_by_field() { + let mut p = plain(1); + p.meta.title = "Harbour".into(); + let c = catalog_of([p]); + assert_eq!(record(&c)["meta"], serde_json::json!({"title": "Harbour"})); + assert_eq!(reopened(&c), c); +} + +/// Given an edited photo, then its settings, history steps, versions and import look are stored +/// as what differs from the defaults. +#[test] +fn develop_settings_are_stored_as_their_difference_from_the_defaults() { + let mut p = plain(1); + p.develop = edited(|s| s.light.exposure = 0.3); + p.history = vec![HistoryStep { label: "Exposure".into(), settings: p.develop.clone() }]; + p.versions = vec![Version { name: "V".into(), created: "2026-10-10".into(), settings: p.develop.clone(), auto: false }]; + p.import_look = Some(edited(|s| s.light.contrast = 20.0)); + let c = catalog_of([p]); + let r = record(&c); + let exposure = serde_json::json!({"light": {"exposure": 0.3}}); + assert_eq!(r["develop"], exposure); + assert_eq!(r["history"][0]["settings"], exposure); + assert_eq!(r["versions"][0]["settings"], exposure); + assert_eq!(r["import_look"], serde_json::json!({"light": {"contrast": 20.0}})); + assert_eq!(reopened(&c), c); +} + +/// The fixture really sets every field: a field added to [`Photo`] or [`Meta`] must be added to +/// it (and to the stored form) before this passes. +#[test] +fn the_full_fixture_sets_every_field() { + let (f, b) = (serde_json::to_value(full()).unwrap(), serde_json::to_value(plain(1)).unwrap()); + for (k, v) in f.as_object().unwrap() { + if !["format", "width", "height", "imported"].contains(&k.as_str()) { + assert_ne!(Some(v), b.get(k), "the fixture leaves `{k}` at its default"); + } + } + let empty = serde_json::to_value(Meta::default()).unwrap(); + for (k, v) in f["meta"].as_object().unwrap() { + assert_ne!(Some(v), empty.get(k), "the fixture leaves `meta.{k}` at its default"); + } + // fields left out of the public form when unset are set too + for k in ["local", "content_hash", "embedded_lens", "copy_of", "copy_name", "import_look", "analysis", "preview_only", "local_baseline"] { + assert!(f.get(k).is_some(), "`{k}`"); + } + for k in ["copyright_status", "usage_terms", "copyright_url", "regions"] { + assert!(f["meta"].get(k).is_some(), "`meta.{k}`"); + } +} + +/// Given a photo with the fields no fixture's format has (a focus point, the build that checked a +/// preview-only raw), when the library is saved and reopened, then the stored form keeps each of +/// them. +#[test] +fn fields_since_the_fixtures_survive_the_stored_form() { + let mut p = plain(1); + p.meta.focus = Some(lightcraft_meta::FocusPoint { + rect: lightcraft_meta::Rect { x0: 0.4, y0: 0.4, x1: 0.5, y1: 0.5 }, + mode: Some("AF-C".into()), + area: Some("Wide".into()), + tracking: None, + }); + p.preview_checked = "0.8.0".into(); + let c = catalog_of([p]); + let r = record(&c); + assert_eq!(r["meta"]["focus"]["mode"], "AF-C"); + assert_eq!(r["preview_checked"], "0.8.0"); + assert_eq!(reopened(&c), c); +} + +/// Given a photo with everything set, when the library is saved and reopened, nothing is lost. +#[test] +fn a_photo_with_everything_set_reads_back_exactly() { + let c = catalog_of([full(), plain(8)]); + assert_eq!(reopened(&c), c); +} + +/// Every change that carries a photo, settings or metadata reads back from the log as it was. +#[test] +fn log_records_read_back_exactly_and_are_stored_compactly() { + let p = full(); + let ops = [ + Op::AddPhoto { photo: Box::new(p.clone()) }, + Op::AddPhoto { photo: Box::new(plain(9)) }, + Op::SetDevelop { id: p.id, settings: p.develop.clone(), label: "Exposure".into(), edited: None }, + Op::SetDevelop { id: p.id, settings: Arc::new(DevelopSettings::default()), label: "Reset".into(), edited: None }, + Op::SetMeta { id: p.id, meta: Box::new(p.meta.clone()) }, + Op::SetMeta { id: p.id, meta: Box::default() }, + Op::SetVersions { id: p.id, versions: p.versions.clone() }, + Op::SetHistory { id: p.id, history: p.history.clone() }, + Op::PushHistory { id: p.id, step: p.history[0].clone() }, + Op::Batch { ops: vec![Op::AddPhoto { photo: Box::new(plain(10)) }] }, + ]; + for (i, op) in ops.iter().enumerate() { + let line = encode_record(i as u64 + 1, op); + assert_eq!(journal::decode_record(&line), Some((i as u64 + 1, op.clone())), "{line}"); + } + let reset = encode_record(1, &ops[3]); + assert!(reset.len() < 200, "a reset stores no settings: {reset}"); + let added = encode_record(1, &ops[1]); + assert!(added.len() < 320, "{added}"); + let cleared = encode_record(1, &ops[5]); + assert!(cleared.len() < 80, "{cleared}"); +} + +/// Settings made before process versions existed leave the process out and read back as the +/// first process; settings on any other process state it. Neither may be confused with the other. +#[test] +fn the_rendering_process_survives() { + let on = |process: &str| -> Arc { Arc::new(serde_json::from_str(process).unwrap()) }; + for json in ["{}", r#"{"process":1}"#, r#"{"process":7}"#, r#"{"process":7,"light":{"exposure":1.0}}"#] { + let mut p = plain(1); + p.develop = on(json); + let c = catalog_of([p]); + assert_eq!(reopened(&c), c, "{json}"); + } + // a new photo: the default settings on the default process, stating only what that needs + let mut p = plain(1); + p.develop = Arc::new(DevelopSettings::default()); + let c = catalog_of([p]); + assert!(record(&c)["develop"].as_object().unwrap().keys().all(|k| k == "process"), "{}", record(&c)["develop"]); + assert_eq!(reopened(&c), c); +} + +/// A value that is read all or nothing is stored whole once any of it differs: a crop rectangle +/// with one edge moved keeps its other edges and its angle (left out one by one, the settings +/// would not read at all). +#[test] +fn a_value_read_all_or_nothing_is_stored_whole() { + let mut v = serde_json::to_value(base()).unwrap(); + v["crop"]["geometry"]["rect"]["x0"] = serde_json::json!(0.25); + let mut p = plain(1); + p.develop = Arc::new(serde_json::from_value(v).unwrap()); + let c = catalog_of([p]); + assert_eq!( + record(&c)["develop"], + serde_json::json!({"crop": {"geometry": {"angle": 0.0, "rect": {"x0": 0.25, "x1": 1.0, "y0": 0.0, "y1": 1.0}}}}) + ); + assert_eq!(reopened(&c), c); +} + +/// Changing any one number, switch or text of the develop settings is stored and read back. +#[test] +fn every_develop_setting_survives_on_its_own() { + fn leaves(v: &Value, path: &mut Vec, out: &mut Vec>) { + match v { + Value::Object(m) if !m.is_empty() => { + for (k, x) in m { + path.push(k.clone()); + leaves(x, path, out); + path.pop(); + } + } + _ => out.push(path.clone()), + } + } + fn at<'a>(v: &'a mut Value, path: &[String]) -> &'a mut Value { + path.iter().fold(v, |v, k| &mut v[k.as_str()]) + } + let default = serde_json::to_value(DevelopSettings::default()).unwrap(); + let mut paths = Vec::new(); + leaves(&default, &mut Vec::new(), &mut paths); + assert!(paths.len() > 100, "{}", paths.len()); + let mut tried = 0; + for path in &paths { + let mut changed = Vec::new(); + match at(&mut default.clone(), path).clone() { + Value::Number(n) => { + let x = n.as_f64().unwrap(); + changed.extend([ + serde_json::json!(x + 1.0), + serde_json::json!(x - 1.0), + serde_json::json!(0), + serde_json::json!(0.25), + serde_json::json!(-0.0), + ]); + } + Value::Bool(b) => changed.push(Value::Bool(!b)), + Value::String(s) => changed.push(Value::String(format!("{s}x"))), + // lists and optional values: see `rich_develop_settings_survive` + Value::Array(_) | Value::Null | Value::Object(_) => {} + } + for value in changed { + let mut v = default.clone(); + *at(&mut v, path) = value; + // values the settings don't accept there are not settings + let Ok(s) = serde_json::from_value::(v) else { continue }; + tried += 1; + let mut p = plain(1); + p.develop = Arc::new(s); + p.history = vec![HistoryStep { label: "x".into(), settings: p.develop.clone() }]; + let c = catalog_of([p]); + assert_eq!(reopened(&c), c, "{}", path.join(".")); + } + } + assert!(tried > 150, "{tried}"); +} + +/// Settings with lists, choices and optional values (masks, curve points, guides, the Upright +/// transform, a locked crop aspect, spots, red eye) read back exactly, in a photo and in the log. +#[test] +fn rich_develop_settings_survive() { + let rich = Arc::new(rich()); + let v = serde_json::to_value(rich.as_ref()).unwrap(); + for list in ["masks", "spots", "red_eye", "point_colors", "disabled_sections"] { + assert!(v[list].as_array().is_some_and(|a| !a.is_empty()), "`{list}`"); + } + assert!(!v["geometry"]["upright_transform"].is_null() && !v["crop"]["aspect"].is_null()); + let mut p = plain(1); + p.develop = rich.clone(); + p.history = vec![HistoryStep { label: "Masks".into(), settings: rich.clone() }]; + let c = catalog_of([p]); + assert_eq!(reopened(&c), c); + let op = Op::SetDevelop { id: PhotoId(1), settings: rich, label: "Masks".into(), edited: None }; + assert_eq!(journal::decode_record(&encode_record(1, &op)), Some((1, op))); +} + +/// A negative zero is a different number in the saved JSON (a camera's as-shot tint of -0.3 +/// rounds to it), and a photo's fingerprint and preview-cache key are made from that JSON: it is +/// stored, also where everything else is the default. Otherwise an untouched Local record would +/// count as changed once the library was reopened. +#[test] +fn a_negative_zero_survives() { + // on its own, where the default is 0.0 + let mut p = plain(1); + p.develop = edited(|s| s.wb.tint = -0.0); + assert_ne!(p.develop.hash64(), base().hash64()); + let c = catalog_of([p]); + assert_eq!(record(&c)["develop"].to_string(), r#"{"wb":{"tint":-0.0}}"#); + assert_eq!(reopened(&c), c); + + // a browsed raw whose as-shot tint rounded to -0.0: still untouched after reopening + let mut p = plain(2); + p.kind = MediaKind::Raw; + p.format = "DNG".into(); + p.as_shot_wb = Some((5200.0, (-0.3f64).round())); + p.develop = edited(|s| { + s.wb.temp = 5200.0; + s.wb.tint = (-0.3f64).round(); + s.detail.sharpen_amount = 40.0; + }); + p.local = true; + p.set_local_baseline(); + assert!(p.untouched_local()); + let c = catalog_of([p.clone()]); + let r = reopened(&c); + assert!(r.photos().next().unwrap().untouched_local()); + + // settings equal to the ones just stored, but for the sign of a zero, are not taken for them + let mut q = plain(3); + q.develop = edited(|s| { + s.wb.temp = 5200.0; + s.wb.tint = 0.0; + s.detail.sharpen_amount = 40.0; + }); + let c = catalog_of([q, p.clone(), plain(4)]); + assert_eq!(reopened(&c), c); + + // and in the log + let op = Op::SetDevelop { id: PhotoId(2), settings: p.develop.clone(), label: "x".into(), edited: None }; + let (_, back) = journal::decode_record(&encode_record(1, &op)).unwrap(); + let Op::SetDevelop { settings, .. } = back else { panic!() }; + assert_eq!(settings.hash64(), p.develop.hash64()); +} + +/// What other parts of the program read (the photo as JSON, and the Local browse fingerprint +/// made from it) is not the stored form: it still states every field. +#[test] +fn the_public_form_of_a_photo_still_states_every_field() { + let v = serde_json::to_value(plain(1)).unwrap(); + for k in + ["kind", "file_size", "captured", "meta", "rating", "flag", "label", "edited", "versions", "history", "deleted", "duration", "as_shot_wb"] + { + assert!(v.get(k).is_some(), "`{k}`"); + } + assert_eq!(v["develop"], serde_json::to_value(base()).unwrap()); + assert_eq!(v["meta"], serde_json::to_value(Meta::default()).unwrap()); +} + +/// A Local record browsed by an earlier version still counts as untouched: its fingerprint is +/// made from the public form, which did not change. (The number is what the format 6 build +/// computes for this record.) +#[test] +fn local_fingerprints_are_unchanged() { + let mut p = plain(1); + p.local = true; + assert_eq!(p.fingerprint(), FINGERPRINT_OF_PLAIN_LOCAL_1); +} +const FINGERPRINT_OF_PLAIN_LOCAL_1: u64 = 18_354_247_549_712_272_181; + +/// The library the fixture of format `version` holds (`fixtures/v-catalog.*`): three photos +/// in the snapshot, with a log of later changes. +pub(crate) fn fixture_library(version: u32) -> Catalog { + let mut library = fixture_snapshot(); + for op in fixture_ops(version) { + library.apply(op).unwrap(); + } + library +} + +/// What the fixtures' snapshot holds: a photo with every field set, an untouched one, and a +/// Local record with rich develop settings. +fn fixture_snapshot() -> Catalog { + let mut rich_photo = plain(9); + rich_photo.develop = Arc::new(rich()); + rich_photo.local = true; + rich_photo.set_local_baseline(); + catalog_of([full(), plain(8), rich_photo]) +} + +/// Writes this build's fixture, `fixtures/v-…`: the fixture library as this build saves +/// it, every file of it (`catalog.snap` as `v-catalog.snap.json`, `catalog.log` as +/// `v-catalog.log.jsonl`, a segment `segments/.json` as `v-segments-.json`). +/// Run it once, when a format is new: put empty files there for the snapshot and the log (the +/// tests include them), run +/// `cargo test -p lightcraft-catalog write_this_formats_fixture -- --ignored`, and list the +/// files it wrote in `tests_format_version::fixture`. They are then what that build wrote, and +/// are never written again. +#[test] +#[ignore = "writes fixtures/v-*"] +fn write_this_formats_fixture() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/fixtures"); + let file = |name: &str| { + let name = match name { + SNAPSHOT => "catalog.snap.json".to_string(), + LOG => "catalog.log.jsonl".to_string(), + other => other.replace('/', "-"), + }; + dir.join(format!("v{VERSION}-{name}")) + }; + let written = |f: &std::path::Path| std::fs::metadata(f).is_ok_and(|m| m.len() > 0); + assert!(!written(&file(SNAPSHOT)) && !written(&file(LOG)), "format {VERSION} has its fixture: a fixture is what that build wrote"); + let m = MemStore::new(); + let (mut j, _, _) = Journal::open(Box::new(m.clone())).unwrap(); + // the snapshot first, then the later changes as the log beside it + let mut library = fixture_snapshot(); + let photos: Vec = library.photos().map(|p| Op::AddPhoto { photo: Box::new((**p).clone()) }).collect(); + j.append(&photos).unwrap(); + j.snapshot(&library).unwrap(); + for op in fixture_ops(VERSION) { + library.apply(op.clone()).unwrap(); + j.append(&[op]).unwrap(); + } + drop(j); + for (name, bytes) in m.files.lock().unwrap().iter() { + std::fs::write(file(name), bytes).unwrap(); + } +} + +/// Given a library saved by the format 6 build (every field of every record written out; the +/// files in `fixtures/` were written by that build from the fixtures above, with a log of later +/// changes), when it is opened, then it reads as it was and is rewritten in the compact form. +#[test] +fn a_v6_library_loads_and_is_upgraded() { + let old = include_str!("fixtures/v6-catalog.snap.json"); + let log = include_str!("fixtures/v6-catalog.log.jsonl"); + assert!(old.starts_with(r#"{"format":"lightcraft-catalog","version":6,"#) && log.lines().count() == later_ops().len()); + let expected = fixture_library(6); + + let m = MemStore::new(); + m.set(SNAPSHOT, old.as_bytes().to_vec()); + m.set(LOG, log.as_bytes().to_vec()); + let (_, mut loaded, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!((r.replayed, r.failed, r.upgraded_from), (later_ops().len(), 0, Some(6))); + loaded.revision = expected.revision; + assert_eq!(loaded, expected); + let public = |c: &Catalog| c.photos().map(|p| serde_json::to_string(p.as_ref()).unwrap()).collect::>(); + assert_eq!(public(&loaded), public(&expected)); + // the Local record browsed with format 6 is still untouched (rating it since made it touched + // in both: compare the fingerprint of its state) + assert_eq!(loaded.photo(PhotoId(9)).unwrap().fingerprint(), expected.photo(PhotoId(9)).unwrap().fingerprint()); + + // rewritten in this format, compactly, and it reads the same again + let new = m.get(SNAPSHOT).unwrap(); + let head: Value = serde_json::from_slice(&new).unwrap(); + assert_eq!(head["version"].as_u64(), Some(u64::from(VERSION))); + assert!(m.get(LOG).unwrap().is_empty()); + // (the snapshot and the segments it lists) + let new_bytes: usize = + m.files.lock().unwrap().iter().filter(|(name, _)| *name == SNAPSHOT || name.starts_with(journal::SEGMENT_PREFIX)).map(|(_, b)| b.len()).sum(); + assert!(new_bytes > new.len() && new_bytes * 2 < old.len() + log.len(), "{} + {} -> {new_bytes}", old.len(), log.len()); + let (_, mut again, r) = Journal::open(Box::new(m)).unwrap(); + again.revision = expected.revision; + assert_eq!((again, r.upgraded_from), (expected, None)); +} + +/// The stored form leaves out values equal to the defaults, so a library depends on what a +/// missing value reads as: if that changed, every photo relying on it would silently change. +/// `develop_defaults.json` is what settings with nothing stated (`{}`) read as. +/// +/// If this fails because a setting was **added**, add it to the file (the test prints what it +/// reads now): libraries that never heard of it take its default. If what a missing value reads +/// as **changed**: saved libraries keep the old value, because each states its own defaults and +/// is read over those (`a_library_written_with_other_defaults_reads_as_it_was_written`); change +/// the file with it. A setting that was removed or renamed needs a loader of its own. (A new +/// default rendering process changes nothing here: settings without a process stay on the first +/// one, and photos on the default one state it.) +#[test] +fn what_missing_develop_settings_read_as_is_unchanged() { + let pinned: Value = serde_json::from_str(include_str!("develop_defaults.json")).unwrap(); + // (what a library states: every setting, also the ones left out of the settings' own JSON) + let now = stored::base().1.clone(); + // (as text too: `Value`'s own comparison takes -0.0 for 0.0) + assert_eq!(now.to_string(), pinned.to_string(), "see this test's comment"); + assert_eq!( + now, + pinned, + "what missing develop settings read as changed; see this test's comment. They read as:\n{}", + serde_json::to_string_pretty(&now).unwrap() + ); +} + +// ---- a library says what its missing values read as + +/// `catalog.snap` as a build with these defaults would have written it: `photos` are stored +/// records by id. +fn snapshot_stating(defaults: &Value, photos: Value) -> Vec { + let mut catalog: Value = serde_json::from_str(&Catalog::new().to_snapshot()).unwrap(); + catalog["photos"] = photos; + catalog["next_photo"] = 100.into(); + format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":2,\"defaults\":{defaults},\"catalog\":{catalog}}}\n").into_bytes() +} + +fn stated_defaults(m: &MemStore) -> Value { + let head: Value = serde_json::from_slice(&m.get(SNAPSHOT).unwrap()).unwrap(); + head["defaults"].clone() +} + +/// This build's defaults with an Exposure of +1 and a red hue of 5: what a build with other +/// defaults states. +fn other_defaults() -> Value { + let mut d = stored::base().1.clone(); + d["light"]["exposure"] = 1.0.into(); + d["mixer"]["red"]["hue"] = 5.0.into(); + d +} + +/// The stored record of an untouched photo, with these develop settings. +fn stored_record(id: u64, develop: Value) -> Value { + let mut r = record(&catalog_of([plain(id)])); + r["id"] = id.into(); + r["develop"] = develop; + r +} + +/// Given a saved library, then its snapshot states what a record's missing develop settings read +/// as: the settings of a record with nothing stated. +#[test] +fn a_library_states_what_missing_settings_read_as() { + let m = MemStore::new(); + let (mut j, _, _) = Journal::open(Box::new(m.clone())).unwrap(); + let pinned: Value = serde_json::from_str(include_str!("develop_defaults.json")).unwrap(); + assert_eq!(stated_defaults(&m), pinned, "a new library"); + j.snapshot(&catalog_of([plain(1)])).unwrap(); + assert_eq!(stated_defaults(&m), pinned, "a saved one"); + // and they are what a record with nothing stated reads as + assert_eq!(serde_json::from_value::(pinned).unwrap(), base()); +} + +/// Given a library written by a build whose defaults were an Exposure of +1 and a red hue of 5, +/// when this build opens it, then its photos are as that build left them: a photo that states +/// nothing has that Exposure and hue (not this build's 0), in its settings and in the history +/// step its log added; a photo that states an Exposure of 0 has 0. And the library is rewritten +/// with this build's defaults, stating what the photos now differ in, so it opens the same again. +#[test] +fn a_library_written_with_other_defaults_reads_as_it_was_written() { + // (in one file; a library in segments: `tests_segments`) + let m = MemStore { single_file: true, ..Default::default() }; + let photos = serde_json::json!({ + "1": stored_record(1, serde_json::json!({})), + "2": stored_record(2, serde_json::json!({"light": {"exposure": 0.0}})), + }); + m.set(SNAPSHOT, snapshot_stating(&other_defaults(), photos)); + let body = r#"{"op":"pushHistory","id":1,"step":{"label":"Import","settings":{}}}"#; + m.set(LOG, format!("{{\"seq\":3,\"crc\":{},\"op\":{body}}}\n", crc32fast::hash(body.as_bytes())).into_bytes()); + + let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(r.other_defaults && r.upgraded_from.is_none() && r.kept.is_empty(), "{r:?}"); + assert_eq!((r.replayed, r.failed), (1, 0)); + let (one, two) = (c.photo(PhotoId(1)).unwrap(), c.photo(PhotoId(2)).unwrap()); + assert_eq!((one.develop.light.exposure, one.develop.mixer.red.hue), (1.0, 5.0)); + assert_eq!((one.history[0].settings.light.exposure, one.history[0].settings.mixer.red.hue), (1.0, 5.0)); + assert_eq!((two.develop.light.exposure, two.develop.mixer.red.hue), (0.0, 5.0)); + // everything else is what both builds have + let mut expected = base(); + expected.light.exposure = 1.0; + expected.mixer.red.hue = 5.0; + assert_eq!(*one.develop, expected); + + // rewritten: this build's defaults, the photos' differences from them stated, no log + assert_eq!(stated_defaults(&m), stored::base().1); + assert!(m.get(LOG).unwrap().is_empty()); + let saved: Value = serde_json::from_slice(&m.get(SNAPSHOT).unwrap()).unwrap(); + assert_eq!(saved["catalog"]["photos"]["1"]["develop"].to_string(), r#"{"light":{"exposure":1.0},"mixer":{"red":{"hue":5.0}}}"#); + assert_eq!(saved["catalog"]["photos"]["2"]["develop"].to_string(), r#"{"mixer":{"red":{"hue":5.0}}}"#); + let (_, mut again, r) = Journal::open(Box::new(m)).unwrap(); + again.revision = c.revision; + assert!(!r.other_defaults); + assert_eq!(again, c); +} + +/// Given a library written before a setting existed (its defaults don't state it), when this +/// build opens it, then it is read as it is, the setting taking this build's default, and it is +/// not rewritten for that. +#[test] +fn a_library_that_only_lacks_newer_settings_is_read_as_it_is() { + let mut older = stored::base().1.clone(); + older.as_object_mut().unwrap().remove("lens_blur").unwrap(); + older["light"].as_object_mut().unwrap().remove("blacks").unwrap(); + let m = MemStore::new(); + let snap = snapshot_stating(&older, serde_json::json!({"1": stored_record(1, serde_json::json!({}))})); + m.set(SNAPSHOT, snap.clone()); + let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(!r.other_defaults, "{r:?}"); + assert_eq!(*c.photo(PhotoId(1)).unwrap().develop, base()); + assert_eq!(m.get(SNAPSHOT), Some(snap), "not rewritten"); +} + +/// Given a library written with other defaults that can't be rewritten (the disk is full), when +/// it is opened, then it is refused and left as it is: appending to it would leave out values +/// that mean something else in the file. +#[test] +fn a_library_with_other_defaults_that_cannot_be_rewritten_is_refused() { + struct ReadOnly(MemStore); + impl Store for ReadOnly { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.0.read(name) + } + fn write_atomic(&mut self, _: &str, _: &[u8]) -> std::io::Result<()> { + Err(std::io::Error::other("disk full")) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.0.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.0.truncate(name, len) + } + fn describe(&self) -> String { + "read-only".into() + } + } + let m = MemStore::new(); + let snap = snapshot_stating(&other_defaults(), serde_json::json!({"1": stored_record(1, serde_json::json!({}))})); + m.set(SNAPSHOT, snap.clone()); + let e = Journal::open(Box::new(ReadOnly(m.clone()))).err().expect("refused"); + assert!(matches!(e, CatalogError::Io(_)), "{e:?}"); + assert_eq!(m.files.lock().unwrap().clone(), [(SNAPSHOT.to_string(), snap)].into_iter().collect()); +} + +/// A reader of one library's defaults leaves the next library read on the thread alone. +#[test] +fn reading_over_a_librarys_defaults_ends_with_that_library() { + let m = MemStore::new(); + m.set(SNAPSHOT, snapshot_stating(&other_defaults(), serde_json::json!({"1": stored_record(1, serde_json::json!({}))}))); + Journal::open(Box::new(m)).unwrap(); + let plainly: DevelopSettings = serde_json::from_str::(&record(&catalog_of([plain(1)])).to_string()).map(|p| (*p.develop).clone()).unwrap(); + assert_eq!(plainly, base()); +} + +/// Given a library written by a build whose default for a setting that is left out of the +/// settings' JSON at its default was another one (the HDR section, the camera's local tone, +/// Denoise on or off), when this build opens it, then a photo that states nothing has the +/// library's value, not this build's: the library states those settings too. +#[test] +fn a_default_that_is_never_written_is_stated_all_the_same() { + let ours = stored::base().1.clone(); + assert!(ours["hdr"].is_object() && ours["profile"]["camera_local_tone"] == false && ours["enhance"]["denoise_on"].is_null(), "{ours}"); + let mut theirs = ours.clone(); + theirs["hdr"]["enabled"] = true.into(); + theirs["profile"]["camera_local_tone"] = true.into(); + theirs["enhance"]["denoise_on"] = true.into(); + let m = MemStore::new(); + m.set(SNAPSHOT, snapshot_stating(&theirs, serde_json::json!({"1": stored_record(1, serde_json::json!({}))}))); + let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(r.other_defaults, "{r:?}"); + let d = &c.photo(PhotoId(1)).unwrap().develop; + assert_eq!((d.hdr.enabled, d.profile.camera_local_tone, d.enhance.denoise_on), (true, true, Some(true))); + assert_eq!(**d, { + let mut expected = base(); + expected.hdr.enabled = true; + expected.profile.camera_local_tone = true; + expected.enhance.denoise_on = Some(true); + expected + }); + // and it opens the same once rewritten with this build's defaults + let (_, mut again, r) = Journal::open(Box::new(m)).unwrap(); + again.revision = c.revision; + assert!(!r.other_defaults); + assert_eq!(again, c); +} + +/// The settings whose JSON is left out at their default are exactly the ones the library +/// states by hand (`stored::UNWRITTEN`), and the rendering process, which has no default to +/// state. A setting given `skip_serializing_if` later fails here until it is stated too. +#[test] +fn every_setting_left_out_of_its_json_is_stated() { + let mut skipped = Skipped::default(); + base().serialize(&mut skipped).unwrap(); + let mut expected: Vec = stored::UNWRITTEN.iter().map(|(path, _)| path.join(".")).collect(); + expected.push("process".into()); + expected.sort(); + skipped.found.sort(); + assert_eq!(skipped.found, expected); + // and with them, the library states every leaf of the settings + let stated = &stored::base().1; + for (path, _) in stored::UNWRITTEN { + assert!(path.iter().try_fold(stated, |v, k| v.get(*k)).is_some(), "{path:?}"); + } +} + +/// Given a library written by a build that knew a setting this build doesn't, when this build +/// opens it, then it reads it as it is (the setting is not this build's to read, whatever it is +/// read over) and does not rewrite it for that. +#[test] +fn a_library_that_knows_more_settings_is_read_as_it_is() { + let mut newer = stored::base().1.clone(); + newer["light"]["glow"] = 7.0.into(); + newer["aurora"] = serde_json::json!({"amount": 1.0}); + let m = MemStore::new(); + let snap = snapshot_stating(&newer, serde_json::json!({"1": stored_record(1, serde_json::json!({}))})); + m.set(SNAPSHOT, snap.clone()); + let (_, c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(!r.other_defaults, "{r:?}"); + assert_eq!(*c.photo(PhotoId(1)).unwrap().develop, base()); + assert_eq!(m.get(SNAPSHOT), Some(snap), "not rewritten"); +} + +/// Walks a value and collects the struct fields it leaves out (`skip_serializing_if`), by path. +#[derive(Default)] +struct Skipped { + path: Vec<&'static str>, + found: Vec, +} + +type Walked = std::result::Result<(), std::fmt::Error>; + +impl serde::Serializer for &mut Skipped { + type Ok = (); + type Error = std::fmt::Error; + type SerializeSeq = serde::ser::Impossible<(), std::fmt::Error>; + type SerializeTuple = serde::ser::Impossible<(), std::fmt::Error>; + type SerializeTupleStruct = serde::ser::Impossible<(), std::fmt::Error>; + type SerializeTupleVariant = serde::ser::Impossible<(), std::fmt::Error>; + type SerializeMap = serde::ser::Impossible<(), std::fmt::Error>; + type SerializeStruct = Self; + type SerializeStructVariant = serde::ser::Impossible<(), std::fmt::Error>; + + fn serialize_struct(self, _: &'static str, _: usize) -> std::result::Result { + Ok(self) + } + fn serialize_some(self, v: &T) -> Walked { + v.serialize(self) + } + fn serialize_newtype_struct(self, _: &'static str, v: &T) -> Walked { + v.serialize(self) + } + // (lists and choices hold no setting with a default of its own: not walked) + fn serialize_seq(self, _: Option) -> std::result::Result { + Err(std::fmt::Error) + } + fn serialize_tuple(self, _: usize) -> std::result::Result { + Err(std::fmt::Error) + } + fn serialize_tuple_struct(self, _: &'static str, _: usize) -> std::result::Result { + Err(std::fmt::Error) + } + fn serialize_tuple_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> std::result::Result { + Err(std::fmt::Error) + } + fn serialize_map(self, _: Option) -> std::result::Result { + Err(std::fmt::Error) + } + fn serialize_struct_variant( + self, + _: &'static str, + _: u32, + _: &'static str, + _: usize, + ) -> std::result::Result { + Err(std::fmt::Error) + } + fn serialize_newtype_variant(self, _: &'static str, _: u32, _: &'static str, _: &T) -> Walked { + Ok(()) + } + fn serialize_bool(self, _: bool) -> Walked { + Ok(()) + } + fn serialize_i8(self, _: i8) -> Walked { + Ok(()) + } + fn serialize_i16(self, _: i16) -> Walked { + Ok(()) + } + fn serialize_i32(self, _: i32) -> Walked { + Ok(()) + } + fn serialize_i64(self, _: i64) -> Walked { + Ok(()) + } + fn serialize_u8(self, _: u8) -> Walked { + Ok(()) + } + fn serialize_u16(self, _: u16) -> Walked { + Ok(()) + } + fn serialize_u32(self, _: u32) -> Walked { + Ok(()) + } + fn serialize_u64(self, _: u64) -> Walked { + Ok(()) + } + fn serialize_f32(self, _: f32) -> Walked { + Ok(()) + } + fn serialize_f64(self, _: f64) -> Walked { + Ok(()) + } + fn serialize_char(self, _: char) -> Walked { + Ok(()) + } + fn serialize_str(self, _: &str) -> Walked { + Ok(()) + } + fn serialize_bytes(self, _: &[u8]) -> Walked { + Ok(()) + } + fn serialize_none(self) -> Walked { + Ok(()) + } + fn serialize_unit(self) -> Walked { + Ok(()) + } + fn serialize_unit_struct(self, _: &'static str) -> Walked { + Ok(()) + } + fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Walked { + Ok(()) + } +} + +impl serde::ser::SerializeStruct for &mut Skipped { + type Ok = (); + type Error = std::fmt::Error; + + fn serialize_field(&mut self, key: &'static str, v: &T) -> Walked { + self.path.push(key); + // (a list or a choice: nothing in it to walk) + let _ = v.serialize(&mut **self); + self.path.pop(); + Ok(()) + } + fn skip_field(&mut self, key: &'static str) -> Walked { + self.found.push(self.path.iter().chain([&key]).copied().collect::>().join(".")); + Ok(()) + } + fn end(self) -> Walked { + Ok(()) + } +} diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index e91f0bfff0c..c2073d1b441 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -4,6 +4,7 @@ //! ```text //! LightCraft Library/ //! catalog.snap catalog.log (lightcraft-catalog journal) +//! segments/ (the snapshot's photos: JSON files that catalog.snap lists) //! presets.json view.json (user presets + favourites; last source/sort/selection) //! prefs.json (library preferences: XMP sidecars, import defaults, cache size, last export) //! thumbs/ (rendered thumbnail cache, safe to delete) @@ -306,6 +307,20 @@ struct SettingsLoad { blocked: Vec<&'static str>, } +/// What to tell the person when opening the library upgraded it: the files it was are kept +/// beside it (as large as it was), and are theirs to delete. +fn kept_note(report: &LoadReport) -> Option { + if report.kept.is_empty() { + return None; + } + // (a library whose log was damaged: that log is the other half of what it was) + let kept: Vec<&str> = report.kept.iter().chain(&report.damaged).map(String::as_str).collect(); + Some(format!( + "This library was upgraded for this version of LightCraft, and earlier versions can't open it now. The library as it was is kept beside it as {}: delete it once the earlier version is no longer wanted (docs/catalog-persistence.md, \"Going back to an older version\").", + kept.join(" and ") + )) +} + impl SettingsLoad { fn read(&mut self, store: &mut dyn Store, name: &'static str) -> Option { let bytes = match store.read(name) { @@ -465,6 +480,11 @@ impl Session { #[cfg(not(target_arch = "wasm32"))] self.faces.library_changed(); let (mut journal, mut catalog, report) = Journal::open(catalog)?; + if lock.as_ref().is_some_and(|l| l.held()) { + // (only with the library's lock actually held, not one the file system could not give: + // see `Journal::remove_unlisted_segments`) + journal.remove_unlisted_segments(); + } // A loaded catalog counts revisions from 0, like every other one. Caches (sidebar counts, // keyword tree, the grid's list…) are keyed on the revision, so give each library loaded // in this process its own range: otherwise an empty library opened after one that was @@ -569,6 +589,7 @@ impl Session { self.tidy_thumbnail_cache(); } let view_written = self.view_json(); + let kept = kept_note(&report); self.library = Some(Library { dir, on_disk, @@ -581,7 +602,7 @@ impl Session { forgot_local: None, presets_saved, view_written, - settings_warnings: unlocked_warning(lock.as_ref()).into_iter().chain(settings.warnings).collect(), + settings_warnings: unlocked_warning(lock.as_ref()).into_iter().chain(kept).chain(settings.warnings).collect(), warnings_reported: 0, blocked: settings.blocked, lock: lock.take(), @@ -679,9 +700,11 @@ impl Session { lib.unsaved_error.as_deref().filter(|_| !self.pending_log.is_empty()).map(|e| (self.pending_log.len(), e)) } - /// Flush everything and write a snapshot (on quit). Ends an open interaction first. + /// Flush everything and compact the log into a snapshot (on quit). Ends an open interaction + /// first. A large catalog with only a short log keeps the log instead (see + /// [`Journal::wants_snapshot_on_close`]): everything is saved, and the next open replays it. /// - /// The snapshot is written even when appending the queued ops fails: it is a fresh file + /// The snapshot is always written when appending the queued ops fails: it is a fresh file /// holding everything in memory, so it saves those ops too (the log handle may be the only /// thing that's broken). Fails only if nothing could be saved; the ops then stay queued. pub fn close_library(&mut self) -> Result<()> { @@ -694,7 +717,20 @@ impl Session { let unlogged = if persisted.is_err() { self.pending_log.len() as u64 } else { 0 }; let Some(lib) = self.library.as_mut() else { return Ok(()) }; let before = lib.journal.seq(); - let snapshot = lib.journal.snapshot_with_unlogged(&self.catalog, unlogged); + let saved = unlogged == 0 && persisted.is_ok(); + if saved { + // a compaction that is under way (the save above may have started it) finishes first: + // it empties the log, and the catalog isn't written a second time below + if let Err(e) = lib.journal.wait() { + log::error!("library: compaction: {e}"); + } + } + let snapshot = if !saved || lib.journal.wants_snapshot_on_close() { + lib.journal.snapshot_with_unlogged(&self.catalog, unlogged) + } else { + // everything is in the log, which is short: the next open replays it + Ok(()) + }; if unlogged > 0 && lib.journal.seq() == before + unlogged { // the snapshot holds the queued ops: they are saved, never append them again log::info!("library: {unlogged} queued change(s) saved in the closing snapshot"); diff --git a/crates/engine/src/tests_forget_local.rs b/crates/engine/src/tests_forget_local.rs index 229b262a04c..061ad309102 100644 --- a/crates/engine/src/tests_forget_local.rs +++ b/crates/engine/src/tests_forget_local.rs @@ -198,13 +198,26 @@ fn upgraded_catalogs_forget_nothing_at_first() { look_elsewhere(&mut s); s.close_library().unwrap(); drop(s); - // strip the times and baselines, as an older version would have written the snapshot + // the snapshot as an older version would have written it: one file holding the photos, + // without the times and baselines let snap = std::fs::read_to_string(lib.join("catalog.snap")).unwrap(); let mut v: serde_json::Value = serde_json::from_str(&snap).unwrap(); + let segments = v.as_object_mut().unwrap().remove("segments").unwrap(); + v.as_object_mut().unwrap().remove("photos"); + v["version"] = 1.into(); v["catalog"].as_object_mut().unwrap().remove("browsed"); - for p in v["catalog"]["photos"].as_object_mut().unwrap().values_mut() { - p.as_object_mut().unwrap().remove("local_baseline"); + let mut photos = serde_json::Map::new(); + for segment in segments.as_array().unwrap() { + let file = lib.join(segment["name"].as_str().unwrap()); + let held: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + photos.extend(held["photos"].as_object().unwrap().clone()); + std::fs::remove_file(file).unwrap(); } + assert_eq!(photos.len(), 1); + for p in photos.values_mut() { + assert!(p.as_object_mut().unwrap().remove("local_baseline").is_some()); + } + v["catalog"]["photos"] = photos.into(); std::fs::write(lib.join("catalog.snap"), serde_json::to_vec(&v).unwrap()).unwrap(); set(&clock, "2027-01-01T10:00:00"); let s = open(&lib, &clock); diff --git a/crates/engine/src/tests_library.rs b/crates/engine/src/tests_library.rs index 5460dc0207e..9fd96679042 100644 --- a/crates/engine/src/tests_library.rs +++ b/crates/engine/src/tests_library.rs @@ -59,7 +59,8 @@ fn edits_survive_restart_without_close() { fn threshold_compaction_runs_in_the_background() { let dir = temp_dir("bg-compact"); let mut s = open(&dir, true); - s.library.as_mut().unwrap().journal_mut().policy = lightcraft_catalog::SnapshotPolicy { max_records: 8, max_bytes: u64::MAX }; + s.library.as_mut().unwrap().journal_mut().policy = + lightcraft_catalog::SnapshotPolicy { max_records: 8, max_bytes: u64::MAX, snapshot_share: 0, ..Default::default() }; let ids: Vec<_> = s.catalog.photos().map(|p| p.id).collect(); let mut background = 0; for k in 0..60usize { @@ -73,10 +74,36 @@ fn threshold_compaction_runs_in_the_background() { let expect = s.catalog.to_snapshot(); let copy = temp_dir("bg-compact-crash"); std::fs::create_dir_all(©).unwrap(); - for f in ["catalog.snap", "catalog.log"] { - if dir.join(f).exists() { - std::fs::copy(dir.join(f), copy.join(f)).unwrap(); + // the catalog's files as they are at one moment: copied again if the compaction in + // flight replaced any of them meanwhile (a crash is an instant, a copy is not) + let catalog_files = || -> Vec<(String, Vec)> { + let names = |sub: &str| -> Vec { + std::fs::read_dir(dir.join(sub)) + .map(|d| d.filter_map(|e| e.ok()?.file_name().into_string().ok()).map(|n| format!("{sub}{n}")).collect()) + .unwrap_or_default() + }; + // the snapshot and the log, and the snapshot's segments in their folder + let mut files: Vec<_> = names("") + .into_iter() + .filter(|n| n.starts_with("catalog.") && n != "catalog.lock") + .chain(names("segments/")) + .filter(|n| !n.ends_with(".tmp")) + .filter_map(|n| std::fs::read(dir.join(&n)).ok().map(|b| (n, b))) + .collect(); + files.sort(); + files + }; + let mut files = catalog_files(); + loop { + let again = catalog_files(); + if again == files { + break; } + files = again; + } + std::fs::create_dir_all(copy.join("segments")).unwrap(); + for (name, bytes) in &files { + std::fs::write(copy.join(name), bytes).unwrap(); } let s2 = open(©, true); assert_eq!(s2.catalog.to_snapshot(), expect); diff --git a/crates/engine/src/tests_persist.rs b/crates/engine/src/tests_persist.rs index 4fb3f0234cb..39309fdbde7 100644 --- a/crates/engine/src/tests_persist.rs +++ b/crates/engine/src/tests_persist.rs @@ -137,7 +137,8 @@ fn failed_append_of_undo_is_reported_and_retried() { fn failed_snapshot_does_not_fail_the_command() { let store = Flaky { snapshots_only: true, ..Default::default() }; let mut s = open(&store, false); - s.library.as_mut().unwrap().journal_mut().policy = SnapshotPolicy { max_records: 1, max_bytes: u64::MAX }; + s.library.as_mut().unwrap().journal_mut().policy = + SnapshotPolicy { max_records: 1, max_bytes: u64::MAX, snapshot_share: 0, ..Default::default() }; store.set_failing(true); s.execute("album.create", &json!({"name": "A"})).unwrap(); s.execute("album.create", &json!({"name": "B"})).unwrap(); @@ -191,3 +192,64 @@ fn close_fails_when_nothing_can_be_saved() { s.close_library().unwrap(); assert_eq!(s.unsaved(), None); } + +/// Given a library with a large catalog, when it is closed after one change, then the snapshot +/// is not rewritten for it: the change is in the log, and opening the library again shows it. +/// A small library (the default) is compacted on close as before, and closing with nothing +/// changed writes nothing. +#[test] +fn close_rewrites_a_large_snapshot_only_when_the_log_is_long() { + let store = Flaky::default(); + let mut s = open(&store, true); + let id = s.selection.active.unwrap(); + let snap = || store.files.get("catalog.snap").unwrap(); + let log = || store.files.get("catalog.log").unwrap_or_default(); + + // small: compacted on close + s.execute("photo.rate", &json!({"rating": 2})).unwrap(); + assert!(!log().is_empty()); + s.close_library().unwrap(); + assert!(log().is_empty()); + let compacted = snap(); + + // nothing changed: nothing written + let written = s.library.as_ref().unwrap().journal().stats().snapshots; + s.close_library().unwrap(); + assert_eq!(s.library.as_ref().unwrap().journal().stats().snapshots, written); + + // "large": the snapshot is above what a close rewrites in passing + s.library.as_mut().unwrap().journal_mut().policy.close_bytes = 0; + s.execute("photo.rate", &json!({"rating": 5})).unwrap(); + s.close_library().unwrap(); + assert_eq!(snap(), compacted, "the snapshot was rewritten"); + assert!(!log().is_empty()); + let expect = s.catalog.to_snapshot(); + drop(s); + let s2 = open(&store, true); + assert_eq!(s2.catalog.to_snapshot(), expect); + assert_eq!(s2.catalog.photo(id).unwrap().rating, 5); +} + +/// Given a library saved by an earlier version, when it is opened, then the person is told once +/// that it was upgraded and where the library as it was is kept (the files are theirs to +/// delete), and `library.info` lists it; a library that was not upgraded says nothing. +#[test] +fn an_upgraded_library_says_where_what_it_was_is_kept() { + let dir = std::env::temp_dir().join(format!("lightcraft-kept-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("catalog.snap"), include_str!("../../catalog/src/fixtures/v6-catalog.snap.json")).unwrap(); + std::fs::write(dir.join("catalog.log"), include_str!("../../catalog/src/fixtures/v6-catalog.log.jsonl")).unwrap(); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + let told = s.take_library_warnings(); + assert!(told.iter().any(|w| w.contains("catalog.snap.v6-8") && w.contains("catalog.log.v6-8") && w.contains("delete")), "{told:?}"); + assert!(dir.join("catalog.snap.v6-8").exists() && dir.join("catalog.log.v6-8").exists()); + let info = s.execute("library.info", &serde_json::json!({})).unwrap(); + assert!(info["settingsWarnings"].to_string().contains("catalog.snap.v6-8"), "{info}"); + s.close_library().unwrap(); + s.open_library(&dir, false).unwrap(); + assert!(!s.take_library_warnings().iter().any(|w| w.contains("upgraded"))); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md new file mode 100644 index 00000000000..94c2421b820 --- /dev/null +++ b/docs/catalog-persistence.md @@ -0,0 +1,295 @@ +# Catalog persistence: what is stored and when it is rewritten + +The catalog is saved in the library folder by `crates/catalog/src/journal.rs`: + +- `catalog.log`: one JSON line per change. Every change is appended and fsynced before its command returns. +- `catalog.snap`: the snapshot the log is compacted into now and then. It holds everything but the photos (albums, + keywords, folders, counters) and lists the segment files. +- `segments/-.json`: the **segments**, each a run of photos in id order, as JSON. The numbers in a + name say which photos it starts at and at which change it was written; what tells LightCraft which photos a segment + holds is the list in `catalog.snap`. + +This page covers catalog formats 10 (compact records) and 11 (segments): the stored form of records, the segments, the +rule for when to compact, and the measurements behind them. + +## The stored form + +A photo's record states only what was set (`crates/catalog/src/stored.rs`): + +- fields of the photo and of its metadata that are empty, zero or unset are left out; +- develop settings (the photo's, and those of its history steps, versions and import look) are stored as their + difference from the defaults: `{}` for a photo nobody edited. + +Reading did not change: a missing field reads as its default, so libraries of formats 1 to 9 load as they are and are +rewritten in the current format when first opened. Earlier builds refuse a library in a newer format. + +The files an upgrade replaces are kept: see "Going back to an older version" below. + +`catalog.query` and the other commands still return every field. That public form of a photo is also what a Local +record's fingerprint and the preview-cache key are made from, so neither changed. + +Three rules keep what is left out safe: + +- **A value is left out only where that reads back the same.** Which values that holds for is worked out from the + types themselves when the program starts, not from a list: not the rendering process (a missing process means the + first one), and not single fields of a value that is read all or nothing (the crop rectangle). +- **Every difference is read back and compared before it is written.** Settings that would not survive are stored in + full, as before. +- **The library says what a missing value reads as.** `catalog.snap` states it (`"defaults"`: the settings of a + record with nothing stated, about 2.8 kB once per library), and that covers the log beside it. Every setting is + stated, also the few whose own JSON is left out at their default (the white balance scale, the HDR section, the + camera's local tone, Denoise on or off); only the rendering process is not, since a record without one is on the first process in every build. So what a photo's + record means does not depend on the defaults of the LightCraft that reads it: + - a build with the same defaults reads the records as they are, at no cost; + - a build that only has settings the library never heard of does too (they take that build's default), and so + does one that lacks settings the library knows (it would not read them whatever it read them over); + - a build whose defaults differ reads every record over the library's own, then rewrites the library with its own + before anything is added to it (`LoadReport::other_defaults`). If that can't be written, the library is refused + and left as it is. + + What a missing value reads as in the current build is also pinned by a test + (`crates/catalog/src/develop_defaults.json`), so a changed default is seen when it is made. A setting that is + removed or renamed needs a loader of its own. + +## Going back to an older version + +Opening a library with a newer LightCraft rewrites it in that version's format, and older versions then refuse it +(safely: they say so and change nothing). So that this is not a one-way step, the upgrade first keeps the files the +library was, byte for byte, beside it: + +- `catalog.snap.v-` and `catalog.log.v-`, where `` is the format they are in and + `` the number of the last change the library held when it was upgraded (a library that had no log, or only a + log, has only the one file). `Journal::open` reports their names (`LoadReport::kept`) and logs them. +- The kept files stay unless the library is known to be in its old format still: once the upgrade is written, + nothing that fails after it takes them away. +- A library that can't be kept, or whose upgrade can't be written (a full disk, a folder that can't be written to), + is not opened where working in it as it is would not be safe: one that states no defaults for develop settings + (formats before 10), or other ones than this version's. The error says why, and the catalog is not changed (a torn + last record of its log is still cut off, as on any open). A library that states this version's defaults opens as + it is, and the next open tries again. +- A library whose log was damaged is upgraded like any other. What it was is then its snapshot, kept under the name + above, and its log, kept as `catalog.log.damaged-`: the snapshot alone is the library without the changes + that log held. +- Nothing removes the kept files. They are as large as the library was; LightCraft says so once when it has upgraded + a library (and `library.info` lists it under `settingsWarnings`). Delete them once the older version is no longer + wanted. The browser build keeps none (it always runs the newest version). + +**To go back**, with LightCraft closed: move `catalog.snap`, `catalog.log` **and the `segments` folder** away, then +give each kept file its own name back: `catalog.snap.v-` becomes `catalog.snap`, and the kept log +(`catalog.log.v-`, or `catalog.log.damaged-` where the log was damaged) becomes `catalog.log`. A +library that had only one of them (no log, or no snapshot) has only that one to rename. The older version opens the +library as it was when it was upgraded; changes made since, in the newer version, are in what was moved away and +are not carried back. + +The `segments` folder must go with them. It holds the newer library's photos, and left in place it would be taken for +leftovers once a newer version has opened the library the older one wrote (when it next opens it), and removed. + +Only a library in one file (formats up to 10) is kept this way. One already in segments would need its segments kept +too; no upgrade from such a format exists yet, and a backup (below) is the way back from a future one. + +## Segments (format 11) + +A compaction used to rewrite the whole catalog. Now it writes only the segments whose photos changed +(`crates/catalog/src/segments.rs`), so its cost follows what changed, and opening a library reads its segments on +several threads. + +- **Which segments changed** is not worked out from the changes logged. The journal keeps the photos as the segments + on disk hold them (shared pointers, not copies) and compares: a photo is unchanged while the catalog still points + to the same one, and changing a photo copies it. So a segment is rewritten exactly when one of its photos was + changed, added or removed, whatever did it. +- **Size.** A segment holds up to 4096 photos and about 2 MB (measured: "Segment size" below): where records are + large (edited photos with their history), fewer photos, down to 64. One that changes is cut into pieces once it holds more than twice that; one + left without photos is dropped. Photos added after a full last segment start new ones, so an import leaves the + existing segments alone. A small library is one segment. +- **Commit.** New segments are written under names no snapshot lists (several at once, each fsynced), then + `catalog.snap` is replaced atomically, which is the commit, then the files it no longer lists are removed. A crash + at any point leaves a snapshot with all its segments; files nothing lists are removed when the library is next + opened by a program that holds its lock. +- **Checks on open.** Each segment's size, CRC-32, photo count and range of ids, and the total number of photos, must + be what `catalog.snap` states. A damaged or missing segment fails the open with an error naming the file, and + nothing is modified. Segment files without a `catalog.snap` are refused, not opened as a new library. +- **Upgrade.** A one-file library (formats up to 10) is split when first opened: the segments are written, read back + and compared with the photos that were loaded, and only then does the new `catalog.snap` replace the old one. If + they don't read back the same, the one file stays: a format 10 library opens from it as before (and the next open + tries again), an older one is not opened (see "Going back to an older version"). +- **Stores without segments.** The browser build keeps the photos in `catalog.snap` itself (its storage holds a fixed + set of files). Either layout is read wherever it is found; a desktop library folder is not a browser library. + +## When the log is compacted + +`SnapshotPolicy`, where "what it would rewrite" is `catalog.snap`, the segments holding changed photos, and a sixteenth +of the catalog for looking through it (all of the catalog where there are no segments): + +| When | Rule | +|---|---| +| While working | The log is long (2000 records or 16 MB) **and** has grown to a quarter of what a compaction would rewrite; or it has reached 256 MB. | +| On quit, rewriting up to 64 MB | Whatever log there is. | +| On quit, rewriting more | Only when the log is long (2000 records or 16 MB). | + +Changes within a few segments are compacted every 2000 records however large the library; changes spread all over +it, and bulk imports into a very large one, less often. A log is never left longer than 2000 records from one session +to the next, so what a damaged record in it can cost is what it always was. + +## Measurements: compact records and compaction by size (format 10) + +`cargo run --release -p lightcraft-catalog --example persist_bench -- `, on an Apple M1 Max +(internal SSD), 2026-10-10; "before" is main at `b70ae174`. Three kinds of library: + +- **Browsed raws** (the default): 90 % Local browse records of raws on their import defaults, 10 % library photos with + one edit and one history step. +- **JPEG library** (`PERSIST_BENCH_MIX=library`): imported JPEGs nobody edited, each with a title. +- **Edited raws** (`PERSIST_BENCH_MIX=edited`): every photo edited, with 20 history steps. + +### Size of a record + +| Library | Before | After | +|---|---|---| +| Browsed raws | 3,688 B | 585 B | +| JPEG library | 3,403 B | 412 B | +| Edited raws, 20 history steps | 56,513 B | 3,414 B | + +### Importing (one change per photo, compacting whenever it is due) + +| Library | Photos | Compactions before | Snapshots written before | Time before | Compactions after | Snapshots written after | Time after | +|---|---|---|---|---|---|---|---| +| Browsed raws | 10,000 | 5 | 0.11 GB | 0.6 s | 5 | 0.02 GB | 0.4 s | +| Browsed raws | 100,000 | 50 | 9.4 GB | 17.7 s | 15 | 0.25 GB | 3.1 s | +| Browsed raws | 300,000 | 150 | 83.6 GB | 136 s | 21 | 0.90 GB | 8.9 s | +| JPEG library | 100,000 | 50 | 8.7 GB | 15.3 s | 16 | 0.21 GB | 1.9 s | +| JPEG library | 300,000 | 150 | 77.1 GB | 122 s | 21 | 0.59 GB | 5.1 s | +| Edited raws | 20,000 | 40 | 23.2 GB | 40.0 s | 8 | 0.27 GB | 14.3 s | + +Before, the snapshots written grow with the square of the library (75 times the final snapshot at 300,000 photos); +after, they stay at 3 to 5 times the final snapshot. + +### One compaction, and opening the library + +| Library | Photos | Snapshot before | Snapshot after | Compaction before | Compaction after | Open before | Open after | +|---|---|---|---|---|---|---|---| +| Browsed raws | 100,000 | 369 MB | 58.5 MB | 572 ms | 214 ms | 1,222 ms | 255 ms | +| Browsed raws | 300,000 | 1,107 MB | 176 MB | 1,659 ms | 586 ms | 3,698 ms | 758 ms | +| JPEG library | 100,000 | 340 MB | 41.2 MB | 495 ms | 88 ms | 1,134 ms | 183 ms | +| JPEG library | 300,000 | 1,021 MB | 124 MB | 1,480 ms | 195 ms | 3,415 ms | 550 ms | +| Edited raws | 20,000 | 1,130 MB | 68.3 MB | 1,809 ms | 2,797 ms | 3,860 ms | 443 ms | + +Compaction is the synchronous time; natively it runs on a worker thread and blocked the caller for 10 to 25 ms in +every run above, before and after. Appending one change took 4.1 to 4.9 ms (median, with its fsync) in every run. + +**Where it costs more.** Settings that differ from the defaults are read back before they are written, which takes +more processor time than writing them in full: about 1.6 times per snapshot when every photo has 20 history steps +(the last row). That snapshot is 17 times smaller and written 5 times less often during the import above, and on a +worker thread the whole compaction went from 4.6 s to 2.9 s; it is slower only where the snapshot is written +synchronously (the browser build, and quitting). + +### Larger libraries (after only) + +An import at these sizes was not run before the change: at 300,000 photos it already wrote 77 to 84 GB. + +| Library | Photos | Snapshot | Import | Snapshots written | Compaction | Caller blocked | Open | +|---|---|---|---|---|---|---|---| +| Browsed raws | 1,000,000 | 589 MB | 27.9 s | 2.6 GB | 1.9 s | 33 ms | 2.6 s | +| JPEG library | 1,000,000 | 414 MB | 16.1 s | 2.0 GB | 0.56 s | 37 ms | 1.8 s | +| JPEG library | 3,500,000 | 1,454 MB | 55.8 s | 6.7 GB | 1.9 s | 72 ms | 6.4 s | + +Replaying a log when the library is opened cost 0.3 to 1.1 ms per 1000 records up to 300,000 photos (200,000 rating +changes: 51 to 217 ms). + +**What this did not change.** The whole catalog was still written as one file, which format 11 changes. + +## Measurements: segments (format 11) + +Same benchmark and machine; "before" is format 10 (one file) at `f43b0fdc`. These tables were measured with segments +of up to 8192 photos and about 4 MB, the sizes before "Segment size" below halved them. "One place" is 1000 changes to the first +1000 photos; "all over" is a change to every 50th photo of the library, which touches every segment. + +| Library | Photos | Open before | Open after | Compaction, one place before | after | Compaction, all over before | after | +|---|---|---|---|---|---|---|---| +| JPEG library | 100,000 | 175 ms | 59 ms | 81 ms (41 MB) | 49 ms (4.1 MB) | 88 ms | 129 ms | +| JPEG library | 300,000 | 532 ms | 147 ms | 187 ms (124 MB) | 48 ms (4.1 MB) | 191 ms | 283 ms | +| JPEG library | 1,000,000 | 1,767 ms | 518 ms | 570 ms (414 MB) | 58 ms (4.1 MB) | 577 ms | 886 ms | +| JPEG library | 3,500,000 | 6,129 ms | 1,714 ms | 2,009 ms (1,455 MB) | 75 ms (4.2 MB) | 2,060 ms | 3,360 ms | +| Browsed raws | 100,000 | 251 ms | 63 ms | 210 ms (58 MB) | 62 ms (4.7 MB) | 209 ms | 167 ms | +| Browsed raws | 300,000 | 741 ms | 165 ms | 575 ms (176 MB) | 63 ms (4.7 MB) | 581 ms | 363 ms | +| Edited raws | 20,000 | 399 ms | 132 ms | 2,742 ms (68 MB) | 326 ms (6.8 MB) | 2,731 ms | 731 ms | + +Importing (one change per photo, compacting whenever it is due): + +| Library | Photos | Snapshots written before | Time before | Snapshots written after | Time after | +|---|---|---|---|---|---| +| JPEG library | 100,000 | 0.25 GB | 1.9 s | 0.10 GB | 3.1 s | +| JPEG library | 300,000 | 0.72 GB | 5.2 s | 0.25 GB | 7.7 s | +| JPEG library | 1,000,000 | 2.4 GB | 16.6 s | 0.56 GB | 20.3 s | +| JPEG library | 3,500,000 | 8.2 GB | 57.5 s | 1.7 GB | 61.0 s | +| Browsed raws | 300,000 | 1.08 GB | 9.2 s | 0.33 GB | 10.6 s | +| Edited raws | 20,000 | 0.34 GB | 14.0 s | 0.07 GB | 6.4 s | + +Appending one change (4.1 to 5.0 ms) and how long a background compaction blocks the caller (10 to 30 ms; 70 ms at +3.5 million photos) are as before. + +**Where it costs more.** + +- **Rewriting every segment at once** is slower than writing one file where records are small (JPEG libraries: 1.5 + times), because each segment file is made durable on its own. It happens when changes touch every segment, and once + when a one-file library is split. +- **Importing** small records takes up to 1.6 times as long in this benchmark, which measures the catalog alone: + compactions are smaller but more frequent, and each looks through the catalog for what changed. A real import also + reads every file, which takes far longer than either. + +**What this does not change.** The whole catalog is still held in memory: the 3.5 million photo runs peaked at 30 to +32 GB before and after (the benchmark holds two to three copies of the catalog). Not measured: how long replaying a +long log takes at that size (the benchmark's figure there is dominated by memory pressure from those copies). + +### Segment size + +How large a segment is is a setting (`SnapshotPolicy::segment_photos`, `segment_bytes`), not part of the format: a +library written with one size opens with another, and its segments are cut to the new size as they are next +rewritten. These runs varied the number of photos per segment with no size in bytes (same machine; a one-off harness +around `Journal`, not kept in the repository; one run per row, saves and opens the median of three; page cache warm). +"20 places" is 50 changes at each of 20 places spread over the library. The megabytes are what a save rewrites, which +is also what the next backup copies. + +3.5 million unedited JPEGs (1,455 MB of catalog): + +| Photos per segment | Segment size | Segments | Open | One place | 20 places | All over | +|---|---|---|---|---|---|---| +| 2,048 | 0.9 MB | 1,709 | 1,116 ms | 48 ms (1.0 MB) | 143 ms (17 MB) | 7.8 s | +| 4,096 | 1.7 MB | 855 | 975 ms | 56 ms (1.8 MB) | 138 ms (34 MB) | 4.7 s | +| 8,192 | 3.4 MB | 428 | 1,002 ms | 63 ms (3.4 MB) | 189 ms (68 MB) | 3.3 s | +| 16,384 | 6.8 MB | 214 | 998 ms | 75 ms (6.8 MB) | 290 ms (136 MB) | 2.6 s | +| 32,768 | 13.6 MB | 107 | 844 ms | 95 ms (13.5 MB) | 432 ms (272 MB) | 2.1 s | +| 65,536 | 26.9 MB | 54 | 864 ms | 146 ms (27.0 MB) | 803 ms (544 MB) | 2.0 s | + +1 million unedited JPEGs (414 MB), with the import that made them ("written": all snapshots together, as a multiple of +the final one). A segment holds at most the photos per segment of its row, so a library of 1 million photos needs at +least 1,000,000 ÷ that many segments (245 at 4,096): the counts below are the ones the harness reported and are lower +than that for every row, so they do not describe a library of exactly 1 million photos; the harness +was not kept, and they were not remeasured. Read the columns as how the sizes compare with each other, not as counts +for a library of that size (the 3.5 million table above counts as expected): + +| Photos per segment | Segments | Import | Written | Open | One place | 20 places | All over | +|---|---|---|---|---|---|---|---| +| 1,024 | 922 | 29.5 s | 1.08 | 333 ms | 40 ms | 131 ms (9 MB) | 4.3 s | +| 2,048 | 442 | 24.7 s | 1.14 | 256 ms | 39 ms | 127 ms (21 MB) | 2.1 s | +| 4,096 | 207 | 23.7 s | 1.22 | 250 ms | 45 ms | 176 ms (44 MB) | 1.1 s | +| 8,192 | 91 | 22.9 s | 1.35 | 251 ms | 55 ms | 235 ms (102 MB) | 0.84 s | +| 16,384 | 49 | 20.4 s | 1.78 | 258 ms | 61 ms | 308 ms (182 MB) | 0.66 s | +| 65,536 | 14 | 19.7 s | 2.92 | 305 ms | 139 ms | 516 ms (413 MB) | 0.53 s | + +50,000 edited raws with 20 history steps each (169 MB): + +| Photos per segment | Segment size | Open | One place | 20 places | All over | +|---|---|---|---|---|---| +| 128 | 0.4 MB | 115 ms | 94 ms (3.5 MB) | 179 ms (12 MB) | 1.9 s | +| 256 | 0.9 MB | 116 ms | 122 ms (3.5 MB) | 218 ms (21 MB) | 1.3 s | +| 512 | 1.7 MB | 119 ms | 188 ms (3.5 MB) | 324 ms (38 MB) | 1.1 s | +| 1,024 | 6.7 MB | 127 ms | 340 ms (6.8 MB) | 1,172 ms (135 MB) | 1.1 s | +| 4,096 | 18.7 MB | 199 ms | 917 ms (20 MB) | 1,904 ms (169 MB) | 1.9 s | +| 8,192 | 28.1 MB | 286 ms | 1,598 ms (35 MB) | 2,844 ms (169 MB) | 2.8 s | + +What a save of a few changes rewrites follows the size of a segment, and for edited photos so does its time. Changes +to every segment go the other way, since each file is made durable on its own. Opening is the same from about 2000 +photos per segment up. So segments are about 2 MB and at most 4096 photos: half of what they were (8192 photos, 4 +MB), which halves what scattered changes rewrite and what a backup after them copies, and makes a save that touches +every segment (rare, and in the background) about 1.4 times as slow where records are small. The size is not +adjusted to how a library is used: it already follows the size of the records, the measurements are flat around it, +and every change of size would rewrite segments that backups share. diff --git a/docs/web.md b/docs/web.md index b275e837d29..e7b04fdd2b4 100644 --- a/docs/web.md +++ b/docs/web.md @@ -88,7 +88,9 @@ are the same in every version, so serve them with `Cache-Control: no-cache` (not when the main thread can write it (`FileSystemFileHandle.createWritable`: Chrome, Edge, Firefox, recent Safari), otherwise IndexedDB. Both hold the same layout: - `library/catalog.snap`, `library/catalog.log`: the same crash-safe journal as the desktop app - (`lightcraft-catalog`), plus `presets.json`, `view.json`, `prefs.json` and `ui.json` (panel + (`lightcraft-catalog`), with the catalog in one file (the desktop app keeps the photos in + segment files beside it, see `docs/catalog-persistence.md`; a desktop library folder is not a + browser library), plus `presets.json`, `view.json`, `prefs.json` and `ui.json` (panel layout). The catalog `Store` is a memory mirror loaded at start-up; every change is flushed in the background within a frame or two, each file replaced atomically, in modification order (`apps/lightcraft-web/src/files.rs`). View state and UI prefs are saved every second when they diff --git a/docs/whats-new.md b/docs/whats-new.md index 2f02ffb91b0..37aecbeb338 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -488,6 +488,29 @@ files, the same files as `library.import` (issue #1080). They used to be skipped without a word. - Compare and Reference View panes say "Rendering…" (or that the photo can't be opened) the same way, so a magnified preview isn't taken for the photo when checking focus at 1:1. +### Large libraries +- The catalog on disk is several times smaller: a photo's record states only what was set (no empty fields, no default + develop settings), about 0.4 to 0.6 kB for an unedited photo where it was 3.4 to 3.7 kB. Edits, history steps and + versions are stored as what differs from the defaults. +- Saving follows what changed, not the size of the library: the catalog is compacted while you work when the log of + changes is long (2000 records or 16 MB) and has grown to a quarter of what a compaction would rewrite (`catalog.snap`, + the segments holding changed photos, and a sixteenth of the catalog for looking through it), or when it reaches + 256 MB; on quit, a log is compacted when the rewrite is up to 64 MB or, above that, when the log is long (2000 records or 16 MB). It used to be + rewritten every 2000 changes. Importing 100,000 + photos rewrote it 50 times (9.4 GB written); it is now 15 times (0.25 GB). Quitting no longer rewrites a large + catalog for a handful of changes. +- The catalog's photos are saved in segment files (JSON files in `segments/` beside `catalog.snap`), and saving rewrites only the + segments whose photos changed: after edits in one place, 2 MB where it was the whole catalog (about 60 ms where it was 2 s, + for 3.5 million photos). Opening reads the segments on several threads: 0.15 s where it was 0.5 s for 300,000 photos, + 1.7 s where it was 6.1 s for 3.5 million. A damaged segment is named when the library is opened, and nothing is + modified. +- Libraries are upgraded when first opened (catalog format 11) and can't be opened by earlier versions afterwards. The + photos of a library in a folder on disk are split into segments only once the segments written read back the same. + Copy or back up the whole library folder: `catalog.snap` alone no longer holds the photos. (The browser build keeps + its photos in `catalog.snap`.) + The library as it was is kept beside it (`catalog.snap.v-`, `catalog.log.v-`): to go back, see + `docs/catalog-persistence.md`. + Numbers and the measurements behind them: `docs/catalog-persistence.md`. ### Lens corrections - Sony A7R VI (ILCE-7RM6) raws are corrected for lens distortion from the table the camera records in each file,