From cb38a07acce82b3a206d2b1ab217ff68f8748505 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 23 Oct 2026 07:59:27 -0400 Subject: [PATCH 01/61] Catalog: an upgrade keeps the files it replaces Opening a library in an older format rewrites it in this build's, and older builds then refuse it: a one-way step. Journal::open now first keeps the files the library was, byte for byte, as catalog.snap.v- and catalog.log.v-, and reports their names (LoadReport::kept). Put back under their own names they are the library as the older build left it (docs/catalog-persistence.md, Going back to an older version). A library whose files can't be kept is not upgraded (it opens as it is; the next open tries again), and an upgrade that fails leaves no copy; kept files stay whenever the upgrade may have been written. A library whose log was damaged is an upgrade like any other: its snapshot is kept beside the damaged log, and it is refused if that log can't be replaced. The person is told once where the library as it was is kept. A library left in its old format at open is upgraded by a later snapshot (compaction, or closing), which keeps its files first and is not written when it can't. The browser build keeps none (Store::keeps_replaced_formats). Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft-web/src/files.rs | 4 + .../catalog/src/fixtures/v6-catalog.log.jsonl | 5 + .../catalog/src/fixtures/v6-catalog.snap.json | 1 + crates/catalog/src/journal.rs | 187 ++++++++++-- crates/catalog/src/store.rs | 28 ++ crates/catalog/src/tests_format_version.rs | 276 ++++++++++++++++++ crates/engine/src/library.rs | 17 +- crates/engine/src/tests/persist.rs | 24 ++ docs/catalog-persistence.md | 34 +++ docs/whats-new.md | 5 + xtask/src/ci_quick.rs | 2 + 11 files changed, 564 insertions(+), 19 deletions(-) create mode 100644 crates/catalog/src/fixtures/v6-catalog.log.jsonl create mode 100644 crates/catalog/src/fixtures/v6-catalog.snap.json create mode 100644 docs/catalog-persistence.md diff --git a/apps/lightcraft-web/src/files.rs b/apps/lightcraft-web/src/files.rs index 9cd934ce57d..4712e2c83e0 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/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/journal.rs b/crates/catalog/src/journal.rs index 2600d794a45..f938fa2176e 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -62,6 +62,18 @@ //! 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 left in its old format at open +//! (its files couldn't be kept, or the upgrade couldn't be written) is upgraded by a later +//! snapshot (compaction, or closing), which keeps the files as they are then first and is not +//! written when it can't. //! - **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 @@ -91,6 +103,16 @@ impl Default for SnapshotPolicy { } } +/// 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: its damaged log would be appended to after the damage, + /// so the snapshot must also have replaced that log. + Repair, +} + /// What happened while loading. #[derive(Clone, Debug, Default, PartialEq)] pub struct LoadReport { @@ -116,6 +138,9 @@ 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, } /// Where persistence time goes (reported by `library.info` → `persistence`; printed to stderr @@ -182,6 +207,11 @@ pub struct Journal { /// `seq` of the last durable op. seq: u64, snapshot_seq: u64, + /// The snapshot in the store is still in an older format (`Some(format)`): the library was + /// not upgraded at open, because its files could not be kept or the upgrade could not be + /// written. A later snapshot (a compaction, or closing) writes the upgrade then, + /// and keeps the files first ([`Journal::keep_before_upgrade`]). + behind: Option, log_records: u64, log_bytes: u64, pub policy: SnapshotPolicy, @@ -339,23 +369,25 @@ struct SnapFile { 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 its damaged log can't be replaced + /// or its snapshot can't be kept (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 { + 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}")))?; + 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))); @@ -374,6 +406,7 @@ impl Journal { store, seq: snapshot_seq, snapshot_seq, + behind: None, log_records: 0, log_bytes: 0, policy: SnapshotPolicy::default(), @@ -452,12 +485,23 @@ impl Journal { needs_newline = !has_nl; } + // 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)); 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)?, + } } else { if good_end < log.len() { report.torn_bytes = (log.len() - good_end) as u64; @@ -471,31 +515,125 @@ 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}"); } - } 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}"); - } - } - // 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}"), + } else if let (Some(from), None) = (older, &report.damaged) { + // The library may go on as it is when it can't be upgraded now (the next open tries + // again): what is appended to an older format reads the same in every build. + if let Some(kept) = j.upgrade(&catalog, from, snap.as_deref(), &log, Upgrade::May)? { + report.upgraded_from = Some(from); + report.kept = kept; + } else { + j.behind = Some(from); } } 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); + } + 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); + } + } + } + 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> { + if !self.store.keeps_replaced_formats() { + 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}"); + } + } + } + + /// A library that was left in an older format at open (see `behind`) keeps its files, as + /// they are now, before a snapshot upgrades it. An error means they could not be kept (or + /// read): the snapshot is not written, so the library stays as it was, with its way back. + fn keep_before_upgrade(&mut self) -> Result<()> { + let Some(from) = self.behind else { return Ok(()) }; + let snap = self.store.read(SNAPSHOT).map_err(io)?; + let log = self.store.read(LOG).map_err(io)?.unwrap_or_default(); + let kept = self.keep_replaced(from, snap.as_deref(), &log).map_err(io)?; + log::info!("catalog: the files of format v{from} are kept as {kept:?} before the upgrade"); + Ok(()) + } + /// Append ops (already applied to the live catalog) durably, in order. pub fn append(&mut self, ops: &[Op]) -> Result<()> { if ops.is_empty() { @@ -557,6 +695,12 @@ impl Journal { } let t0 = web_time::Instant::now(); let seq = self.seq.checked_add(unlogged).ok_or_else(|| CatalogError::Corrupt(format!("{SNAPSHOT}: op counter overflow")))?; + if let Err(e) = self.keep_before_upgrade() { + // not upgraded without its way back; try again later like any failed snapshot + self.stats.failed_snapshots += 1; + self.retry_at_records = self.log_records + self.policy.max_records; + return Err(e); + } let mut timing = match write_snapshot(self.store.as_mut(), seq, catalog) { Ok(t) => t, Err(e) => { @@ -569,6 +713,7 @@ impl Journal { // the snapshot is durable: it holds every op up to `seq` self.seq = seq; self.snapshot_seq = seq; + self.behind = None; let t2 = web_time::Instant::now(); // A crash here leaves old records in the log; they are skipped by seq on load. self.store.write_atomic(LOG, b"").map_err(io)?; @@ -593,6 +738,11 @@ impl Journal { return Ok(()); } let t0 = web_time::Instant::now(); + if let Err(e) = self.keep_before_upgrade() { + self.stats.failed_snapshots += 1; + self.retry_at_records = self.log_records + self.policy.max_records; + return Err(e); + } let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) }; let copy = catalog.clone(); let seq = self.seq; @@ -656,6 +806,7 @@ impl Journal { // Keep exactly the ones appended since (a crash before this rewrite skips the stale ones). let t1 = web_time::Instant::now(); self.snapshot_seq = p.seq; + self.behind = None; 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; diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index a79930f14af..48d28587f1e 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -35,6 +35,19 @@ 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 + } /// Human-readable location (diagnostics). fn describe(&self) -> String; /// Another handle on the same files that a worker thread can write `catalog.snap` through @@ -183,6 +196,17 @@ 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 describe(&self) -> String { self.dir.display().to_string() } @@ -248,6 +272,10 @@ 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 describe(&self) -> String { "memory".into() } diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index e31d7fe0c49..8bb6e7c0c75 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -243,3 +243,279 @@ fn op_variants_are_versioned() { 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"); } + +// ---- 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() + } +} + +/// The library `fixtures/v-catalog.*` holds, written by the build of format `N`. +fn fixture(version: u32) -> Option<(&'static str, &'static str)> { + match version { + 6 => Some((include_str!("fixtures/v6-catalog.snap.json"), include_str!("fixtures/v6-catalog.log.jsonl"))), + _ => None, + } +} + +/// A format 6 library (the fixture) in a store. +fn v6_library() -> (MemStore, Vec, Vec) { + let (snap, log) = fixture(6).unwrap(); + let m = MemStore::new(); + m.set(SNAPSHOT, snap.as_bytes().to_vec()); + m.set(LOG, log.as_bytes().to_vec()); + (m, snap.as_bytes().to_vec(), log.as_bytes().to_vec()) +} + +/// 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 not upgraded without its way back: it opens as it is, with its files as they were and +/// nothing half kept, and is upgraded once there is room. +#[test] +fn a_library_that_cannot_be_kept_is_not_upgraded() { + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.log.v") }; + let (_, c, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0)); + 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 opens 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 (_, c, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0)); + 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 an older library that was not upgraded at open (its files can't be kept), when a later +/// snapshot would upgrade it (a compaction, or closing), then that snapshot is not written: the +/// library stays as it was, with nothing half kept, and is never upgraded without its way back. +#[test] +fn a_library_that_could_not_be_kept_is_not_upgraded_by_a_later_snapshot_either() { + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.log.v") }; + let (mut j, c, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!(r.upgraded_from, None); + assert!(j.snapshot(&c).is_err(), "closing"); + assert!(j.snapshot_in_background(&c).is_err(), "a compaction"); + 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"); +} + +/// Given an older library whose upgrade could not be written at open (a full disk), when a later +/// snapshot is written (the disk has room again), then the files it was are kept first, as the +/// open would have kept them, and the library is upgraded. +#[test] +fn a_library_left_in_its_old_format_keeps_its_files_when_a_later_snapshot_upgrades_it() { + static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, c, r) = Journal::open(Box::new(store)).unwrap(); + assert_eq!((r.upgraded_from, r.kept.len()), (None, 0)); + assert!(j.snapshot(&c).is_err(), "still full"); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [LOG, "catalog.log.v6-8", SNAPSHOT, "catalog.snap.v6-8"], "kept, not upgraded"); + FULL.store(false, std::sync::atomic::Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log))); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); +} + +/// Given an older library whose log is damaged and whose snapshot can't be kept, when it is +/// opened, then it is refused and left as it was (it is not repaired without its way back). +#[test] +fn a_damaged_older_library_whose_snapshot_cannot_be_kept_is_refused() { + 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); + let damaged = format!("{}\n", lines.join("\n")).into_bytes(); + m.set(LOG, damaged.clone()); + let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.snap.v") }; + let e = Journal::open(Box::new(store)).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("can't be kept")), "{e}"); + assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(damaged))); +} diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index a5071b4b358..09be39388ca 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -309,6 +309,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) { @@ -575,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, @@ -588,7 +603,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(), diff --git a/crates/engine/src/tests/persist.rs b/crates/engine/src/tests/persist.rs index 7ebf8464bf8..82be29e44d7 100644 --- a/crates/engine/src/tests/persist.rs +++ b/crates/engine/src/tests/persist.rs @@ -216,3 +216,27 @@ fn a_preset_that_cannot_be_written_counts_as_unsaved_until_it_is() { assert!(s.unsaved().is_none(), "written once the disk works again"); assert!(String::from_utf8_lossy(&stored(&files)).contains("Mine")); } + +/// 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..b222f4db2b6 --- /dev/null +++ b/docs/catalog-persistence.md @@ -0,0 +1,34 @@ +# Catalog persistence + +The catalog is two files in the library folder (`crates/catalog/src/journal.rs`): `catalog.snap`, a JSON snapshot of +the whole catalog, and `catalog.log`, one JSON line per change made since. Every change is appended to the log and +fsynced before its command returns; now and then the log is compacted into a new snapshot. This page covers what +happens to a library's files when a newer version opens it. + +## 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 whose files can't be kept, or whose upgrade can't be written (a full disk, a folder that can't be written + to), is not upgraded: it opens as it is, with no copy left lying about, and the next open tries again. If what is on + disk after a failed write can't be read back to say whether the upgrade was written, the library is refused instead + (its way back stays). A library left like that is upgraded by its next snapshot, during the session or when it is + closed, and that snapshot keeps the files first too (and is not written when they can't be kept). +- 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. If the snapshot can't be kept, or the damaged log can't be replaced, the library is refused and left + as it was (changes made in it would be appended after the damage, where the next open would not read them). +- 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` and `catalog.log` away, then rename the kept pair to +`catalog.snap` and `catalog.log`. The older version opens the library as it was when it was upgraded; changes made +since, in the newer version, are in the files that were moved away and are not carried back. diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c25920034..b46e7b9833f 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -2,6 +2,11 @@ ## 2026-10-24 +### A library keeps a copy of itself before it is upgraded +- Opening a library saved by an earlier version upgrades it, and earlier versions can't open it afterwards. The library + as it was is now kept beside it (`catalog.snap.v-`, `catalog.log.v-`), and LightCraft says + where once: to go back, see `docs/catalog-persistence.md`. A library that can't be kept is not upgraded. + ### Relative-date filters and smart albums follow the clock - A current view or source count using “in the last” rules now refreshes when the session clock moves into a new minute, even when no catalog edit occurred. This fixes stale photos remaining in the grid and stale counts for diff --git a/xtask/src/ci_quick.rs b/xtask/src/ci_quick.rs index be3e5777df7..450f0b2f082 100644 --- a/xtask/src/ci_quick.rs +++ b/xtask/src/ci_quick.rs @@ -44,6 +44,8 @@ const EMBEDDED: &[(&str, &[&str])] = &[ ("xtask/src/raw_samples.rs", &["lightcraft-raw"]), ("crates/ui-egui/src/menus.rs", &["xtask"]), ("crates/ui-egui/src/menus/", &["xtask"]), + ("crates/catalog/src/fixtures/v6-catalog.snap.json", &["lightcraft-engine"]), + ("crates/catalog/src/fixtures/v6-catalog.log.jsonl", &["lightcraft-engine"]), ]; /// The packages that compile in `path` from outside their own directory. From 1ec43eedd6daf514fc8184ce2b4af8f7aa8a8e04 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 00:25:40 -0400 Subject: [PATCH 02/61] Catalog: a later upgrade tells where it kept the files it replaced A library left in an older format at open keeps its files when a later snapshot upgrades it. Those files are the library as it was at open (the snapshot, and the log up to its length then), under the names the open would have given them, so what is appended meanwhile in this build's ops is never in them. The snapshot hands the names on (Journal::take_kept) and the engine tells the person once, as the open does. Appends are not refused meanwhile (a library whose files can't be copied would save nothing): the module doc and the persistence doc say so. --- crates/catalog/src/journal.rs | 70 +++++++++++++++++++--- crates/catalog/src/tests_format_version.rs | 56 +++++++++++++++++ crates/engine/src/library.rs | 29 +++++++-- crates/engine/src/tests/persist.rs | 38 ++++++++++++ docs/catalog-persistence.md | 9 ++- 5 files changed, 187 insertions(+), 15 deletions(-) diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index f938fa2176e..5a444d4c062 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -38,7 +38,9 @@ //! # 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 appended to under a snapshot of this build's format. (Except +//! for a library left in an older format because its files could not be kept or its upgrade +//! written: it goes on as it is, and its log gets this build's ops until a snapshot upgrades it.) //! //! | Version | Written by | Adds | //! |---|---|---| @@ -212,6 +214,14 @@ pub struct Journal { /// written. A later snapshot (a compaction, or closing) writes the upgrade then, /// and keeps the files first ([`Journal::keep_before_upgrade`]). behind: Option, + /// What the library was at open while `behind` is set: the `seq` its files held and the + /// length of its log. Appends only add to the log after that, so the first `log_len` bytes + /// and the snapshot are what an older build left, whatever is appended meanwhile. + behind_at: (u64, u64), + /// The files [`Journal::keep_before_upgrade`] kept for a snapshot that is not written yet, + /// and, once that snapshot is, the names for [`Journal::take_kept`]. + kept_pending: Option>, + kept_written: Vec, log_records: u64, log_bytes: u64, pub policy: SnapshotPolicy, @@ -407,6 +417,9 @@ impl Journal { seq: snapshot_seq, snapshot_seq, behind: None, + behind_at: (0, 0), + kept_pending: None, + kept_written: Vec::new(), log_records: 0, log_bytes: 0, policy: SnapshotPolicy::default(), @@ -523,12 +536,16 @@ impl Journal { } } else if let (Some(from), None) = (older, &report.damaged) { // The library may go on as it is when it can't be upgraded now (the next open tries - // again): what is appended to an older format reads the same in every build. + // again). Appends are not refused meanwhile: refusing them would leave a library + // whose files can't be copied (little room left) unable to save anything. What is + // appended is this build's ops; the files kept when a later snapshot upgrades it are + // the library as it is here (`behind_at`), which an older build reads. if let Some(kept) = j.upgrade(&catalog, from, snap.as_deref(), &log, Upgrade::May)? { report.upgraded_from = Some(from); report.kept = kept; } else { j.behind = Some(from); + j.behind_at = (j.seq, j.log_bytes); } } catalog.revision = 0; @@ -623,17 +640,54 @@ impl Journal { } /// A library that was left in an older format at open (see `behind`) keeps its files, as - /// they are now, before a snapshot upgrades it. An error means they could not be kept (or - /// read): the snapshot is not written, so the library stays as it was, with its way back. + /// they were then, before a snapshot upgrades it: the snapshot as it is (nothing writes it + /// until the upgrade) and the log up to its length at open (what was appended since is this + /// build's, which an older build may refuse). The names are those the open would have kept + /// them under, so they are written again as they are when a snapshot failed and is tried + /// again, and files kept for an upgrade that did not land are never left behind under other + /// names. An error means they could not be kept (or read): the snapshot is not written, so + /// the library stays as it was, with its way back. fn keep_before_upgrade(&mut self) -> Result<()> { let Some(from) = self.behind else { return Ok(()) }; + if self.kept_pending.is_some() { + return Ok(()); + } let snap = self.store.read(SNAPSHOT).map_err(io)?; - let log = self.store.read(LOG).map_err(io)?.unwrap_or_default(); - let kept = self.keep_replaced(from, snap.as_deref(), &log).map_err(io)?; + // (a write of the snapshot that failed after it landed leaves one that is not what was + // to be kept under this name) + if let Some(bytes) = snap.as_deref() + && serde_json::from_slice::(bytes).ok().map(|h| h.version) != Some(from) + { + return Err(CatalogError::Io(format!("the snapshot is no longer in format v{from}, and can't be kept as it was"))); + } + let mut log = self.store.read(LOG).map_err(io)?.unwrap_or_default(); + let (seq, log_len) = self.behind_at; + log.truncate(usize::try_from(log_len).unwrap_or(usize::MAX)); + let at = std::mem::replace(&mut self.seq, seq); + let kept = self.keep_replaced(from, snap.as_deref(), &log); + self.seq = at; + let kept = kept.map_err(io)?; log::info!("catalog: the files of format v{from} are kept as {kept:?} before the upgrade"); + self.kept_pending = Some(kept); Ok(()) } + /// The snapshot that upgrades a library left behind is durable: the files kept for it are + /// now the library's way back, for [`Journal::take_kept`] to tell. + fn upgraded_later(&mut self) { + self.behind = None; + if let Some(kept) = self.kept_pending.take() { + self.kept_written.extend(kept); + } + } + + /// The files a snapshot kept when it upgraded a library that was left in an older format at + /// open (see `behind`), once, after it was written: [`LoadReport::kept`] has only what the + /// open kept. Empty when there are none. + pub fn take_kept(&mut self) -> Vec { + std::mem::take(&mut self.kept_written) + } + /// Append ops (already applied to the live catalog) durably, in order. pub fn append(&mut self, ops: &[Op]) -> Result<()> { if ops.is_empty() { @@ -713,7 +767,7 @@ impl Journal { // the snapshot is durable: it holds every op up to `seq` self.seq = seq; self.snapshot_seq = seq; - self.behind = None; + self.upgraded_later(); let t2 = web_time::Instant::now(); // A crash here leaves old records in the log; they are skipped by seq on load. self.store.write_atomic(LOG, b"").map_err(io)?; @@ -806,7 +860,7 @@ impl Journal { // Keep exactly the ones appended since (a crash before this rewrite skips the stale ones). let t1 = web_time::Instant::now(); self.snapshot_seq = p.seq; - self.behind = None; + self.upgraded_later(); 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; diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index 8bb6e7c0c75..cf0fc99d15e 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -519,3 +519,59 @@ fn a_damaged_older_library_whose_snapshot_cannot_be_kept_is_refused() { assert!(matches!(&e, CatalogError::Io(why) if why.contains("can't be kept")), "{e}"); assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(damaged))); } + +/// Given an older library that was not upgraded at open (its files can't be kept), when a later +/// snapshot upgrades it, then the files that snapshot kept are told once, after it is written +/// (not before, not for a snapshot that failed, and the open's report has none). +#[test] +fn the_files_a_later_snapshot_keeps_are_told_once_it_is_written() { + static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let (m, _, _) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, c, r) = Journal::open(Box::new(store)).unwrap(); + assert!(r.kept.is_empty()); + assert!(j.snapshot(&c).is_err(), "still full"); + assert!(j.take_kept().is_empty(), "kept for a snapshot that is not written: nothing to tell yet"); + FULL.store(false, std::sync::atomic::Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]); + assert!(j.take_kept().is_empty(), "once"); +} + +/// Given a library left in its old format whose snapshot failed after its files were kept, when +/// it goes on (more changes are appended, in this build's ops) and a later snapshot upgrades it, +/// then the files kept are the library as it was at open, under the names the open would have +/// given them: nothing piles up, and an older build can read them whatever was appended since. +#[test] +fn files_kept_by_a_later_snapshot_are_the_library_as_it_was_at_open() { + static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let (m, snap, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); + assert!(j.snapshot(&c).is_err()); + j.append(&[Op::SetLabelName { label: ColorLabel::ALL[0], name: Some("x".into()) }]).unwrap(); + assert!(j.snapshot(&c).is_err(), "still full"); + FULL.store(false, std::sync::atomic::Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!(j.take_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))); + assert_eq!(m.files.lock().unwrap().keys().filter(|k| k.contains(".v6-")).count(), 2, "{:?}", m.files.lock().unwrap().keys()); +} + +/// Given a library left in its old format whose snapshot write failed after it landed (the share +/// dropped the answer), when a later snapshot would keep its files, then the snapshot that is +/// there is not kept under the old format's name, and nothing is deleted. +#[test] +fn a_snapshot_that_landed_is_not_kept_as_the_old_format() { + static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let (m, _, log) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); + // the upgrade landed after all, though the write said it failed + m.set(SNAPSHOT, b"{\"format\":\"lightcraft-catalog\",\"version\":99,\"seq\":8,\"catalog\":{}}\n".to_vec()); + let e = j.snapshot(&c).unwrap_err(); + assert!(e.to_string().contains("no longer in format"), "{e}"); + assert!(j.take_kept().is_empty()); + assert_eq!(m.get(LOG), Some(log)); + assert!(!m.files.lock().unwrap().keys().any(|k| k.starts_with("catalog.snap.v")), "{:?}", m.files.lock().unwrap().keys()); +} diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 09be39388ca..bf284087b5f 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -271,12 +271,24 @@ fn presets_json(s: &Session) -> String { /// Finish a background compaction that is done (cheap otherwise). A failed one lost nothing (the /// log is kept whole) and is retried later; it is reported like other persistence errors. fn poll_compaction(lib: &mut Library) { - if let Err(e) = lib.journal.poll() { + let polled = lib.journal.poll(); + note_upgrade_kept(lib); + if let Err(e) = polled { log::error!("library: compaction: {e}"); lib.last_error = Some(format!("compaction: {e}")); } } +/// A snapshot that upgraded a library left in an older format at open kept the files it was: +/// tell so once, like the open does ([`kept_note`]). Cheap when nothing was kept. +fn note_upgrade_kept(lib: &mut Library) { + let kept = lib.journal.take_kept(); + if let Some(note) = kept_note(&kept, None) { + lib.settings_warnings.push(note); + lib.report.kept.extend(kept); + } +} + /// How long the frame loop waits before retrying a failed append (commands retry at once). const RETRY_BACKOFF: std::time::Duration = std::time::Duration::from_secs(2); @@ -311,12 +323,12 @@ struct SettingsLoad { /// 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() { +fn kept_note(kept: &[String], damaged: Option<&String>) -> Option { + if 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(); + let kept: Vec<&str> = kept.iter().chain(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 ") @@ -589,7 +601,7 @@ impl Session { self.tidy_thumbnail_cache(); } let view_written = self.view_json(); - let kept = kept_note(&report); + let kept = kept_note(&report.kept, report.damaged.as_ref()); self.library = Some(Library { dir, on_disk, @@ -663,6 +675,8 @@ impl Session { log::error!("library: compaction: {e}"); lib.last_error = Some(format!("compaction: {e}")); } + // (a compaction that wrote its snapshot at once, where there is no worker thread) + note_upgrade_kept(lib); let due = self.library.as_ref().is_some_and(|l| l.presets_saved.differs(self) && !l.blocked.contains(&"presets.json")); if !due { return Ok(()); @@ -857,6 +871,7 @@ impl Session { log::error!("library: compaction: {e}"); lib.last_error = Some(format!("compaction: {e}")); } + note_upgrade_kept(lib); } /// Compact the log into a snapshot now. @@ -866,7 +881,9 @@ impl Session { return Err(EngineError::Other("can't compact during an interaction".into())); } if let Some(lib) = self.library.as_mut() { - lib.journal.snapshot(&self.catalog)?; + let snapshot = lib.journal.snapshot(&self.catalog); + note_upgrade_kept(lib); + snapshot?; } Ok(()) } diff --git a/crates/engine/src/tests/persist.rs b/crates/engine/src/tests/persist.rs index 82be29e44d7..43c8723eaf5 100644 --- a/crates/engine/src/tests/persist.rs +++ b/crates/engine/src/tests/persist.rs @@ -240,3 +240,41 @@ fn an_upgraded_library_says_where_what_it_was_is_kept() { s.close_library().unwrap(); let _ = std::fs::remove_dir_all(&dir); } + +/// Given an older library that could not keep its files at open, when a later compaction upgrades +/// it (the files can be kept now), then the person is told once where the library as it was is +/// kept, as when the open upgrades it. +#[test] +fn a_later_upgrade_says_where_what_it_was_is_kept() { + let dir = std::env::temp_dir().join(format!("lightcraft-kept-later-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); + std::fs::write(dir.join("catalog.snap.v6-8").join("in the way"), b"x").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(); + assert!(s.take_library_warnings().iter().all(|w| !w.contains("upgraded")), "not upgraded at open"); + assert!(s.compact_library().is_err(), "its files can't be kept yet"); + std::fs::remove_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); + s.compact_library().unwrap(); + let on_disk = |prefix: &str| { + let mut names: Vec = std::fs::read_dir(&dir) + .unwrap() + .map(|e| e.unwrap()) + .filter(|e| e.path().is_file()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.starts_with(prefix) && !n.ends_with(".tmp")) + .collect(); + names.sort(); + names + }; + let (snap, log) = (on_disk("catalog.snap.v6-"), on_disk("catalog.log.v6-")); + assert_eq!((snap.len(), log.len()), (1, 1), "the files as they were are kept"); + let told = s.take_library_warnings(); + assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0]) && w.contains("delete")), "{told:?}"); + let info = s.execute("library.info", &serde_json::json!({})).unwrap(); + assert!(info["settingsWarnings"].to_string().contains(&snap[0]), "{info}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index b222f4db2b6..50558f38a22 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -20,7 +20,14 @@ library was, byte for byte, beside it: to), is not upgraded: it opens as it is, with no copy left lying about, and the next open tries again. If what is on disk after a failed write can't be read back to say whether the upgrade was written, the library is refused instead (its way back stays). A library left like that is upgraded by its next snapshot, during the session or when it is - closed, and that snapshot keeps the files first too (and is not written when they can't be kept). + closed, and that snapshot keeps the files first too (and is not written when they can't be kept). When a snapshot + during the session does that, LightCraft tells where the files are kept, as it does at open (a snapshot at close + has no one left to tell: the files are in the folder, named as above). The files kept are the library as it was + when it opened (the snapshot, and the log up to where it ended then): what was changed since is in the files that + replace them, and never in the kept ones, so an older version opens them whatever was changed. Until then, changes + go on being appended to the library as it is, so that they can be saved at all where there is no room for a copy of + its files. (If the session ends without that snapshot, the next open keeps the log as it is then, which holds + those changes, and tells so; the files kept earlier stay beside it.) - 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. If the snapshot can't be kept, or the damaged log can't be replaced, the library is refused and left From 26cf95dfaab719f89b5a1d6eae6b4de5ffc673bd Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 01:10:17 -0400 Subject: [PATCH 03/61] Catalog: a snapshot already in this format is the upgrade done, and the later upgrade's tests and docs are exact A library left in its old format whose snapshot is in this build's format already (a write that landed and reported a failure) no longer fails every snapshot until it is reopened: it is the upgrade done, with nothing to keep. Tests now cover the files kept at open's length and seq when changes were made before the first attempt, the snapshot that landed after its files were kept, no second copy on a retry, the background worker's result and telling once. The docs say what the kept files hold when a session already added changes in the old format, what going back loses, and that a snapshot at close or a library switch has no one to tell. --- crates/catalog/src/journal.rs | 29 ++++--- crates/catalog/src/tests_format_version.rs | 98 ++++++++++++++++++---- crates/engine/src/library.rs | 2 - crates/engine/src/tests/persist.rs | 73 ++++++++++++---- docs/catalog-persistence.md | 19 +++-- 5 files changed, 169 insertions(+), 52 deletions(-) diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 5a444d4c062..68f7021f2ce 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -216,7 +216,9 @@ pub struct Journal { behind: Option, /// What the library was at open while `behind` is set: the `seq` its files held and the /// length of its log. Appends only add to the log after that, so the first `log_len` bytes - /// and the snapshot are what an older build left, whatever is appended meanwhile. + /// and the snapshot are the library as this session opened it, whatever is appended + /// meanwhile (an earlier session of this build may have appended already, while the library + /// stayed in its old format: that is in them, and an older build may refuse it). behind_at: (u64, u64), /// The files [`Journal::keep_before_upgrade`] kept for a snapshot that is not written yet, /// and, once that snapshot is, the names for [`Journal::take_kept`]. @@ -643,9 +645,12 @@ impl Journal { /// they were then, before a snapshot upgrades it: the snapshot as it is (nothing writes it /// until the upgrade) and the log up to its length at open (what was appended since is this /// build's, which an older build may refuse). The names are those the open would have kept - /// them under, so they are written again as they are when a snapshot failed and is tried - /// again, and files kept for an upgrade that did not land are never left behind under other - /// names. An error means they could not be kept (or read): the snapshot is not written, so + /// them under, so files kept for an upgrade that did not land are never left behind under + /// other names. Kept once: when a snapshot failed and is tried again, they stay as they are + /// (the failed one may have landed all the same, and the snapshot is then no longer what + /// could be kept). A snapshot that is already in this build's format (that landed after its + /// files were kept, or before them, reporting a failure) is the upgrade done, with nothing + /// to keep. An error means they could not be kept (or read): the snapshot is not written, so /// the library stays as it was, with its way back. fn keep_before_upgrade(&mut self) -> Result<()> { let Some(from) = self.behind else { return Ok(()) }; @@ -653,12 +658,16 @@ impl Journal { return Ok(()); } let snap = self.store.read(SNAPSHOT).map_err(io)?; - // (a write of the snapshot that failed after it landed leaves one that is not what was - // to be kept under this name) - if let Some(bytes) = snap.as_deref() - && serde_json::from_slice::(bytes).ok().map(|h| h.version) != Some(from) - { - return Err(CatalogError::Io(format!("the snapshot is no longer in format v{from}, and can't be kept as it was"))); + if let Some(bytes) = snap.as_deref() { + match serde_json::from_slice::(bytes).ok().map(|h| h.version) { + Some(v) if v == from => {} + // the upgrade is written already: the snapshot after it is a plain one + Some(VERSION) => { + self.upgraded_later(); + return Ok(()); + } + _ => return Err(CatalogError::Io(format!("the snapshot is no longer in format v{from}, and can't be kept as it was"))), + } } let mut log = self.store.read(LOG).map_err(io)?.unwrap_or_default(); let (seq, log_len) = self.behind_at; diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index cf0fc99d15e..bc7bb95338e 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -538,18 +538,19 @@ fn the_files_a_later_snapshot_keeps_are_told_once_it_is_written() { assert!(j.take_kept().is_empty(), "once"); } -/// Given a library left in its old format whose snapshot failed after its files were kept, when -/// it goes on (more changes are appended, in this build's ops) and a later snapshot upgrades it, +/// Given a library opened in its old format (its upgrade could not be written) that is then +/// changed, in this build's ops, before any snapshot is tried, when a later snapshot upgrades it, /// then the files kept are the library as it was at open, under the names the open would have -/// given them: nothing piles up, and an older build can read them whatever was appended since. +/// given them: not the log as it is now, and nothing piles up. (An older build can read them +/// whatever was appended since.) #[test] fn files_kept_by_a_later_snapshot_are_the_library_as_it_was_at_open() { static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); let (m, snap, log) = v6_library(); let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); - assert!(j.snapshot(&c).is_err()); j.append(&[Op::SetLabelName { label: ColorLabel::ALL[0], name: Some("x".into()) }]).unwrap(); + assert!(m.get(LOG).unwrap().len() > log.len(), "the log has grown"); assert!(j.snapshot(&c).is_err(), "still full"); FULL.store(false, std::sync::atomic::Ordering::SeqCst); j.snapshot(&c).unwrap(); @@ -558,20 +559,89 @@ fn files_kept_by_a_later_snapshot_are_the_library_as_it_was_at_open() { assert_eq!(m.files.lock().unwrap().keys().filter(|k| k.contains(".v6-")).count(), 2, "{:?}", m.files.lock().unwrap().keys()); } -/// Given a library left in its old format whose snapshot write failed after it landed (the share -/// dropped the answer), when a later snapshot would keep its files, then the snapshot that is -/// there is not kept under the old format's name, and nothing is deleted. +/// Given a library left in its old format whose snapshot is in this build's format already (a +/// write that landed and reported a failure, before anything was kept), when snapshots are +/// written, then each of them works: the upgrade is done, with nothing to keep (the old files +/// are gone from under that name), and nothing is refused until the library is reopened. #[test] -fn a_snapshot_that_landed_is_not_kept_as_the_old_format() { +fn a_snapshot_that_landed_is_the_upgrade_done() { static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); let (m, _, log) = v6_library(); let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); - // the upgrade landed after all, though the write said it failed - m.set(SNAPSHOT, b"{\"format\":\"lightcraft-catalog\",\"version\":99,\"seq\":8,\"catalog\":{}}\n".to_vec()); - let e = j.snapshot(&c).unwrap_err(); - assert!(e.to_string().contains("no longer in format"), "{e}"); + FULL.store(false, std::sync::atomic::Ordering::SeqCst); + m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":8,\"catalog\":{}}}\n", c.to_snapshot()).into_bytes()); + j.snapshot(&c).unwrap(); + j.snapshot(&c).unwrap(); assert!(j.take_kept().is_empty()); - assert_eq!(m.get(LOG), Some(log)); - assert!(!m.files.lock().unwrap().keys().any(|k| k.starts_with("catalog.snap.v")), "{:?}", m.files.lock().unwrap().keys()); + assert_eq!(snapshot_version(&m), u64::from(VERSION)); + assert!(!m.files.lock().unwrap().keys().any(|k| k.contains(".v6-")), "nothing kept from a snapshot that is not the old one"); + let _ = log; +} + +/// Given a library left in its old format, when a snapshot lands after its files were kept but +/// reports a failure, and the snapshot is tried again, then the retry goes through, and the files +/// told are the old library, not the snapshot that is there now. +#[test] +fn a_snapshot_that_landed_after_its_files_were_kept_is_tried_again() { + static LAND: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + struct Landing { + inner: Refusing, + } + impl Store for Landing { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.inner.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + use std::sync::atomic::Ordering::SeqCst; + if name == SNAPSHOT && LAND.load(SeqCst) == 1 { + // lands, and says it did not (the share dropped the answer) + self.inner.files.write_atomic(name, data)?; + LAND.store(2, SeqCst); + return Err(std::io::Error::other("the share went away")); + } + self.inner.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + self.inner.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + self.inner.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + self.inner.remove(name) + } + fn describe(&self) -> String { + "landing".into() + } + } + let (m, snap, log) = v6_library(); + let store = + Landing { inner: Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && LAND.load(std::sync::atomic::Ordering::SeqCst) == 0 } }; + let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); + LAND.store(1, std::sync::atomic::Ordering::SeqCst); + assert!(j.snapshot(&c).is_err(), "landed, and said it did not"); + assert_eq!(snapshot_version(&m), u64::from(VERSION), "it did land"); + j.snapshot(&c).unwrap(); + assert_eq!(j.take_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)), "the old library, not the snapshot that landed"); + assert!(j.take_kept().is_empty(), "told once"); +} + +/// Given a library left in its old format whose snapshot failed after its files were kept, when +/// the snapshot is tried again (a compaction retries as the log grows), then the files are not +/// copied again: a large library is not written out in full at every retry. +#[test] +fn files_kept_for_a_failed_snapshot_are_not_written_again_on_a_retry() { + static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let (m, _, _) = v6_library(); + let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); + assert!(j.snapshot(&c).is_err()); + m.set("catalog.snap.v6-8", b"marker".to_vec()); + assert!(j.snapshot(&c).is_err(), "still full"); + assert_eq!(m.get("catalog.snap.v6-8"), Some(b"marker".to_vec()), "not written again"); + FULL.store(false, std::sync::atomic::Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]); } diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index bf284087b5f..c957dd016fa 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -675,8 +675,6 @@ impl Session { log::error!("library: compaction: {e}"); lib.last_error = Some(format!("compaction: {e}")); } - // (a compaction that wrote its snapshot at once, where there is no worker thread) - note_upgrade_kept(lib); let due = self.library.as_ref().is_some_and(|l| l.presets_saved.differs(self) && !l.blocked.contains(&"presets.json")); if !due { return Ok(()); diff --git a/crates/engine/src/tests/persist.rs b/crates/engine/src/tests/persist.rs index 43c8723eaf5..68686ab8380 100644 --- a/crates/engine/src/tests/persist.rs +++ b/crates/engine/src/tests/persist.rs @@ -241,40 +241,77 @@ fn an_upgraded_library_says_where_what_it_was_is_kept() { let _ = std::fs::remove_dir_all(&dir); } -/// Given an older library that could not keep its files at open, when a later compaction upgrades -/// it (the files can be kept now), then the person is told once where the library as it was is -/// kept, as when the open upgrades it. -#[test] -fn a_later_upgrade_says_where_what_it_was_is_kept() { - let dir = std::env::temp_dir().join(format!("lightcraft-kept-later-{}", std::process::id())); +/// An older library (format 6) that could not keep its files at open: a directory sits where the +/// first kept file goes. +fn library_that_could_not_keep_its_files(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("lightcraft-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); std::fs::write(dir.join("catalog.snap.v6-8").join("in the way"), b"x").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(); + dir +} + +/// The names of the files kept for format 6 in `dir`. +fn kept_for_v6(dir: &std::path::Path, prefix: &str) -> Vec { + let mut names: Vec = std::fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap()) + .filter(|e| e.path().is_file()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.starts_with(prefix) && !n.ends_with(".tmp")) + .collect(); + names.sort(); + names +} + +/// Given an older library that could not keep its files at open, when a later compaction upgrades +/// it (the files can be kept now), then the person is told once where the library as it was is +/// kept, as when the open upgrades it, and a later compaction tells nothing more. +#[test] +fn a_later_upgrade_says_where_what_it_was_is_kept() { + let dir = library_that_could_not_keep_its_files("kept-later"); let mut s = Session::new(); s.open_library(&dir, false).unwrap(); assert!(s.take_library_warnings().iter().all(|w| !w.contains("upgraded")), "not upgraded at open"); assert!(s.compact_library().is_err(), "its files can't be kept yet"); std::fs::remove_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); s.compact_library().unwrap(); - let on_disk = |prefix: &str| { - let mut names: Vec = std::fs::read_dir(&dir) - .unwrap() - .map(|e| e.unwrap()) - .filter(|e| e.path().is_file()) - .map(|e| e.file_name().to_string_lossy().into_owned()) - .filter(|n| n.starts_with(prefix) && !n.ends_with(".tmp")) - .collect(); - names.sort(); - names - }; - let (snap, log) = (on_disk("catalog.snap.v6-"), on_disk("catalog.log.v6-")); + let (snap, log) = (kept_for_v6(&dir, "catalog.snap.v6-"), kept_for_v6(&dir, "catalog.log.v6-")); assert_eq!((snap.len(), log.len()), (1, 1), "the files as they were are kept"); let told = s.take_library_warnings(); assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0]) && w.contains("delete")), "{told:?}"); let info = s.execute("library.info", &serde_json::json!({})).unwrap(); assert!(info["settingsWarnings"].to_string().contains(&snap[0]), "{info}"); + s.compact_library().unwrap(); + assert!(s.take_library_warnings().is_empty(), "told once"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The same, when the compaction is written by the background worker: the person is told once its +/// result is taken (the frame loop's `persist`), not before. +#[test] +fn a_background_upgrade_says_where_what_it_was_is_kept() { + let dir = library_that_could_not_keep_its_files("kept-background"); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + let _ = s.take_library_warnings(); + std::fs::remove_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); + s.compact_soon(); + let started = std::time::Instant::now(); + let mut told = Vec::new(); + while told.is_empty() && started.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(10)); + s.persist().unwrap(); + told = s.take_library_warnings(); + } + let (snap, log) = (kept_for_v6(&dir, "catalog.snap.v6-"), kept_for_v6(&dir, "catalog.log.v6-")); + assert_eq!((snap.len(), log.len()), (1, 1)); + assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0])), "{told:?}"); + s.persist().unwrap(); + assert!(s.take_library_warnings().is_empty(), "told once"); s.close_library().unwrap(); let _ = std::fs::remove_dir_all(&dir); } diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index 50558f38a22..31838e4c87e 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -12,8 +12,8 @@ Opening a library with a newer LightCraft rewrites it in that version's format, 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 number of the last change the library held when it was upgraded (or, where the upgrade was left for a + later snapshot, when the library was opened; 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 whose files can't be kept, or whose upgrade can't be written (a full disk, a folder that can't be written @@ -21,10 +21,12 @@ library was, byte for byte, beside it: disk after a failed write can't be read back to say whether the upgrade was written, the library is refused instead (its way back stays). A library left like that is upgraded by its next snapshot, during the session or when it is closed, and that snapshot keeps the files first too (and is not written when they can't be kept). When a snapshot - during the session does that, LightCraft tells where the files are kept, as it does at open (a snapshot at close - has no one left to tell: the files are in the folder, named as above). The files kept are the library as it was - when it opened (the snapshot, and the log up to where it ended then): what was changed since is in the files that - replace them, and never in the kept ones, so an older version opens them whatever was changed. Until then, changes + during the session does that, LightCraft tells where the files are kept, as it does at open (a snapshot when the + library is closed, or switched away from in Settings, has no one left to tell: the files are in the folder, named + as above). The files kept are the library as it was when it opened (the snapshot, and the log up to where it ended + then): what was changed since is in the files that replace them, not in the kept ones. (An earlier session of this + version may have added changes while the library stayed in its old format: they are in the log it opened with, and + an older version may refuse them.) Until then, changes go on being appended to the library as it is, so that they can be saved at all where there is no room for a copy of its files. (If the session ends without that snapshot, the next open keeps the log as it is then, which holds those changes, and tells so; the files kept earlier stay beside it.) @@ -37,5 +39,6 @@ library was, byte for byte, beside it: wanted. The browser build keeps none (it always runs the newest version). **To go back**, with LightCraft closed: move `catalog.snap` and `catalog.log` away, then rename the kept pair to -`catalog.snap` and `catalog.log`. The older version opens the library as it was when it was upgraded; changes made -since, in the newer version, are in the files that were moved away and are not carried back. +`catalog.snap` and `catalog.log`. The older version opens the library as it was when it was upgraded (where the upgrade came +from a later snapshot: as it was when it was opened, so the changes made between that and the upgrade are not carried +back either); changes made since, in the newer version, are in the files that were moved away. From d50ad6f460c5f8aead443277eb529d62770149be Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 12:49:06 -0400 Subject: [PATCH 04/61] Catalog: a write that fails leaves no staging file, so a copy that can't be kept leaves nothing lying about FsStore::write_atomic left `.tmp` behind when the write, the sync or the rename failed, and write_atomic_with left it when the rename failed. The files an upgrade keeps are written through it, so a full disk or a taken name left a partial `catalog.snap.v6-8.tmp` beside the library, against the documented all-or-nothing keep and "no copy left lying about". Both now remove the staging file on any failure. Co-Authored-By: Claude --- crates/catalog/src/store.rs | 48 ++++++++++++++++++++-- crates/catalog/src/tests_format_version.rs | 21 ++++++++++ crates/engine/src/tests/persist.rs | 2 +- 3 files changed, 67 insertions(+), 4 deletions(-) diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index 48d28587f1e..19ff6ff9cb9 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -123,12 +123,18 @@ impl Store for FsStore { self.appender = None; } let tmp = self.path(&format!("{name}.tmp")); - { + let staged = (|| { let mut f = create_staging(&tmp)?; f.write_all(data)?; f.sync_all()?; + drop(f); + std::fs::rename(&tmp, self.path(name)) + })(); + if let Err(e) = staged { + // no staging file is left beside the library (a kept copy is all or nothing) + let _ = std::fs::remove_file(&tmp); + return Err(e); } - std::fs::rename(&tmp, self.path(name))?; self.sync_dir(); Ok(()) } @@ -154,7 +160,10 @@ impl Store for FsStore { return Err(e); } }; - std::fs::rename(&tmp, self.path(name))?; + if let Err(e) = std::fs::rename(&tmp, self.path(name)) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } self.sync_dir(); Ok(n) } @@ -333,3 +342,36 @@ mod tests_staging { let _ = std::fs::remove_dir_all(&dir); } } + +#[cfg(test)] +mod tests_failed_write { + use super::*; + + fn dir_with_a_directory_at(tag: &str, name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("lc-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join(name)).unwrap(); + dir + } + + /// A write that can't land (here the rename fails, the name being a directory) leaves no staging file behind: the + /// files a library keeps before an upgrade are "all or nothing", and a `.tmp` beside them is a copy lying about. + #[test] + fn write_atomic_that_fails_leaves_no_staging_file() { + let dir = dir_with_a_directory_at("write-atomic-fails", "catalog.snap.v6-8"); + let mut store = FsStore::open(&dir).unwrap(); + assert!(store.write_atomic("catalog.snap.v6-8", b"{}").is_err()); + assert!(!dir.join("catalog.snap.v6-8.tmp").exists(), "a staging file was left behind"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// The streamed write cleans up the same way when the rename fails (it already did when the content can't be written). + #[test] + fn write_atomic_with_that_fails_to_rename_leaves_no_staging_file() { + let dir = dir_with_a_directory_at("write-atomic-with-fails", "catalog.log"); + let mut store = FsStore::open(&dir).unwrap(); + assert!(store.write_atomic_with("catalog.log", &mut |w| w.write_all(b"[1]")).is_err()); + assert!(!dir.join("catalog.log.tmp").exists(), "a staging file was left behind"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index bc7bb95338e..8c2ce48f715 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -359,6 +359,27 @@ fn a_library_that_cannot_be_kept_is_not_upgraded() { assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, Some(6), 2)); } +/// Given an older library on disk whose files can't be kept (the name of one is taken by a directory), when it is +/// opened, then it is not upgraded, and no copy or half-written staging file of the files it tried to keep is left +/// lying about in the library's folder. +#[test] +fn a_library_on_disk_that_cannot_be_kept_leaves_nothing_lying_about() { + let dir = std::env::temp_dir().join(format!("lc-keep-fails-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("catalog.log.v6-8")).unwrap(); + let (snap, log) = fixture(6).unwrap(); + std::fs::write(dir.join(SNAPSHOT), snap).unwrap(); + std::fs::write(dir.join(LOG), log).unwrap(); + + let (_, c, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0)); + let mut names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + names.sort(); + assert_eq!(names, [LOG, "catalog.log.v6-8", SNAPSHOT], "nothing but the library and the name that was taken"); + assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), snap.as_bytes()); + let _ = std::fs::remove_dir_all(&dir); +} + /// Given an older library whose upgrade can't be written, when it is opened, then it opens as it /// was, with no copy of it left lying about: there is nothing to go back from. #[test] diff --git a/crates/engine/src/tests/persist.rs b/crates/engine/src/tests/persist.rs index 68686ab8380..8d02dae5ce9 100644 --- a/crates/engine/src/tests/persist.rs +++ b/crates/engine/src/tests/persist.rs @@ -260,7 +260,7 @@ fn kept_for_v6(dir: &std::path::Path, prefix: &str) -> Vec { .map(|e| e.unwrap()) .filter(|e| e.path().is_file()) .map(|e| e.file_name().to_string_lossy().into_owned()) - .filter(|n| n.starts_with(prefix) && !n.ends_with(".tmp")) + .filter(|n| n.starts_with(prefix)) .collect(); names.sort(); names From c8be9db6f8dafbc94cc96ae5f95332ab5438ff8f Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 10:21:52 -0400 Subject: [PATCH 05/61] Catalog: the docs and comments say what a failed later snapshot leaves: the files kept at open stay, as they were then --- crates/catalog/src/journal.rs | 21 ++++++++++++--------- docs/catalog-persistence.md | 6 ++++-- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 68f7021f2ce..c47a718d08e 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -63,19 +63,21 @@ //! - **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. +//! (Except where the upgrade can't be written or its files can't be kept: see *Format versions*.) //! [`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 left in its old format at open -//! (its files couldn't be kept, or the upgrade couldn't be written) is upgraded by a later -//! snapshot (compaction, or closing), which keeps the files as they are then first and is not -//! written when it can't. +//! library on disk is known to be in its old format still: an upgrade at open 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 left in its old format +//! at open (its files couldn't be kept, or the upgrade couldn't be written) is upgraded by a +//! later snapshot (compaction, or closing), which first keeps the files as they were at open +//! (the snapshot, and the log up to where it ended then) and is not written when it can't. Those +//! files stay even if that snapshot then fails and the library is still in its old format. //! - **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 @@ -382,8 +384,9 @@ struct SnapFile { impl Journal { /// Open (or create) the catalog in `store`: load the snapshot, replay the log, repair a torn /// 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 its damaged log can't be replaced - /// or its snapshot can't be kept (see the module docs → *Format versions*). + /// modified), or if the library is in an older format and its damaged log can't be replaced, + /// its snapshot can't be kept, or it can't be told whether its upgrade was written (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)?; diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index 31838e4c87e..ba4943ea59a 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -14,8 +14,10 @@ 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 (or, where the upgrade was left for a later snapshot, when the library was opened; 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. +- The files kept at open stay unless the library is known to be in its old format still, because the upgrade at open + did not happen (then they keep nothing, and are removed again): once the upgrade is written, nothing that fails + after it takes them away. The files a later snapshot keeps (below) stay too, even if that snapshot then fails and + the library is still in its old format. - A library whose files can't be kept, or whose upgrade can't be written (a full disk, a folder that can't be written to), is not upgraded: it opens as it is, with no copy left lying about, and the next open tries again. If what is on disk after a failed write can't be read back to say whether the upgrade was written, the library is refused instead From af6b1c558e1e4627b1669e59405404112b78cf1d Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 11:05:53 -0400 Subject: [PATCH 06/61] Catalog: the damaged-log bullet and the module docs say what is left when the log can't be replaced, and what a later snapshot keeps --- crates/catalog/src/journal.rs | 8 +++++--- docs/catalog-persistence.md | 6 ++++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index c47a718d08e..a50df582632 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -63,13 +63,15 @@ //! - **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. -//! (Except where the upgrade can't be written or its files can't be kept: see *Format versions*.) -//! [`LoadReport::upgraded_from`] says when that happened. +//! (Except where the upgrade can't be written or its files can't be kept: see the next rule.) +//! [`LoadReport::upgraded_from`] says when the upgrade happened at open. //! - **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 +//! their own names, they are the library as the older build left it (what a later snapshot +//! keeps is the library as it was at open: a torn tail already cut, and what a session of this +//! build appended while it stayed in its old format, which an older build may refuse). They stay unless the //! library on disk is known to be in its old format still: an upgrade at open 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 diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index ba4943ea59a..5239f842267 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -34,8 +34,10 @@ library was, byte for byte, beside it: those changes, and tells so; the files kept earlier stay beside it.) - 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. If the snapshot can't be kept, or the damaged log can't be replaced, the library is refused and left - as it was (changes made in it would be appended after the damage, where the next open would not read them). + that log held. If the snapshot can't be kept, the library is refused and left as it was; if the damaged log can't + be replaced after the upgrade was written, it is refused too, and its way back (the kept snapshot and + `catalog.log.damaged-`) stays (changes made in it would be appended after the damage, where the next open + would not read them). - 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). From f9e835806102779465e3df64cff411964016d3b8 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 29 Oct 2026 14:54:32 -0400 Subject: [PATCH 07/61] Upgrade notice names a damaged log kept by the upgrade; the way back renames a kept catalog.log.damaged- like any kept log --- crates/engine/src/library.rs | 5 ++-- crates/engine/src/tests/persist.rs | 45 ++++++++++++++++++++++++++++++ docs/catalog-persistence.md | 7 +++-- 3 files changed, 53 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index c957dd016fa..e1765de1d16 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -324,7 +324,7 @@ struct SettingsLoad { /// 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(kept: &[String], damaged: Option<&String>) -> Option { - if kept.is_empty() { + if kept.is_empty() && damaged.is_none() { return None; } // (a library whose log was damaged: that log is the other half of what it was) @@ -601,7 +601,8 @@ impl Session { self.tidy_thumbnail_cache(); } let view_written = self.view_json(); - let kept = kept_note(&report.kept, report.damaged.as_ref()); + // (a damaged log is only part of "what the library was" when opening upgraded it: a library in this format that lost its log's tail was not upgraded) + let kept = kept_note(&report.kept, report.damaged.as_ref().filter(|_| report.upgraded_from.is_some())); self.library = Some(Library { dir, on_disk, diff --git a/crates/engine/src/tests/persist.rs b/crates/engine/src/tests/persist.rs index 8d02dae5ce9..5f861e6785c 100644 --- a/crates/engine/src/tests/persist.rs +++ b/crates/engine/src/tests/persist.rs @@ -241,6 +241,51 @@ fn an_upgraded_library_says_where_what_it_was_is_kept() { let _ = std::fs::remove_dir_all(&dir); } +/// The v6 fixture's log with its second record replaced by garbage (a record after it is still good, so it is damage, not a torn tail). +fn damaged_v6_log() -> String { + let log = include_str!("../../../catalog/src/fixtures/v6-catalog.log.jsonl"); + log.lines().enumerate().map(|(i, l)| if i == 1 { "not a record" } else { l }).collect::>().join("\n") + "\n" +} + +/// Given a library from an earlier version that has only a damaged log, when it is opened and upgraded, then the person is told +/// where the damaged log is kept (there is no kept snapshot to name it beside). +#[test] +fn an_upgraded_library_with_only_a_damaged_log_says_where_the_log_is_kept() { + let dir = std::env::temp_dir().join(format!("lightcraft-kept-dmg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("catalog.log"), damaged_v6_log()).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("upgraded") && w.contains("catalog.log.damaged-")), "{told:?}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A library already in this version's format whose log was damaged was not upgraded: it is not told it was. +#[test] +fn a_current_library_with_a_damaged_log_is_not_told_it_was_upgraded() { + let dir = std::env::temp_dir().join(format!("lightcraft-cur-dmg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.open_library(&dir, true).unwrap(); + s.execute("photo.rate", &serde_json::json!({"rating": 3})).unwrap(); + s.execute("photo.rate", &serde_json::json!({"rating": 4})).unwrap(); + s.execute("photo.rate", &serde_json::json!({"rating": 5})).unwrap(); + drop(s); + let log = std::fs::read_to_string(dir.join("catalog.log")).unwrap(); + let broken: Vec<&str> = log.lines().enumerate().map(|(i, l)| if i == 1 { "not a record" } else { l }).collect(); + std::fs::write(dir.join("catalog.log"), broken.join("\n") + "\n").unwrap(); + let mut s = Session::new(); + let damaged = s.open_library(&dir, false).unwrap().damaged.clone(); + assert!(damaged.is_some_and(|name| dir.join(name).exists()), "the log was found damaged and kept"); + let told = s.take_library_warnings(); + assert!(!told.iter().any(|w| w.contains("upgraded")), "{told:?}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + /// An older library (format 6) that could not keep its files at open: a directory sits where the /// first kept file goes. fn library_that_could_not_keep_its_files(name: &str) -> std::path::PathBuf { diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index 5239f842267..5e35a05557f 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -42,7 +42,10 @@ library was, byte for byte, beside it: 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` and `catalog.log` away, then rename the kept pair to -`catalog.snap` and `catalog.log`. The older version opens the library as it was when it was upgraded (where the upgrade came +**To go back**, with LightCraft closed: move `catalog.snap` and `catalog.log` away, then rename each kept file that exists +to `catalog.snap` and `catalog.log` (a library that had no log, or only a log, kept only the one file: rename only that +one, and leave the other name unused). Where the log was damaged, the kept log is `catalog.log.damaged-`: it takes +the place of `catalog.log` like any kept log (the older version reads it up to the damage and handles it as it did +before), beside the kept snapshot when there is one. The older version opens the library as it was when it was upgraded (where the upgrade came from a later snapshot: as it was when it was opened, so the changes made between that and the upgrade are not carried back either); changes made since, in the newer version, are in the files that were moved away. From c6f52eb3871cd82a16ba66724827b7b3fb0f0509 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 23 Oct 2026 11:00:36 -0400 Subject: [PATCH 08/61] Catalog: the store can write files that a later write names, list its files and sync folders it can The catalog store gets what a snapshot in several files will need, with no caller yet: `Store::remove`, `Store::write_new_with` (a file that doesn't exist yet, durable in itself), `Store::sync` (one checked sync of the folders for all of them), `Store::list` and `Store::segmented` (the default can't hold segments: the browser's store). `FsStore` writes files into the library's `segments/` folder (made with its first file, and refused where `segments` is a file or a link to a folder elsewhere), lists them as `segments/`, and syncs. What exists today is unchanged: `write_atomic` and `write_atomic_with` still sync the folder on a best-effort basis and never fail for it. Only the new `sync` reports a folder sync that fails, except on a file system that can't sync folders (EBADF, EINVAL, "not supported": the platform's own number, and macOS's EOPNOTSUPP 102, which is ENETRESET on Linux), where it does nothing, as on Windows. Nothing reads or writes `segments` yet: `crate::segments` holds only the names of the files, and the tests are of the store alone. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 3 + crates/catalog/src/segments.rs | 18 ++ crates/catalog/src/store.rs | 431 ++++++++++++++++++++++++--- crates/catalog/src/tests_segments.rs | 220 ++++++++++++++ 4 files changed, 634 insertions(+), 38 deletions(-) create mode 100644 crates/catalog/src/segments.rs create mode 100644 crates/catalog/src/tests_segments.rs diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a6972..0515b530c2b 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -24,6 +24,7 @@ pub mod model; pub mod query; pub mod rules; pub mod safe_file; +pub mod segments; pub mod stacks; pub mod store; pub mod tally; @@ -1211,6 +1212,8 @@ mod tests_repair; #[cfg(test)] mod tests_scale; #[cfg(test)] +mod tests_segments; +#[cfg(test)] mod tests_tally; #[cfg(test)] mod tests_torn_append; diff --git a/crates/catalog/src/segments.rs b/crates/catalog/src/segments.rs new file mode 100644 index 00000000000..c2ad2ea47a1 --- /dev/null +++ b/crates/catalog/src/segments.rs @@ -0,0 +1,18 @@ +//! Where the segment files of a snapshot in several files will be: in a folder of the library's +//! own, named `segments/-.json`. The stores ([`crate::store`]) know these names: +//! they make the folder, list its files and sync it. Nothing writes or reads segments yet: what +//! they hold, and how they are written and read, come with the catalog format that uses them. + +/// 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`]. (A file an interrupted write left is the same name plus `.tmp`, +/// and is listed under this prefix too.) +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}") +} diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index a79930f14af..ad2e4070126 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,21 @@ 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. A name that is + /// taken is an [`io::ErrorKind::AlreadyExists`] error and that file keeps its content. The + /// default can't promise that (its replacing write would overwrite): such a store refuses. + fn write_new_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result { + let _ = (name, fill); + Err(io::Error::new(io::ErrorKind::Unsupported, "this store can't create new files")) + } + /// Make the files written with [`Store::write_new_with`] durable in their folders (the + /// library's, and its `segments/` 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 +50,23 @@ 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")) + } + /// The names of the files it holds that it can be asked for by name (a file with a name no + /// other call would accept isn't listed). 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 @@ -73,16 +105,162 @@ impl FsStore { pub fn dir(&self) -> &Path { &self.dir } - fn path(&self, name: &str) -> PathBuf { - self.dir.join(name) + /// Where the file `name` is. A name is a file of the library's folder, or of its segments + /// folder (`segments/`): anything else (an absolute name, `..`, deeper folders) would + /// leave the library and is refused before the file system is touched. + fn path(&self, name: &str) -> io::Result { + let valid_part = |p: &str| !matches!(p, "" | "." | "..") && !p.contains(['\\', ':', '\0', '/']); + let ok = match name.split_once('/') { + None => valid_part(name) && name != crate::segments::SEGMENT_DIR, + Some((folder, file)) => folder == crate::segments::SEGMENT_DIR && valid_part(file), + }; + if ok { + Ok(self.dir.join(name)) + } else { + Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{name:?} is not a name of the catalog's files"))) + } + } + /// The folder a file is in: the library's, or the one its name states (`segments/…`). + fn folder_of(&self, name: &str) -> io::Result { + Ok(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); + } + /// The new content of `name`, written and fsynced into its staging file (`.tmp`, in the + /// folder of the file): the staging file's path and the content's length. The staging file + /// is removed again if writing fails. + fn stage(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result<(PathBuf, u64)> { + 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)?; + w.flush()?; + let f = w.inner.into_inner().map_err(|e| e.into_error())?; + f.sync_all()?; + Ok(w.n) + })(); + match written { + Ok(n) => Ok((tmp, n)), + Err(e) => { + let _ = std::fs::remove_file(&tmp); + Err(e) + } } } + /// 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)) +} + +/// The file `tmp` becomes `dest` only if `dest` doesn't exist: a name that is taken is an +/// `AlreadyExists` error and its file is untouched (`rename` would replace it). A hard link is +/// the no-replace move `std` offers on every platform; on a file system without them (some +/// network shares, FAT) see [`rename_if_absent`]. `tmp` is removed afterwards, and if that fails +/// (a virus scanner holding it open) the next write of the name clears it. +fn commit_new(tmp: &Path, dest: &Path) -> io::Result<()> { + let linked = match std::fs::hard_link(tmp, dest) { + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Err(e), + Err(_) => rename_if_absent(tmp, dest), + Ok(()) => Ok(()), + }; + let _ = std::fs::remove_file(tmp); + linked +} + +/// [`commit_new`] where hard links aren't there: the name is looked up (a dangling link counts +/// as taken), then `tmp` renamed. A file that appears between the two is replaced: the one +/// window a file system without a no-replace move leaves. +fn rename_if_absent(tmp: &Path, dest: &Path) -> io::Result<()> { + match std::fs::symlink_metadata(dest) { + Ok(_) => Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{} exists", dest.display()))), + Err(e) if e.kind() == io::ErrorKind::NotFound => std::fs::rename(tmp, dest), + Err(e) => Err(e), + } +} + +/// Whether a directory entry whose type was asked for is a file. An entry that is gone by the +/// time it is looked at isn't one; any other failure is the caller's (a listing that skipped +/// the entry would pass for complete). +fn is_listed_file(kind: io::Result) -> io::Result { + match kind { + Ok(t) => Ok(t.is_file()), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(e), + } } /// A new staging file at `tmp`: whatever is already there (a leftover from a crashed save, or a link) is removed first @@ -97,7 +275,7 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result impl Store for FsStore { fn read(&mut self, name: &str) -> io::Result>> { - match std::fs::read(self.path(name)) { + match std::fs::read(self.path(name)?) { Ok(b) => Ok(Some(b)), Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e), @@ -109,49 +287,50 @@ impl Store for FsStore { if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } - let tmp = self.path(&format!("{name}.tmp")); + 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(); + std::fs::rename(&tmp, self.path(name)?)?; + // (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 { - 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")); - let written = (|| { - let mut w = Counter { inner: io::BufWriter::with_capacity(1 << 20, create_staging(&tmp)?), n: 0 }; - fill(&mut w)?; - w.flush()?; - let f = w.inner.into_inner().map_err(|e| e.into_error())?; - f.sync_all()?; - Ok(w.n) - })(); - let n = match written { - Ok(n) => n, - Err(e) => { - let _ = std::fs::remove_file(&tmp); - return Err(e); - } - }; - std::fs::rename(&tmp, self.path(name))?; - self.sync_dir(); + let (tmp, n) = self.stage(name, fill)?; + std::fs::rename(&tmp, self.path(name)?)?; + // (renamed already, as on `main`: a folder that can't be synced is no reason to say nothing was written) + Self::sync_folder(&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 { + let (tmp, n) = self.stage(name, fill)?; + commit_new(&tmp, &self.path(name)?)?; Ok(n) } fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> { use std::io::Write; if self.appender.as_ref().is_none_or(|(n, _)| n != name) { - check_regular_directory_entry(&self.path(name))?; - let existed = self.path(name).exists(); - let f = std::fs::OpenOptions::new().create(true).append(true).open(self.path(name))?; + let path = self.path(name)?; + check_regular_directory_entry(&path)?; + let existed = path.exists(); + let f = std::fs::OpenOptions::new().create(true).append(true).open(path)?; if !existed { self.sync_dir(); } @@ -172,8 +351,9 @@ impl Store for FsStore { if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } - check_regular_directory_entry(&self.path(name))?; - let f = match std::fs::OpenOptions::new().write(true).open(self.path(name)) { + let path = self.path(name)?; + check_regular_directory_entry(&path)?; + let f = match std::fs::OpenOptions::new().write(true).open(path) { Ok(f) => f, // nothing to cut (an append that failed before creating the file) Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), @@ -183,6 +363,70 @@ 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; + } + // (a file in a folder of the library's own, as for writing and listing: never through a link) + let folder = self.folder_of(name)?; + if folder != self.dir { + match std::fs::symlink_metadata(&folder) { + Ok(m) if m.is_dir() => {} + Ok(_) => return Err(io::Error::other(format!("{} is not a folder", folder.display()))), + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(io::Error::new(e.kind(), format!("{}: {e}", folder.display()))), + } + } + 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 is_listed_file(entry.file_type())? + && let Ok(name) = entry.file_name().into_string() + && self.path(&name).is_ok() + { + 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 is_listed_file(entry.file_type())? + && let Ok(name) = entry.file_name().into_string() + && self.path(&format!("{}{name}", crate::segments::SEGMENT_PREFIX)).is_ok() + { + 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() } @@ -216,6 +460,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 { @@ -238,6 +485,17 @@ impl Store for MemStore { self.set(name, data.to_vec()); Ok(()) } + fn write_new_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn io::Write) -> io::Result<()>) -> io::Result { + let mut data = Vec::new(); + fill(&mut data)?; + let mut files = self.files.lock().unwrap_or_else(|e| e.into_inner()); + if files.contains_key(name) { + return Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{name} exists"))); + } + let n = data.len() as u64; + files.insert(name.to_string(), data); + Ok(n) + } fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> { self.files.lock().unwrap_or_else(|e| e.into_inner()).entry(name.to_string()).or_default().extend_from_slice(data); Ok(()) @@ -248,6 +506,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() } @@ -305,3 +573,90 @@ 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}"); + } + } +} + +#[cfg(test)] +mod tests_listing { + #[cfg(unix)] + use super::{FsStore, Store}; + use super::{is_listed_file, rename_if_absent}; + use std::io::{Error, ErrorKind}; + + /// Where hard links aren't there, a taken name is still refused and left as it was, and a + /// free one is taken by the rename. + #[test] + fn the_fallback_without_hard_links_refuses_a_taken_name() { + let dir = std::env::temp_dir().join(format!("lc-no-links-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (tmp, dest) = (dir.join("x.tmp"), dir.join("x")); + std::fs::write(&tmp, b"new").unwrap(); + rename_if_absent(&tmp, &dest).unwrap(); + assert_eq!((std::fs::read(&dest).unwrap(), tmp.exists()), (b"new".to_vec(), false)); + std::fs::write(&tmp, b"newer").unwrap(); + assert_eq!(rename_if_absent(&tmp, &dest).unwrap_err().kind(), ErrorKind::AlreadyExists); + assert_eq!(std::fs::read(&dest).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A file whose name the store would refuse for every other call isn't listed, so a name + /// that is listed can always be read and removed. + #[cfg(unix)] + #[test] + fn a_listed_name_is_one_the_store_accepts() { + let dir = std::env::temp_dir().join(format!("lc-listing-names-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut store = FsStore::open(&dir).unwrap(); + std::fs::write(dir.join("a:b"), b"").unwrap(); + std::fs::write(dir.join("catalog.snap"), b"").unwrap(); + std::fs::create_dir_all(dir.join("segments")).unwrap(); + std::fs::write(dir.join("segments/1:1.json"), b"").unwrap(); + assert_eq!(store.list().unwrap(), ["catalog.snap"]); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A directory entry whose type can't be read fails the listing (it would pass for complete + /// without it); one that vanished meanwhile is just not there. + #[test] + fn a_failed_file_type_is_an_error_not_a_missing_file() { + let e = is_listed_file(Err(Error::from(ErrorKind::PermissionDenied))).unwrap_err(); + assert_eq!(e.kind(), ErrorKind::PermissionDenied); + assert!(!is_listed_file(Err(Error::from(ErrorKind::NotFound))).unwrap()); + let dir = std::env::temp_dir().join(format!("lc-listing-type-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("sub")).unwrap(); + std::fs::write(dir.join("f"), b"").unwrap(); + for entry in std::fs::read_dir(&dir).unwrap() { + let entry = entry.unwrap(); + assert_eq!(is_listed_file(entry.file_type()).unwrap(), entry.file_name() == "f"); + } + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/catalog/src/tests_segments.rs b/crates/catalog/src/tests_segments.rs new file mode 100644 index 00000000000..a7467871f26 --- /dev/null +++ b/crates/catalog/src/tests_segments.rs @@ -0,0 +1,220 @@ +//! The store's side of a snapshot in several files (`crate::segments`): the segments folder is +//! made with its first file, files are written under names that don't exist yet, listed and +//! synced. Nothing in the catalog writes or reads them yet. + +use crate::segments::segment_file; +use crate::*; + +/// 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); +} + +/// A file written with `write_new_with` is durable in itself, leaves no staging file, is +/// listed by the name the catalog gives it, and `sync` has nothing to say about a folder that can +/// be synced. +#[test] +fn a_file_written_for_a_later_write_to_name_is_listed_and_synced() { + let dir = std::env::temp_dir().join(format!("lc-segments-new-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut store = FsStore::open(&dir).unwrap(); + assert!(store.segmented()); + let n = store.write_new_with(&segment_file("1-1"), &mut |w| w.write_all(b"[1]")).unwrap(); + assert_eq!(n, 3); + store.write_new_with(&segment_file("2-1"), &mut |w| w.write_all(b"[2]")).unwrap(); + store.sync().unwrap(); + assert_eq!(std::fs::read(dir.join("segments/1-1.json")).unwrap(), b"[1]"); + let mut listed = store.list().unwrap(); + listed.sort(); + assert_eq!(listed, ["segments/1-1.json", "segments/2-1.json"]); + assert!(!dir.join("segments/1-1.json.tmp").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A write that fails leaves nothing of the file behind, and no folder entry names it. +#[test] +fn a_write_that_fails_leaves_no_file() { + let dir = std::env::temp_dir().join(format!("lc-segments-fail-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut store = FsStore::open(&dir).unwrap(); + let e = store.write_new_with(&segment_file("1-1"), &mut |_| Err(std::io::Error::other("no room"))).unwrap_err(); + assert!(e.to_string().contains("no room"), "{e}"); + assert!(store.list().unwrap().is_empty()); + assert!(!dir.join("segments/1-1.json.tmp").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The segments folder is the library's own: a file of that name is an error that says so, for +/// writing and for listing (what is listed may be removed). +#[test] +fn a_file_where_the_segments_folder_goes_is_refused() { + let dir = std::env::temp_dir().join(format!("lc-segments-file-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut store = FsStore::open(&dir).unwrap(); + std::fs::write(dir.join("segments"), b"not a folder").unwrap(); + let e = store.write_new_with(&segment_file("1-1"), &mut |w| w.write_all(b"[]")).unwrap_err(); + assert!(e.to_string().contains("is not a folder"), "{e}"); + let e = store.write_atomic(&segment_file("1-1"), b"[]").unwrap_err(); + assert!(e.to_string().contains("is not a folder"), "{e}"); + let e = store.list().unwrap_err(); + assert!(e.to_string().contains("is not a folder"), "{e}"); + assert_eq!(std::fs::read(dir.join("segments")).unwrap(), b"not a folder"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A link to a folder elsewhere is not the library's own folder either: nothing is written +/// through it and nothing in it is listed. +#[cfg(unix)] +#[test] +fn a_link_where_the_segments_folder_goes_is_refused() { + let base = std::env::temp_dir().join(format!("lc-segments-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (dir, elsewhere) = (base.join("library"), base.join("elsewhere")); + std::fs::create_dir_all(&elsewhere).unwrap(); + let mut store = FsStore::open(&dir).unwrap(); + std::os::unix::fs::symlink(&elsewhere, dir.join("segments")).unwrap(); + let e = store.write_new_with(&segment_file("1-1"), &mut |w| w.write_all(b"[]")).unwrap_err(); + assert!(e.to_string().contains("is not a folder"), "{e}"); + assert!(store.list().is_err()); + std::fs::write(elsewhere.join("1-1.json"), b"theirs").unwrap(); + let e = store.remove(&segment_file("1-1")).unwrap_err(); + assert!(e.to_string().contains("is not a folder"), "{e}"); + assert_eq!(std::fs::read(elsewhere.join("1-1.json")).unwrap(), b"theirs", "nothing was removed through the link"); + std::fs::remove_file(elsewhere.join("1-1.json")).unwrap(); + assert!(std::fs::read_dir(&elsewhere).unwrap().next().is_none(), "nothing went through the link"); + let _ = std::fs::remove_dir_all(&base); +} + +/// What exists today is unchanged: a plain file is written whole, in the library folder, and +/// `write_atomic_with` reports its length, as before (it does not make the segments folder). +#[test] +fn the_streamed_write_of_a_plain_file_is_what_it_was() { + let dir = std::env::temp_dir().join(format!("lc-segments-plain-with-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut store = FsStore::open(&dir).unwrap(); + let n = store.write_atomic_with("catalog.snap", &mut |w| w.write_all(b"{}\n")).unwrap(); + assert_eq!(n, 3); + assert_eq!(std::fs::read(dir.join("catalog.snap")).unwrap(), b"{}\n"); + assert!(!dir.join("segments").exists()); + assert_eq!(store.list().unwrap(), ["catalog.snap"]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The in-memory store lists what it holds, and holds segments unless it is made to keep one file. +#[test] +fn the_memory_store_lists_its_files() { + let mut store = MemStore::new(); + assert!(store.segmented()); + store.write_atomic("catalog.snap", b"{}").unwrap(); + assert_eq!(store.list().unwrap(), ["catalog.snap"]); + store.remove("catalog.snap").unwrap(); + assert!(store.list().unwrap().is_empty()); +} + +/// A name that is taken is an error and its file keeps what it had: a second `write_new_with` +/// never replaces (a plain rename would), and leaves no staging file. +#[test] +fn writing_a_new_file_never_replaces_one_that_exists() { + let dir = std::env::temp_dir().join(format!("lc-segments-exists-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut store = FsStore::open(&dir).unwrap(); + store.write_new_with(&segment_file("1-1"), &mut |w| w.write_all(b"first")).unwrap(); + let e = store.write_new_with(&segment_file("1-1"), &mut |w| w.write_all(b"second")).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists, "{e}"); + assert_eq!(std::fs::read(dir.join("segments/1-1.json")).unwrap(), b"first"); + assert!(!dir.join("segments/1-1.json.tmp").exists()); + // (a file of the library folder too, and a file that appeared meanwhile) + std::fs::write(dir.join("catalog.snap"), b"theirs").unwrap(); + let e = store.write_new_with("catalog.snap", &mut |w| w.write_all(b"ours")).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists, "{e}"); + assert_eq!(std::fs::read(dir.join("catalog.snap")).unwrap(), b"theirs"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The memory store holds to the same contract, and a store that doesn't override the method +/// refuses rather than replace. +#[test] +fn the_memory_store_does_not_replace_a_new_file_either() { + let mut store = MemStore::new(); + assert_eq!(store.write_new_with("segments/1-1.json", &mut |w| w.write_all(b"first")).unwrap(), 5); + let e = store.write_new_with("segments/1-1.json", &mut |w| w.write_all(b"second")).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::AlreadyExists); + assert_eq!(store.get("segments/1-1.json").unwrap(), b"first"); + + struct Plain(MemStore); + impl Store for Plain { + fn read(&mut self, n: &str) -> std::io::Result>> { + self.0.read(n) + } + fn write_atomic(&mut self, n: &str, d: &[u8]) -> std::io::Result<()> { + self.0.write_atomic(n, d) + } + fn append(&mut self, n: &str, d: &[u8]) -> std::io::Result<()> { + self.0.append(n, d) + } + fn truncate(&mut self, n: &str, l: u64) -> std::io::Result<()> { + self.0.truncate(n, l) + } + fn describe(&self) -> String { + String::new() + } + } + let mut plain = Plain(MemStore::new()); + plain.write_atomic("a", b"kept").unwrap(); + let e = plain.write_new_with("a", &mut |w| w.write_all(b"x")).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::Unsupported); + assert_eq!(plain.read("a").unwrap().unwrap(), b"kept"); +} + +/// Names that leave the library's folder are refused before the file system is touched, by +/// every operation that takes a name; the names the catalog uses still work. +#[test] +fn names_that_leave_the_library_are_refused() { + let base = std::env::temp_dir().join(format!("lc-segments-names-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("library"); + let mut store = FsStore::open(&dir).unwrap(); + std::fs::write(base.join("outside"), b"keep").unwrap(); + let outside = base.join("outside").display().to_string(); + for name in [ + "../outside", + "segments/../../outside", + "a/b", + "segments/a/b", + "segments/", + "segments", + "", + ".", + "..", + "segments/..", + "/etc/passwd", + outside.as_str(), + "other/x.json", + "a\\b", + ] { + let bad = |e: std::io::Error| assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{name:?}: {e}"); + bad(store.write_new_with(name, &mut |w| w.write_all(b"x")).unwrap_err()); + bad(store.write_atomic(name, b"x").unwrap_err()); + bad(store.write_atomic_with(name, &mut |w| w.write_all(b"x")).unwrap_err()); + bad(store.read(name).unwrap_err()); + bad(store.append(name, b"x").unwrap_err()); + bad(store.truncate(name, 0).unwrap_err()); + bad(store.remove(name).unwrap_err()); + } + assert_eq!(std::fs::read(base.join("outside")).unwrap(), b"keep"); + assert!(std::fs::read_dir(&base).unwrap().count() == 2, "nothing was made beside the library"); + store.write_atomic("catalog.snap", b"{}").unwrap(); + store.write_new_with(&segment_file("1-1"), &mut |w| w.write_all(b"[]")).unwrap(); + store.write_atomic("catalog.log.damaged-3", b"x").unwrap(); + assert_eq!(store.read("catalog.snap").unwrap().unwrap(), b"{}"); + let _ = std::fs::remove_dir_all(&base); +} From c08a8187d0f21888f45a42cc0d6d8169b2c646f5 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 23 Oct 2026 08:03:10 -0400 Subject: [PATCH 09/61] Catalog: a library states what its missing develop settings read as A develop setting a record leaves out reads as its default, so a default that changed in the code would change every photo relying on it. catalog.snap now states the defaults it was written with ("defaults"), and they cover the log beside it. A build whose own defaults differ reads the library's settings over the library's (stored::reading_over) and rewrites it with its own before anything is appended (LoadReport::other_defaults); a library that only lacks newer settings, or knows more, is read as it is. What a missing value reads as in this build is pinned by a test (develop_defaults.json). Every record is still written in full, and the format stays 9: older builds ignore the extra header field. This is the reading half of the compact records of the next change. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/develop_defaults.json | 229 ++++++++++++ crates/catalog/src/journal.rs | 51 ++- crates/catalog/src/lib.rs | 4 + crates/catalog/src/model.rs | 5 +- crates/catalog/src/stored.rs | 161 +++++++++ crates/catalog/src/tests_journal.rs | 7 +- crates/catalog/src/tests_stored.rs | 421 +++++++++++++++++++++++ docs/catalog-persistence.md | 21 ++ 8 files changed, 888 insertions(+), 11 deletions(-) create mode 100644 crates/catalog/src/develop_defaults.json create mode 100644 crates/catalog/src/stored.rs create mode 100644 crates/catalog/src/tests_stored.rs 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/journal.rs b/crates/catalog/src/journal.rs index a50df582632..ad8d8c80ebf 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -1,7 +1,7 @@ //! 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 +//! - `catalog.snap` — `{"format":"lightcraft-catalog","version":V,"seq":N,"defaults":{…},"catalog":{…}}`, the //! state after op `N` in catalog format `V` ([`VERSION`]); replaced atomically (temp + fsync + //! rename). //! - `catalog.log` — JSON lines, one per op applied after the snapshot: @@ -65,6 +65,11 @@ //! library is never a mix, and older builds refuse it from then on instead of reading part of it. //! (Except where the upgrade can't be written or its files can't be kept: see the next rule.) //! [`LoadReport::upgraded_from`] says when the upgrade happened at open. +//! - **A snapshot states what its records' missing develop settings read as** (`"defaults"`, see +//! [`crate::stored`]): the defaults of the build that wrote it, which cover the log beside it. +//! Written from this build on; an older snapshot states none, and is read over this build's. A +//! build whose defaults differ reads the library over the library's own, and rewrites it with +//! its own before anything is appended ([`LoadReport::other_defaults`]). //! - **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 @@ -147,6 +152,10 @@ pub struct LoadReport { /// 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 @@ -344,9 +353,9 @@ 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. +/// whole-file string). The bytes are exactly [`snapshot_head`] (`seq`), the catalog's JSON +/// (`serde_json`) and `}\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 { let t0 = web_time::Instant::now(); let mut serialize_ms = 0.0; @@ -356,7 +365,7 @@ fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io // 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\":")?; + write!(b, "{}", snapshot_head(seq))?; serde_json::to_writer(&mut b, catalog).map_err(std::io::Error::other)?; b.write_all(b"}\n")?; b.flush()?; @@ -369,11 +378,20 @@ fn write_snapshot(store: &mut dyn Store, seq: u64, catalog: &Catalog) -> std::io /// 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. + #[serde(default)] + defaults: Option, } /// The whole `catalog.snap` (after [`SnapHeader`] was checked; `format` and `version` are ignored). @@ -394,6 +412,9 @@ impl Journal { let snap = store.read(SNAPSHOT).map_err(io)?; let log = store.read(LOG).map_err(io)?; report.created = snap.is_none() && log.is_none(); + // (dropped once the snapshot 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; 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 @@ -404,6 +425,11 @@ impl Journal { if h.version > VERSION { return Err(newer(format!("{SNAPSHOT} is catalog format v{}", h.version))); } + 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 { @@ -505,10 +531,13 @@ 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)?; @@ -522,6 +551,7 @@ impl Journal { } None => j.snapshot(&catalog)?, } + rewritten = true; } else { if good_end < log.len() { report.torn_bytes = (log.len() - good_end) as u64; @@ -537,17 +567,18 @@ impl Journal { } 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()); + let empty = format!("{}{}}}\n", snapshot_head(0), 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}"); } - } else if let (Some(from), None) = (older, &report.damaged) { + } else if let (Some(from), false) = (older, rewritten) { // The library may go on as it is when it can't be upgraded now (the next open tries // again). Appends are not refused meanwhile: refusing them would leave a library // whose files can't be copied (little room left) unable to save anything. What is // appended is this build's ops; the files kept when a later snapshot upgrades it are // the library as it is here (`behind_at`), which an older build reads. if let Some(kept) = j.upgrade(&catalog, from, snap.as_deref(), &log, Upgrade::May)? { + rewritten = true; report.upgraded_from = Some(from); report.kept = kept; } else { @@ -555,6 +586,12 @@ impl Journal { j.behind_at = (j.seq, j.log_bytes); } } + 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)) } diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a6972..ccaab219888 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -26,6 +26,7 @@ pub mod rules; pub mod safe_file; pub mod stacks; pub mod store; +mod stored; pub mod tally; use std::collections::BTreeMap; @@ -96,6 +97,7 @@ pub enum Op { }, SetDevelop { id: PhotoId, + #[serde(deserialize_with = "stored::read_settings")] settings: Arc, label: String, edited: Option, @@ -1211,6 +1213,8 @@ mod tests_repair; #[cfg(test)] mod tests_scale; #[cfg(test)] +mod tests_stored; +#[cfg(test)] mod tests_tally; #[cfg(test)] mod tests_torn_append; diff --git a/crates/catalog/src/model.rs b/crates/catalog/src/model.rs index b405e1db965..aab45f438ae 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/stored.rs b/crates/catalog/src/stored.rs new file mode 100644 index 00000000000..5e5648416ab --- /dev/null +++ b/crates/catalog/src/stored.rs @@ -0,0 +1,161 @@ +//! What a library's missing develop settings read as: the reading half of the stored form of +//! catalog records ([`crate::journal`]). +//! +//! A record in `catalog.snap` or `catalog.log` may leave a develop setting out: the settings of +//! a photo, and those of its history steps, versions and import look, are read by the types' +//! `Deserialize`, where a missing field takes its default. Libraries whose records state every +//! setting load as they are. +//! +//! **A library says what its missing values read as.** A value that is not in the file reads as +//! the default, 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, until the library's next snapshot states it (the build +//! that adds a setting, or changes a default it has, is the one to take care of that). +//! +//! That works where a setting is a value in a struct, which the settings are, and because the +//! library states every setting, also those the settings' own JSON leaves out at their default +//! ([`UNWRITTEN`]). It does not reach the entries of lists inside the settings (masks, spots): +//! an entry's missing value takes the default of the entry's own type. 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::sync::{Arc, OnceLock}; + +use lightcraft_develop::DevelopSettings; +use serde::{Deserialize, Deserializer}; +use serde_json::Value; + +/// 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: what a record that leaves them out reads as. +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)) +} + +/// 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, + } +} diff --git a/crates/catalog/src/tests_journal.rs b/crates/catalog/src/tests_journal.rs index 26b4e902ab6..ea0d34a8266 100644 --- a/crates/catalog/src/tests_journal.rs +++ b/crates/catalog/src/tests_journal.rs @@ -286,8 +286,8 @@ 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. +/// The streamed snapshot is byte-for-byte what was written before streaming (issue #37), with +/// the defaults a library states; FsStore and MemStore agree. #[test] fn streamed_snapshot_keeps_the_on_disk_format() { let (m, _, full) = sample_catalog_with_log(); @@ -295,9 +295,10 @@ fn streamed_snapshot_keeps_the_on_disk_format() { assert_eq!(c.to_snapshot(), full.to_snapshot()); j.snapshot(&c).unwrap(); let legacy = format!( - "{{\"format\":\"lightcraft-catalog\",\"version\":{},\"seq\":{},\"catalog\":{}}}\n", + "{{\"format\":\"lightcraft-catalog\",\"version\":{},\"seq\":{},\"defaults\":{},\"catalog\":{}}}\n", crate::journal::VERSION, j.seq(), + crate::stored::base().0, c.to_snapshot() ); assert_eq!(String::from_utf8(m.get(SNAPSHOT).unwrap()).unwrap(), legacy); diff --git a/crates/catalog/src/tests_stored.rs b/crates/catalog/src/tests_stored.rs new file mode 100644 index 00000000000..038c2c2cc5e --- /dev/null +++ b/crates/catalog/src/tests_stored.rs @@ -0,0 +1,421 @@ +//! What a library's missing develop settings read as ([`crate::stored`]): a saved library states +//! them, and a build whose own differ reads the library over them. + +use std::sync::Arc; + +use lightcraft_develop::DevelopSettings; +use serde::Serialize; +use serde_json::Value; + +use crate::journal::{LOG, SNAPSHOT, VERSION}; +use crate::*; + +/// Settings with nothing stated, as every saved library reads them: every value its default, +/// on the first rendering process (a missing process never means "the default one"). +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 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() +} + +/// A record may leave a setting out, 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, so it opens the same again. +#[test] +fn a_library_written_with_other_defaults_reads_as_it_was_written() { + let m = MemStore::new(); + 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, no log + assert_eq!(stated_defaults(&m), stored::base().1); + assert!(m.get(LOG).unwrap().is_empty()); + 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/docs/catalog-persistence.md b/docs/catalog-persistence.md index 5e35a05557f..5f5505db469 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -5,6 +5,27 @@ the whole catalog, and `catalog.log`, one JSON line per change made since. Every fsynced before its command returns; now and then the log is compacted into a new snapshot. This page covers what happens to a library's files when a newer version opens it. +## What a missing value reads as + +A record may leave a develop setting out (the photo's, and those of its history steps, versions and import look); a +missing field reads as its default. A default that changed in the code would then change every photo relying on it, +so the library says what its missing values read as: + +- `catalog.snap` states them (`"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. +- 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 (its + files still state the library's own defaults, so the next open reads it the same way). +- Snapshots written before this state none; they are read over the defaults of the build that reads them, as before. + +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 From 3cdf82117dfcd85545b74a5e0f46113fbfc8970e Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 12:39:08 -0400 Subject: [PATCH 10/61] Catalog: say what the next open reads after a rewrite for other defaults fails The sentence said the library's files still state its own defaults. That holds when catalog.snap could not be written; when it was written and only the log could not be emptied, they state this build's, and the log's records are skipped as stale. --- docs/catalog-persistence.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index 5f5505db469..7b71cb559ca 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -19,8 +19,9 @@ so the library says what its missing values read as: 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 (its - files still state the library's own defaults, so the next open reads it the same way). + before anything is added to it (`LoadReport::other_defaults`). If that can't be written, the library is refused, + and the next open reads it the same way: its files still state the library's own defaults, or the new snapshot was + written but the log was not emptied, and the log's records are then skipped as stale. - Snapshots written before this state none; they are read over the defaults of the build that reads them, as before. What a missing value reads as in the current build is also pinned by a test (`crates/catalog/src/develop_defaults.json`), From 9fc9453a4b13751cfec04ca2ae374429acce9a67 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 30 Oct 2026 08:04:54 -0400 Subject: [PATCH 11/61] Catalog: the test for the defaults reading ending with the open leaves the changed values out, and Journal::open's docs list the refusal when the rewrite can't be written --- crates/catalog/src/journal.rs | 5 +++-- crates/catalog/src/tests_stored.rs | 12 ++++++++---- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index ad8d8c80ebf..7b793a768b9 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -405,8 +405,9 @@ impl Journal { /// Open (or create) the catalog in `store`: load the snapshot, replay the log, repair a torn /// 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 its damaged log can't be replaced, - /// its snapshot can't be kept, or it can't be told whether its upgrade was written (see the - /// module docs → *Format versions*). + /// its snapshot can't be kept, or it can't be told whether its upgrade was written, or if the + /// library states other develop defaults than this build's and its rewrite with this build's + /// can't be written, or its log can't then be emptied (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)?; diff --git a/crates/catalog/src/tests_stored.rs b/crates/catalog/src/tests_stored.rs index 038c2c2cc5e..e647581e7d6 100644 --- a/crates/catalog/src/tests_stored.rs +++ b/crates/catalog/src/tests_stored.rs @@ -203,14 +203,18 @@ fn a_library_with_other_defaults_that_cannot_be_rewritten_is_refused() { 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. +/// A reader of one library's defaults leaves the next library read on the thread alone: a record +/// that leaves out the values the library states other defaults for reads as this build's, once +/// the open that read the library is over. #[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()); + let (_, c, r) = Journal::open(Box::new(m)).unwrap(); + assert!(r.other_defaults, "{r:?}"); + assert_eq!(c.photo(PhotoId(1)).unwrap().develop.light.exposure, 1.0, "read over the library's own"); + let plainly: Photo = serde_json::from_value(stored_record(2, serde_json::json!({}))).unwrap(); + assert_eq!(*plainly.develop, base()); } /// Given a library written by a build whose default for a setting that is left out of the From 4decee375ea7f69c7603afa07379efa2a935451f Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 12:07:47 -0400 Subject: [PATCH 12/61] Catalog: the formats are one table, and every format from 6 on has a fixture The catalog formats were a table in journal.rs's module docs that nothing read. They are now one list in code, journal::FORMATS: each row has the format's number, the build that wrote it first, what it adds, and whether it adds an op (NEW_OP) or only fields (FIELDS). VERSION is the newest row this build has. A test holds that the numbers run 1.. without a gap, that a row that adds an op names it, and that the newest op's format is the newest row that adds one (what NEWEST_FIELDS held by hand). Every format from 6 on has a fixture, a small library written by the build of that format, which every later build must open as it was: fixtures v7 to v9 are new (v6 was there), written by their builds from the fixture library of tests_stored.rs. Nothing is written or read differently: VERSION stays 9. Co-Authored-By: Claude Opus 5.5 --- .../catalog/src/fixtures/v7-catalog.log.jsonl | 7 + .../catalog/src/fixtures/v7-catalog.snap.json | 1 + .../catalog/src/fixtures/v8-catalog.log.jsonl | 7 + .../catalog/src/fixtures/v8-catalog.snap.json | 1 + .../catalog/src/fixtures/v9-catalog.log.jsonl | 7 + .../catalog/src/fixtures/v9-catalog.snap.json | 1 + crates/catalog/src/journal.rs | 88 +++++-- crates/catalog/src/lib.rs | 6 +- crates/catalog/src/tests_format_version.rs | 88 +++++-- crates/catalog/src/tests_stored.rs | 222 ++++++++++++++++++ 10 files changed, 391 insertions(+), 37 deletions(-) create mode 100644 crates/catalog/src/fixtures/v7-catalog.log.jsonl create mode 100644 crates/catalog/src/fixtures/v7-catalog.snap.json create mode 100644 crates/catalog/src/fixtures/v8-catalog.log.jsonl create mode 100644 crates/catalog/src/fixtures/v8-catalog.snap.json create mode 100644 crates/catalog/src/fixtures/v9-catalog.log.jsonl create mode 100644 crates/catalog/src/fixtures/v9-catalog.snap.json 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 7b793a768b9..dd95251eb8d 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -42,24 +42,23 @@ //! for a library left in an older format because its files could not be kept or its upgrade //! written: it goes on as it is, and its log gets this build's ops until a snapshot upgrades it.) //! -//! | 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. @@ -97,9 +96,60 @@ use crate::{Catalog, CatalogError, Op, Result}; pub const SNAPSHOT: &str = "catalog.snap"; pub const LOG: &str = "catalog.log"; 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`"), +]; + +/// The catalog format this build writes (and the newest it reads): the newest of [`FORMATS`] +/// that is [`Format::here`]. +pub const VERSION: u32 = newest(FORMATS); + +const fn newest(formats: &[Format]) -> u32 { + match formats.split_last() { + Some((f, _)) if f.here => f.version, + Some((_, rest)) => newest(rest), + None => 0, + } +} /// When [`Journal::wants_snapshot`] says it's time to compact the log. #[derive(Clone, Copy, Debug)] diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index ccaab219888..e2554d37083 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -7,9 +7,9 @@ //! - **determinism**: replaying the log reproduces the state exactly (property-tested). //! //! **Catalog format version** ([`journal::VERSION`], see [`journal`] → *Format versions*): adding -//! an [`Op`] variant or a serialized field means bumping it. Newer builds read every older format -//! (and upgrade it on open); older builds refuse a newer library with [`CatalogError::Newer`] -//! instead of reading part of it. +//! an [`Op`] variant or a serialized field means adding a row to [`journal::FORMATS`]. Newer +//! builds read every older format (and upgrade it on open); older builds refuse a newer library +//! with [`CatalogError::Newer`] instead of reading part of it. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index 8c2ce48f715..f24110685c8 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 { @@ -193,9 +193,8 @@ fn bad_crc_is_still_a_torn_tail() { } /// Guard for the version rule (see `journal` → *Format versions*): adding an [`Op`] variant breaks -/// this match. When it does, bump `journal::VERSION`, add a row to the format table, and add the -/// variant here under the new version. A version that only adds serialized fields raises -/// `NEWEST_FIELDS` instead. +/// this match. When it does, add a row to `journal::FORMATS` (flagged `NEW_OP`) and the variant +/// here under the new number. A format that only adds serialized fields is a `FIELDS` row instead. #[test] fn op_variants_are_versioned() { fn since(op: &Op) -> u32 { @@ -238,10 +237,77 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - /// v9: `Photo.preview_checked` and `Op::SetContent.preview_checked`. - const NEWEST_FIELDS: u32 = 9; + // (format 9 added no op: it added fields) 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 what this build writes is the newest of them it has (a number spoken for by a change +/// that is not here yet, [`Format::here`] false, comes after it): 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..=FORMATS.len() as u32).collect::>()); + let here: Vec = FORMATS.iter().filter(|f| f.here).map(|f| f.version).collect(); + assert_eq!(here, (1..=VERSION).collect::>(), "this build has every format up to the one it writes, and none after"); +} + +/// The library `fixtures/v-catalog.*` holds, written by the build of format `N`. +fn fixture(version: u32) -> Option<(&'static str, &'static str)> { + match version { + 6 => Some((include_str!("fixtures/v6-catalog.snap.json"), include_str!("fixtures/v6-catalog.log.jsonl"))), + 7 => Some((include_str!("fixtures/v7-catalog.snap.json"), include_str!("fixtures/v7-catalog.log.jsonl"))), + 8 => Some((include_str!("fixtures/v8-catalog.snap.json"), include_str!("fixtures/v8-catalog.log.jsonl"))), + 9 => Some((include_str!("fixtures/v9-catalog.snap.json"), include_str!("fixtures/v9-catalog.log.jsonl"))), + _ => None, + } +} + +/// 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((snap, log)) = 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); + assert!(snap.starts_with(&format!("{{\"format\":\"lightcraft-catalog\",\"version\":{},", f.version)), "v{}", f.version); + let m = MemStore::new(); + m.set(SNAPSHOT, snap.as_bytes().to_vec()); + m.set(LOG, log.as_bytes().to_vec()); + 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); + } } // ---- an upgrade keeps what it replaces @@ -276,14 +342,6 @@ impl Store for Refusing { } } -/// The library `fixtures/v-catalog.*` holds, written by the build of format `N`. -fn fixture(version: u32) -> Option<(&'static str, &'static str)> { - match version { - 6 => Some((include_str!("fixtures/v6-catalog.snap.json"), include_str!("fixtures/v6-catalog.log.jsonl"))), - _ => None, - } -} - /// A format 6 library (the fixture) in a store. fn v6_library() -> (MemStore, Vec, Vec) { let (snap, log) = fixture(6).unwrap(); diff --git a/crates/catalog/src/tests_stored.rs b/crates/catalog/src/tests_stored.rs index e647581e7d6..0eae03e66c5 100644 --- a/crates/catalog/src/tests_stored.rs +++ b/crates/catalog/src/tests_stored.rs @@ -30,6 +30,180 @@ fn plain(id: u64) -> Photo { p } +// ---- fixtures (also used, as they are, to write `fixtures/v-catalog.*` with the build of format N) + +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, but for the few that +/// formats after 6 added (the focus point, the History cursor, the preview-only recheck). +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) + 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`]. (The +/// fixtures of formats 8 and 9 hold the same library as format 7's: what those formats added, the +/// History cursor and the preview-only recheck, is not in them.) +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 { @@ -423,3 +597,51 @@ impl serde::ser::SerializeStruct for &mut Skipped { Ok(()) } } + +/// 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-catalog.*`: the fixture library as this +/// build saves it, snapshot and log. Run it once, when a format is new: put two empty files there +/// (the tests include them), then +/// `cargo test -p lightcraft-catalog write_this_formats_fixture -- --ignored`. The files are then +/// what that build wrote, and are never written again. +#[test] +#[ignore = "writes fixtures/v-catalog.*"] +fn write_this_formats_fixture() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/fixtures"); + let (snap, log) = (dir.join(format!("v{VERSION}-catalog.snap.json")), dir.join(format!("v{VERSION}-catalog.log.jsonl"))); + let written = |f: &std::path::Path| std::fs::metadata(f).is_ok_and(|m| m.len() > 0); + assert!(!written(&snap) && !written(&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); + std::fs::write(snap, m.get(SNAPSHOT).unwrap()).unwrap(); + std::fs::write(log, m.get(LOG).unwrap()).unwrap(); +} From a340c332f53f61f0d16d3f48d11c18fb6394f732 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 12:43:40 -0400 Subject: [PATCH 13/61] Catalog: develop settings can be stored as their difference from the defaults The writing half of compact records, for develop settings only and with no caller yet: the settings of a photo, and those of its history steps, versions and import look, stored as their difference from the defaults ({} for an unedited photo). A value is left out only where that reads back the same (worked out from the types on first use: not the rendering process, not single fields of the crop rectangle), every difference is read back before it is written, and a negative zero is kept. writing_full() stores settings whole while a library's header lacks a setting this build has, and states_every_setting() says when that is so. Nothing writes this form yet: records stay as they are, and the format stays 9. The next change names these functions from the ops, stores the photos with them and brings catalog format 10. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 2 + crates/catalog/src/stored.rs | 674 +++++++++++++++++++- crates/catalog/src/tests_stored.rs | 6 +- crates/catalog/src/tests_stored_settings.rs | 236 +++++++ 4 files changed, 905 insertions(+), 13 deletions(-) create mode 100644 crates/catalog/src/tests_stored_settings.rs diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index e2554d37083..a2d99a256bd 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -1215,6 +1215,8 @@ mod tests_scale; #[cfg(test)] mod tests_stored; #[cfg(test)] +mod tests_stored_settings; +#[cfg(test)] mod tests_tally; #[cfg(test)] mod tests_torn_append; diff --git a/crates/catalog/src/stored.rs b/crates/catalog/src/stored.rs index 5e5648416ab..05427bd8920 100644 --- a/crates/catalog/src/stored.rs +++ b/crates/catalog/src/stored.rs @@ -1,10 +1,20 @@ -//! What a library's missing develop settings read as: the reading half of the stored form of -//! catalog records ([`crate::journal`]). +//! The stored form of develop settings, and what a library's missing develop settings read as. //! -//! A record in `catalog.snap` or `catalog.log` may leave a develop setting out: the settings of -//! a photo, and those of its history steps, versions and import look, are read by the types' -//! `Deserialize`, where a missing field takes its default. Libraries whose records state every -//! setting load as they are. +//! A develop setting a record leaves out reads as its default (the types' `Deserialize`: a missing +//! field takes its default), so libraries whose records state every setting load as they are. +//! This module is the writing half of leaving them out: the settings of a photo, and those of its +//! history steps, versions and import look, stored as their **difference from +//! [`DevelopSettings::default`]** (`{}` for an unedited photo). Nothing writes it yet: catalog +//! format 10, in the next change, switches the records over (the `serialize_with` functions +//! [`settings`], [`step`], [`history`] and [`versions`] are what its ops name, and its photos are +//! stored with them), and until then records state settings as formats up to 9 do. +//! +//! **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 that is not in the file reads as //! the default, so a default that changed in the code would change every photo relying on it. So @@ -13,8 +23,10 @@ //! 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, until the library's next snapshot states it (the build -//! that adds a setting, or changes a default it has, is the one to take care of that). +//! heard of takes this build's default, until the library's next snapshot states it. Once records +//! leave settings out (the next change), such a library is rewritten to state them first +//! ([`states_every_setting`]), and until that is written its records state develop settings +//! whole ([`writing_full`]). //! //! That works where a setting is a value in a struct, which the settings are, and because the //! library states every setting, also those the settings' own JSON leaves out at their default @@ -23,12 +35,92 @@ //! 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::{Deserialize, Deserializer}; +use serde::ser::{SerializeMap, SerializeSeq}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; +use crate::{HistoryStep, 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. /// @@ -88,6 +180,21 @@ pub(crate) fn reads_the_same(theirs: &Value) -> bool { agree(theirs, &base().1) } +/// Whether a library that states `theirs` as its defaults states every setting this build has +/// (a build that adds a setting is the one this is for): a record written from now on leaves out +/// what equals this build's default of that setting, so the library must state it first. +#[allow(dead_code, reason = "called by the journal in the change that brings catalog format 10")] +pub(crate) fn states_every_setting(theirs: &Value) -> bool { + fn has(theirs: &Value, ours: &Value) -> bool { + match (theirs, ours) { + (Value::Object(t), Value::Object(o)) => o.iter().all(|(k, y)| t.get(k).is_some_and(|x| has(x, y))), + (Value::Object(_), _) | (_, Value::Object(_)) => false, + _ => true, + } + } + has(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) }; @@ -118,7 +225,7 @@ 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: what a record that leaves them out reads as. +/// 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 { @@ -147,6 +254,17 @@ pub(crate) fn read_optional_settings<'de, D: Deserializer<'de>>(d: D) -> Result< 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) { @@ -159,3 +277,539 @@ fn same(a: &Value, b: &Value) -> bool { _ => 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.text.clear(); + serde_json::to_writer(&mut self.text, value)?; + self.out.differing.insert(key.to_owned(), serde_json::from_slice(&self.text)?); + 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(()); + } + // (from the text just written, not `to_value`: that widens an `f32` to the digits of its + // `f64`, which reads back the same but is 17 digits long) + let mut v: Value = serde_json::from_slice(&self.text)?; + 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() + } +} + +thread_local! { + /// Settings written on this thread are written whole, not as their difference from the + /// defaults ([`writing_full`]). + static WRITING_FULL: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// While it lives, develop settings written on this thread are stored whole, as formats before +/// 10 did, so a record reads back the same over whatever defaults its library states (a value the +/// settings' own JSON leaves out at its default is as in those formats): for a +/// library whose header doesn't state every setting this build has yet, where a difference from +/// this build's defaults would leave out what the header gives no default for. +pub(crate) struct WritingFull(bool); + +impl Drop for WritingFull { + fn drop(&mut self) { + let before = self.0; + let _ = WRITING_FULL.try_with(|w| w.set(before)); + } +} + +#[allow(dead_code, reason = "called by the journal in the change that brings catalog format 10")] +pub(crate) fn writing_full() -> WritingFull { + WritingFull(WRITING_FULL.try_with(|w| w.replace(true)).unwrap_or(false)) +} + +/// Develop settings in their stored form. +struct StoredSettings<'a>(&'a DevelopSettings); + +impl Serialize for StoredSettings<'_> { + fn serialize(&self, s: S) -> Result { + if WRITING_FULL.try_with(|w| w.get()).unwrap_or(false) { + return self.0.serialize(s); + } + 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`]. +#[allow(dead_code, reason = "named by the ops and photos in the change that brings catalog format 10")] +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`]. +#[allow(dead_code, reason = "named by the ops and photos in the change that brings catalog format 10")] +pub(crate) fn step(v: &HistoryStep, s: S) -> Result { + StoredStep::of(v).serialize(s) +} + +/// `serialize_with` for a history in an [`crate::Op`]. +#[allow(dead_code, reason = "named by the ops and photos in the change that brings catalog format 10")] +pub(crate) fn history(v: &[HistoryStep], s: S) -> Result { + StoredList(v, StoredStep::of).serialize(s) +} + +/// `serialize_with` for versions in an [`crate::Op`]. +#[allow(dead_code, reason = "named by the ops and photos in the change that brings catalog format 10")] +pub(crate) fn versions(v: &[Version], s: S) -> Result { + StoredList(v, StoredVersion::of).serialize(s) +} diff --git a/crates/catalog/src/tests_stored.rs b/crates/catalog/src/tests_stored.rs index 0eae03e66c5..3b38e3fc7b1 100644 --- a/crates/catalog/src/tests_stored.rs +++ b/crates/catalog/src/tests_stored.rs @@ -12,7 +12,7 @@ use crate::*; /// Settings with nothing stated, as every saved library reads them: every value its default, /// on the first rendering process (a missing process never means "the default one"). -fn base() -> DevelopSettings { +pub(crate) fn base() -> DevelopSettings { serde_json::from_str("{}").unwrap() } @@ -32,7 +32,7 @@ fn plain(id: u64) -> Photo { // ---- fixtures (also used, as they are, to write `fixtures/v-catalog.*` with the build of format N) -fn edited(d: impl FnOnce(&mut DevelopSettings)) -> Arc { +pub(crate) fn edited(d: impl FnOnce(&mut DevelopSettings)) -> Arc { let mut s = base(); d(&mut s); Arc::new(s) @@ -40,7 +40,7 @@ fn edited(d: impl FnOnce(&mut DevelopSettings)) -> Arc { /// 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 { +pub(crate) 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 }; diff --git a/crates/catalog/src/tests_stored_settings.rs b/crates/catalog/src/tests_stored_settings.rs new file mode 100644 index 00000000000..a84d79aa156 --- /dev/null +++ b/crates/catalog/src/tests_stored_settings.rs @@ -0,0 +1,236 @@ +//! The stored form of develop settings ([`crate::stored`]), on its own: settings are stored as +//! their difference from the defaults and read back exactly. Nothing writes this form into a +//! library yet (catalog format 10 does); the tests name the `serialize_with` functions the way +//! the ops and photos will. + +use std::sync::Arc; + +use lightcraft_develop::DevelopSettings; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::tests_stored::{base, edited, rich}; +use crate::{HistoryStep, Version, stored}; + +/// What a record holds of develop settings, stored the way the format 10 records will. +#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] +struct Record { + #[serde(serialize_with = "stored::settings", deserialize_with = "stored::read_settings")] + develop: Arc, + #[serde(serialize_with = "stored::step")] + step: HistoryStep, + #[serde(serialize_with = "stored::history")] + history: Vec, + #[serde(serialize_with = "stored::versions")] + versions: Vec, +} + +fn record_of(develop: Arc) -> Record { + let history = vec![HistoryStep { label: "x".into(), settings: develop.clone() }]; + let versions = vec![Version { name: "V".into(), created: "2026-10-10".into(), settings: develop.clone(), auto: false }]; + let step = history[0].clone(); + Record { develop, step, history, versions } +} + +fn stored_json(r: &Record) -> Value { + serde_json::to_value(r).unwrap() +} + +/// The record saved and read again, plainly and over the defaults a library states (the path a +/// library written with other defaults takes). The settings must read back with the same public +/// JSON, which tells apart what `==` doesn't (-0.0 and 0.0), and the same hash. +fn reopened(r: &Record) -> Record { + let text = serde_json::to_string(r).unwrap(); + let back: Record = serde_json::from_str(&text).unwrap(); + { + let _over = stored::reading_over(Some(Arc::new(stored::base().1.clone()))); + let over: Record = serde_json::from_str(&text).unwrap(); + assert_eq!(over, back, "read over the library's defaults"); + } + for (a, b) in [ + (&r.develop, &back.develop), + (&r.step.settings, &back.step.settings), + (&r.history[0].settings, &back.history[0].settings), + (&r.versions[0].settings, &back.versions[0].settings), + ] { + assert_eq!(serde_json::to_string(a.as_ref()).unwrap(), serde_json::to_string(b.as_ref()).unwrap()); + assert_eq!(a.hash64(), b.hash64()); + } + back +} + +/// Given settings that differ from the defaults in one value, when they are stored, then only +/// that value is stored, in the photo's, its history steps' and its versions' settings alike. +#[test] +fn develop_settings_are_stored_as_their_difference_from_the_defaults() { + let r = record_of(edited(|s| s.light.exposure = 0.3)); + let exposure = json!({"light": {"exposure": 0.3}}); + let v = stored_json(&r); + assert_eq!(v["develop"], exposure); + assert_eq!(v["step"]["settings"], exposure); + assert_eq!(v["history"][0]["settings"], exposure); + assert_eq!(v["versions"][0]["settings"], exposure); + assert_eq!(reopened(&r), r); + // and untouched settings are `{}` + assert_eq!(stored_json(&record_of(Arc::new(base())))["develop"], json!({})); +} + +/// The rendering process is stored whenever it is not the first: a record without one is on the +/// first process in every build, which is not what the default settings are on. +#[test] +fn the_rendering_process_survives() { + let on = |json: &str| -> Arc { Arc::new(serde_json::from_str(json).unwrap()) }; + for json in ["{}", r#"{"process":1}"#, r#"{"process":7}"#, r#"{"process":7,"light":{"exposure":1.0}}"#] { + let r = record_of(on(json)); + assert_eq!(reopened(&r), r, "{json}"); + } + // new settings: the default ones on the default process, stating only what that needs + let r = record_of(Arc::new(DevelopSettings::default())); + let v = stored_json(&r); + assert!(v["develop"].as_object().unwrap().keys().all(|k| k == "process"), "{}", v["develop"]); + assert_eq!(reopened(&r), r); +} + +/// 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"] = json!(0.25); + let r = record_of(Arc::new(serde_json::from_value(v).unwrap())); + assert_eq!(stored_json(&r)["develop"], json!({"crop": {"geometry": {"angle": 0.0, "rect": {"x0": 0.25, "x1": 1.0, "y0": 0.0, "y1": 1.0}}}})); + assert_eq!(reopened(&r), r); +} + +/// 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([json!(x + 1.0), json!(x - 1.0), json!(0), json!(0.25), 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 r = record_of(Arc::new(s)); + assert_eq!(reopened(&r), r, "{}", 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. +#[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 r = record_of(rich); + assert_eq!(reopened(&r), r); +} + +/// Pen pressure is an `f32`: a stored brush stroke writes it with the digits of an `f32` (0.3), +/// not the 17 of the `f64` it widens to (0.30000001192092896), which would be larger than +/// the record was before. +#[test] +fn a_pen_pressure_is_stored_with_the_digits_it_has() { + use lightcraft_develop::{BrushStroke, Mask, MaskComponent, MaskOp, MaskShape}; + let stroke = BrushStroke { points: vec![lightcraft_geom::Point { x: 0.5, y: 0.5 }], pressure: vec![0.3], ..Default::default() }; + let shape = MaskShape::Brush { strokes: vec![stroke] }; + let component = MaskComponent { name: None, op: MaskOp::default(), invert: false, shape }; + let r = record_of(edited(|s| s.masks = vec![Mask { id: 1, name: "Brush".into(), components: vec![component], ..Default::default() }])); + let text = serde_json::to_string(&r).unwrap(); + assert!(text.contains(r#""pressure":[0.3]"#), "{text}"); + assert_eq!(reopened(&r), r); +} + +/// 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, and settings that equal it but for the +/// sign of a zero are not taken for it. +#[test] +fn a_negative_zero_survives() { + let r = record_of(edited(|s| s.wb.tint = -0.0)); + assert_ne!(r.develop.hash64(), base().hash64()); + assert_eq!(stored_json(&r)["develop"].to_string(), r#"{"wb":{"tint":-0.0}}"#); + assert_eq!(reopened(&r), r); + let positive = record_of(edited(|s| s.wb.tint = 0.0)); + assert_eq!(stored_json(&positive)["develop"], json!({})); + assert_ne!(reopened(&r).develop.hash64(), reopened(&positive).develop.hash64()); +} + +/// While a library's header doesn't state every setting this build has, settings are stored +/// whole (as formats up to 9 did), and only on the thread that asked. +#[test] +fn settings_are_stored_whole_while_asked_to() { + let r = record_of(edited(|s| s.light.exposure = 0.3)); + let whole = { + let _full = stored::writing_full(); + // another thread is not affected + assert_eq!( + std::thread::spawn({ + let r = r.clone(); + move || stored_json(&r)["develop"].clone() + }) + .join() + .unwrap(), + json!({"light": {"exposure": 0.3}}) + ); + stored_json(&r) + }; + assert_eq!(whole["develop"], serde_json::to_value(r.develop.as_ref()).unwrap()); + assert_eq!(whole["history"][0]["settings"], whole["develop"]); + assert_eq!(reopened(&r), r); + // and compact again once the guard is gone + assert_eq!(stored_json(&r)["develop"], json!({"light": {"exposure": 0.3}})); +} + +/// A library states every setting this build has when its stated defaults have every one of +/// this build's; one that lacks a setting does not. +#[test] +fn a_library_states_every_setting_or_does_not() { + let ours = stored::base().1.clone(); + assert!(stored::states_every_setting(&ours)); + let mut fewer = ours.clone(); + fewer["light"].as_object_mut().unwrap().remove("exposure"); + assert!(!stored::states_every_setting(&fewer)); + let mut more = ours; + more["a_setting_a_later_build_has"] = json!(1); + assert!(stored::states_every_setting(&more)); +} From 254e30e4cfed225348325c9fd687112251367b28 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 08:38:00 -0400 Subject: [PATCH 14/61] catalog: read, append and truncate refuse a segments folder that isn't a real folder FsStore::read, append and truncate checked only the final path, so a segments folder that is a link (or a file) let them reach outside the library. They now use the same non-creating folder check as remove (symlink_metadata; a missing folder reads as no file). --- crates/catalog/src/store.rs | 99 ++++++++++++++++++++++++++++++++++--- 1 file changed, 91 insertions(+), 8 deletions(-) diff --git a/crates/catalog/src/store.rs b/crates/catalog/src/store.rs index ad2e4070126..c161b4d450e 100644 --- a/crates/catalog/src/store.rs +++ b/crates/catalog/src/store.rs @@ -124,6 +124,21 @@ impl FsStore { fn folder_of(&self, name: &str) -> io::Result { Ok(self.path(name)?.parent().map_or_else(|| self.dir.clone(), Path::to_path_buf)) } + /// The folder of `name`, if it is the library's own and there: `Ok(None)` when the segments + /// folder isn't there (yet), an error when it is a file or a link (to a folder elsewhere). + /// Nothing is created, so reading, cutting and removing never make a folder. + fn existing_folder_of(&self, name: &str) -> io::Result> { + let folder = self.folder_of(name)?; + if folder == self.dir { + return Ok(Some(folder)); + } + match std::fs::symlink_metadata(&folder) { + Ok(m) if m.is_dir() => Ok(Some(folder)), + Ok(_) => Err(io::Error::other(format!("{} is not a folder", folder.display()))), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(io::Error::new(e.kind(), format!("{}: {e}", folder.display()))), + } + } /// 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. @@ -275,6 +290,9 @@ pub(crate) fn create_staging(tmp: &std::path::Path) -> io::Result impl Store for FsStore { fn read(&mut self, name: &str) -> io::Result>> { + if self.existing_folder_of(name)?.is_none() { + return Ok(None); + } match std::fs::read(self.path(name)?) { Ok(b) => Ok(Some(b)), Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), @@ -327,6 +345,10 @@ impl Store for FsStore { fn append(&mut self, name: &str, data: &[u8]) -> io::Result<()> { use std::io::Write; if self.appender.as_ref().is_none_or(|(n, _)| n != name) { + // (a file in a folder of the library's own: the segments folder is made by a write, not here) + if self.existing_folder_of(name)?.is_none() { + return Err(io::Error::new(io::ErrorKind::NotFound, format!("{name:?}: its folder is not there"))); + } let path = self.path(name)?; check_regular_directory_entry(&path)?; let existed = path.exists(); @@ -351,6 +373,9 @@ impl Store for FsStore { if self.appender.as_ref().is_some_and(|(n, _)| n == name) { self.appender = None; } + if self.existing_folder_of(name)?.is_none() { + return Ok(()); + } let path = self.path(name)?; check_regular_directory_entry(&path)?; let f = match std::fs::OpenOptions::new().write(true).open(path) { @@ -368,14 +393,8 @@ impl Store for FsStore { self.appender = None; } // (a file in a folder of the library's own, as for writing and listing: never through a link) - let folder = self.folder_of(name)?; - if folder != self.dir { - match std::fs::symlink_metadata(&folder) { - Ok(m) if m.is_dir() => {} - Ok(_) => return Err(io::Error::other(format!("{} is not a folder", folder.display()))), - Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(e) => return Err(io::Error::new(e.kind(), format!("{}: {e}", folder.display()))), - } + if self.existing_folder_of(name)?.is_none() { + return Ok(()); } match std::fs::remove_file(self.path(name)?) { Ok(()) => Ok(()), @@ -660,3 +679,67 @@ mod tests_listing { let _ = std::fs::remove_dir_all(&dir); } } + +#[cfg(all(test, unix))] +mod tests_segment_folder { + use super::*; + + /// A library whose `segments` is a link to a folder elsewhere (with `seg.json` in it) or a plain file. + fn library(tag: &str, link: bool) -> io::Result<(PathBuf, PathBuf, FsStore)> { + let root = std::env::temp_dir().join(format!("lc-seg-folder-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let (dir, outside) = (root.join("lib"), root.join("outside")); + std::fs::create_dir_all(&outside)?; + std::fs::write(outside.join("seg.json"), b"keep")?; + let store = FsStore::open(&dir)?; + if link { + std::os::unix::fs::symlink(&outside, dir.join("segments"))?; + } else { + std::fs::write(dir.join("segments"), b"not a folder")?; + } + Ok((root, outside, store)) + } + + /// `read` never returns the bytes of a file behind a `segments` link (or a file named `segments`). + #[test] + fn read_refuses_a_segments_folder_that_is_not_a_real_folder() { + for link in [true, false] { + let (root, _, mut store) = library(&format!("read{link}"), link).unwrap(); + assert!(store.read("segments/seg.json").is_err(), "link: {link}"); + let _ = std::fs::remove_dir_all(&root); + } + } + + /// `append` and `truncate` never change a file behind a `segments` link (or a file named `segments`). + #[test] + fn append_and_truncate_refuse_a_segments_folder_that_is_not_a_real_folder() { + for link in [true, false] { + let (root, outside, mut store) = library(&format!("cut{link}"), link).unwrap(); + assert!(store.append("segments/seg.json", b"more").is_err(), "append, link: {link}"); + assert!(store.truncate("segments/seg.json", 0).is_err(), "truncate, link: {link}"); + assert_eq!(std::fs::read(outside.join("seg.json")).unwrap(), b"keep"); + let _ = std::fs::remove_dir_all(&root); + } + } + + /// A library with a real `segments` folder, or none yet, works as before: reads and cuts + /// of a missing file are "nothing", and no folder is made by them. + #[test] + fn a_real_or_missing_segments_folder_is_unchanged() { + let root = std::env::temp_dir().join(format!("lc-seg-folder-real-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let mut store = FsStore::open(&root).unwrap(); + assert_eq!(store.read("segments/1.json").unwrap(), None); + store.truncate("segments/1.json", 0).unwrap(); + store.remove("segments/1.json").unwrap(); + assert!(!root.join("segments").exists()); + std::fs::create_dir_all(root.join("segments")).unwrap(); + std::fs::write(root.join("segments/1.json"), b"abc").unwrap(); + assert_eq!(store.read("segments/1.json").unwrap(), Some(b"abc".to_vec())); + store.append("segments/1.json", b"d").unwrap(); + store.truncate("segments/1.json", 2).unwrap(); + assert_eq!(std::fs::read(root.join("segments/1.json")).unwrap(), b"ab"); + assert_eq!(store.read("segments/2.json").unwrap(), None); + let _ = std::fs::remove_dir_all(&root); + } +} From 2a51d028060e3a1a3727ddac3c919fc23c1b1508 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 12:45:42 -0400 Subject: [PATCH 15/61] Catalog: compact records are format 10 A photo's record in catalog.snap / catalog.log states only what was set: unset fields of the photo and its metadata are left out, and develop settings (the photo's, its history steps', versions' and import look's) are stored as their difference from the defaults, with the stored form of the previous change. A record of a photo with no metadata goes from 3.2 kB to 0.2 kB. Reading is unchanged, so formats 1-9 load as they are and are rewritten on open; the public JSON of a photo (catalog.query, Local fingerprints, preview-cache keys) is unchanged. Format 10 is the first that leaves values out, so a library that is in a format before 10 (also one that states defaults), or states other ones than this build's, and can't be upgraded, is not opened (it is left as it was, and the error says why). A library in format 10 that lacks a setting this build has is rewritten to state it before a compact record is appended; where that can't be written, its records state develop settings whole until a snapshot is. Co-Authored-By: Claude Opus 5.5 --- .../src/fixtures/v10-catalog.log.jsonl | 7 + .../src/fixtures/v10-catalog.snap.json | 1 + crates/catalog/src/journal.rs | 117 +++- crates/catalog/src/lib.rs | 8 +- crates/catalog/src/stored.rs | 324 ++++++++++- crates/catalog/src/tests_format_version.rs | 197 +------ crates/catalog/src/tests_journal.rs | 2 +- crates/catalog/src/tests_stored.rs | 545 +++++++++++++++--- crates/catalog/src/tests_stored_settings.rs | 7 +- crates/engine/src/tests/persist.rs | 120 ---- docs/catalog-persistence.md | 96 +-- docs/whats-new.md | 11 +- 12 files changed, 984 insertions(+), 451 deletions(-) create mode 100644 crates/catalog/src/fixtures/v10-catalog.log.jsonl create mode 100644 crates/catalog/src/fixtures/v10-catalog.snap.json 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/journal.rs b/crates/catalog/src/journal.rs index dd95251eb8d..c0af652534f 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -38,9 +38,8 @@ //! # 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 appended to under a snapshot of this build's format. (Except -//! for a library left in an older format because its files could not be kept or its upgrade -//! written: it goes on as it is, and its log gets this build's ops until a snapshot upgrades it.) +//! 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). //! //! 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. @@ -64,11 +63,6 @@ //! library is never a mix, and older builds refuse it from then on instead of reading part of it. //! (Except where the upgrade can't be written or its files can't be kept: see the next rule.) //! [`LoadReport::upgraded_from`] says when the upgrade happened at open. -//! - **A snapshot states what its records' missing develop settings read as** (`"defaults"`, see -//! [`crate::stored`]): the defaults of the build that wrote it, which cover the log beside it. -//! Written from this build on; an older snapshot states none, and is read over this build's. A -//! build whose defaults differ reads the library over the library's own, and rewrites it with -//! its own before anything is appended ([`LoadReport::other_defaults`]). //! - **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 @@ -79,11 +73,16 @@ //! library on disk is known to be in its old format still: an upgrade at open 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 left in its old format -//! at open (its files couldn't be kept, or the upgrade couldn't be written) is upgraded by a -//! later snapshot (compaction, or closing), which first keeps the files as they were at open -//! (the snapshot, and the log up to where it ended then) and is not written when it can't. Those -//! files stay even if that snapshot then fails and the library is still in its old format. +//! 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 in a format before 10, or one that states other defaults than this build's +//! ([`crate::stored`]). A record written by this build leaves out what equals this build's +//! defaults, which a build of a format before 10 reads as its own. It is left as it was, and the +//! error says why. (A library in format 10 or later, which writes records so and states its +//! defaults, may go on as it is when it can't be upgraded now: a later snapshot, compaction or +//! closing, upgrades it, first keeps the files as they were at open (the snapshot, and the log +//! up to where it ended then) and is not written when it can't; those files stay even if that +//! snapshot then fails and the library is still in its old format. 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 @@ -137,12 +136,16 @@ pub const FORMATS: &[Format] = &[ 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"), ]; /// The catalog format this build writes (and the newest it reads): the newest of [`FORMATS`] /// that is [`Format::here`]. pub const VERSION: u32 = newest(FORMATS); +/// The first format whose records leave out what equals this build's defaults ([`crate::stored`]). +const COMPACT_RECORDS: u32 = 10; + const fn newest(formats: &[Format]) -> u32 { match formats.split_last() { Some((f, _)) if f.here => f.version, @@ -169,8 +172,10 @@ impl Default for SnapshotPolicy { 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: its damaged log would be appended to after the damage, - /// so the snapshot must also have replaced that log. + /// 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, } @@ -206,6 +211,10 @@ pub struct LoadReport { /// 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, + /// The library's stated defaults lack a setting this build has (it was written by a build + /// that didn't know it): they are restated at open, before any compact record is appended; + /// where that can't be written, records state develop settings whole until a snapshot is. + pub defaults_added: bool, } /// Where persistence time goes (reported by `library.info` → `persistence`; printed to stderr @@ -298,6 +307,12 @@ pub struct Journal { /// A failed append may have left part of its records after `log_bytes`, and cutting them off /// failed too: the next append cuts the log back to `log_bytes` first. tail_dirty: bool, + /// The snapshot's header doesn't state every setting this build has (it was written by a + /// build that didn't know one, and restating it failed at open): develop settings are + /// written whole in every record ([`crate::stored::writing_full`]) until a snapshot, which + /// states them all, is written. Never set where compact records would be unsafe for another + /// reason (other defaults, an older format that can't be upgraded refuse the library). + header_incomplete: bool, } /// A background snapshot in flight. @@ -439,7 +454,7 @@ fn snapshot_head(seq: u64) -> String { struct SnapHeader { format: String, version: u32, - /// What a record's missing develop settings read as. + /// What a record's missing develop settings read as (from format 10 on). #[serde(default)] defaults: Option, } @@ -454,10 +469,12 @@ struct SnapFile { impl Journal { /// Open (or create) the catalog in `store`: load the snapshot, replay the log, repair a torn /// 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 its damaged log can't be replaced, - /// its snapshot can't be kept, or it can't be told whether its upgrade was written, or if the - /// library states other develop defaults than this build's and its rewrite with this build's - /// can't be written, or its log can't then be emptied (see the module docs → *Format versions*). + /// modified), or if the library is in an older format and can't be brought to this build's + /// where it must be (its damaged log can't be replaced, its snapshot can't be kept, or it can't + /// be told whether its upgrade was written: see the module docs → *Format versions*), or if + /// the library states other develop defaults than this build's and its rewrite with this + /// build's can't be written, or its log can't then be emptied, or if a new library's first + /// snapshot can't be written. pub fn open(mut store: Box) -> Result<(Journal, Catalog, LoadReport)> { let mut report = LoadReport::default(); let snap = store.read(SNAPSHOT).map_err(io)?; @@ -466,6 +483,8 @@ impl Journal { // (dropped once the snapshot 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 @@ -476,6 +495,10 @@ impl Journal { if h.version > VERSION { return Err(newer(format!("{SNAPSHOT} is catalog format v{}", h.version))); } + states_defaults = h.defaults.is_some(); + if h.defaults.as_ref().is_some_and(|theirs| !crate::stored::states_every_setting(theirs)) { + report.defaults_added = true; + } 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; @@ -504,6 +527,7 @@ impl Journal { behind_at: (0, 0), kept_pending: None, kept_written: Vec::new(), + header_incomplete: false, log_records: 0, log_bytes: 0, policy: SnapshotPolicy::default(), @@ -619,16 +643,24 @@ impl Journal { if report.created { // tiny: written directly, not counted as a compaction let empty = format!("{}{}}}\n", snapshot_head(0), 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}"); - } + // (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}")))?; } else if let (Some(from), false) = (older, rewritten) { - // The library may go on as it is when it can't be upgraded now (the next open tries - // again). Appends are not refused meanwhile: refusing them would leave a library - // whose files can't be copied (little room left) unable to save anything. What is - // appended is this build's ops; the files kept when a later snapshot upgrades it are - // the library as it is here (`behind_at`), which an older build reads. - if let Some(kept) = j.upgrade(&catalog, from, snap.as_deref(), &log, Upgrade::May)? { + // A library in a format that writes compact records and states its defaults 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 before that (a build of those + // formats reads a missing value as its own default, and a library of format 9 that + // states defaults is still read so by builds that don't know the statement), or one + // that states other defaults, must not be appended to as it is: a record written from + // here on leaves out what equals this build's defaults. (One that only lacks a setting + // this build has may: its records are written whole until it is restated, + // `header_incomplete`.) What is appended is this build's ops; the files kept when a + // later snapshot upgrades it are the library as it is here (`behind_at`). + let how = if report.other_defaults || !states_defaults || from < COMPACT_RECORDS { 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; @@ -639,10 +671,30 @@ impl Journal { } 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. + // anything is appended, since a compact record leaves out what equals the default the + // header states for it. Nothing is kept for that: any build reads a library over the + // defaults it states. If it can't be rewritten the library is refused. j.snapshot(&catalog)?; + } else if report.defaults_added && !rewritten { + // A setting this build has that the header doesn't state: restate it before a + // compact record is appended. If that can't be done now (a full disk, a read-only + // volume; or the upgrade just above failed, which keeps no copies behind, so the + // snapshot is not tried again at once), the library still opens, and every record is + // written whole until a snapshot succeeds (`header_incomplete`). A crash at any point + // finds the old files whole, or a header that states every setting before any compact + // record was written. + j.header_incomplete = true; + if j.behind.is_none() { + match j.snapshot(&catalog) { + Ok(()) => {} + Err(e) if j.header_incomplete => { + log::warn!("catalog: can't restate the library's defaults ({e}); writing whole records until it can") + } + Err(e) => log::warn!("catalog: the library's defaults were restated, but its log could not be reset: {e}"), + } + } } + catalog.revision = 0; Ok((j, catalog, report)) } @@ -798,6 +850,7 @@ impl Journal { let t0 = web_time::Instant::now(); let mut buf = String::new(); let mut seq = self.seq; + let _whole = self.header_incomplete.then(crate::stored::writing_full); for op in ops { seq = seq.checked_add(1).ok_or_else(|| CatalogError::Corrupt(format!("{LOG}: op counter overflow")))?; buf.push_str(&encode_record(seq, op)); @@ -870,6 +923,7 @@ impl Journal { self.seq = seq; self.snapshot_seq = seq; self.upgraded_later(); + self.header_incomplete = false; let t2 = web_time::Instant::now(); // A crash here leaves old records in the log; they are skipped by seq on load. self.store.write_atomic(LOG, b"").map_err(io)?; @@ -963,6 +1017,7 @@ impl Journal { let t1 = web_time::Instant::now(); self.snapshot_seq = p.seq; self.upgraded_later(); + self.header_incomplete = false; 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; diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index a2d99a256bd..76d35173348 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -78,6 +78,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 { @@ -97,13 +98,14 @@ pub enum Op { }, SetDevelop { id: PhotoId, - #[serde(deserialize_with = "stored::read_settings")] + #[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 { @@ -117,16 +119,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. @@ -266,6 +271,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, diff --git a/crates/catalog/src/stored.rs b/crates/catalog/src/stored.rs index 05427bd8920..77f601939c4 100644 --- a/crates/catalog/src/stored.rs +++ b/crates/catalog/src/stored.rs @@ -1,13 +1,18 @@ -//! The stored form of develop settings, and what a library's missing develop settings read as. +//! The stored form of catalog records: what `catalog.snap` and `catalog.log` hold. //! -//! A develop setting a record leaves out reads as its default (the types' `Deserialize`: a missing -//! field takes its default), so libraries whose records state every setting load as they are. -//! This module is the writing half of leaving them out: the settings of a photo, and those of its -//! history steps, versions and import look, stored as their **difference from -//! [`DevelopSettings::default`]** (`{}` for an unedited photo). Nothing writes it yet: catalog -//! format 10, in the next change, switches the records over (the `serialize_with` functions -//! [`settings`], [`step`], [`history`] and [`versions`] are what its ops name, and its photos are -//! stored with them), and until then records state settings as formats up to 9 do. +//! 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.2 kB each for a photo with no metadata, nearly all of it 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 9) 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`, @@ -16,16 +21,16 @@ //! 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 that is not in the file reads as -//! the default, so a default that changed in the code would change every photo relying on it. So +//! **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, until the library's next snapshot states it. Once records -//! leave settings out (the next change), such a library is rewritten to state them first -//! ([`states_every_setting`]), and until that is written its records state develop settings +//! over its own ([`reading_over`]), and then rewrites the library with its own. A build that has +//! more settings than the library states reads a setting the library never heard of as its own +//! default, and rewrites the library to state it ([`states_every_setting`]) before a record +//! that leaves it out is appended; until that rewrite is written (a full disk, a volume that +//! can't be written to) the library opens all the same and its records state develop settings //! whole ([`writing_full`]). //! //! That works where a setting is a value in a struct, which the settings are, and because the @@ -43,7 +48,7 @@ use serde::ser::{SerializeMap, SerializeSeq}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::Value; -use crate::{HistoryStep, Version}; +use crate::{ColorLabel, CopyrightStatus, Flag, HistoryStep, MediaKind, Meta, Photo, PhotoId, Source, Version}; // ---- develop settings @@ -183,7 +188,6 @@ pub(crate) fn reads_the_same(theirs: &Value) -> bool { /// Whether a library that states `theirs` as its defaults states every setting this build has /// (a build that adds a setting is the one this is for): a record written from now on leaves out /// what equals this build's default of that setting, so the library must state it first. -#[allow(dead_code, reason = "called by the journal in the change that brings catalog format 10")] pub(crate) fn states_every_setting(theirs: &Value) -> bool { fn has(theirs: &Value, ours: &Value) -> bool { match (theirs, ours) { @@ -692,7 +696,6 @@ impl Drop for WritingFull { } } -#[allow(dead_code, reason = "called by the journal in the change that brings catalog format 10")] pub(crate) fn writing_full() -> WritingFull { WritingFull(WRITING_FULL.try_with(|w| w.replace(true)).unwrap_or(false)) } @@ -750,7 +753,6 @@ impl Serialize for StoredSettings<'_> { } /// `serialize_with` for settings in an [`crate::Op`]. -#[allow(dead_code, reason = "named by the ops and photos in the change that brings catalog format 10")] pub(crate) fn settings(v: &Arc, s: S) -> Result { StoredSettings(v).serialize(s) } @@ -797,19 +799,295 @@ impl Serialize for StoredList<'_, T, R> { } /// `serialize_with` for a history step in an [`crate::Op`]. -#[allow(dead_code, reason = "named by the ops and photos in the change that brings catalog format 10")] pub(crate) fn step(v: &HistoryStep, s: S) -> Result { StoredStep::of(v).serialize(s) } /// `serialize_with` for a history in an [`crate::Op`]. -#[allow(dead_code, reason = "named by the ops and photos in the change that brings catalog format 10")] pub(crate) fn history(v: &[HistoryStep], s: S) -> Result { StoredList(v, StoredStep::of).serialize(s) } /// `serialize_with` for versions in an [`crate::Op`]. -#[allow(dead_code, reason = "named by the ops and photos in the change that brings catalog format 10")] 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() +} diff --git a/crates/catalog/src/tests_format_version.rs b/crates/catalog/src/tests_format_version.rs index f24110685c8..6f57553fa85 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -282,6 +282,7 @@ fn fixture(version: u32) -> Option<(&'static str, &'static str)> { 7 => Some((include_str!("fixtures/v7-catalog.snap.json"), include_str!("fixtures/v7-catalog.log.jsonl"))), 8 => Some((include_str!("fixtures/v8-catalog.snap.json"), include_str!("fixtures/v8-catalog.log.jsonl"))), 9 => Some((include_str!("fixtures/v9-catalog.snap.json"), include_str!("fixtures/v9-catalog.log.jsonl"))), + 10 => Some((include_str!("fixtures/v10-catalog.snap.json"), include_str!("fixtures/v10-catalog.log.jsonl"))), _ => None, } } @@ -313,9 +314,9 @@ fn every_format_has_a_fixture_that_opens_as_it_was() { // ---- an upgrade keeps what it replaces /// A store whose writes of some files fail. -struct Refusing { - files: MemStore, - refuse: fn(&str) -> bool, +pub(crate) struct Refusing { + pub(crate) files: MemStore, + pub(crate) refuse: fn(&str) -> bool, } impl Store for Refusing { @@ -402,14 +403,15 @@ fn an_upgrade_of_a_log_only_library_keeps_the_log() { } /// Given an older library whose files can't be kept (the disk is full), when it is opened, then -/// it is not upgraded without its way back: it opens as it is, with its files as they were and -/// nothing half kept, and is upgraded once there is room. +/// 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_upgraded() { +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 (_, c, r) = Journal::open(Box::new(store)).unwrap(); - assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0)); + 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"); @@ -418,7 +420,7 @@ fn a_library_that_cannot_be_kept_is_not_upgraded() { } /// Given an older library on disk whose files can't be kept (the name of one is taken by a directory), when it is -/// opened, then it is not upgraded, and no copy or half-written staging file of the files it tried to keep is left +/// opened, then it is refused, and no copy or half-written staging file of the files it tried to keep is left /// lying about in the library's folder. #[test] fn a_library_on_disk_that_cannot_be_kept_leaves_nothing_lying_about() { @@ -429,8 +431,8 @@ fn a_library_on_disk_that_cannot_be_kept_leaves_nothing_lying_about() { std::fs::write(dir.join(SNAPSHOT), snap).unwrap(); std::fs::write(dir.join(LOG), log).unwrap(); - let (_, c, r) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); - assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0)); + let e = Journal::open(Box::new(FsStore::open(&dir).unwrap())).err().expect("refused"); + assert!(matches!(&e, CatalogError::Io(why) if why.contains("older format (v6)") && why.contains("can't be kept")), "{e}"); let mut names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); names.sort(); assert_eq!(names, [LOG, "catalog.log.v6-8", SNAPSHOT], "nothing but the library and the name that was taken"); @@ -438,14 +440,14 @@ fn a_library_on_disk_that_cannot_be_kept_leaves_nothing_lying_about() { let _ = std::fs::remove_dir_all(&dir); } -/// Given an older library whose upgrade can't be written, when it is opened, then it opens as it -/// was, with no copy of it left lying about: there is nothing to go back from. +/// 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 (_, c, r) = Journal::open(Box::new(store)).unwrap(); - assert_eq!((c.photos().count(), r.upgraded_from, r.kept.len()), (3, None, 0)); + 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]); } @@ -551,39 +553,6 @@ fn an_upgrade_that_cannot_be_checked_keeps_its_copies() { assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log))); } -/// Given an older library that was not upgraded at open (its files can't be kept), when a later -/// snapshot would upgrade it (a compaction, or closing), then that snapshot is not written: the -/// library stays as it was, with nothing half kept, and is never upgraded without its way back. -#[test] -fn a_library_that_could_not_be_kept_is_not_upgraded_by_a_later_snapshot_either() { - let (m, snap, log) = v6_library(); - let store = Refusing { files: m.clone(), refuse: |name| name.starts_with("catalog.log.v") }; - let (mut j, c, r) = Journal::open(Box::new(store)).unwrap(); - assert_eq!(r.upgraded_from, None); - assert!(j.snapshot(&c).is_err(), "closing"); - assert!(j.snapshot_in_background(&c).is_err(), "a compaction"); - 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"); -} - -/// Given an older library whose upgrade could not be written at open (a full disk), when a later -/// snapshot is written (the disk has room again), then the files it was are kept first, as the -/// open would have kept them, and the library is upgraded. -#[test] -fn a_library_left_in_its_old_format_keeps_its_files_when_a_later_snapshot_upgrades_it() { - static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); - let (m, snap, log) = v6_library(); - let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; - let (mut j, c, r) = Journal::open(Box::new(store)).unwrap(); - assert_eq!((r.upgraded_from, r.kept.len()), (None, 0)); - assert!(j.snapshot(&c).is_err(), "still full"); - assert_eq!(m.files.lock().unwrap().keys().collect::>(), [LOG, "catalog.log.v6-8", SNAPSHOT, "catalog.snap.v6-8"], "kept, not upgraded"); - FULL.store(false, std::sync::atomic::Ordering::SeqCst); - j.snapshot(&c).unwrap(); - assert_eq!((m.get("catalog.snap.v6-8"), m.get("catalog.log.v6-8")), (Some(snap), Some(log))); - assert_eq!(snapshot_version(&m), u64::from(VERSION)); -} - /// Given an older library whose log is damaged and whose snapshot can't be kept, when it is /// opened, then it is refused and left as it was (it is not repaired without its way back). #[test] @@ -599,128 +568,14 @@ fn a_damaged_older_library_whose_snapshot_cannot_be_kept_is_refused() { assert_eq!((m.get(SNAPSHOT), m.get(LOG)), (Some(snap), Some(damaged))); } -/// Given an older library that was not upgraded at open (its files can't be kept), when a later -/// snapshot upgrades it, then the files that snapshot kept are told once, after it is written -/// (not before, not for a snapshot that failed, and the open's report has none). -#[test] -fn the_files_a_later_snapshot_keeps_are_told_once_it_is_written() { - static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); - let (m, _, _) = v6_library(); - let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; - let (mut j, c, r) = Journal::open(Box::new(store)).unwrap(); - assert!(r.kept.is_empty()); - assert!(j.snapshot(&c).is_err(), "still full"); - assert!(j.take_kept().is_empty(), "kept for a snapshot that is not written: nothing to tell yet"); - FULL.store(false, std::sync::atomic::Ordering::SeqCst); - j.snapshot(&c).unwrap(); - assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]); - assert!(j.take_kept().is_empty(), "once"); -} - -/// Given a library opened in its old format (its upgrade could not be written) that is then -/// changed, in this build's ops, before any snapshot is tried, when a later snapshot upgrades it, -/// then the files kept are the library as it was at open, under the names the open would have -/// given them: not the log as it is now, and nothing piles up. (An older build can read them -/// whatever was appended since.) -#[test] -fn files_kept_by_a_later_snapshot_are_the_library_as_it_was_at_open() { - static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); - let (m, snap, log) = v6_library(); - let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; - let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); - j.append(&[Op::SetLabelName { label: ColorLabel::ALL[0], name: Some("x".into()) }]).unwrap(); - assert!(m.get(LOG).unwrap().len() > log.len(), "the log has grown"); - assert!(j.snapshot(&c).is_err(), "still full"); - FULL.store(false, std::sync::atomic::Ordering::SeqCst); - j.snapshot(&c).unwrap(); - assert_eq!(j.take_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))); - assert_eq!(m.files.lock().unwrap().keys().filter(|k| k.contains(".v6-")).count(), 2, "{:?}", m.files.lock().unwrap().keys()); -} - -/// Given a library left in its old format whose snapshot is in this build's format already (a -/// write that landed and reported a failure, before anything was kept), when snapshots are -/// written, then each of them works: the upgrade is done, with nothing to keep (the old files -/// are gone from under that name), and nothing is refused until the library is reopened. +/// 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_snapshot_that_landed_is_the_upgrade_done() { - static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); - let (m, _, log) = v6_library(); - let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; - let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); - FULL.store(false, std::sync::atomic::Ordering::SeqCst); - m.set(SNAPSHOT, format!("{{\"format\":\"lightcraft-catalog\",\"version\":{VERSION},\"seq\":8,\"catalog\":{}}}\n", c.to_snapshot()).into_bytes()); - j.snapshot(&c).unwrap(); - j.snapshot(&c).unwrap(); - assert!(j.take_kept().is_empty()); - assert_eq!(snapshot_version(&m), u64::from(VERSION)); - assert!(!m.files.lock().unwrap().keys().any(|k| k.contains(".v6-")), "nothing kept from a snapshot that is not the old one"); - let _ = log; -} - -/// Given a library left in its old format, when a snapshot lands after its files were kept but -/// reports a failure, and the snapshot is tried again, then the retry goes through, and the files -/// told are the old library, not the snapshot that is there now. -#[test] -fn a_snapshot_that_landed_after_its_files_were_kept_is_tried_again() { - static LAND: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); - struct Landing { - inner: Refusing, - } - impl Store for Landing { - fn read(&mut self, name: &str) -> std::io::Result>> { - self.inner.read(name) - } - fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { - use std::sync::atomic::Ordering::SeqCst; - if name == SNAPSHOT && LAND.load(SeqCst) == 1 { - // lands, and says it did not (the share dropped the answer) - self.inner.files.write_atomic(name, data)?; - LAND.store(2, SeqCst); - return Err(std::io::Error::other("the share went away")); - } - self.inner.write_atomic(name, data) - } - fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { - self.inner.append(name, data) - } - fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { - self.inner.truncate(name, len) - } - fn remove(&mut self, name: &str) -> std::io::Result<()> { - self.inner.remove(name) - } - fn describe(&self) -> String { - "landing".into() - } - } - let (m, snap, log) = v6_library(); - let store = - Landing { inner: Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && LAND.load(std::sync::atomic::Ordering::SeqCst) == 0 } }; - let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); - LAND.store(1, std::sync::atomic::Ordering::SeqCst); - assert!(j.snapshot(&c).is_err(), "landed, and said it did not"); - assert_eq!(snapshot_version(&m), u64::from(VERSION), "it did land"); - j.snapshot(&c).unwrap(); - assert_eq!(j.take_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)), "the old library, not the snapshot that landed"); - assert!(j.take_kept().is_empty(), "told once"); -} - -/// Given a library left in its old format whose snapshot failed after its files were kept, when -/// the snapshot is tried again (a compaction retries as the log grows), then the files are not -/// copied again: a large library is not written out in full at every retry. -#[test] -fn files_kept_for_a_failed_snapshot_are_not_written_again_on_a_retry() { - static FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); - let (m, _, _) = v6_library(); - let store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && FULL.load(std::sync::atomic::Ordering::SeqCst) }; - let (mut j, c, _) = Journal::open(Box::new(store)).unwrap(); - assert!(j.snapshot(&c).is_err()); - m.set("catalog.snap.v6-8", b"marker".to_vec()); - assert!(j.snapshot(&c).is_err(), "still full"); - assert_eq!(m.get("catalog.snap.v6-8"), Some(b"marker".to_vec()), "not written again"); - FULL.store(false, std::sync::atomic::Ordering::SeqCst); - j.snapshot(&c).unwrap(); - assert_eq!(j.take_kept(), ["catalog.snap.v6-8", "catalog.log.v6-8"]); +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 ea0d34a8266..b261961337a 100644 --- a/crates/catalog/src/tests_journal.rs +++ b/crates/catalog/src/tests_journal.rs @@ -287,7 +287,7 @@ fn fs_store_roundtrip() { } /// The streamed snapshot is byte-for-byte what was written before streaming (issue #37), with -/// the defaults a library states; FsStore and MemStore agree. +/// the defaults a library states since format 10; FsStore and MemStore agree. #[test] fn streamed_snapshot_keeps_the_on_disk_format() { let (m, _, full) = sample_catalog_with_log(); diff --git a/crates/catalog/src/tests_stored.rs b/crates/catalog/src/tests_stored.rs index 3b38e3fc7b1..27aa03b6acb 100644 --- a/crates/catalog/src/tests_stored.rs +++ b/crates/catalog/src/tests_stored.rs @@ -1,5 +1,5 @@ -//! What a library's missing develop settings read as ([`crate::stored`]): a saved library states -//! them, and a build whose own differ reads the library over them. +//! 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; @@ -7,11 +7,16 @@ use lightcraft_develop::DevelopSettings; use serde::Serialize; use serde_json::Value; -use crate::journal::{LOG, SNAPSHOT, VERSION}; +use crate::journal::{LOG, SNAPSHOT, VERSION, encode_record}; +use crate::tests_format_version::Refusing; 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 (a missing process never means "the default one"). +/// 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. pub(crate) fn base() -> DevelopSettings { serde_json::from_str("{}").unwrap() } @@ -30,8 +35,6 @@ fn plain(id: u64) -> Photo { p } -// ---- fixtures (also used, as they are, to write `fixtures/v-catalog.*` with the build of format N) - pub(crate) fn edited(d: impl FnOnce(&mut DevelopSettings)) -> Arc { let mut s = base(); d(&mut s); @@ -137,7 +140,7 @@ fn full() -> Photo { name: Some("Ana".into()), description: None, }], - // (no format with a fixture had it) + // (no format with a fixture had it; see `fields_since_the_fixtures_survive_the_stored_form`) focus: None, }; p.rating = 4; @@ -218,8 +221,372 @@ fn record(c: &Catalog) -> Value { v["photos"].as_object().unwrap().values().next().unwrap().clone() } -/// A record may leave a setting out, so a library depends on what a missing value reads as: if -/// that changed, every photo relying on it would silently change. +/// 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 sets every field of the photo's and the metadata's public form (and the listed +/// ones that form leaves out when unset): a field added to [`Photo`] or [`Meta`] that is always +/// written must be set in it before this passes. (A new field that is left out when unset is +/// still stated by the stored form at compile time: `StoredPhoto` and `StoredMeta` list every +/// field.) +#[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); +} + +/// 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-catalog.*`: the fixture library as this +/// build saves it, snapshot and log. Run it once, when a format is new: put two empty files there +/// (the tests include them), then +/// `cargo test -p lightcraft-catalog write_this_formats_fixture -- --ignored`. The files are then +/// what that build wrote, and are never written again. +#[test] +#[ignore = "writes fixtures/v-catalog.*"] +fn write_this_formats_fixture() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/fixtures"); + let (snap, log) = (dir.join(format!("v{VERSION}-catalog.snap.json")), dir.join(format!("v{VERSION}-catalog.log.jsonl"))); + let written = |f: &std::path::Path| std::fs::metadata(f).is_ok_and(|m| m.len() > 0); + assert!(!written(&snap) && !written(&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); + std::fs::write(snap, m.get(SNAPSHOT).unwrap()).unwrap(); + std::fs::write(log, m.get(LOG).unwrap()).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()); + assert!(new.len() * 2 < old.len() + log.len(), "{} + {} -> {}", old.len(), log.len(), new.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 @@ -277,6 +644,26 @@ fn stored_record(id: u64, develop: Value) -> Value { r } +/// Given a format 9 library that states this build's defaults (what #2948 writes) and whose +/// upgrade can't be written, when it is opened, then it is refused and left as it was: a compact +/// record appended under its format 9 header would be read by builds of that format as their own +/// defaults. It opens, upgraded, once the disk takes the write. +#[test] +fn a_format_9_library_that_states_defaults_is_refused_when_it_cannot_be_upgraded() { + let snap = String::from_utf8(snapshot_stating(&stored::base().1, serde_json::json!({}))).unwrap(); + let snap = snap.replace(&format!("\"version\":{VERSION}"), "\"version\":9").into_bytes(); + let m = MemStore::new(); + m.set(SNAPSHOT, snap.clone()); + 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), None)); + assert_eq!(m.files.lock().unwrap().keys().collect::>(), [SNAPSHOT], "nothing half kept"); + + let (_, _, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert_eq!(r.upgraded_from, Some(9)); +} + /// 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] @@ -295,7 +682,7 @@ fn a_library_states_what_missing_settings_read_as() { /// 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, so it opens the same again. +/// 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() { let m = MemStore::new(); @@ -320,9 +707,12 @@ fn a_library_written_with_other_defaults_reads_as_it_was_written() { expected.mixer.red.hue = 5.0; assert_eq!(*one.develop, expected); - // rewritten: this build's defaults, no log + // 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); @@ -330,20 +720,93 @@ fn a_library_written_with_other_defaults_reads_as_it_was_written() { } /// 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. +/// build opens it, then the setting reads as this build's default, the library is rewritten +/// stating it before anything is appended, and a compact record appended after that is read back +/// by a reader that takes its defaults from the header: the setting is this build's default, not +/// whatever the build that reads it next has (this fails where the header is left as it was: it +/// would state no default for what the compact record leaves out). #[test] -fn a_library_that_only_lacks_newer_settings_is_read_as_it_is() { +fn a_library_that_lacks_newer_settings_is_restated_before_a_compact_record_is_appended() { 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:?}"); + let (mut j, mut c, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(r.defaults_added && !r.other_defaults, "{r:?}"); assert_eq!(*c.photo(PhotoId(1)).unwrap().develop, base()); - assert_eq!(m.get(SNAPSHOT), Some(snap), "not rewritten"); + assert_ne!(m.get(SNAPSHOT), Some(snap), "rewritten"); + assert_eq!(stated_defaults(&m), stored::base().1, "now states every setting"); + + // a compact append: the setting at its default is left out of the record, because the header + // now states it + let mut edited = (*c.photo(PhotoId(1)).unwrap().develop).clone(); + edited.light.exposure = 0.5; + let op = Op::SetDevelop { id: PhotoId(1), settings: Arc::new(edited), label: "Exposure".into(), edited: None }; + c.apply(op.clone()).unwrap(); + j.append(&[op]).unwrap(); + drop(j); + let log = String::from_utf8(m.get(LOG).unwrap()).unwrap(); + assert!(!log.contains("lens_blur"), "left out of the record: {log}"); + let (_, again, r) = Journal::open(Box::new(m.clone())).unwrap(); + assert!(!r.defaults_added, "{r:?}"); + assert_eq!(again.photo(PhotoId(1)).unwrap().develop.light.exposure, 0.5); + assert_eq!(again.photo(PhotoId(1)).unwrap().develop.lens_blur, base().lens_blur); + // and read over the header's defaults, as a build with other defaults would read it + let head = stated_defaults(&m); + let _over = stored::reading_over(Some(Arc::new(head))); + let (_, over, _) = Journal::open(Box::new(m)).unwrap(); + assert_eq!(over.photo(PhotoId(1)).unwrap().develop.lens_blur, base().lens_blur); +} + +/// Given such a library whose rewrite can't be written (the disk is full), when it is opened, +/// then it opens as it was, every record states its develop settings whole (a compact record +/// would leave out a setting the header gives no default for), and once a snapshot can be written +/// the header states every setting and the records are compact. +#[test] +fn a_library_whose_defaults_cannot_be_restated_writes_whole_records_until_it_can() { + static DISK_FULL: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true); + let mut older = stored::base().1.clone(); + older.as_object_mut().unwrap().remove("lens_blur").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 store = Refusing { files: m.clone(), refuse: |name| name == SNAPSHOT && DISK_FULL.load(std::sync::atomic::Ordering::SeqCst) }; + let (mut j, mut c, r) = Journal::open(Box::new(store)).unwrap(); + assert!(r.defaults_added, "{r:?}"); + assert_eq!(m.get(SNAPSHOT), Some(snap), "as it was"); + + let edit = |c: &Catalog, exposure: f64| { + let mut edited = (*c.photo(PhotoId(1)).unwrap().develop).clone(); + edited.light.exposure = exposure; + Op::SetDevelop { id: PhotoId(1), settings: Arc::new(edited), label: "Exposure".into(), edited: None } + }; + let op = edit(&c, 0.5); + c.apply(op.clone()).unwrap(); + j.append(&[op]).unwrap(); + let log = String::from_utf8(m.get(LOG).unwrap()).unwrap(); + assert!(log.contains("lens_blur"), "whole while the header can't give its default: {log}"); + assert!(j.snapshot(&c).is_err(), "still full"); + let op = edit(&c, 0.6); + c.apply(op.clone()).unwrap(); + j.append(&[op]).unwrap(); + assert!(String::from_utf8(m.get(LOG).unwrap()).unwrap().lines().last().unwrap().contains("lens_blur")); + + DISK_FULL.store(false, std::sync::atomic::Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!(stated_defaults(&m), stored::base().1, "now states every setting"); + let op = edit(&c, 0.7); + c.apply(op.clone()).unwrap(); + j.append(&[op]).unwrap(); + let log = String::from_utf8(m.get(LOG).unwrap()).unwrap(); + assert!(!log.contains("lens_blur"), "compact once it does: {log}"); + drop(j); + let (_, again, r) = Journal::open(Box::new(m)).unwrap(); + assert!(!r.defaults_added, "{r:?}"); + let develop = &again.photo(PhotoId(1)).unwrap().develop; + assert_eq!(develop.light.exposure, 0.7); + assert_eq!(develop.lens_blur, base().lens_blur); } /// Given a library written with other defaults that can't be rewritten (the disk is full), when @@ -597,51 +1060,3 @@ impl serde::ser::SerializeStruct for &mut Skipped { Ok(()) } } - -/// 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-catalog.*`: the fixture library as this -/// build saves it, snapshot and log. Run it once, when a format is new: put two empty files there -/// (the tests include them), then -/// `cargo test -p lightcraft-catalog write_this_formats_fixture -- --ignored`. The files are then -/// what that build wrote, and are never written again. -#[test] -#[ignore = "writes fixtures/v-catalog.*"] -fn write_this_formats_fixture() { - let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/fixtures"); - let (snap, log) = (dir.join(format!("v{VERSION}-catalog.snap.json")), dir.join(format!("v{VERSION}-catalog.log.jsonl"))); - let written = |f: &std::path::Path| std::fs::metadata(f).is_ok_and(|m| m.len() > 0); - assert!(!written(&snap) && !written(&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); - std::fs::write(snap, m.get(SNAPSHOT).unwrap()).unwrap(); - std::fs::write(log, m.get(LOG).unwrap()).unwrap(); -} diff --git a/crates/catalog/src/tests_stored_settings.rs b/crates/catalog/src/tests_stored_settings.rs index a84d79aa156..68dbab8e1fe 100644 --- a/crates/catalog/src/tests_stored_settings.rs +++ b/crates/catalog/src/tests_stored_settings.rs @@ -1,7 +1,6 @@ //! The stored form of develop settings ([`crate::stored`]), on its own: settings are stored as -//! their difference from the defaults and read back exactly. Nothing writes this form into a -//! library yet (catalog format 10 does); the tests name the `serialize_with` functions the way -//! the ops and photos will. +//! their difference from the defaults and read back exactly. The tests name the `serialize_with` +//! functions the way the ops and photos do; the photo and the log are tested in `tests_stored`. use std::sync::Arc; @@ -12,7 +11,7 @@ use serde_json::{Value, json}; use crate::tests_stored::{base, edited, rich}; use crate::{HistoryStep, Version, stored}; -/// What a record holds of develop settings, stored the way the format 10 records will. +/// What a record holds of develop settings, stored the way format 10 records are. #[derive(Serialize, Deserialize, Clone, PartialEq, Debug)] struct Record { #[serde(serialize_with = "stored::settings", deserialize_with = "stored::read_settings")] diff --git a/crates/engine/src/tests/persist.rs b/crates/engine/src/tests/persist.rs index 5f861e6785c..82be29e44d7 100644 --- a/crates/engine/src/tests/persist.rs +++ b/crates/engine/src/tests/persist.rs @@ -240,123 +240,3 @@ fn an_upgraded_library_says_where_what_it_was_is_kept() { s.close_library().unwrap(); let _ = std::fs::remove_dir_all(&dir); } - -/// The v6 fixture's log with its second record replaced by garbage (a record after it is still good, so it is damage, not a torn tail). -fn damaged_v6_log() -> String { - let log = include_str!("../../../catalog/src/fixtures/v6-catalog.log.jsonl"); - log.lines().enumerate().map(|(i, l)| if i == 1 { "not a record" } else { l }).collect::>().join("\n") + "\n" -} - -/// Given a library from an earlier version that has only a damaged log, when it is opened and upgraded, then the person is told -/// where the damaged log is kept (there is no kept snapshot to name it beside). -#[test] -fn an_upgraded_library_with_only_a_damaged_log_says_where_the_log_is_kept() { - let dir = std::env::temp_dir().join(format!("lightcraft-kept-dmg-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - std::fs::write(dir.join("catalog.log"), damaged_v6_log()).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("upgraded") && w.contains("catalog.log.damaged-")), "{told:?}"); - s.close_library().unwrap(); - let _ = std::fs::remove_dir_all(&dir); -} - -/// A library already in this version's format whose log was damaged was not upgraded: it is not told it was. -#[test] -fn a_current_library_with_a_damaged_log_is_not_told_it_was_upgraded() { - let dir = std::env::temp_dir().join(format!("lightcraft-cur-dmg-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - let mut s = Session::new(); - s.open_library(&dir, true).unwrap(); - s.execute("photo.rate", &serde_json::json!({"rating": 3})).unwrap(); - s.execute("photo.rate", &serde_json::json!({"rating": 4})).unwrap(); - s.execute("photo.rate", &serde_json::json!({"rating": 5})).unwrap(); - drop(s); - let log = std::fs::read_to_string(dir.join("catalog.log")).unwrap(); - let broken: Vec<&str> = log.lines().enumerate().map(|(i, l)| if i == 1 { "not a record" } else { l }).collect(); - std::fs::write(dir.join("catalog.log"), broken.join("\n") + "\n").unwrap(); - let mut s = Session::new(); - let damaged = s.open_library(&dir, false).unwrap().damaged.clone(); - assert!(damaged.is_some_and(|name| dir.join(name).exists()), "the log was found damaged and kept"); - let told = s.take_library_warnings(); - assert!(!told.iter().any(|w| w.contains("upgraded")), "{told:?}"); - s.close_library().unwrap(); - let _ = std::fs::remove_dir_all(&dir); -} - -/// An older library (format 6) that could not keep its files at open: a directory sits where the -/// first kept file goes. -fn library_that_could_not_keep_its_files(name: &str) -> std::path::PathBuf { - let dir = std::env::temp_dir().join(format!("lightcraft-{name}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); - std::fs::write(dir.join("catalog.snap.v6-8").join("in the way"), b"x").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(); - dir -} - -/// The names of the files kept for format 6 in `dir`. -fn kept_for_v6(dir: &std::path::Path, prefix: &str) -> Vec { - let mut names: Vec = std::fs::read_dir(dir) - .unwrap() - .map(|e| e.unwrap()) - .filter(|e| e.path().is_file()) - .map(|e| e.file_name().to_string_lossy().into_owned()) - .filter(|n| n.starts_with(prefix)) - .collect(); - names.sort(); - names -} - -/// Given an older library that could not keep its files at open, when a later compaction upgrades -/// it (the files can be kept now), then the person is told once where the library as it was is -/// kept, as when the open upgrades it, and a later compaction tells nothing more. -#[test] -fn a_later_upgrade_says_where_what_it_was_is_kept() { - let dir = library_that_could_not_keep_its_files("kept-later"); - let mut s = Session::new(); - s.open_library(&dir, false).unwrap(); - assert!(s.take_library_warnings().iter().all(|w| !w.contains("upgraded")), "not upgraded at open"); - assert!(s.compact_library().is_err(), "its files can't be kept yet"); - std::fs::remove_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); - s.compact_library().unwrap(); - let (snap, log) = (kept_for_v6(&dir, "catalog.snap.v6-"), kept_for_v6(&dir, "catalog.log.v6-")); - assert_eq!((snap.len(), log.len()), (1, 1), "the files as they were are kept"); - let told = s.take_library_warnings(); - assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0]) && w.contains("delete")), "{told:?}"); - let info = s.execute("library.info", &serde_json::json!({})).unwrap(); - assert!(info["settingsWarnings"].to_string().contains(&snap[0]), "{info}"); - s.compact_library().unwrap(); - assert!(s.take_library_warnings().is_empty(), "told once"); - s.close_library().unwrap(); - let _ = std::fs::remove_dir_all(&dir); -} - -/// The same, when the compaction is written by the background worker: the person is told once its -/// result is taken (the frame loop's `persist`), not before. -#[test] -fn a_background_upgrade_says_where_what_it_was_is_kept() { - let dir = library_that_could_not_keep_its_files("kept-background"); - let mut s = Session::new(); - s.open_library(&dir, false).unwrap(); - let _ = s.take_library_warnings(); - std::fs::remove_dir_all(dir.join("catalog.snap.v6-8")).unwrap(); - s.compact_soon(); - let started = std::time::Instant::now(); - let mut told = Vec::new(); - while told.is_empty() && started.elapsed() < std::time::Duration::from_secs(30) { - std::thread::sleep(std::time::Duration::from_millis(10)); - s.persist().unwrap(); - told = s.take_library_warnings(); - } - let (snap, log) = (kept_for_v6(&dir, "catalog.snap.v6-"), kept_for_v6(&dir, "catalog.log.v6-")); - assert_eq!((snap.len(), log.len()), (1, 1)); - assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0])), "{told:?}"); - s.persist().unwrap(); - assert!(s.take_library_warnings().is_empty(), "told once"); - s.close_library().unwrap(); - let _ = std::fs::remove_dir_all(&dir); -} diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index 7b71cb559ca..d071616e1d6 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -2,30 +2,56 @@ The catalog is two files in the library folder (`crates/catalog/src/journal.rs`): `catalog.snap`, a JSON snapshot of the whole catalog, and `catalog.log`, one JSON line per change made since. Every change is appended to the log and -fsynced before its command returns; now and then the log is compacted into a new snapshot. This page covers what -happens to a library's files when a newer version opens it. +fsynced before its command returns; now and then the log is compacted into a new snapshot. This page covers what a +record in those files states (catalog format 10) and what happens to a library's files when a newer version opens it. -## What a missing value reads as +## The stored form -A record may leave a develop setting out (the photo's, and those of its history steps, versions and import look); a -missing field reads as its default. A default that changed in the code would then change every photo relying on it, -so the library says what its missing values read as: +A photo's record states only what was set (`crates/catalog/src/stored.rs`): -- `catalog.snap` states them (`"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. -- 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 the next open reads it the same way: its files still state the library's own defaults, or the new snapshot was - written but the log was not emptied, and the log's records are then skipped as stale. -- Snapshots written before this state none; they are read over the defaults of the build that reads them, as before. +- 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. -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. +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 format 10 when first opened. Builds before format 10 refuse a format 10 library. A new library whose +`catalog.snap` can't be written (a full disk, a read-only volume) is not opened either, since what was added to its log +would leave out defaults that nothing states. + +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 on first use, 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 lacks settings the library knows reads it as it is (it would not read them whatever it read them + over), and one that has settings the library never heard of reads them as its own default, then rewrites the + library to state them before a record that leaves them out is added (`LoadReport::defaults_added`). If that rewrite + can't be written (a full disk, a read-only volume) the library still opens, and its records state develop settings + whole, as formats before 10 did, until a snapshot (a compaction, or closing) succeeds; then compact records start. + A crash at any point leaves the old files whole, or a header that states every setting before any compact record; + - 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 rewrite can't be written, the library is + refused: its files still state the library's own defaults, or the new snapshot was written and only the log was not + emptied (its records are then skipped as stale), so the next open reads it the same way. No compact record follows a + header that doesn't state what it relies on. + + 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 @@ -40,20 +66,22 @@ library was, byte for byte, beside it: did not happen (then they keep nothing, and are removed again): once the upgrade is written, nothing that fails after it takes them away. The files a later snapshot keeps (below) stay too, even if that snapshot then fails and the library is still in its old format. -- A library whose files can't be kept, or whose upgrade can't be written (a full disk, a folder that can't be written - to), is not upgraded: it opens as it is, with no copy left lying about, and the next open tries again. If what is on - disk after a failed write can't be read back to say whether the upgrade was written, the library is refused instead - (its way back stays). A library left like that is upgraded by its next snapshot, during the session or when it is - closed, and that snapshot keeps the files first too (and is not written when they can't be kept). When a snapshot - during the session does that, LightCraft tells where the files are kept, as it does at open (a snapshot when the - library is closed, or switched away from in Settings, has no one left to tell: the files are in the folder, named - as above). The files kept are the library as it was when it opened (the snapshot, and the log up to where it ended - then): what was changed since is in the files that replace them, not in the kept ones. (An earlier session of this - version may have added changes while the library stayed in its old format: they are in the log it opened with, and - an older version may refuse them.) Until then, changes - go on being appended to the library as it is, so that they can be saved at all where there is no room for a copy of - its files. (If the session ends without that snapshot, the next open keeps the log as it is then, which holds - those changes, and tells so; the files kept earlier stay beside it.) +- 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 in a format before 10 (builds of those formats + read a setting a record leaves out as their own default), or one that states other defaults 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). If what is on disk after a failed write can't be read back to say whether the upgrade was written, the + library is refused too (its way back stays). + A library in format 10 or later, which states its defaults, opens as it is (if it lacks a setting this version has, + records are written whole until the snapshot that upgrades it, which keeps its files first): a later snapshot, during + the session or when it is closed, upgrades it, keeps the files first and is not written when they can't be kept, and + the next open tries again. The files that snapshot keeps are the library as it was when it opened (the snapshot, and + the log up to where it ended then): what was changed since is in the files that replace them, not in the kept ones. + When a snapshot during the session does that, LightCraft tells where the files are kept, as it does at open (a + snapshot when the library is closed, or switched away from in Settings, has no one left to tell: the files are in the + folder, named as above). Until then, changes go on being appended to the library as it is, so that they can be saved + at all where there is no room for a copy of its files. (If the session ends without that snapshot, the next open keeps + the log as it is then, which holds those changes, and tells so; the files kept earlier stay beside it.) - 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. If the snapshot can't be kept, the library is refused and left as it was; if the damaged log can't diff --git a/docs/whats-new.md b/docs/whats-new.md index b46e7b9833f..5ba8e08256d 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -5,7 +5,16 @@ ### A library keeps a copy of itself before it is upgraded - Opening a library saved by an earlier version upgrades it, and earlier versions can't open it afterwards. The library as it was is now kept beside it (`catalog.snap.v-`, `catalog.log.v-`), and LightCraft says - where once: to go back, see `docs/catalog-persistence.md`. A library that can't be kept is not upgraded. + where once: to go back, see `docs/catalog-persistence.md`. + +### 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.2 kB for a photo with no metadata where it was 3.2 kB (a photo with camera metadata also + stores that, as before). Edits, history steps and versions are stored as what differs from the defaults. +- Libraries are upgraded when first opened (catalog format 10) and can't be opened by earlier versions afterwards. + A library from before format 10 whose upgrade can't be written (a full disk, a folder that can't be written to) or + whose files can't be kept is not opened: LightCraft says why and leaves its catalog as it was, and it opens once + there is room. A new library that can't be created is refused in the same way. ### Relative-date filters and smart albums follow the clock - A current view or source count using “in the last” rules now refreshes when the session clock moves into a new From 50b6190b13506511f392f2f93fb0963c4434c3a8 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 23 Oct 2026 11:08:46 -0400 Subject: [PATCH 16/61] Catalog: the segments of a snapshot: their names, rules, writer and reader, with no caller yet `crate::segments` holds what the snapshot in segments (catalog format 11) is made of: the segment table, how a segment is named, which stretches of photos change and how they are cut into pieces of a size the caller states, the checksummed writer (on several threads where the store gives handles, and every new file in the folder before anything lists it), the check of a segment list a snapshot may state, and the reader that checks every segment against its listed size, CRC, photo count and id range and names the file that is wrong. `stored::PhotoRange` writes a run of photos in their stored form. Nothing in the catalog calls it yet, and nothing reads or writes format 11: the journal that uses it, the format row, the segment size policy and the docs come in the next change. Its own unit tests exercise it (write and read back on one thread and on several; only the changed segments written; splits and removals; a damaged, missing, miscounted or foreign segment named in the error; a failed write leaving no new file behind, on one thread and on several; unlisted files discarded and nothing else), and the dead-code allowance on the module goes with the journal. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/lib.rs | 1 + crates/catalog/src/segments.rs | 942 ++++++++++++++++++++++++++++++++- crates/catalog/src/stored.rs | 13 + 3 files changed, 952 insertions(+), 4 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index ac573516b3d..98ae3645d28 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -43,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}; diff --git a/crates/catalog/src/segments.rs b/crates/catalog/src/segments.rs index c2ad2ea47a1..315cc381493 100644 --- a/crates/catalog/src/segments.rs +++ b/crates/catalog/src/segments.rs @@ -1,7 +1,55 @@ -//! Where the segment files of a snapshot in several files will be: in a folder of the library's -//! own, named `segments/-.json`. The stores ([`crate::store`]) know these names: -//! they make the folder, list its files and sync it. Nothing writes or reads segments yet: what -//! they hold, and how they are written and read, come with the catalog format that uses them. +//! 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 at most +//! `Size::per` photos (fewer where records are large, so that a piece is about `Size::bytes`; +//! the journal states both) 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. +//! +//! This module is the writer and reader of the segments, used by [`crate::journal`] for format 11 +//! (the journal that calls it comes in the next change; until then only the tests below do). + +#![allow(dead_code, reason = "called by the journal in the change that brings format 11")] + +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"; @@ -16,3 +64,889 @@ pub const SEGMENT_SUFFIX: &str = ".json"; 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 (the journal's policy states it). + pub per: usize, + /// And about this many bytes (the journal's policy states it too; 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 { + return Err(corrupt(format!("{name} is damaged ({} bytes where the snapshot lists {})", bytes.len(), segment.bytes))); + } + if crc32fast::hash(&bytes) != segment.crc { + return Err(corrupt(format!("{name} is damaged (its checksum is not the one the snapshot lists)"))); + } + 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)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::MemStore; + use std::collections::BTreeSet; + + fn photo(id: u64) -> Photo { + Photo::new( + PhotoId(id), + crate::Source::File { path: format!("/pictures/2019/trip/IMG_{id:06}.jpg") }, + &format!("IMG_{id:06}.jpg"), + "JPEG", + 4032, + 3024, + "2026-10-10T12:00:00", + ) + } + + fn photos(ids: impl IntoIterator) -> Photos { + ids.into_iter().map(|id| (PhotoId(id), Arc::new(photo(id)))).collect() + } + + /// `per` photos to a segment, whatever their size. + fn size(per: usize) -> Size { + Size { per, bytes: 0, record_bytes: 0 } + } + + /// Write `photos` over the segments and baseline given, as the snapshot of op `seq`. + fn write_over(store: &mut MemStore, photos: &Photos, segments: &[Segment], baseline: &Photos, seq: u64, per: usize) -> Written { + let on_disk = OnDisk { version: 11, seq, segments, baseline, size: size(per), verify: true }; + write(store, photos, &on_disk).unwrap() + } + + fn names(segments: &[Segment]) -> BTreeSet { + segments.iter().map(|s| s.name.clone()).collect() + } + + /// Given photos and no segments, when they are written and read back, then the segments are + /// runs of `per` photos in id order that read back as the photos, whether read on one thread + /// or on several. + #[test] + fn written_segments_read_back_as_the_photos() { + let held = photos(1..=10); + let mut store = MemStore::new(); + let out = write_over(&mut store, &held, &[], &Photos::new(), 7, 4); + // (10 photos: more than twice 4, so in pieces of 4) + assert_eq!(out.segments.iter().map(|s| (s.first.0, s.photos)).collect::>(), [(1, 4), (5, 4), (9, 2)]); + assert_eq!((out.written, out.new.len(), out.obsolete.len()), (3, 3, 0)); + assert!(out.segments.iter().all(|s| s.name.starts_with("segments/") && s.name.ends_with("-7.json"))); + assert_eq!(out.bytes, out.segments.iter().map(|s| s.bytes).sum::()); + assert_eq!(load(&mut store, Vec::new(), &out.segments).unwrap(), held); + let parallel = MemStore { background: true, ..store.clone() }; + let handles = readers(¶llel, 8); + let mut reading = parallel.clone(); + assert_eq!(load(&mut reading, handles, &out.segments).unwrap(), held); + } + + /// Given segments on disk, when nothing changed, then nothing is written and every segment is + /// kept; when one photo is replaced, then only the segment that holds it is written again, + /// under a new name, and the file it was is obsolete. + #[test] + fn only_the_segments_whose_photos_changed_are_written() { + let mut held = photos(1..=12); + let mut store = MemStore::new(); + let first = write_over(&mut store, &held, &[], &Photos::new(), 1, 4); + let baseline = held.clone(); + let again = write_over(&mut store, &held, &first.segments, &baseline, 2, 4); + assert_eq!((again.written, again.segments.clone(), again.obsolete.len(), again.changed.len()), (0, first.segments.clone(), 0, 0)); + // photo 6 is changed (a copy: the baseline still points at the one on disk) + let mut edited = photo(6); + edited.rating = 3; + held.insert(PhotoId(6), Arc::new(edited)); + let next = write_over(&mut store, &held, &first.segments, &baseline, 3, 4); + assert_eq!(next.written, 1); + assert_eq!(next.obsolete, vec![first.segments[1].name.clone()]); + assert_eq!(names(&next.segments).difference(&names(&first.segments)).count(), 1); + assert_eq!((next.segments[0].clone(), next.segments[2].clone()), (first.segments[0].clone(), first.segments[2].clone())); + assert_eq!(load(&mut store, Vec::new(), &next.segments).unwrap(), held); + // and what is on disk now is known from the stretch that changed + let mut on_disk = baseline.clone(); + refresh(&mut on_disk, &held, &next.changed); + assert!(on_disk.iter().zip(&held).all(|((a, p), (b, q))| a == b && Arc::ptr_eq(p, q))); + } + + /// Given segments on disk, when photos are added after a full last segment they start + /// segments of their own; when the last one grows past twice `per` it is written in pieces; + /// and when all of a segment's photos are removed it is dropped. + #[test] + fn segments_split_when_they_grow_and_go_when_they_empty() { + let mut store = MemStore::new(); + let mut held = photos(1..=8); + let out = write_over(&mut store, &held, &[], &Photos::new(), 1, 4); + assert_eq!(out.segments.iter().map(|s| s.photos).collect::>(), [8], "8 is not more than twice 4: one segment"); + // the last segment is full: the added photos are segments of their own, and it is kept + let baseline = held.clone(); + held.extend(photos(9..=10)); + let added = write_over(&mut store, &held, &out.segments, &baseline, 2, 4); + assert_eq!(added.segments.iter().map(|s| (s.first.0, s.photos)).collect::>(), [(1, 8), (9, 2)]); + assert_eq!((added.written, added.segments[0].clone()), (1, out.segments[0].clone())); + // the last one is not full (2 of 4): it takes the added photos, and splits at 20 > 2 * 4 + let baseline = held.clone(); + held.extend(photos(11..=20)); + let grown = write_over(&mut store, &held, &added.segments, &baseline, 3, 4); + assert_eq!(grown.segments.iter().map(|s| (s.first.0, s.photos)).collect::>(), [(1, 8), (9, 4), (13, 4), (17, 4)]); + assert_eq!((grown.written, grown.obsolete), (3, vec![added.segments[1].name.clone()])); + // every photo of the first segment is removed: it goes, the others stay as they are + let baseline = held.clone(); + held.retain(|id, _| id.0 > 8); + let gone = write_over(&mut store, &held, &grown.segments, &baseline, 4, 4); + assert_eq!(gone.segments, grown.segments[1..]); + assert_eq!((gone.written, gone.obsolete), (0, vec![grown.segments[0].name.clone()])); + assert_eq!(load(&mut store, Vec::new(), &gone.segments).unwrap(), held); + } + + /// Given a list of segments, then only this module's file names, each once, in id order, are + /// a list a snapshot may state. + #[test] + fn a_segment_list_is_checked() { + let seg = |name: &str, first: u64| Segment { name: name.into(), first: PhotoId(first), photos: 1, bytes: 1, crc: 0 }; + assert!(check_list(&[seg("segments/1-1.json", 1), seg("segments/5-1.json", 5)]).is_ok()); + for (list, says) in [ + (vec![seg("segments/1-1.json", 1), seg("segments/1-1.json", 5)], "twice"), + (vec![seg("segments/5-1.json", 5), seg("segments/1-1.json", 1)], "order"), + (vec![seg("segments/1-1.json", 1), seg("segments/2-1.json", 1)], "order"), + (vec![seg("../catalog.log", 1)], "not a segment"), + (vec![seg("catalog.snap", 1)], "not a segment"), + (vec![seg("segments/a.json", 1)], "not a segment"), + (vec![seg("segments/.json", 1)], "not a segment"), + ] { + assert!(check_list(&list).unwrap_err().contains(says), "{list:?}"); + } + assert!(valid_name(&segment_file("12-3-1")) && !valid_name("segments/12-3.json.tmp") && !valid_name("segments/../x.json")); + } + + /// Given segments, when one is missing, changed, cut short or not a catalog segment, then + /// loading fails with an error that names the file, and nothing is returned. + #[test] + fn a_damaged_segment_fails_the_load_and_is_named() { + let held = photos(1..=20); + let mut store = MemStore::new(); + let out = write_over(&mut store, &held, &[], &Photos::new(), 1, 4); + let name = out.segments[1].name.clone(); + let bytes = store.get(&name).unwrap(); + let mut flipped = bytes.clone(); + flipped[10] ^= 1; + for (damaged, says) in [(Some(flipped), "damaged"), (Some(bytes[..bytes.len() - 5].to_vec()), "damaged"), (None, "missing")] { + let mut broken = store.clone(); + match damaged { + Some(d) => broken.set(&name, d), + None => broken.remove(&name).unwrap(), + } + let e = load(&mut broken, Vec::new(), &out.segments).unwrap_err(); + assert!(e.to_string().contains(&name) && e.to_string().contains(says), "{e}"); + } + // listed with the sizes of a file that is not a segment (the right size and checksum) + let other = br#"{"format":"something-else","photos":{}}"#.to_vec(); + let mut elsewhere = out.segments.clone(); + elsewhere[1] = Segment { bytes: other.len() as u64, crc: crc32fast::hash(&other), ..elsewhere[1].clone() }; + store.set(&name, other); + let e = load(&mut store, Vec::new(), &elsewhere).unwrap_err(); + assert!(e.to_string().contains(&name) && e.to_string().contains("not a catalog segment"), "{e}"); + } + + /// Given a segment file whose size and checksum are the listed ones but whose photos are not + /// what the list says (a writer that listed it wrongly, or a file put in another's place), + /// when the library is loaded, then the load fails naming the file. + #[test] + fn a_segment_whose_photos_are_not_the_ones_listed_fails_the_load() { + let held = photos(1..=12); + let mut store = MemStore::new(); + let out = write_over(&mut store, &held, &[], &Photos::new(), 1, 4); + let name = out.segments[1].name.clone(); + let bytes = store.get(&name).unwrap(); + + // the list says three photos where the file holds four + let mut fewer = out.segments.clone(); + fewer[1].photos -= 1; + let e = load(&mut store, Vec::new(), &fewer).unwrap_err(); + assert!(e.to_string().contains(&name) && e.to_string().contains("holds 4 photos where the snapshot lists 3"), "{e}"); + + // the file of another segment (right size and checksum, four photos, but ids 1 to 4) + let mut other = MemStore::new(); + let first = write_over(&mut other, &photos(1..=4), &[], &Photos::new(), 1, 4); + let theirs = other.get(&first.segments[0].name).unwrap(); + assert_ne!(theirs, bytes); + let mut swapped = out.segments.clone(); + swapped[1] = Segment { bytes: theirs.len() as u64, crc: crc32fast::hash(&theirs), ..swapped[1].clone() }; + store.set(&name, theirs); + let e = load(&mut store, Vec::new(), &swapped).unwrap_err(); + assert!(e.to_string().contains(&name) && e.to_string().contains("holds photos of another segment"), "{e}"); + + // the file of the next segment (ids 9 to 12), which starts where this one ends + let later = store.get(&out.segments[2].name).unwrap(); + let mut swapped = out.segments.clone(); + swapped[1] = Segment { bytes: later.len() as u64, crc: crc32fast::hash(&later), ..swapped[1].clone() }; + store.set(&name, later); + let e = load(&mut store, Vec::new(), &swapped).unwrap_err(); + assert!(e.to_string().contains(&name) && e.to_string().contains("holds photos of another segment"), "{e}"); + } + + /// Given files in a store, when the unlisted segments are discarded, then those (and the + /// leftover of one being written) go, and nothing else does. + #[test] + fn only_unlisted_segment_files_are_discarded() { + let held = photos(1..=4); + let mut store = MemStore::new(); + let out = write_over(&mut store, &held, &[], &Photos::new(), 1, 4); + for name in ["catalog.snap", "catalog.log", "segments/9-1.json", "segments/9-2.json.tmp", "segments/notes.txt"] { + store.set(name, b"x".to_vec()); + } + assert_eq!(files(&mut store).unwrap(), 2); + assert!(present(&mut store, &names(&out.segments).into_iter().collect::>())); + discard_unlisted(&mut store, &out.segments); + let left: BTreeSet = store.files.lock().unwrap().keys().cloned().collect(); + let expected: BTreeSet = + names(&out.segments).into_iter().chain(["catalog.snap", "catalog.log", "segments/notes.txt"].map(String::from)).collect(); + assert_eq!(left, expected); + } + + /// Given segments by their first ids, then the segment that holds (or would hold) an id is + /// the last one that starts at or before it, the first one for ids below them all. + #[test] + fn the_segment_of_a_photo_is_the_last_that_starts_at_or_before_it() { + let seg = |first: u64| Segment { name: segment_file(&format!("{first}-1")), first: PhotoId(first), photos: 1, bytes: 1, crc: 0 }; + let list = [seg(10), seg(20), seg(30)]; + assert_eq!([5, 10, 19, 20, 99].map(|id| segment_of(&list, PhotoId(id))), [Some(0), Some(0), Some(0), Some(1), Some(2)]); + assert_eq!(segment_of(&[], PhotoId(1)), None); + } + + /// A store that can't write one file. + struct FailsAt { + files: MemStore, + name: &'static str, + /// Offer further handles (that fail in the same way). + parallel: bool, + } + + impl Store for FailsAt { + 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 name == self.name { Err(std::io::Error::other("disk full")) } else { self.files.write_atomic(name, data) } + } + fn write_new_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> std::io::Result { + if name == self.name { Err(std::io::Error::other("disk full")) } else { self.files.write_new_with(name, fill) } + } + fn sync(&mut self) -> std::io::Result<()> { + self.files.sync() + } + 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 background_writer(&self) -> Option> { + self.parallel.then(|| Box::new(FailsAt { files: self.files.clone(), name: self.name, parallel: true }) as Box) + } + fn describe(&self) -> String { + "fails".into() + } + } + + /// Given a store that can't write one of the segments a snapshot needs, when the snapshot is + /// written, then it fails, and the segments it did write are removed again (nothing lists + /// them), so the folder is as it was. + #[test] + fn a_failed_write_leaves_no_new_segment_behind() { + let mut held = photos(1..=20); + let mut mem = MemStore::new(); + let first = write_over(&mut mem, &held, &[], &Photos::new(), 1, 4); + assert_eq!(first.segments.len(), 5); + let before: BTreeSet = mem.files.lock().unwrap().keys().cloned().collect(); + let baseline = held.clone(); + for id in [2, 10] { + let mut edited = photo(id); + edited.rating = 1; + held.insert(PhotoId(id), Arc::new(edited)); + } + // segments 1 and 9 are written again, as `1-2` and `9-2`: the second one fails + let mut store = FailsAt { files: mem.clone(), name: "segments/9-2.json", parallel: false }; + let on_disk = OnDisk { version: 11, seq: 2, segments: &first.segments, baseline: &baseline, size: size(4), verify: false }; + let e = write(&mut store, &held, &on_disk).err().expect("the write fails"); + assert!(e.to_string().contains("disk full"), "{e}"); + assert_eq!(mem.files.lock().unwrap().keys().cloned().collect::>(), before); + assert_eq!(load(&mut mem, Vec::new(), &first.segments).unwrap(), baseline); + } + + /// Given a store that gives further handles, when a snapshot of many pieces is written, then + /// the pieces are written on several threads and the result is the one a single thread gives + /// (the same segments, in order, with the same checksums), and it reads back. + #[test] + fn pieces_written_on_several_threads_are_the_ones_one_thread_writes() { + if std::thread::available_parallelism().map_or(1, |n| n.get()) < 2 { + return; + } + let held = photos(1..=60); + let mut one = MemStore::new(); + let single = write_over(&mut one, &held, &[], &Photos::new(), 1, 4); + assert_eq!(single.segments.len(), 15); + let mut many = MemStore::new(); + many.background = true; + assert!(readers(&many, 15).len() >= 2); + let parallel = write_over(&mut many, &held, &[], &Photos::new(), 1, 4); + assert_eq!(parallel.segments, single.segments); + let handles = readers(&many, 15); + assert_eq!(load(&mut many, handles, ¶llel.segments).unwrap(), held); + } + + /// Given segments on disk and a store that gives further handles but can't write one of the + /// many pieces every photo's change needs, when the snapshot is written, then it fails and + /// none of the pieces that were written stays. + #[test] + fn a_failed_piece_among_those_written_on_several_threads_leaves_no_new_segment_behind() { + if std::thread::available_parallelism().map_or(1, |n| n.get()) < 2 { + return; + } + let baseline = photos(1..=60); + let mut mem = MemStore::new(); + let first = write_over(&mut mem, &baseline, &[], &Photos::new(), 1, 4); + let before: BTreeSet = mem.files.lock().unwrap().keys().cloned().collect(); + // every photo changed: every segment is written again, as `-2` + let held: Photos = baseline + .keys() + .map(|id| { + let mut edited = photo(id.0); + edited.rating = 2; + (*id, Arc::new(edited)) + }) + .collect(); + let mut store = FailsAt { files: mem.clone(), name: "segments/29-2.json", parallel: true }; + assert!(readers(&store, 15).len() >= 2); + let on_disk = OnDisk { version: 11, seq: 2, segments: &first.segments, baseline: &baseline, size: size(4), verify: false }; + let e = write(&mut store, &held, &on_disk).err().expect("the write fails"); + assert!(e.to_string().contains("disk full"), "{e}"); + assert_eq!(mem.files.lock().unwrap().keys().cloned().collect::>(), before); + assert_eq!(load(&mut mem, Vec::new(), &first.segments).unwrap(), baseline); + } +} diff --git a/crates/catalog/src/stored.rs b/crates/catalog/src/stored.rs index 77f601939c4..3eec7f7d206 100644 --- a/crates/catalog/src/stored.rs +++ b/crates/catalog/src/stored.rs @@ -1091,3 +1091,16 @@ pub(crate) fn photos(v: &BTreeMap>, s: S) -> } 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() + } +} From 852b8fadab72a7cd15f5d969e7314c347f6f40a8 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 13:54:04 -0400 Subject: [PATCH 17/61] Catalog: the journal saves the snapshot in segments and opens one (format 11) A library in a folder on disk keeps its photos in segment files (`segments/-.json`, at most 4096 photos each) that `catalog.snap` lists with their size, CRC-32 and photo count. Every compaction writes every segment, on several threads, under names no snapshot lists, then replaces `catalog.snap` atomically (the commit), then removes the files it no longer lists; opening reads the segments on several threads. A one-file library is split on first open, and its one file is replaced only once the segments read back the same. Stores without segments (the browser build) keep the photos in `catalog.snap`, as before. A damaged or missing segment fails the open with an error naming the file, and a list of segments that does not add up to the photos `catalog.snap` states is refused. Format 11 is a new row of `FORMATS` (it adds fields, not an op) with a fixture library in segments, `v11-*`. An older build refuses it untouched, so going back takes the files the upgrade kept, and now takes the segments along. A library whose upgrade at open could not be written (or whose old files could not be kept) stays in its old format: a later compaction, by hand, on close or in the background, keeps the old files first and then writes the upgrade. A change that could not be appended to the log is then saved in the format on disk, in one file, so none is lost; closing such a library is not refused when everything is in the log and only the compaction failed. This writes every segment each time: writing only the segments whose photos changed, removing the segment files a crash left, refusing segment files without a `catalog.snap`, and sizing a segment by its bytes are the next changes, and the module-level dead-code allowance of `segments` stays until the last of them. The compaction rule is the one that was there (2000 records or 16 MB of log). 300,000 browsed raws (180 MB as one file), one run each on an M1 Max with other builds running: opening 259 ms -> 78 ms; a synchronous compaction of 2000 records 840 ms -> 448 ms (median of 3); an append during a background compaction p95 7.7-7.9 ms -> 17.5-20.0 ms. Measured on this commit and on its parent. Co-Authored-By: Claude Opus 5.5 --- .../src/fixtures/v11-catalog.log.jsonl | 7 + .../src/fixtures/v11-catalog.snap.json | 1 + .../src/fixtures/v11-segments-7-3.json | 1 + crates/catalog/src/journal.rs | 425 ++++++- crates/catalog/src/lib.rs | 48 + crates/catalog/src/segments.rs | 15 +- crates/catalog/src/tests_background.rs | 18 +- crates/catalog/src/tests_format_version.rs | 60 +- crates/catalog/src/tests_journal.rs | 44 +- crates/catalog/src/tests_segments.rs | 1078 ++++++++++++++++- crates/catalog/src/tests_stored.rs | 39 +- crates/engine/src/library.rs | 10 + crates/engine/src/tests/forget_local.rs | 19 +- crates/engine/src/tests/library.rs | 66 +- crates/engine/src/tests/persist.rs | 77 +- docs/catalog-persistence.md | 108 +- docs/web.md | 4 +- docs/whats-new.md | 16 +- 18 files changed, 1891 insertions(+), 145 deletions(-) create mode 100644 crates/catalog/src/fixtures/v11-catalog.log.jsonl create mode 100644 crates/catalog/src/fixtures/v11-catalog.snap.json create mode 100644 crates/catalog/src/fixtures/v11-segments-7-3.json 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/journal.rs b/crates/catalog/src/journal.rs index 6280b11c8e6..6e0f70d49ba 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,"defaults":{…},"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. @@ -81,19 +83,23 @@ //! error says why. (A library in format 10 or later, which writes records so and states its //! defaults, may go on as it is when it can't be upgraded now: a later snapshot, compaction or //! closing, upgrades it, first keeps the files as they were at open (the snapshot, and the log -//! up to where it ended then) and is not written when it can't; those files stay even if that -//! snapshot then fails and the library is still in its old format. The next open tries again.) +//! up to where it ended then) and is not written when it can't be (a change that could not be +//! appended to the log is then saved in the format on disk, in one file, so none is lost); +//! those files stay even if that snapshot then fails and the library is still in its old +//! format. 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}; 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"; /// One catalog format: a number in `catalog.snap` that says how the library beside it is written. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -137,6 +143,7 @@ pub const FORMATS: &[Format] = &[ 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`] @@ -159,11 +166,14 @@ const fn newest(formats: &[Format]) -> u32 { pub struct SnapshotPolicy { pub max_records: u64, pub max_bytes: u64, + /// Photos per segment (see [`crate::segments`]): a segment is written in pieces of this many + /// once it holds more than twice as many. + pub segment_photos: usize, } impl Default for SnapshotPolicy { fn default() -> Self { - SnapshotPolicy { max_records: 2000, max_bytes: 16 << 20 } + SnapshotPolicy { max_records: 2000, max_bytes: 16 << 20, segment_photos: 4096 } } } @@ -241,15 +251,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 (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). @@ -260,8 +275,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. pub bytes: u64, + /// Segments written. + pub segments: u64, /// Log records the snapshot compacted. pub records: u64, } @@ -281,6 +298,8 @@ pub struct Journal { /// `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, /// The snapshot in the store is still in an older format (`Some(format)`): the library was /// not upgraded at open, because its files could not be kept or the upgrade could not be /// written. A later snapshot (a compaction, or closing) writes the upgrade then, @@ -290,12 +309,22 @@ pub struct Journal { /// length of its log. Appends only add to the log after that, so the first `log_len` bytes /// and the snapshot are the library as this session opened it, whatever is appended /// meanwhile (an earlier session of this build may have appended already, while the library - /// stayed in its old format: that is in them, and an older build may refuse it). + /// stayed in its old format: that is in them, and an older build may refuse it). After + /// changes were saved in the old format ([`Journal::save_in_old_format`]) it is the `seq` + /// that snapshot holds and an empty log: its log was reset. behind_at: (u64, u64), /// The files [`Journal::keep_before_upgrade`] kept for a snapshot that is not written yet, /// and, once that snapshot is, the names for [`Journal::take_kept`]. kept_pending: Option>, kept_written: Vec, + /// The segments `catalog.snap` lists, and the photos they hold (see [`crate::segments`]). + segments: Vec, + /// `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::keep_replaced`]). + opened_with_segments: bool, log_records: u64, log_bytes: u64, pub policy: SnapshotPolicy, @@ -327,7 +356,9 @@ struct Pending { started: web_time::Instant, /// Time the caller spent starting it. start_ms: f64, - worker: std::thread::JoinHandle>, + /// 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>, } fn io(e: std::io::Error) -> CatalogError { @@ -417,27 +448,105 @@ 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 [`snapshot_head`] (`seq`), the catalog's JSON -/// (`serde_json`) and `}\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], + /// 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, +} + +/// Write the snapshot of `job`: every segment, 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 { + // (no photos are taken to be on disk as they are: every segment is written) + let baseline = Photos::new(); + let on_disk = + segments::OnDisk { version: VERSION, seq: job.seq, segments: job.segments, baseline: &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, "{}", snapshot_head(seq))?; - 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() }) + 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) = written.map_or((Vec::new(), 0, 0), |w| (w.segments, w.written, w.bytes)); + 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() }) } /// The highest `seq` a snapshot may hold; beyond it the counter is treated as corrupt, far from overflow. @@ -446,7 +555,35 @@ 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) + snapshot_head_in(VERSION, seq) +} + +/// [`snapshot_head`] of a snapshot in format `version`. +fn snapshot_head_in(version: u32, seq: u64) -> String { + format!("{{\"format\":\"{FORMAT}\",\"version\":{version},\"seq\":{seq},\"defaults\":{},\"catalog\":", crate::stored::base().0) +} + +/// Write the snapshot of the state after op `seq` as one file in the older format `version` +/// (10: the photos in `catalog.snap`, no segments), as a build of that format wrote it. Used +/// where the upgrade can't be done (the files of that format can't be kept, or the new snapshot +/// can't be written), so that the library is not upgraded, and what is only in memory is still +/// saved. An error leaves the snapshot before this one as it was. +fn write_one_file_snapshot(store: &mut dyn Store, seq: u64, version: u32, catalog: &Catalog) -> std::io::Result { + let t0 = web_time::Instant::now(); + let mut serialize_ms = 0.0; + let head_bytes = store.write_atomic_with(SNAPSHOT, &mut |w| { + use std::io::Write; + let t = web_time::Instant::now(); + let mut b = std::io::BufWriter::with_capacity(1 << 20, w); + write!(b, "{}", snapshot_head_in(version, seq))?; + 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(()) + })?; + let timing = SnapshotTiming { serialize_ms, write_sync_ms: (ms_since(t0) - serialize_ms).max(0.0), bytes: head_bytes, ..Default::default() }; + Ok(Saved { timing, segments: Vec::new(), head_bytes, inline_photos: !catalog.is_empty() }) } /// Just the identification of `catalog.snap` (read before the catalog itself). @@ -464,6 +601,35 @@ 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))) } impl Journal { @@ -480,8 +646,11 @@ impl Journal { let snap = store.read(SNAPSHOT).map_err(io)?; let log = store.read(LOG).map_err(io)?; report.created = snap.is_none() && log.is_none(); - // (dropped once the snapshot and the log are read: their records are read over the - // library's own defaults where those are not this build's) + 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; @@ -509,25 +678,53 @@ impl Journal { 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(); + 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), + })?; + 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, seq: snapshot_seq, snapshot_seq, + snapshot_bytes, behind: None, behind_at: (0, 0), kept_pending: None, kept_written: Vec::new(), header_incomplete: false, + opened_with_segments: !listed.is_empty(), + segments: listed, + inline_photos, log_records: 0, log_bytes: 0, policy: SnapshotPolicy::default(), @@ -638,6 +835,7 @@ impl Journal { j.store .write_atomic(SNAPSHOT, empty.as_bytes()) .map_err(|e| CatalogError::Io(format!("can't write the new library's {SNAPSHOT}: {e}")))?; + j.snapshot_bytes = empty.len() as u64; } else if let (Some(from), false) = (older, rewritten) { // A library in a format that writes compact records and states its defaults may go on // as it is when it can't be upgraded now (the next open tries again): what is appended @@ -775,7 +973,9 @@ impl Journal { /// 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> { - if !self.store.keeps_replaced_formats() { + // (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; @@ -804,10 +1004,11 @@ impl Journal { /// A library that was left in an older format at open (see `behind`) keeps its files, as /// they were then, before a snapshot upgrades it: the snapshot as it is (nothing writes it - /// until the upgrade) and the log up to its length at open (what was appended since is this + /// until the upgrade, but for [`Journal::save_in_old_format`], which moves `behind_at` to + /// what it wrote) and the log up to its length at open (what was appended since is this /// build's, which an older build may refuse). The names are those the open would have kept /// them under, so files kept for an upgrade that did not land are never left behind under - /// other names. Kept once: when a snapshot failed and is tried again, they stay as they are + /// other names. Kept once (until changes are saved in the old format, which replaces them): when a snapshot failed and is tried again, they stay as they are /// (the failed one may have landed all the same, and the snapshot is then no longer what /// could be kept). A snapshot that is already in this build's format (that landed after its /// files were kept, or before them, reporting a failure) is the upgrade done, with nothing @@ -918,24 +1119,51 @@ impl Journal { if let Err(e) = self.wait() { log::warn!("catalog: background snapshot failed ({e}); writing one now"); } + // (a library left behind at open has its files kept first: `keep_before_upgrade`) let t0 = web_time::Instant::now(); let seq = self.seq.checked_add(unlogged).ok_or_else(|| CatalogError::Corrupt(format!("{SNAPSHOT}: op counter overflow")))?; if let Err(e) = self.keep_before_upgrade() { // not upgraded without its way back; try again later like any failed snapshot self.stats.failed_snapshots += 1; self.retry_at_records = self.log_records + self.policy.max_records; - return Err(e); + return match self.behind { + // ... but what is only in memory is saved all the same, in the format on disk + Some(from) if unlogged > 0 && self.segments.is_empty() => self.save_in_old_format(catalog, seq, from, e), + _ => Err(e), + }; } - let mut timing = match write_snapshot(self.store.as_mut(), seq, catalog) { - Ok(t) => t, + let job = Job { seq, catalog, segments: &self.segments, size: self.segment_size(), verify: self.inline_photos || self.segments.is_empty() }; + 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; - return Err(io(e)); + // The new snapshot may have been committed all the same (the failure came after + // its rename): then the upgrade is done and the files kept before are its way + // back, told when asked for. A disk that can't be read, or still reads the old + // format, stays `behind`: what was kept stays for the next try, which does not + // keep again (unless the changes are saved in the old format just below, which + // makes it obsolete: `save_in_old_format` removes it). + // (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) + if self.on_disk_version() == Some(Some(VERSION)) { + self.upgraded_later(); + } + self.retry_at_records = self.log_records.saturating_add(self.policy.max_records); + return match self.behind { + // Still in the old format: what is only in memory is saved all the same, in + // the format on disk. + Some(from) if unlogged > 0 && self.segments.is_empty() => self.save_in_old_format(catalog, seq, from, io(e)), + _ => Err(io(e)), + }; } }; - // the snapshot is durable: it holds every op up to `seq` + // the snapshot is durable: it holds every op up to `seq`, and the files it replaced + // (if the library was behind) are kept + self.behind = None; + let mut timing = saved.timing; + self.adopt(saved); self.seq = seq; self.snapshot_seq = seq; self.upgraded_later(); @@ -955,6 +1183,53 @@ impl Journal { Ok(()) } + /// [`Journal::snapshot_with_unlogged`] where the upgrade can't be done (`why`: the files of + /// the format on disk, `from`, can't be kept, or the new snapshot can't be written): the snapshot is written in that format, + /// one file, with the `unlogged` ops in it, so that they are saved, and the library is still + /// `behind` (the upgrade is tried again by the next snapshot, which keeps this one: the + /// files kept before, the library as it was at open, go, as they are not the way back from + /// what is on disk now). If that can't be written either, it is `why` that is returned and + /// nothing has changed. + fn save_in_old_format(&mut self, catalog: &Catalog, seq: u64, from: u32, why: CatalogError) -> Result<()> { + let t0 = web_time::Instant::now(); + // only over what is known to be the format `from`: not over an upgrade that may have taken effect + if self.on_disk_version() != Some(Some(from)) { + return Err(why); + } + let saved = match write_one_file_snapshot(self.store.as_mut(), seq, from, catalog) { + Ok(saved) => saved, + Err(e) => { + log::warn!("catalog: can't upgrade from format v{from} ({why}), and can't save in that format either: {e}"); + return Err(why); + } + }; + log::warn!("catalog: can't upgrade from format v{from} ({why}): saved in that format, not upgraded"); + let mut timing = saved.timing; + self.adopt(saved); + self.seq = seq; + self.snapshot_seq = seq; + // (a header that states this build's defaults: records are compact again) + self.header_incomplete = false; + if let Some(kept) = self.kept_pending.take() { + self.forget_kept(&kept); + } + self.behind_at = (seq, 0); + let t2 = web_time::Instant::now(); + // A crash here leaves old records in the log; they are skipped by seq on load. + self.store.write_atomic(LOG, b"").map_err(io)?; + timing.reset_ms = ms_since(t2); + timing.total_ms = ms_since(t0); + timing.blocking_ms = timing.total_ms; + timing.records = self.log_records; + self.record_snapshot(timing); + self.log_records = 0; + self.log_bytes = 0; + // (the upgrade is tried again once the log has grown by a compaction's worth, or on close) + self.retry_at_records = self.policy.max_records; + self.tail_dirty = false; + Ok(()) + } + /// Compact like [`Journal::snapshot`], but write the snapshot on a worker thread from a copy /// of `catalog` (cheap: photos are shared) when the store supports it (else synchronously). /// `catalog` must reflect every appended op. Appends go on meanwhile; [`Journal::poll`] @@ -972,7 +1247,13 @@ impl Journal { 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 the segment list with it. Nothing else writes snapshots meanwhile. + let listed = self.segments.clone(); + let (size, verify) = (self.segment_size(), self.inline_photos || self.segments.is_empty()); + let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || { + let job = Job { seq, catalog: ©, segments: &listed, size, verify }; + write_snapshot(writer.as_mut(), &job) + }); let worker = match spawned { Ok(w) => w, Err(e) => { @@ -1018,25 +1299,32 @@ impl Journal { 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, + let saved = match written { + Ok(saved) => saved, Err(e) => { // the log still holds every record: nothing lost, retry later 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}"); + // (it may have been committed all the same, its folder not synced: then the library + // is upgraded and what was kept before stays) + if self.on_disk_version() == Some(Some(VERSION)) { + self.upgraded_later(); + } return Err(io(e)); } }; // `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); self.snapshot_seq = p.seq; self.upgraded_later(); self.header_incomplete = false; 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)); } @@ -1053,6 +1341,18 @@ impl Journal { Ok(()) } + /// How large the segments of a snapshot are to be. + fn segment_size(&self) -> segments::Size { + segments::Size { per: self.policy.segment_photos, bytes: 0, record_bytes: 0 } + } + + /// A snapshot was committed: what is on disk now. + fn adopt(&mut self, saved: Saved) { + self.snapshot_bytes = saved.head_bytes + saved.segments.iter().map(|s| s.bytes).sum::(); + self.segments = saved.segments; + self.inline_photos = saved.inline_photos; + } + fn record_snapshot(&mut self, t: SnapshotTiming) { self.stats.snapshots += 1; self.stats.last_snapshot = t; @@ -1060,9 +1360,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, @@ -1075,7 +1376,12 @@ 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. @@ -1085,6 +1391,23 @@ impl Journal { && (self.log_records >= self.policy.max_records || self.log_bytes >= self.policy.max_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 library is still in an older format than this build's: its upgrade was put off at + /// open, and a snapshot (a compaction, or closing) makes it. + pub fn upgrade_put_off(&self) -> bool { + self.behind.is_some() + } + + /// The segments `catalog.snap` lists. + pub fn segments(&self) -> &[Segment] { + &self.segments + } + pub fn seq(&self) -> u64 { self.seq } diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 98ae3645d28..b9ef9e2b823 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -1048,6 +1048,54 @@ 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(), + } + } + + /// 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() diff --git a/crates/catalog/src/segments.rs b/crates/catalog/src/segments.rs index 315cc381493..62dcec4aa90 100644 --- a/crates/catalog/src/segments.rs +++ b/crates/catalog/src/segments.rs @@ -28,8 +28,8 @@ //! **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. +//! it, the new one with all of its. Segment files nothing lists (a crash can leave some) are not +//! removed yet. //! //! **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. @@ -37,10 +37,11 @@ //! **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. //! -//! This module is the writer and reader of the segments, used by [`crate::journal`] for format 11 -//! (the journal that calls it comes in the next change; until then only the tests below do). +//! This module is the writer and reader of the segments, used by [`crate::journal`] for format 11. +//! The journal does not yet keep the baseline between snapshots, so each one writes every segment; +//! writing only the ones whose photos changed comes in the next change. -#![allow(dead_code, reason = "called by the journal in the change that brings format 11")] +#![allow(dead_code, reason = "the journal calls the rest of it (keeping the baseline, listing the folder) in the next changes")] use std::collections::BTreeMap; use std::ops::Bound; @@ -122,7 +123,7 @@ enum Step { pub(crate) struct Size { /// At most this many (the journal's policy states it). pub per: usize, - /// And about this many bytes (the journal's policy states it too; 0: any). + /// And about this many bytes (0: any; the journal does not set it yet). 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. @@ -442,7 +443,7 @@ pub(crate) fn write(store: &mut dyn Store, photos: &Photos, on_disk: &OnDisk<'_> } /// 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. +/// what stays is left where it is. pub(crate) fn discard(store: &mut dyn Store, names: &[String]) { for name in names { if valid_name(name.strip_suffix(".tmp").unwrap_or(name)) diff --git a/crates/catalog/src/tests_background.rs b/crates/catalog/src/tests_background.rs index 5235c3e1712..9ef02e6ae35 100644 --- a/crates/catalog/src/tests_background.rs +++ b/crates/catalog/src/tests_background.rs @@ -63,6 +63,12 @@ impl Store for Gated { self.files.write_atomic(name, &buf)?; Ok(buf.len() as u64) } + fn write_new_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> std::io::Result { + self.files.write_new_with(name, fill) + } + fn sync(&mut self) -> std::io::Result<()> { + self.files.sync() + } fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { self.files.append(name, data) } @@ -72,6 +78,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 +184,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, ..SnapshotPolicy::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 6f57553fa85..5bf4539c2f3 100644 --- a/crates/catalog/src/tests_format_version.rs +++ b/crates/catalog/src/tests_format_version.rs @@ -237,7 +237,8 @@ fn op_variants_are_versioned() { Op::SetHistoryCursor { .. } => 8, } } - // (format 9 added no op: it added fields) + // (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 }); // 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"); @@ -275,18 +276,34 @@ fn a_format_number_means_one_format() { assert_eq!(here, (1..=VERSION).collect::>(), "this build has every format up to the one it writes, and none after"); } -/// The library `fixtures/v-catalog.*` holds, written by the build of format `N`. -fn fixture(version: u32) -> Option<(&'static str, &'static str)> { +/// 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((include_str!("fixtures/v6-catalog.snap.json"), include_str!("fixtures/v6-catalog.log.jsonl"))), - 7 => Some((include_str!("fixtures/v7-catalog.snap.json"), include_str!("fixtures/v7-catalog.log.jsonl"))), - 8 => Some((include_str!("fixtures/v8-catalog.snap.json"), include_str!("fixtures/v8-catalog.log.jsonl"))), - 9 => Some((include_str!("fixtures/v9-catalog.snap.json"), include_str!("fixtures/v9-catalog.log.jsonl"))), - 10 => Some((include_str!("fixtures/v10-catalog.snap.json"), include_str!("fixtures/v10-catalog.log.jsonl"))), + 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. @@ -294,21 +311,23 @@ fn fixture(version: u32) -> Option<(&'static str, &'static str)> { 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((snap, log)) = fixture(f.version) else { + 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 = MemStore::new(); - m.set(SNAPSHOT, snap.as_bytes().to_vec()); - m.set(LOG, log.as_bytes().to_vec()); + 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 @@ -345,11 +364,9 @@ impl Store for Refusing { /// A format 6 library (the fixture) in a store. fn v6_library() -> (MemStore, Vec, Vec) { - let (snap, log) = fixture(6).unwrap(); - let m = MemStore::new(); - m.set(SNAPSHOT, snap.as_bytes().to_vec()); - m.set(LOG, log.as_bytes().to_vec()); - (m, snap.as_bytes().to_vec(), log.as_bytes().to_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 @@ -427,16 +444,17 @@ fn a_library_on_disk_that_cannot_be_kept_leaves_nothing_lying_about() { let dir = std::env::temp_dir().join(format!("lc-keep-fails-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(dir.join("catalog.log.v6-8")).unwrap(); - let (snap, log) = fixture(6).unwrap(); - std::fs::write(dir.join(SNAPSHOT), snap).unwrap(); - std::fs::write(dir.join(LOG), log).unwrap(); + let files = fixture(6).unwrap(); + for (name, content) in &files { + std::fs::write(dir.join(name), content).unwrap(); + } let e = Journal::open(Box::new(FsStore::open(&dir).unwrap())).err().expect("refused"); assert!(matches!(&e, CatalogError::Io(why) if why.contains("older format (v6)") && why.contains("can't be kept")), "{e}"); let mut names: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); names.sort(); assert_eq!(names, [LOG, "catalog.log.v6-8", SNAPSHOT], "nothing but the library and the name that was taken"); - assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), snap.as_bytes()); + assert_eq!(std::fs::read(dir.join(SNAPSHOT)).unwrap(), files.iter().find(|(n, _)| *n == SNAPSHOT).unwrap().1.as_bytes()); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/catalog/src/tests_journal.rs b/crates/catalog/src/tests_journal.rs index b261961337a..f2ccec07d1a 100644 --- a/crates/catalog/src/tests_journal.rs +++ b/crates/catalog/src/tests_journal.rs @@ -286,34 +286,42 @@ fn fs_store_roundtrip() { let _ = std::fs::remove_dir_all(&dir); } -/// The streamed snapshot is byte-for-byte what was written before streaming (issue #37), with -/// the defaults a library states since format 10; 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\":{},\"defaults\":{},\"catalog\":{}}}\n", - crate::journal::VERSION, - j.seq(), - crate::stored::base().0, - 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_segments.rs b/crates/catalog/src/tests_segments.rs index a7467871f26..47f32182121 100644 --- a/crates/catalog/src/tests_segments.rs +++ b/crates/catalog/src/tests_segments.rs @@ -2,9 +2,1085 @@ //! made with its first file, files are written under names that don't exist yet, listed and //! synced. Nothing in the catalog writes or reads them yet. -use crate::segments::segment_file; +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 the log is compacted, then every segment is written again under a +/// new name and the files of the snapshot before are gone (no photo is taken to be on disk as +/// it is: see the module docs of `segments`). +#[test] +fn a_compaction_writes_every_segment_and_removes_the_old_files() { + let (m, mut j, mut c) = library(12, 4); + let before = listed(&m); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(6), rating: 5 }]); + j.snapshot(&c).unwrap(); + let after = listed(&m); + assert_eq!((before.len(), after.len()), (3, 3)); + assert_eq!(before.intersection(&after).count(), 0, "{before:?} -> {after:?}"); + assert_eq!(j.stats().last_snapshot.segments, 3); + // the files of the snapshot before are gone + assert_eq!(segment_files(&m), after); + 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); + 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 write_new_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> std::io::Result { + self.frame(); + self.files.write_new_with(name, fill) + } + fn sync(&mut self) -> std::io::Result<()> { + self.files.sync() + } + 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 the +/// library goes on from there. +#[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 (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}"); + // 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(); + 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_same(&reopen(&m), &c); + // the next compaction writes the changes made meanwhile + j.snapshot(&c).unwrap(); + assert_eq!(j.stats().last_snapshot.segments, 3); + 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()); +} + +/// 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(_)))); +} + +/// 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 write_new_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> 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_new_with(name, fill) + } + fn sync(&mut self) -> std::io::Result<()> { + self.files.sync() + } + 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_v10_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>, + /// The files an upgrade keeps (`catalog.snap.v…`, `catalog.log.v…`) can't be written: no room. + refuse_kept: Arc>, + /// `catalog.snap` can't be written at all. + refuse_snap: Arc>, + /// `catalog.snap` can't be read. + unreadable_snap: Arc>, + /// Snapshots can be written on a worker thread (through a handle on the same files). + background: Arc>, +} + +impl Store for Garbling { + fn read(&mut self, name: &str) -> std::io::Result>> { + if name == SNAPSHOT && *self.unreadable_snap.lock().unwrap() { + return Err(std::io::Error::other("unreadable")); + } + 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<()> { + if *self.refuse_kept.lock().unwrap() && (name.starts_with("catalog.snap.v") || name.starts_with("catalog.log.v")) { + return Err(std::io::Error::other("disk full")); + } + if name == SNAPSHOT && *self.refuse_snap.lock().unwrap() { + return Err(std::io::Error::other("no room for the snapshot")); + } + 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 write_new_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> std::io::Result { + self.files.write_new_with(name, fill) + } + fn sync(&mut self) -> std::io::Result<()> { + self.files.sync() + } + 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 background_writer(&self) -> Option> { + (*self.background.lock().unwrap()).then(|| Box::new(self.clone()) as Box) + } + 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 }]); + // closing wants the upgrade; a compaction (also the one in the background) keeps the old + // files first and then writes it. Here the segments written don't read back, so it fails + // and the library stays as it was, with the files kept and no segment left over + let snapshot = store.files.get(SNAPSHOT).unwrap(); + assert!(j.upgrade_put_off()); + assert!(j.snapshot_in_background(&loaded).is_err()); + assert_eq!(store.files.get(SNAPSHOT).unwrap(), snapshot); + assert!(segment_files(&store.files).is_empty()); + *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 + assert!(!j.upgrade_put_off(), "still put off after the compaction by hand"); + let mut loaded = loaded; + run(&mut j, &mut loaded, vec![Op::SetRating { id: PhotoId(8), rating: 3 }]); + 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 is closed, then closing wants the upgrade +/// written (an older snapshot must not stay under this build's records), but only with the files +/// it was kept first: where they can't be kept the compaction fails, the library stays as it was +/// and opens again with its changes replayed from the log. +#[test] +fn closing_a_library_put_off_upgrades_it_only_with_the_old_files_kept() { + 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.upgrade_put_off()); + assert!(j.snapshot(&loaded).is_err(), "the old files can't be kept"); + 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 whose upgrade was put off because its old files can't be kept (no room), when +/// it is closed with changes that were never written to the log (their append failed), then the +/// snapshot is written in the format that is on disk, one file, with those changes in it: nothing +/// is upgraded without its way back, and nothing is lost. A later attempt, with room, keeps that +/// snapshot (changes included) and upgrades. +#[test] +fn unlogged_changes_are_saved_in_the_old_format_where_the_old_files_cannot_be_kept() { + 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.refuse_kept.lock().unwrap() = true; + let (mut j, mut loaded, r) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!(r.upgraded_from, None, "put off: its files can't be kept"); + let before = j.seq(); + // a change applied in memory whose append failed + let op = Op::SetRating { id: PhotoId(8), rating: 4 }; + loaded.apply(op).unwrap(); + j.snapshot_with_unlogged(&loaded, 1).unwrap(); + assert_eq!(j.seq(), before + 1, "the change is in the snapshot"); + assert_eq!(manifest(&store.files)["version"], 10, "still the format on disk"); + assert!(manifest(&store.files).get("segments").is_none(), "one file, as that format is written"); + assert!(segment_files(&store.files).is_empty() && store.files.get(LOG).is_some_and(|l| l.is_empty())); + assert!(j.upgrade_put_off(), "the upgrade is still to be done"); + drop(j); + // a crash or a quit now: it opens, from the old format, with the change + let (mut j, again, r) = Journal::open(Box::new(store.clone())).unwrap(); + assert_eq!((r.upgraded_from, r.replayed), (None, 0)); + assert_same(&again, &loaded); + + // with room, the next attempt keeps the snapshot as it is now and upgrades + *store.refuse_kept.lock().unwrap() = false; + let saved = store.files.get(SNAPSHOT).unwrap(); + let seq = j.seq(); + j.snapshot(&again).unwrap(); + assert_eq!(manifest(&store.files)["version"], u64::from(VERSION)); + assert_eq!(store.files.get(&format!("{SNAPSHOT}.v10-{seq}")), Some(saved)); + assert_same(&reopen(&store.files), &loaded); +} + +/// Given a library put off whose changes were saved in the old format (one file, its log reset), +/// when more changes are appended and the upgrade is then tried in the same session, with room, +/// then the files kept are that old-format snapshot, whole: not the open-time files, and not a +/// prefix of the log as it has grown since (which would cut a record). +#[test] +fn the_upgrade_after_a_save_in_the_old_format_keeps_that_snapshot_in_the_same_session() { + 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.refuse_kept.lock().unwrap() = true; + let (mut j, mut loaded, _) = Journal::open(Box::new(store.clone())).unwrap(); + loaded.apply(Op::SetRating { id: PhotoId(8), rating: 4 }).unwrap(); + j.snapshot_with_unlogged(&loaded, 1).unwrap(); + let saved = store.files.get(SNAPSHOT).unwrap(); + let seq = j.seq(); + let op = Op::SetRating { id: PhotoId(8), rating: 2 }; + loaded.apply(op.clone()).unwrap(); + j.append(&[op]).unwrap(); + assert!(store.files.get(LOG).is_some_and(|l| !l.is_empty()), "the log has grown since the save"); + *store.refuse_kept.lock().unwrap() = false; + j.snapshot(&loaded).unwrap(); + assert_eq!(store.files.get(&format!("{SNAPSHOT}.v10-{seq}")), Some(saved)); + assert!(store.files.get(&format!("{LOG}.v10-{seq}")).is_none_or(|l| l.is_empty()), "the log as it was when that snapshot was written"); + let mut told = j.take_kept(); + told.sort(); + let on_disk: Vec = store.files.files.lock().unwrap().keys().filter(|k| k.contains(".v10-")).cloned().collect(); + assert_eq!(told, on_disk, "told what is kept, once written"); + drop(j); + assert_same(&reopen(&store.files), &loaded); +} + +/// Given a library whose upgrade was put off, when its old files can be kept but the upgrade then +/// can't be written (the segments don't read back), and closing has changes that were never +/// logged, then they are saved in the old format too, and what was kept for the failed try is +/// gone again (nothing was upgraded). +#[test] +fn unlogged_changes_are_saved_in_the_old_format_where_the_upgrade_cannot_be_written() { + 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, _) = Journal::open(Box::new(store.clone())).unwrap(); + loaded.apply(Op::SetRating { id: PhotoId(8), rating: 4 }).unwrap(); + j.snapshot_with_unlogged(&loaded, 1).unwrap(); + assert_eq!(manifest(&store.files)["version"], 10); + assert!(segment_files(&store.files).is_empty()); + assert!(store.files.files.lock().unwrap().keys().all(|k| !k.contains(".v10-")), "no copy of a try that upgraded nothing"); + drop(j); + assert_same(&reopen(&store.files), &loaded); +} + +/// Given a library whose upgrade was put off and whose old files can't be kept, when there is +/// nothing unlogged, then the compaction fails and the files are as they were; and when there is +/// but the old format can't be written either, it fails with the keeping error and changes nothing. +#[test] +fn nothing_is_written_where_neither_the_upgrade_nor_the_old_format_can_be() { + 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.refuse_kept.lock().unwrap() = true; + let (mut j, mut loaded, _) = Journal::open(Box::new(store.clone())).unwrap(); + assert!(j.snapshot(&loaded).is_err()); + assert_eq!((store.files.get(SNAPSHOT), store.files.get(LOG)), (Some(old.as_bytes().to_vec()), Some(log.as_bytes().to_vec()))); + + *store.refuse_snap.lock().unwrap() = true; + loaded.apply(Op::SetRating { id: PhotoId(8), rating: 4 }).unwrap(); + let before = j.seq(); + let e = j.snapshot_with_unlogged(&loaded, 1).unwrap_err(); + assert!(e.to_string().contains("disk full") && !e.to_string().contains("no room for the snapshot"), "the keeping error: {e}"); + assert_eq!((j.seq(), store.files.get(SNAPSHOT), store.files.get(LOG)), (before, Some(old.as_bytes().to_vec()), Some(log.as_bytes().to_vec()))); +} + +/// Given a library whose upgrade was put off and whose disk can't be read to say what format it +/// is in (an upgrade that failed may have taken effect), when changes that were never logged +/// are to be saved, then nothing is written: a one-file snapshot over a library that may have +/// been upgraded would drop its segments. +#[test] +fn nothing_is_saved_in_the_old_format_over_a_disk_that_cannot_be_read() { + 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.refuse_kept.lock().unwrap() = true; + let (mut j, mut loaded, _) = Journal::open(Box::new(store.clone())).unwrap(); + *store.unreadable_snap.lock().unwrap() = true; + loaded.apply(Op::SetRating { id: PhotoId(8), rating: 4 }).unwrap(); + assert!(j.snapshot_with_unlogged(&loaded, 1).is_err()); + assert_eq!((store.files.get(SNAPSHOT), store.files.get(LOG)), (Some(old.as_bytes().to_vec()), Some(log.as_bytes().to_vec()))); +} + +/// Given a snapshot saved in the old format because the upgrade could not be done, when the log +/// has grown by a compaction's worth since, then compaction is due again (it tries the upgrade +/// again): the wait is counted from that snapshot, not from the log it emptied. +#[test] +fn the_upgrade_is_tried_again_a_compactions_worth_after_the_old_format_save() { + 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.refuse_kept.lock().unwrap() = true; + let (mut j, mut loaded, _) = Journal::open(Box::new(store.clone())).unwrap(); + j.policy = SnapshotPolicy { max_records: 1, ..SnapshotPolicy::default() }; + loaded.apply(Op::SetRating { id: PhotoId(8), rating: 4 }).unwrap(); + j.snapshot_with_unlogged(&loaded, 1).unwrap(); + assert!(!j.wants_snapshot(), "nothing since"); + run(&mut j, &mut loaded, vec![Op::SetRating { id: PhotoId(8), rating: 5 }]); + assert!(j.wants_snapshot(), "a compaction's worth since"); +} + +/// 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"); + assert!(!j.upgrade_put_off(), "the upgrade is done all the same"); + assert_eq!(j.take_kept(), [format!("{SNAPSHOT}.v10-{kept_seq}"), format!("{LOG}.v10-{kept_seq}")], "and the files kept are told"); + // and a later compaction (the one on quit) does not keep the new format's head over them + *store.fail_after_snap.lock().unwrap() = false; + j.snapshot(&loaded).unwrap(); + assert_eq!(store.files.get(&format!("{SNAPSHOT}.v10-{kept_seq}")).as_deref(), Some(old.as_bytes()), "still the way back"); +} + +/// The same where the compaction is written by the background worker: the failure that comes +/// after the commit is the upgrade done, and the files kept are told. +#[test] +fn a_background_compaction_that_failed_after_its_commit_is_the_upgrade_done() { + 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; + *store.background.lock().unwrap() = true; + let kept_seq = j.seq(); + j.snapshot_in_background(&loaded).unwrap(); + assert!(j.wait().is_err(), "the worker's write took effect and was said to have failed"); + assert_eq!(manifest(&store.files)["version"], u64::from(VERSION)); + assert!(!j.upgrade_put_off(), "the upgrade is done all the same"); + assert_eq!(j.take_kept(), [format!("{SNAPSHOT}.v10-{kept_seq}"), format!("{LOG}.v10-{kept_seq}")], "and the files kept are told"); + 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); +} + +/// 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); + } +} + +/// 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-13.json", "5-13.json", "9-13.json"]); + drop(j); + // left by a crash, and a file that is somebody else's: opening removes none of them + 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 (j, back, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + assert_same(&back, &c); + assert_eq!(names(&dir.join("segments")), ["1-13.json", "5-13.json", "77-1.json", "77-2.json.tmp", "9-13.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). +#[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(); + 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)] + { + // 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")); + 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); + } + } +} + /// 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() { diff --git a/crates/catalog/src/tests_stored.rs b/crates/catalog/src/tests_stored.rs index 27aa03b6acb..17be942d84e 100644 --- a/crates/catalog/src/tests_stored.rs +++ b/crates/catalog/src/tests_stored.rs @@ -523,18 +523,28 @@ fn fixture_snapshot() -> Catalog { catalog_of([full(), plain(8), rich_photo]) } -/// Writes this build's fixture, `fixtures/v-catalog.*`: the fixture library as this -/// build saves it, snapshot and log. Run it once, when a format is new: put two empty files there -/// (the tests include them), then -/// `cargo test -p lightcraft-catalog write_this_formats_fixture -- --ignored`. The files are then -/// what that build wrote, and are never written again. +/// 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-catalog.*"] +#[ignore = "writes fixtures/v-*"] fn write_this_formats_fixture() { let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/fixtures"); - let (snap, log) = (dir.join(format!("v{VERSION}-catalog.snap.json")), dir.join(format!("v{VERSION}-catalog.log.jsonl"))); + 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(&snap) && !written(&log), "format {VERSION} has its fixture: a fixture is what that build wrote"); + 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 @@ -547,8 +557,9 @@ fn write_this_formats_fixture() { j.append(&[op]).unwrap(); } drop(j); - std::fs::write(snap, m.get(SNAPSHOT).unwrap()).unwrap(); - std::fs::write(log, m.get(LOG).unwrap()).unwrap(); + 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 @@ -579,7 +590,10 @@ fn a_v6_library_loads_and_is_upgraded() { 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()); - assert!(new.len() * 2 < old.len() + log.len(), "{} + {} -> {}", old.len(), log.len(), new.len()); + // (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)); @@ -685,7 +699,8 @@ fn a_library_states_what_missing_settings_read_as() { /// 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() { - let m = MemStore::new(); + // (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}})), diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index e1765de1d16..c51b356d4b0 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) @@ -740,6 +741,7 @@ 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 saved = unlogged == 0 && persisted.is_ok(); let snapshot = lib.journal.snapshot_with_unlogged(&self.catalog, unlogged); if unlogged > 0 && lib.journal.seq() == before + unlogged { // the snapshot holds the queued ops: they are saved, never append them again @@ -751,6 +753,14 @@ impl Session { } let result = match (persisted, snapshot) { (_, Ok(())) => Ok(()), + // everything is in the log and only the compaction failed (a library whose upgrade is + // put off, with no room to keep its old files): the next open replays the log, so + // closing (also to switch libraries) is not refused for it + (_, Err(s)) if saved => { + log::warn!("library: closed without compacting: {s}"); + lib.last_error = Some(format!("compaction: {s}")); + Ok(()) + } // neither the log nor the snapshot took the queued ops (Err(EngineError::NotSaved(e)), Err(s)) if lib.journal.seq() == before => Err(EngineError::NotSaved(format!("{e}; snapshot: {s}"))), (_, Err(s)) => Err(s.into()), diff --git a/crates/engine/src/tests/forget_local.rs b/crates/engine/src/tests/forget_local.rs index 9f5d1f57270..7586ae57535 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 b2eb8cb9494..cb768da39d0 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, ..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); @@ -839,3 +866,34 @@ fn the_hold_of_the_view_is_kept_with_the_library_and_holds_nothing_over_from_ano s.close_library().unwrap(); let _ = std::fs::remove_dir_all(&dir); } + +/// Given a library in the older one-file format whose upgrade is put off because there is no room +/// to keep its old files (here: their names are taken by folders), when changes were made and the +/// library is closed (switching to another one does that), then closing succeeds: every change is +/// in the log, and the next open replays it. Only the upgrade waits; the reason is logged and kept in `last_error`. +#[test] +fn closing_a_library_whose_upgrade_is_put_off_succeeds_when_everything_is_logged() { + let dir = temp_dir("put-off-close"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("catalog.snap"), include_str!("../../../catalog/src/fixtures/v10-catalog.snap.json")).unwrap(); + std::fs::write(dir.join("catalog.log"), include_str!("../../../catalog/src/fixtures/v10-catalog.log.jsonl")).unwrap(); + // (the names the kept files would have, for the change the library is at when it is opened + // (10) and when it is closed, after an edit) + for seq in 10..=14 { + for kept in ["catalog.snap", "catalog.log"] { + std::fs::create_dir(dir.join(format!("{kept}.v10-{seq}"))).unwrap(); + } + } + let mut s = open(&dir, false); + assert_eq!(s.library.as_ref().unwrap().report.upgraded_from, None, "put off"); + s.execute("library.select", &json!({"ids": [8]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 2})).unwrap(); + let expect = s.catalog.to_snapshot(); + s.close_library().expect("everything is in the log"); + assert!(s.library.as_ref().unwrap().last_error.is_some(), "the upgrade that could not be done is said"); + drop(s); + let s = open(&dir, false); + assert_eq!(s.catalog.to_snapshot(), expect); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests/persist.rs b/crates/engine/src/tests/persist.rs index 82be29e44d7..3f54f7c2999 100644 --- a/crates/engine/src/tests/persist.rs +++ b/crates/engine/src/tests/persist.rs @@ -137,7 +137,7 @@ 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, ..SnapshotPolicy::default() }; store.set_failing(true); s.execute("album.create", &json!({"name": "A"})).unwrap(); s.execute("album.create", &json!({"name": "B"})).unwrap(); @@ -240,3 +240,78 @@ fn an_upgraded_library_says_where_what_it_was_is_kept() { s.close_library().unwrap(); let _ = std::fs::remove_dir_all(&dir); } + +/// A library in the one-file format (10) that could not keep its files at open: a directory sits where the +/// first kept file goes. +fn library_that_could_not_keep_its_files(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("lightcraft-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("catalog.snap.v10-10")).unwrap(); + std::fs::write(dir.join("catalog.snap.v10-10").join("in the way"), b"x").unwrap(); + std::fs::write(dir.join("catalog.snap"), include_str!("../../../catalog/src/fixtures/v10-catalog.snap.json")).unwrap(); + std::fs::write(dir.join("catalog.log"), include_str!("../../../catalog/src/fixtures/v10-catalog.log.jsonl")).unwrap(); + dir +} + +/// The names of the files kept for format 10 in `dir`. +fn kept_for_v10(dir: &std::path::Path, prefix: &str) -> Vec { + let mut names: Vec = std::fs::read_dir(dir) + .unwrap() + .map(|e| e.unwrap()) + .filter(|e| e.path().is_file()) + .map(|e| e.file_name().to_string_lossy().into_owned()) + .filter(|n| n.starts_with(prefix) && !n.ends_with(".tmp")) + .collect(); + names.sort(); + names +} + +/// Given a library in the one-file format that could not keep its files at open, when a later compaction upgrades +/// it (the files can be kept now), then the person is told once where the library as it was is +/// kept, as when the open upgrades it, and a later compaction tells nothing more. +#[test] +fn a_later_upgrade_says_where_what_it_was_is_kept() { + let dir = library_that_could_not_keep_its_files("kept-later"); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + assert!(s.take_library_warnings().iter().all(|w| !w.contains("upgraded")), "not upgraded at open"); + assert!(s.compact_library().is_err(), "its files can't be kept yet"); + std::fs::remove_dir_all(dir.join("catalog.snap.v10-10")).unwrap(); + s.compact_library().unwrap(); + let (snap, log) = (kept_for_v10(&dir, "catalog.snap.v10-"), kept_for_v10(&dir, "catalog.log.v10-")); + assert_eq!((snap.len(), log.len()), (1, 1), "the files as they were are kept"); + let told = s.take_library_warnings(); + assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0]) && w.contains("delete")), "{told:?}"); + let info = s.execute("library.info", &serde_json::json!({})).unwrap(); + assert!(info["settingsWarnings"].to_string().contains(&snap[0]), "{info}"); + s.compact_library().unwrap(); + assert!(s.take_library_warnings().is_empty(), "told once"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The same, when the compaction is written by the background worker: the person is told once its +/// result is taken (the frame loop's `persist`), not before. +#[test] +fn a_background_upgrade_says_where_what_it_was_is_kept() { + let dir = library_that_could_not_keep_its_files("kept-background"); + let mut s = Session::new(); + s.open_library(&dir, false).unwrap(); + let _ = s.take_library_warnings(); + std::fs::remove_dir_all(dir.join("catalog.snap.v10-10")).unwrap(); + s.compact_soon(); + let started = std::time::Instant::now(); + let mut told = Vec::new(); + while told.is_empty() && started.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(10)); + s.persist().unwrap(); + told = s.take_library_warnings(); + } + let (snap, log) = (kept_for_v10(&dir, "catalog.snap.v10-"), kept_for_v10(&dir, "catalog.log.v10-")); + assert_eq!((snap.len(), log.len()), (1, 1)); + assert!(told.iter().any(|w| w.contains(&snap[0]) && w.contains(&log[0])), "{told:?}"); + s.persist().unwrap(); + assert!(s.take_library_warnings().is_empty(), "told once"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index d071616e1d6..97e2898fd13 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -1,9 +1,16 @@ # Catalog persistence -The catalog is two files in the library folder (`crates/catalog/src/journal.rs`): `catalog.snap`, a JSON snapshot of -the whole catalog, and `catalog.log`, one JSON line per change made since. Every change is appended to the log and -fsynced before its command returns; now and then the log is compacted into a new snapshot. This page covers what a -record in those files states (catalog format 10) and what happens to a library's files when a newer version opens it. +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 (what a record states) and 11 (the photos in segments), and what happens to a +library's files when a newer version opens it. ## The stored form @@ -61,7 +68,7 @@ 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 (or, where the upgrade was left for a - later snapshot, when the library was opened; 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. + later snapshot, when the library was opened, or when changes were last saved in the old format; 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 files kept at open stay unless the library is known to be in its old format still, because the upgrade at open did not happen (then they keep nothing, and are removed again): once the upgrade is written, nothing that fails after it takes them away. The files a later snapshot keeps (below) stay too, even if that snapshot then fails and @@ -74,28 +81,87 @@ library was, byte for byte, beside it: library is refused too (its way back stays). A library in format 10 or later, which states its defaults, opens as it is (if it lacks a setting this version has, records are written whole until the snapshot that upgrades it, which keeps its files first): a later snapshot, during - the session or when it is closed, upgrades it, keeps the files first and is not written when they can't be kept, and - the next open tries again. The files that snapshot keeps are the library as it was when it opened (the snapshot, and - the log up to where it ended then): what was changed since is in the files that replace them, not in the kept ones. - When a snapshot during the session does that, LightCraft tells where the files are kept, as it does at open (a - snapshot when the library is closed, or switched away from in Settings, has no one left to tell: the files are in the - folder, named as above). Until then, changes go on being appended to the library as it is, so that they can be saved - at all where there is no room for a copy of its files. (If the session ends without that snapshot, the next open keeps - the log as it is then, which holds those changes, and tells so; the files kept earlier stay beside it.) + the session or when it is closed, upgrades it, keeps the files first and is not written when they can't be kept (a + change that could not be appended to the log is still saved when the upgrade can't be done, whether the files can't + be kept or the new snapshot can't be written: in the format on disk, in one file, so nothing is lost and nothing is + upgraded without its way back; the files kept before then go, since they are not the way back from what is on disk + now), and the next open tries again. The files that snapshot keeps are the library as it was when it opened (the + snapshot, and the log up to where it ended then; where changes were saved in the old format meanwhile, that + one-file snapshot, with no log): what was changed since is in the files that replace them, not in the kept ones. A snapshot that fails and is tried again keeps them once. When a snapshot during the session does + that, LightCraft tells where the files are kept, as it does at open (a snapshot when the library is closed, or + switched away from in Settings, has no one left to tell: the files are in the folder, named as above). Until then, + changes go on being appended to the library as it is, so that they can be saved at all where there is no room for a + copy of its files. (If the session ends without that snapshot, the next open keeps the log as it is then, which + holds those changes, and tells so; the files kept earlier stay beside it.) - 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. If the snapshot can't be kept, the library is refused and left as it was; if the damaged log can't be replaced after the upgrade was written, it is refused too, and its way back (the kept snapshot and `catalog.log.damaged-`) stays (changes made in it would be appended after the damage, where the next open would not read them). -- Nothing removes the kept files. They are as large as the library was; LightCraft says so once when it has upgraded +- Once the upgrade is written, 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` and `catalog.log` away, then rename each kept file that exists -to `catalog.snap` and `catalog.log` (a library that had no log, or only a log, kept only the one file: rename only that -one, and leave the other name unused). Where the log was damaged, the kept log is `catalog.log.damaged-`: it takes -the place of `catalog.log` like any kept log (the older version reads it up to the damage and handles it as it did -before), beside the kept snapshot when there is one. The older version opens the library as it was when it was upgraded (where the upgrade came -from a later snapshot: as it was when it was opened, so the changes made between that and the upgrade are not carried -back either); changes made since, in the newer version, are in the files that were moved away. +**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 (where the upgrade came from a later snapshot: as it was when it was opened, or when +changes were last saved in the old format, so the changes made between that and the upgrade are not carried back +either); changes made since, in the newer version, +are in what was moved away and are not carried back. The `segments` folder goes with them because it holds the newer library's photos: left in place +it only takes room. + +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 is the way back from a future one. + +## Segments (format 11) + +A library in a folder on disk keeps its photos in segment files (`crates/catalog/src/segments.rs`), and opening it +reads them on several threads. + +- **Size.** A segment holds up to 4096 photos (`SnapshotPolicy::segment_photos`: a setting, not part of the format, so + a library written with one size opens with another). One that grows past twice that is cut into pieces; one left + without photos is dropped. A small library is one segment. The size follows the number of photos, not the size of + their records: a library of heavily edited photos has larger segments (sizing by bytes is a later change). +- **What a compaction writes.** Every segment, each under a name no snapshot lists and 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. (Rewriting only the segments whose photos changed is a later + change.) A crash can leave segment files nothing lists; they are never read, never written over, and nothing + removes them yet. +- **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. +- **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, + a later compaction and quitting try again, keeping the files first (once, until changes are saved in the old format), see "Going back to an older + version"), + an older one is not opened. +- **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. + +## Measurements: segments (format 11) + +`cargo run --release -p lightcraft-catalog --example persist_bench -- 300000`, one run of each on an +Apple M1 Max (internal SSD) on 2026-10-25, with other builds running on the machine (a load average of 20 to 50), so read +the figures as rough. The catalog is 300,000 photos in the benchmark's default mix (90 % Local browse records of raws, +10 % library photos with an edit), 180 MB in one file. "Before" is the parent of this change, which writes that one +file; "after" writes segments. + +| | Before (one file) | After (segments) | +|---|---|---| +| Open (load the snapshot, replay the log) | 259 ms | 78 ms | +| Compaction of 2000 records, synchronous (median of 3) | 840 ms | 448 ms | +| Compaction in the background, the worker's time (3 runs) | 922 to 1,072 ms | 752 to 767 ms | +| Caller blocked by a background compaction (median) | 15.4 ms | 13.9 ms | +| Appending one change, with its fsync (median) | 4.3 ms | 4.1 ms | +| An append during a background compaction: median and p95 (3 runs) | 4.2 to 4.5 ms, 7.7 to 7.9 ms | 5.6 to 7.4 ms, 17.5 to 20.0 ms | + +Every compaction writes every segment in this change, on several threads, so a compaction of a catalog this size is +quicker than writing one file, and opening is about three times quicker. Appends made while a background compaction runs +are slower, because the segments are made durable on several threads at once while the log is. Only this one mix +and size were measured. + +**What this does not change.** The whole catalog is held in memory, as before. diff --git a/docs/web.md b/docs/web.md index bce143a6248..f6d7158a8ef 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 5ba8e08256d..82d00055a5d 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -11,10 +11,18 @@ - 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.2 kB for a photo with no metadata where it was 3.2 kB (a photo with camera metadata also stores that, as before). Edits, history steps and versions are stored as what differs from the defaults. -- Libraries are upgraded when first opened (catalog format 10) and can't be opened by earlier versions afterwards. - A library from before format 10 whose upgrade can't be written (a full disk, a folder that can't be written to) or - whose files can't be kept is not opened: LightCraft says why and leaves its catalog as it was, and it opens once - there is room. A new library that can't be created is refused in the same way. +- The catalog's photos are saved in segment files (JSON files in `segments/` beside `catalog.snap`), and opening a + library reads them on several threads: in one run, 0.08 s where it was 0.26 s for 300,000 photos (numbers: + `docs/catalog-persistence.md`). A damaged segment is named when the library is opened, and nothing is modified. 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`.) +- 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. A library from before format 10 whose upgrade can't be written (a full disk, a folder that can't be written + to) or whose files can't be kept is not opened: LightCraft says why and leaves its catalog as it was, and it opens + once there is room. A new library that can't be created is refused in the same way. A format 10 library in that case + opens as it is and is upgraded by a later save, which keeps its files first; changes that could not be logged are + saved in format 10, in one file, so that none is lost. ### Relative-date filters and smart albums follow the clock - A current view or source count using “in the last” rules now refreshes when the session clock moves into a new From 9e9e84cdaebafe723991bd8147cb26364d7d160d Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 20:41:10 -0400 Subject: [PATCH 18/61] Catalog: map the v10 catalog fixtures in ci_quick::EMBEDDED --- xtask/src/ci_quick.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/xtask/src/ci_quick.rs b/xtask/src/ci_quick.rs index 450f0b2f082..f683411ec89 100644 --- a/xtask/src/ci_quick.rs +++ b/xtask/src/ci_quick.rs @@ -46,6 +46,8 @@ const EMBEDDED: &[(&str, &[&str])] = &[ ("crates/ui-egui/src/menus/", &["xtask"]), ("crates/catalog/src/fixtures/v6-catalog.snap.json", &["lightcraft-engine"]), ("crates/catalog/src/fixtures/v6-catalog.log.jsonl", &["lightcraft-engine"]), + ("crates/catalog/src/fixtures/v10-catalog.snap.json", &["lightcraft-engine"]), + ("crates/catalog/src/fixtures/v10-catalog.log.jsonl", &["lightcraft-engine"]), ]; /// The packages that compile in `path` from outside their own directory. From d88a313aef8416db8227a1d7f8c43f7314f05c9b Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Mon, 26 Oct 2026 11:36:49 -0400 Subject: [PATCH 19/61] Catalog: the put-off upgrade's tests, from #2958, run on format 11's one-file store Moved from #2958 (ae75897435, catalog-snapshot-scale-p4c), whose own change had become only these tests after #2867. `tests_upgrade_attempts.rs` is the file as it was there, with the same `mod` line in `journal.rs`, and its opening comment no longer says that no format can be put off (a format 10 library can be on this build). Ten tests that set up a put-off upgrade's state by hand (the library as it was at open, behind) and check that it keeps one pair of files however many attempts fail, writes them once, tells them once the snapshot that works is written, and takes a snapshot that landed all the same as the upgrade done. The store they use is one file, as the browser's is: they don't cover the segments of format 11. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/journal.rs | 4 + crates/catalog/src/tests_upgrade_attempts.rs | 308 +++++++++++++++++++ 2 files changed, 312 insertions(+) create mode 100644 crates/catalog/src/tests_upgrade_attempts.rs diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 6e0f70d49ba..4fc6879cb83 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -1462,3 +1462,7 @@ mod tests_resync { assert_eq!(resync(&line, 100).map(|(at, (seq, _))| (at, seq)), Some((fragment, 5))); } } + +#[cfg(test)] +#[path = "tests_upgrade_attempts.rs"] +mod tests_upgrade_attempts; diff --git a/crates/catalog/src/tests_upgrade_attempts.rs b/crates/catalog/src/tests_upgrade_attempts.rs new file mode 100644 index 00000000000..ba0183bf92a --- /dev/null +++ b/crates/catalog/src/tests_upgrade_attempts.rs @@ -0,0 +1,308 @@ +//! The files a put-off upgrade keeps ([`Journal::keep_before_upgrade`]): one pair, the library as +//! it was at open, kept once however many attempts fail, and told once the one that works is +//! written. A child of `journal` because it sets the private `behind` (a library whose upgrade +//! was put off at open) by hand, so each failure of the attempts can be made at will. The store +//! here is a one-file store (it doesn't take the segments of format 11). + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use super::*; +use crate::store::MemStore; +use crate::{Photo, Source}; + +/// A store whose write of `catalog.snap` fails while `fail` is set (also through the background +/// writer) and, with `fail_log`, whose write of `catalog.log` does. +#[derive(Clone, Default)] +struct Failing { + files: MemStore, + fail: Arc, + fail_log: Arc, + /// A write of `catalog.snap` takes effect and is then said to have failed. + fail_after: Arc, + /// A write of `catalog.snap` panics: before it takes effect, or (`panic_after`) after. + panic_before: Arc, + panic_after: Arc, + /// The next read of `catalog.snap` fails (a disk that stumbles). + blind: Arc, + /// How many files were written under a kept name (`….v-`). + kept_writes: Arc, +} + +impl Store for Failing { + fn read(&mut self, name: &str) -> std::io::Result>> { + if name == SNAPSHOT && self.blind.swap(false, Ordering::SeqCst) { + 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.contains(".v") { + self.kept_writes.fetch_add(1, Ordering::SeqCst); + } + if (name == SNAPSHOT && self.fail.load(Ordering::SeqCst)) || (name == LOG && self.fail_log.load(Ordering::SeqCst)) { + return Err(std::io::Error::other("disk full")); + } + if name == SNAPSHOT && self.panic_before.load(Ordering::SeqCst) { + panic!("the snapshot worker died"); + } + self.files.write_atomic(name, data)?; + if name == SNAPSHOT && self.panic_after.load(Ordering::SeqCst) { + panic!("the snapshot worker died"); + } + if name == SNAPSHOT && self.fail_after.load(Ordering::SeqCst) { + 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 describe(&self) -> String { + "failing".into() + } + fn background_writer(&self) -> Option> { + self.files.background.then(|| Box::new(self.clone()) as Box) + } +} + +/// A library with a log, whose snapshot on disk states an older format (`from`), and a journal +/// that is behind it, as an open that put the upgrade off leaves it. The snapshot and the log at +/// that point are returned: they are what the files kept for the upgrade must hold. +fn put_off(background: bool) -> (Failing, Journal, Catalog, u32, (Vec, Vec)) { + let from = VERSION - 1; + let files = MemStore { background, ..MemStore::new() }; + let store = Failing { files: files.clone(), ..Default::default() }; + let (mut j, mut c, _) = Journal::open(Box::new(store.clone())).unwrap(); + add_photo(&mut j, &mut c); + let snap = String::from_utf8(files.get(SNAPSHOT).unwrap()).unwrap(); + files.set(SNAPSHOT, snap.replacen(&format!("\"version\":{VERSION},"), &format!("\"version\":{from},"), 1).into_bytes()); + j.behind = Some(from); + j.behind_at = (j.seq, j.log_bytes); + store.fail.store(true, Ordering::SeqCst); + let at_open = (files.get(SNAPSHOT).unwrap(), files.get(LOG).unwrap()); + (store, j, c, from, at_open) +} + +fn add_photo(j: &mut Journal, c: &mut Catalog) { + let id = c.alloc_photo_id(); + let photo = Photo::new(id, Source::File { path: format!("/pictures/IMG_{:06}.jpg", id.0) }, "IMG.jpg", "JPEG", 4032, 3024, "2026-10-10T12:00:00"); + let op = Op::AddPhoto { photo: Box::new(photo) }; + c.apply(op.clone()).unwrap(); + j.append(&[op]).unwrap(); +} + +/// The files kept for the upgrade (`….v-`), by name. +fn kept(m: &MemStore) -> Vec { + m.files.lock().unwrap().keys().filter(|k| k.contains(".v")).cloned().collect() +} + +/// The names the open would have kept the library under. +fn kept_names(from: u32, seq: u64) -> Vec { + let mut names = vec![format!("{LOG}.v{from}-{seq}"), format!("{SNAPSHOT}.v{from}-{seq}")]; + names.sort(); + names +} + +fn sorted(mut names: Vec) -> Vec { + names.sort(); + names +} + +fn attempt(j: &mut Journal, c: &Catalog, background: bool) -> Result<()> { + if background { j.snapshot_in_background(c).and_then(|()| j.wait()) } else { j.snapshot(c) } +} + +/// Given a library whose upgrade was put off and a disk that can't take the snapshot, when +/// compaction is tried again and again with changes in between, then one pair of files is kept, +/// as the open would have named it, and written once: tries that fail don't pile copies up on a +/// disk that is already full, and none of them is told as written. +#[test] +fn failed_attempts_keep_one_pair() { + for background in [false, true] { + let (store, mut j, mut c, from, at_open) = put_off(background); + let names = kept_names(from, j.behind_at.0); + for _ in 0..3 { + add_photo(&mut j, &mut c); + assert!(attempt(&mut j, &c, background).is_err(), "background: {background}"); + assert_eq!(kept(&store.files), names, "background: {background}"); + assert!(j.take_kept().is_empty(), "nothing is written yet to tell"); + } + assert_eq!(store.kept_writes.load(Ordering::SeqCst), 2, "the snapshot and the log, once"); + assert_eq!((store.files.get(&names[1]), j.behind), (Some(at_open.0), Some(from)), "background: {background}"); + } +} + +/// Given a library put off and changed since it was opened, when a later attempt works, then the +/// files kept are the library as it was at open (not the log as it is now), it is upgraded, and +/// the files are told once. +#[test] +fn a_later_attempt_upgrades_and_tells_what_it_kept() { + for background in [false, true] { + let (store, mut j, mut c, from, at_open) = put_off(background); + let names = kept_names(from, j.behind_at.0); + add_photo(&mut j, &mut c); + assert!(attempt(&mut j, &c, background).is_err()); + assert!(j.take_kept().is_empty()); + store.fail.store(false, Ordering::SeqCst); + add_photo(&mut j, &mut c); + assert!(store.files.get(LOG).unwrap().len() > at_open.1.len(), "the log has grown"); + attempt(&mut j, &c, background).unwrap(); + assert_eq!(kept(&store.files), names, "background: {background}"); + assert_eq!((store.files.get(&names[1]), store.files.get(&names[0])), (Some(at_open.0), Some(at_open.1)), "as it was at open"); + assert_eq!(sorted(j.take_kept()), names); + assert!(j.take_kept().is_empty(), "once"); + assert_eq!((j.behind, snapshot_version_on(&store.files)), (None, u64::from(VERSION)), "background: {background}"); + } +} + +fn snapshot_version_on(m: &MemStore) -> u64 { + serde_json::from_slice::(&m.get(SNAPSHOT).unwrap()).unwrap()["version"].as_u64().unwrap() +} + +/// Given an attempt whose snapshot takes effect but is reported as failed (the folder could not +/// be synced) after its files were kept, when it is tried again, then it works, and the files told +/// are the old library, not the snapshot that landed. Also where the attempt was a background one +/// that nobody waited for (the journal is dropped): the kept files stay. +#[test] +fn an_attempt_that_took_effect_all_the_same_is_tried_again() { + for how in ["sync", "background", "dropped"] { + let (store, mut j, mut c, from, at_open) = put_off(how != "sync"); + store.fail.store(false, Ordering::SeqCst); + store.fail_after.store(true, Ordering::SeqCst); + add_photo(&mut j, &mut c); + let names = kept_names(from, j.behind_at.0); + match how { + "sync" => assert!(j.snapshot(&c).is_err(), "{how}"), + "background" => assert!(j.snapshot_in_background(&c).and_then(|()| j.wait()).is_err(), "{how}"), + _ => j.snapshot_in_background(&c).unwrap(), + } + if how == "dropped" { + let files = store.files.clone(); + drop(j); + assert_eq!((kept(&files), files.get(&names[1])), (names, Some(at_open.0)), "{how}"); + continue; + } + assert_eq!(snapshot_version_on(&store.files), u64::from(VERSION), "{how}: it did land"); + store.fail_after.store(false, Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!(sorted(j.take_kept()), names, "{how}"); + assert_eq!((store.files.get(&names[1]), j.behind), (Some(at_open.0), None), "{how}: the old library, not the snapshot that landed"); + assert_eq!(store.kept_writes.load(Ordering::SeqCst), 2, "{how}: not written again"); + } +} + +/// Given a library put off whose snapshot is in this build's format already (a write that landed +/// and reported a failure before anything was kept), when snapshots are written, then each of +/// them works: the upgrade is done, with nothing to keep or tell. +#[test] +fn a_snapshot_that_landed_is_the_upgrade_done() { + let (store, mut j, c, from, _) = put_off(false); + store.fail.store(false, Ordering::SeqCst); + let snap = String::from_utf8(store.files.get(SNAPSHOT).unwrap()).unwrap(); + store.files.set(SNAPSHOT, snap.replacen(&format!("\"version\":{from},"), &format!("\"version\":{VERSION},"), 1).into_bytes()); + j.snapshot(&c).unwrap(); + j.snapshot(&c).unwrap(); + assert_eq!((kept(&store.files), j.take_kept(), j.behind), (Vec::::new(), Vec::::new(), None)); +} + +/// Given a library put off whose snapshot is in some other format than the one it was put off +/// in or this build's, when a snapshot is written, then it is refused and nothing is kept: what +/// the files would keep is not the library it was. +#[test] +fn a_snapshot_in_another_format_is_not_kept() { + let (store, mut j, c, from, _) = put_off(false); + store.fail.store(false, Ordering::SeqCst); + let snap = String::from_utf8(store.files.get(SNAPSHOT).unwrap()).unwrap(); + let other = snap.replacen(&format!("\"version\":{from},"), "\"version\":3,", 1); + store.files.set(SNAPSHOT, other.clone().into_bytes()); + assert!(j.snapshot(&c).is_err()); + assert_eq!((kept(&store.files), store.files.get(SNAPSHOT), j.behind), (Vec::::new(), Some(other.into_bytes()), Some(from))); +} + +/// Given an attempt whose worker dies (a panic) before its snapshot takes effect, when the +/// journal is waited for and the next attempt works, then the files kept for the first one are +/// the ones told: they are not written again. +#[test] +fn a_worker_that_dies_keeps_the_files_for_the_next_attempt() { + let (store, mut j, mut c, from, at_open) = put_off(true); + let names = kept_names(from, j.behind_at.0); + store.fail.store(false, Ordering::SeqCst); + store.panic_before.store(true, Ordering::SeqCst); + add_photo(&mut j, &mut c); + j.snapshot_in_background(&c).unwrap(); + assert!(j.wait().is_err()); + assert_eq!((kept(&store.files), j.behind), (names.clone(), Some(from))); + store.panic_before.store(false, Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!((sorted(j.take_kept()), store.files.get(&names[1]), j.behind), (names, Some(at_open.0), None)); + assert_eq!(store.kept_writes.load(Ordering::SeqCst), 2, "written once"); +} + +/// Given a store that has no background writer (the compaction is written synchronously), when a +/// background compaction is asked for, then the old files are kept once, not once by the request +/// and again by the synchronous write it falls back to. +#[test] +fn a_background_request_without_a_writer_keeps_the_files_once() { + let (store, mut j, mut c, _, _) = put_off(false); + store.fail.store(false, Ordering::SeqCst); + add_photo(&mut j, &mut c); + j.snapshot_in_background(&c).unwrap(); + assert_eq!(store.kept_writes.load(Ordering::SeqCst), 2, "the snapshot and the log, once"); +} + +/// Given a put-off library whose snapshot is written but whose log then can't be emptied, when +/// that fails, then the upgrade is done all the same: the library is no longer behind, the files +/// kept stay and are told, and nothing keeps the new format over them. +#[test] +fn an_upgrade_whose_log_cannot_be_emptied_is_done_and_tells() { + let (store, mut j, mut c, from, at_open) = put_off(false); + let names = kept_names(from, j.behind_at.0); + store.fail.store(false, Ordering::SeqCst); + store.fail_log.store(true, Ordering::SeqCst); + add_photo(&mut j, &mut c); + assert!(j.snapshot(&c).is_err(), "the log could not be emptied"); + assert_eq!((snapshot_version_on(&store.files), j.behind), (u64::from(VERSION), None)); + assert_eq!((sorted(j.take_kept()), kept(&store.files), store.files.get(&names[1])), (names.clone(), names.clone(), Some(at_open.0))); + store.fail_log.store(false, Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!((kept(&store.files), store.kept_writes.load(Ordering::SeqCst)), (names, 2), "nothing kept again"); +} + +/// Given a worker that dies after its snapshot took effect, when the next snapshot comes, then +/// it works, and the files told are the old library, written once. +#[test] +fn a_worker_that_dies_after_its_commit_leaves_the_way_back_as_it_was() { + let (store, mut j, mut c, from, at_open) = put_off(true); + let names = kept_names(from, j.behind_at.0); + store.fail.store(false, Ordering::SeqCst); + store.panic_after.store(true, Ordering::SeqCst); + add_photo(&mut j, &mut c); + j.snapshot_in_background(&c).unwrap(); + assert!(j.wait().is_err()); + store.panic_after.store(false, Ordering::SeqCst); + j.snapshot(&c).unwrap(); + assert_eq!((sorted(j.take_kept()), store.files.get(&names[1]), j.behind), (names, Some(at_open.0), None)); + assert_eq!(store.kept_writes.load(Ordering::SeqCst), 2, "written once"); +} + +/// Given a put-off library whose snapshot can't be read when the files are to be kept (a disk that +/// stumbles), when a snapshot is written, then it is refused and nothing is kept or changed; the +/// next one keeps the files and upgrades. +#[test] +fn a_disk_that_cannot_be_read_keeps_nothing_and_is_tried_again() { + let (store, mut j, c, from, at_open) = put_off(false); + let names = kept_names(from, j.behind_at.0); + store.fail.store(false, Ordering::SeqCst); + store.blind.store(true, Ordering::SeqCst); + assert!(j.snapshot(&c).is_err(), "the read that fails"); + assert_eq!((kept(&store.files), store.files.get(SNAPSHOT), j.behind), (Vec::::new(), Some(at_open.0.clone()), Some(from))); + j.snapshot(&c).unwrap(); + assert_eq!((sorted(j.take_kept()), store.files.get(&names[1]), j.behind), (names, Some(at_open.0), None)); +} From 038f346360203e8657ff110b848b807b9c894dd9 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 13:59:40 -0400 Subject: [PATCH 20/61] Catalog: segment files nothing lists are removed when the library is opened, and segments without a snapshot are refused A crash between writing segments and committing `catalog.snap`, or between the commit and removing the files it replaced, leaves segment files nothing lists. They are never read and never written over, but they take room. `Journal::remove_unlisted_segments` removes them, and the engine calls it only when it holds the library's lock (to anyone else, the segments another program is writing for its next snapshot look the same). It goes by `catalog.snap` as it is on disk together with what the journal takes it to list (they differ after a snapshot whose outcome it never learned), removes nothing when that file can't be read, only ever removes segment files, and leaves them all alone for as long as the journal is open when the library was opened from a one-file `catalog.snap`: an older one put back over a newer folder may be all that is left of the newer catalog. Segment files without a `catalog.snap` (a folder copied or synced in part, a `catalog.snap` that was removed) are refused instead of being opened as a new, empty library that would abandon them, unless the log holds every change from the first (a library whose first snapshot got as far as writing segments and no further). A folder whose segments can't be listed is refused as well. No file is written differently: this only removes files that no snapshot lists, and refuses more. The format stays 11. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/journal.rs | 42 ++++- crates/catalog/src/segments.rs | 8 +- crates/catalog/src/tests_segments.rs | 220 ++++++++++++++++++++++++++- crates/engine/src/library.rs | 5 + docs/catalog-persistence.md | 10 +- docs/whats-new.md | 3 + 6 files changed, 273 insertions(+), 15 deletions(-) diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 4fc6879cb83..80d6c3ea2aa 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -323,7 +323,7 @@ pub struct Journal { /// where there are no segments). inline_photos: bool, /// The snapshot read when the library was opened listed segments (see - /// [`Journal::keep_replaced`]). + /// [`Journal::remove_unlisted_segments`]). opened_with_segments: bool, log_records: u64, log_bytes: u64, @@ -632,6 +632,12 @@ 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 if the snapshot is unreadable or a newer LightCraft's (then nothing is @@ -646,6 +652,19 @@ impl Journal { let snap = store.read(SNAPSHOT).map_err(io)?; let log = store.read(LOG).map_err(io)?; report.created = snap.is_none() && log.is_none(); + // 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; @@ -1408,6 +1427,27 @@ impl Journal { &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 { self.seq } diff --git a/crates/catalog/src/segments.rs b/crates/catalog/src/segments.rs index 62dcec4aa90..4b442bae33e 100644 --- a/crates/catalog/src/segments.rs +++ b/crates/catalog/src/segments.rs @@ -28,8 +28,8 @@ //! **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 (a crash can leave some) are not -//! removed yet. +//! it, the new one with all of its. Segment files nothing lists (a crash can leave some) are +//! removed on request by an opener that holds the library's lock, and left alone otherwise. //! //! **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. @@ -41,7 +41,7 @@ //! The journal does not yet keep the baseline between snapshots, so each one writes every segment; //! writing only the ones whose photos changed comes in the next change. -#![allow(dead_code, reason = "the journal calls the rest of it (keeping the baseline, listing the folder) in the next changes")] +#![allow(dead_code, reason = "the journal calls the rest of it (keeping the baseline) in the next change")] use std::collections::BTreeMap; use std::ops::Bound; @@ -443,7 +443,7 @@ pub(crate) fn write(store: &mut dyn Store, photos: &Photos, on_disk: &OnDisk<'_> } /// Remove segment files (ones that are not, or no longer, listed). Failing to is not an error: -/// what stays is left where it is. +/// what stays is removed when an opener that holds the library's lock asks for it. pub(crate) fn discard(store: &mut dyn Store, names: &[String]) { for name in names { if valid_name(name.strip_suffix(".tmp").unwrap_or(name)) diff --git a/crates/catalog/src/tests_segments.rs b/crates/catalog/src/tests_segments.rs index 47f32182121..70bda7cc352 100644 --- a/crates/catalog/src/tests_segments.rs +++ b/crates/catalog/src/tests_segments.rs @@ -218,8 +218,8 @@ impl Store for Filmed { } /// 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 the -/// library goes on from there. +/// 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(); @@ -248,9 +248,11 @@ fn a_crash_at_any_point_of_a_compaction_loses_nothing() { frames.push(crash_copy(&store.files)); assert!(frames.len() >= 6, "{} writes", frames.len()); for (k, frame) in frames.iter().enumerate() { - let (j2, back, report) = Journal::open(Box::new(frame.clone())).unwrap(); + 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(); @@ -367,6 +369,184 @@ fn a_snapshot_with_a_bad_segment_list_is_refused() { 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 write_new_with(&mut self, name: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> std::io::Result { + self.files.write_new_with(name, fill) + } + fn sync(&mut self) -> std::io::Result<()> { + self.files.sync() + } + 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] @@ -1029,20 +1209,21 @@ fn segments_are_json_files_in_a_folder_of_their_own() { j.snapshot(&c).unwrap(); assert_eq!(names(&dir.join("segments")), ["1-13.json", "5-13.json", "9-13.json"]); drop(j); - // left by a crash, and a file that is somebody else's: opening removes none of them + // 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 (j, back, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); + let (mut j, back, _) = Journal::open(Box::new(FsStore::open(&dir).unwrap())).unwrap(); assert_same(&back, &c); - assert_eq!(names(&dir.join("segments")), ["1-13.json", "5-13.json", "77-1.json", "77-2.json.tmp", "9-13.json", "notes.txt"]); + j.remove_unlisted_segments(); + assert_eq!(names(&dir.join("segments")), ["1-13.json", "5-13.json", "9-13.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). +/// 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| { @@ -1054,6 +1235,12 @@ fn a_segments_folder_that_is_not_one_is_an_error_that_says_so() { // 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(); @@ -1065,6 +1252,7 @@ fn a_segments_folder_that_is_not_one_is_an_error_that_says_so() { #[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(); @@ -1073,11 +1261,29 @@ fn a_segments_folder_that_is_not_one_is_an_error_that_says_so() { 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); } } diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index c51b356d4b0..e145ead2953 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -495,6 +495,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 diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index 97e2898fd13..91178347b40 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -128,11 +128,15 @@ reads them on several threads. - **What a compaction writes.** Every segment, each under a name no snapshot lists and 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. (Rewriting only the segments whose photos changed is a later - change.) A crash can leave segment files nothing lists; they are never read, never written over, and nothing - removes them yet. + change.) A crash can leave segment files nothing lists. They are never read and never written over, and they are + removed when the library is next opened by a program that holds its lock (to a second program, the segments the + first is writing for its next snapshot look the same). Only segment files are ever removed: not other files in the + folder, and not the files of a one-file `catalog.snap` put back over a newer folder, which may be all there is of + the newer catalog (they go when the library, by then in segments, is next opened). - **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. + nothing is modified. Segment files without a `catalog.snap` are refused, not opened as a new library, unless the + log holds every change from the first (a library whose first snapshot never finished). - **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, diff --git a/docs/whats-new.md b/docs/whats-new.md index 82d00055a5d..ae419f1d12f 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -16,6 +16,9 @@ `docs/catalog-persistence.md`). A damaged segment is named when the library is opened, and nothing is modified. 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`.) +- Segment files that a crash left beside a library are removed the next time it is opened, and a library folder that has + segment files but no `catalog.snap` (a folder copied in part, or a `catalog.snap` that was removed) is no longer + opened as a new, empty library: LightCraft says that the snapshot is missing and changes nothing. - 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. A library from before format 10 whose upgrade can't be written (a full disk, a folder that can't be written From 870cdea9a67b6a39da27d885f65b3c25c7e2aa1a Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 14:15:37 -0400 Subject: [PATCH 21/61] Catalog: a compaction writes only the segments whose photos changed The journal keeps the photos as the segments on disk hold them (the baseline: shared pointers to the photos, not copies) and compares: a photo is the same as on disk while the catalog still points to the same one, and changing a photo copies it. A compaction therefore rewrites exactly the segments with a photo that was changed, added or removed, whatever did it, and nothing is worked out from the ops. The baseline is taken from the segments when a library in segments is opened, brought up to date over the stretches of ids a snapshot wrote, and handed to a background snapshot's worker and back with its result. Where nothing is known to be on disk (a one-file library being split, a snapshot thread that did not start or died, segments read over other defaults than this build's) the next snapshot writes every segment. Photos added after a full last segment start new segments, so an import leaves the others alone. A segment is now also sized by its bytes: `SnapshotPolicy::segment_bytes` (2 MB) cuts a segment with large records (edited photos with their history) into fewer photos, down to 64, by what a record takes on average in the snapshot there is. `segment_photos` stays 4096. Neither is part of the format. The module-level dead-code allowance of `segments` goes, since everything in it has a caller. The files written have the same shape as before, so the format stays 11 and nothing about compatibility changes. The compaction rule is the one that was there (2000 records or 16 MB of log); only what a compaction costs changes. 300,000 browsed raws (180 MB), one run each on an M1 Max with other builds running, measured on this commit and on its parent: a compaction of 2000 records 545 ms -> 48 ms (median of 3); after 1000 changes in one place 180.3 MB written in 421 ms -> 2.5 MB in 59 ms; after 6000 changes all over the library it writes everything either way (497 ms -> 554 ms). `persist_bench` gains those two compactions. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/examples/persist_bench.rs | 27 +- .../proptest-regressions/tests_segments.txt | 7 + crates/catalog/src/journal.rs | 141 +++++--- crates/catalog/src/lib.rs | 5 + crates/catalog/src/segments.rs | 26 +- crates/catalog/src/tests_segments.rs | 336 +++++++++++++++++- docs/catalog-persistence.md | 122 +++++-- docs/whats-new.md | 3 + 8 files changed, 556 insertions(+), 111 deletions(-) create mode 100644 crates/catalog/proptest-regressions/tests_segments.txt diff --git a/crates/catalog/examples/persist_bench.rs b/crates/catalog/examples/persist_bench.rs index 1fc05588c66..68f54be4b37 100644 --- a/crates/catalog/examples/persist_bench.rs +++ b/crates/catalog/examples/persist_bench.rs @@ -87,8 +87,7 @@ fn main() -> std::result::Result<(), Box> { j.append(&ops)?; } 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); + println!("== {n} photos ({} local): snapshot {:.1} MB", cat.photos().filter(|p| p.local).count(), j.snapshot_bytes() as f64 / 1e6); let t = Instant::now(); let copy = cat.clone(); @@ -158,6 +157,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 +194,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 +206,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(), 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/journal.rs b/crates/catalog/src/journal.rs index 80d6c3ea2aa..79c17c284fa 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -95,7 +95,7 @@ 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"; @@ -166,14 +166,23 @@ const fn newest(formats: &[Format]) -> u32 { pub struct SnapshotPolicy { pub max_records: u64, pub max_bytes: u64, - /// Photos per segment (see [`crate::segments`]): a segment is written in pieces of this many - /// once it holds more than twice as many. + /// 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, } impl Default for SnapshotPolicy { fn default() -> Self { - SnapshotPolicy { max_records: 2000, max_bytes: 16 << 20, segment_photos: 4096 } + SnapshotPolicy { + max_records: 2000, + max_bytes: 16 << 20, + // (measured: docs/catalog-persistence.md, "Segment size") + segment_photos: 4096, + segment_bytes: 2 << 20, + } } } @@ -260,8 +269,8 @@ pub struct PersistStats { #[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct SnapshotTiming { - /// Writing the segments (serialised, fsynced and, when a one-file library is split, read - /// back). + /// Writing the segments that changed (serialised, fsynced and, when a one-file library is + /// split, read back). pub serialize_ms: f64, /// Writing `catalog.snap` (serialised, `sync_all`, the atomic rename) and removing the /// segment files it no longer lists. @@ -275,7 +284,7 @@ pub struct SnapshotTiming { pub blocking_ms: f64, /// Written by a worker thread. pub background: bool, - /// Bytes written: `catalog.snap` and the segments. + /// Bytes written: `catalog.snap` and the segments that changed. pub bytes: u64, /// Segments written. pub segments: u64, @@ -317,8 +326,10 @@ pub struct Journal { /// and, once that snapshot is, the names for [`Journal::take_kept`]. kept_pending: Option>, kept_written: Vec, + 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, @@ -358,7 +369,7 @@ struct Pending { start_ms: f64, /// 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>, + worker: std::thread::JoinHandle<(std::io::Result, Photos)>, } fn io(e: std::io::Error) -> CatalogError { @@ -455,6 +466,7 @@ struct Job<'a> { 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. @@ -470,9 +482,11 @@ struct Saved { 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)>, } -/// Write the snapshot of `job`: every segment, then `catalog.snap`, which +/// 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. @@ -480,22 +494,24 @@ fn write_snapshot(store: &mut dyn Store, job: &Job<'_>) -> std::io::Result = w.segments.iter().map(|s| s.name.clone()).collect(); + if !segments::present(store, &listed) { + 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; @@ -538,7 +554,7 @@ fn write_snapshot(store: &mut dyn Store, job: &Job<'_>) -> std::io::Result segments::discard(store, &w.obsolete), None => segments::discard(store, &job.segments.iter().map(|s| s.name.clone()).collect::>()), } - let (segments, count, bytes) = written.map_or((Vec::new(), 0, 0), |w| (w.segments, w.written, w.bytes)); + 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), @@ -546,7 +562,7 @@ fn write_snapshot(store: &mut dyn Store, job: &Job<'_>) -> std::io::Result 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) { @@ -741,8 +764,10 @@ impl Journal { kept_pending: None, kept_written: Vec::new(), header_incomplete: false, + head_bytes, opened_with_segments: !listed.is_empty(), segments: listed, + baseline, inline_photos, log_records: 0, log_bytes: 0, @@ -854,7 +879,8 @@ impl Journal { j.store .write_atomic(SNAPSHOT, empty.as_bytes()) .map_err(|e| CatalogError::Io(format!("can't write the new library's {SNAPSHOT}: {e}")))?; - j.snapshot_bytes = empty.len() as u64; + j.head_bytes = empty.len() as u64; + j.snapshot_bytes = j.head_bytes; } else if let (Some(from), false) = (older, rewritten) { // A library in a format that writes compact records and states its defaults may go on // as it is when it can't be upgraded now (the next open tries again): what is appended @@ -1151,7 +1177,14 @@ impl Journal { _ => Err(e), }; } - let job = Job { seq, catalog, segments: &self.segments, size: self.segment_size(), verify: self.inline_photos || self.segments.is_empty() }; + let job = Job { + seq, + catalog, + segments: &self.segments, + baseline: &self.baseline, + size: self.segment_size(catalog), + verify: self.inline_photos || self.segments.is_empty(), + }; let saved = match write_snapshot(self.store.as_mut(), &job) { Ok(saved) => saved, Err(e) => { @@ -1182,7 +1215,14 @@ impl Journal { // (if the library was behind) are kept self.behind = None; let mut timing = saved.timing; - self.adopt(saved); + // 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; self.upgraded_later(); @@ -1224,7 +1264,7 @@ impl Journal { }; log::warn!("catalog: can't upgrade from format v{from} ({why}): saved in that format, not upgraded"); let mut timing = saved.timing; - self.adopt(saved); + self.adopt(saved, Photos::new()); self.seq = seq; self.snapshot_seq = seq; // (a header that states this build's defaults: records are compact again) @@ -1266,16 +1306,26 @@ impl Journal { let Some(mut writer) = self.store.background_writer() else { return self.snapshot(catalog) }; let copy = catalog.clone(); let seq = self.seq; - // The worker takes the segment list with it. Nothing else writes snapshots meanwhile. + // 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 (size, verify) = (self.segment_size(), self.inline_photos || self.segments.is_empty()); + let baseline = std::mem::take(&mut self.baseline); + let (size, verify) = (self.segment_size(catalog), self.inline_photos || self.segments.is_empty()); let spawned = std::thread::Builder::new().name("catalog-snapshot".into()).spawn(move || { - let job = Job { seq, catalog: ©, segments: &listed, size, verify }; - write_snapshot(writer.as_mut(), &job) + 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); } @@ -1317,11 +1367,14 @@ 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"))); + // (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.saturating_add(self.policy.max_records); log::error!("catalog: background snapshot failed: {e}"); @@ -1337,7 +1390,7 @@ impl Journal { // 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); + self.adopt(saved, on_disk); self.snapshot_seq = p.seq; self.upgraded_later(); self.header_incomplete = false; @@ -1360,15 +1413,20 @@ impl Journal { Ok(()) } - /// How large the segments of a snapshot are to be. - fn segment_size(&self) -> segments::Size { - segments::Size { per: self.policy.segment_photos, bytes: 0, record_bytes: 0 } + /// 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) { + 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; } @@ -1470,10 +1528,11 @@ impl Drop for Journal { /// snapshot of a journal reopened on the same files). The log is left whole: the snapshot's /// 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() - { - log::error!("catalog: background snapshot failed: {e}"); + if let Some(p) = self.pending.take() { + let (written, _) = p.worker.join().unwrap_or_else(|_| (Err(std::io::Error::other("snapshot thread panicked")), Photos::new())); + if let Err(e) = written { + log::error!("catalog: background snapshot failed: {e}"); + } } } } diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index b9ef9e2b823..3f13bf3c505 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -1091,6 +1091,11 @@ impl Catalog { } } + /// 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; diff --git a/crates/catalog/src/segments.rs b/crates/catalog/src/segments.rs index 4b442bae33e..400975a42b0 100644 --- a/crates/catalog/src/segments.rs +++ b/crates/catalog/src/segments.rs @@ -36,12 +36,6 @@ //! //! **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. -//! -//! This module is the writer and reader of the segments, used by [`crate::journal`] for format 11. -//! The journal does not yet keep the baseline between snapshots, so each one writes every segment; -//! writing only the ones whose photos changed comes in the next change. - -#![allow(dead_code, reason = "the journal calls the rest of it (keeping the baseline) in the next change")] use std::collections::BTreeMap; use std::ops::Bound; @@ -123,7 +117,7 @@ enum Step { pub(crate) struct Size { /// At most this many (the journal's policy states it). pub per: usize, - /// And about this many bytes (0: any; the journal does not set it yet). + /// 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. @@ -597,14 +591,6 @@ pub(crate) fn load(store: &mut dyn Store, handles: Vec>, segments 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)) -} - #[cfg(test)] mod tests { use super::*; @@ -824,16 +810,6 @@ mod tests { assert_eq!(left, expected); } - /// Given segments by their first ids, then the segment that holds (or would hold) an id is - /// the last one that starts at or before it, the first one for ids below them all. - #[test] - fn the_segment_of_a_photo_is_the_last_that_starts_at_or_before_it() { - let seg = |first: u64| Segment { name: segment_file(&format!("{first}-1")), first: PhotoId(first), photos: 1, bytes: 1, crc: 0 }; - let list = [seg(10), seg(20), seg(30)]; - assert_eq!([5, 10, 19, 20, 99].map(|id| segment_of(&list, PhotoId(id))), [Some(0), Some(0), Some(0), Some(1), Some(2)]); - assert_eq!(segment_of(&[], PhotoId(1)), None); - } - /// A store that can't write one file. struct FailsAt { files: MemStore, diff --git a/crates/catalog/src/tests_segments.rs b/crates/catalog/src/tests_segments.rs index 70bda7cc352..0126349d2f8 100644 --- a/crates/catalog/src/tests_segments.rs +++ b/crates/catalog/src/tests_segments.rs @@ -103,24 +103,72 @@ fn photos_are_saved_in_segments_listed_by_the_snapshot() { assert_same(&reopen(&m), &c); } -/// Given a saved library, when the log is compacted, then every segment is written again under a -/// new name and the files of the snapshot before are gone (no photo is taken to be on disk as -/// it is: see the module docs of `segments`). +/// 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_writes_every_segment_and_removes_the_old_files() { +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.len(), after.len()), (3, 3)); - assert_eq!(before.intersection(&after).count(), 0, "{before:?} -> {after:?}"); - assert_eq!(j.stats().last_snapshot.segments, 3); - // the files of the snapshot before are gone + 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 in segments, when a file a compaction would keep is removed behind its +/// back (a program that had the library open without its lock), then the compaction fails +/// instead of committing a `catalog.snap` that lists a file that is gone, and the library still +/// opens as it was. +#[test] +fn a_kept_segment_that_was_removed_stops_the_compaction() { + let (m, mut j, mut c) = library(12, 4); + let snapshot = m.get(SNAPSHOT); + let kept = listed(&m).into_iter().next().unwrap(); + m.files.lock().unwrap().remove(&kept); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(6), rating: 5 }]); + assert!(j.snapshot(&c).is_err()); + assert_eq!(m.get(SNAPSHOT), snapshot); + assert_eq!(segment_files(&m).len(), 2, "only the segments that were there stay"); +} + +/// 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() { @@ -159,6 +207,13 @@ fn widely_spaced_ids_fill_segments_like_any_others() { 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); } @@ -270,16 +325,18 @@ fn a_background_compaction_writes_segments_and_keeps_later_changes() { 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 writes the changes made meanwhile + // the next compaction rewrites the segments of what changed meanwhile j.snapshot(&c).unwrap(); - assert_eq!(j.stats().last_snapshot.segments, 3); + assert_eq!(j.stats().last_snapshot.segments, 2); assert_eq!(segment_files(&m), listed(&m)); assert_same(&reopen(&m), &c); } @@ -572,6 +629,98 @@ fn a_segment_list_that_does_not_hold_every_photo_is_refused() { 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). @@ -1144,6 +1293,134 @@ fn a_store_without_segments_keeps_one_file() { assert_same(&reopen(&back), &c3); } +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, @@ -1183,6 +1460,41 @@ fn a_library_in_segments_with_other_defaults_reads_as_it_was_written() { } } +/// 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. @@ -1207,7 +1519,7 @@ fn segments_are_json_files_in_a_folder_of_their_own() { 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-13.json", "5-13.json", "9-13.json"]); + 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")] { @@ -1216,7 +1528,7 @@ fn segments_are_json_files_in_a_folder_of_their_own() { 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-13.json", "5-13.json", "9-13.json", "notes.txt"]); + 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); } diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index 91178347b40..9fffb2bccb4 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -118,17 +118,25 @@ too; no upgrade from such a format exists yet, and a backup is the way back from ## Segments (format 11) -A library in a folder on disk keeps its photos in segment files (`crates/catalog/src/segments.rs`), and opening it -reads them on several threads. - -- **Size.** A segment holds up to 4096 photos (`SnapshotPolicy::segment_photos`: a setting, not part of the format, so - a library written with one size opens with another). One that grows past twice that is cut into pieces; one left - without photos is dropped. A small library is one segment. The size follows the number of photos, not the size of - their records: a library of heavily edited photos has larger segments (sizing by bytes is a later change). -- **What a compaction writes.** Every segment, each under a name no snapshot lists and each fsynced, then +A compaction used to rewrite the whole catalog. A library in a folder on disk keeps its photos in segment files +(`crates/catalog/src/segments.rs`), and a compaction writes only the segments whose photos changed, 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. Where nothing is known to be on disk (a library just upgraded from one + file, a snapshot thread that did not start or died, a library read over other defaults than this build's) every + segment is written. +- **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 (`SnapshotPolicy::segment_photos`, + `segment_bytes`: settings, not part of the format, so a library written with one size opens with another; the + record size of photos in no segment yet is taken from the snapshot there is). 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 (several at once, each fsynced) under names no snapshot lists, 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. (Rewriting only the segments whose photos changed is a later - change.) A crash can leave segment files nothing lists. They are never read and never written over, and they are + at any point leaves a snapshot with all its segments. A crash can leave segment files nothing lists. They are never read and never written over, and they are removed when the library is next opened by a program that holds its lock (to a second program, the segments the first is writing for its next snapshot look the same). Only segment files are ever removed: not other files in the folder, and not the files of a one-file `catalog.snap` put back over a newer folder, which may be all there is of @@ -146,26 +154,82 @@ reads them on several threads. - **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. -## Measurements: segments (format 11) +## Measurements: only the changed segments are written (format 11) `cargo run --release -p lightcraft-catalog --example persist_bench -- 300000`, one run of each on an -Apple M1 Max (internal SSD) on 2026-10-25, with other builds running on the machine (a load average of 20 to 50), so read -the figures as rough. The catalog is 300,000 photos in the benchmark's default mix (90 % Local browse records of raws, -10 % library photos with an edit), 180 MB in one file. "Before" is the parent of this change, which writes that one -file; "after" writes segments. +Apple M1 Max (internal SSD) on 2026-10-25, with other builds running on the machine (a load average of 15 to 40), so read +the figures as rough. The catalog is the benchmark's default mix of 300,000 photos (90 % Local browse records of raws, +10 % library photos with an edit), 180 MB. "Before" is the parent of this change, which writes every segment each time; +"after" writes the ones whose photos changed. -| | Before (one file) | After (segments) | +| | Before (every segment) | After (changed segments) | |---|---|---| -| Open (load the snapshot, replay the log) | 259 ms | 78 ms | -| Compaction of 2000 records, synchronous (median of 3) | 840 ms | 448 ms | -| Compaction in the background, the worker's time (3 runs) | 922 to 1,072 ms | 752 to 767 ms | -| Caller blocked by a background compaction (median) | 15.4 ms | 13.9 ms | -| Appending one change, with its fsync (median) | 4.3 ms | 4.1 ms | -| An append during a background compaction: median and p95 (3 runs) | 4.2 to 4.5 ms, 7.7 to 7.9 ms | 5.6 to 7.4 ms, 17.5 to 20.0 ms | - -Every compaction writes every segment in this change, on several threads, so a compaction of a catalog this size is -quicker than writing one file, and opening is about three times quicker. Appends made while a background compaction runs -are slower, because the segments are made durable on several threads at once while the log is. Only this one mix -and size were measured. - -**What this does not change.** The whole catalog is held in memory, as before. +| Compaction of 2000 records (changes to one photo), synchronous (median of 3) | 545 ms | 48 ms | +| The same in the background, the worker's time (3 runs) | 785 to 929 ms | 102 to 111 ms | +| An append during a background compaction: median and p95 (3 runs) | 5.8 to 9.2 ms, 24.8 to 30.6 ms | 4.4 to 5.8 ms, 8.7 to 9.3 ms | +| Compaction after 1000 changes in one place (the first 1000 photos) | 180.3 MB written, 421 ms | 2.5 MB written, 59 ms | +| Compaction after 6000 changes all over the library (every 50th photo) | 180.3 MB written, 497 ms | 180.3 MB written, 554 ms | +| Open | 81 ms | 77 ms | +| Appending one change, with its fsync (median) | 4.2 ms | 4.1 ms | + +Changes in one place write about what the segments there hold, and the time follows. Changes that touch every segment +write all of them, as before, and the 11 % more time in the one run above is within what these runs vary by here; the +extra cost is looking through the catalog for what changed. Only this one mix and size were measured for this change. + +**What this does not change.** The whole catalog is still held in memory. + +### 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 were made on this change before it was split into parts (the same segment writer and the same +changed-segments rule), and were not repeated for the parts. They 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, which keeps what scattered changes rewrite +and what a backup after them copies small, 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/whats-new.md b/docs/whats-new.md index ae419f1d12f..176a4ec7974 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -16,6 +16,9 @@ `docs/catalog-persistence.md`). A damaged segment is named when the library is opened, and nothing is modified. 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`.) +- Saving rewrites only the segments whose photos changed: after edits in one place, 2.5 MB where it was the whole + catalog (59 ms where it was 421 ms, for 300,000 photos; one run, `docs/catalog-persistence.md`). A segment holds up to + 4096 photos and about 2 MB. - Segment files that a crash left beside a library are removed the next time it is opened, and a library folder that has segment files but no `catalog.snap` (a folder copied in part, or a `catalog.snap` that was removed) is no longer opened as a new, empty library: LightCraft says that the snapshot is missing and changes nothing. From f381d2e4f32179f88d8c5a49be961371eba526ef Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 18:18:02 -0400 Subject: [PATCH 22/61] Catalog: back up the library to a dated folder that shares unchanged files File > Back Up Library (library.backup) copies the catalog (catalog.snap, its segments, catalog.log and the presets / view / preferences files; not the photos) to a folder named after the time in Backups in the library folder, the library's backup folder (library.backupPreferences) or the one given. A backup opens as a library. A segment is never changed once written, so one of the same name, size and CRC in the backup before is the same file: it is hard-linked, not copied, once it was read and found sound. Each backup stands on its own. One million photos: 1.0 s for the first backup; 3.4 MB copied and 122 files shared after edits in one place. The backup reads the files as they are on disk (the snapshot, its segments, the log, the snapshot again; started over if it changed), so the library stays in use. Every file is checked against the size and CRC the snapshot states. It is written as .partial and renamed when whole. backup.json lists every file with its size and CRC; library.checkBackup reads a backup against it. In the app it runs in the background with a row in the activity stack and a toast at the end; the command itself returns when the backup is made. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/backup.rs | 522 ++++++++++++++++++++ crates/catalog/src/journal.rs | 2 +- crates/catalog/src/lib.rs | 3 + crates/catalog/src/segments.rs | 4 +- crates/catalog/src/tests_backup.rs | 480 ++++++++++++++++++ crates/engine/src/activity.rs | 2 +- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/backup.rs | 256 ++++++++++ crates/engine/src/lib.rs | 9 + crates/engine/src/library.rs | 5 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/backup.rs | 245 +++++++++ crates/ui-egui/locales/cs-formats.json | 2 + crates/ui-egui/locales/cs.json | 5 + crates/ui-egui/locales/de-formats.json | 2 + crates/ui-egui/locales/de.json | 5 + crates/ui-egui/locales/es-formats.json | 2 + crates/ui-egui/locales/es.json | 5 + crates/ui-egui/locales/fr-formats.json | 2 + crates/ui-egui/locales/fr.json | 5 + crates/ui-egui/locales/it-formats.json | 20 + crates/ui-egui/locales/ja-formats.json | 2 + crates/ui-egui/locales/ja.json | 5 + crates/ui-egui/locales/ka-formats.json | 2 + crates/ui-egui/locales/ka.json | 5 + crates/ui-egui/locales/pl-formats.json | 2 + crates/ui-egui/locales/pl.json | 5 + crates/ui-egui/locales/pt-br-formats.json | 2 + crates/ui-egui/locales/pt-br.json | 5 + crates/ui-egui/locales/ru-formats.json | 2 + crates/ui-egui/locales/ru.json | 5 + crates/ui-egui/locales/uk-formats.json | 2 + crates/ui-egui/locales/uk.json | 5 + crates/ui-egui/locales/zh-hans-formats.json | 2 + crates/ui-egui/locales/zh-hans.json | 5 + crates/ui-egui/locales/zh-hant-formats.json | 2 + crates/ui-egui/locales/zh-hant.json | 5 + crates/ui-egui/src/app.rs | 22 + crates/ui-egui/src/app/frame.rs | 1 + crates/ui-egui/src/menus/menubar.rs | 3 + crates/ui-egui/src/menus/menubar/tests.rs | 18 + crates/ui-egui/src/menus/run.rs | 13 +- crates/ui-egui/src/state.rs | 3 + docs/web.md | 3 +- 44 files changed, 1692 insertions(+), 6 deletions(-) create mode 100644 crates/catalog/src/backup.rs create mode 100644 crates/catalog/src/tests_backup.rs create mode 100644 crates/engine/src/cmd/backup.rs create mode 100644 crates/engine/src/tests/backup.rs diff --git a/crates/catalog/src/backup.rs b/crates/catalog/src/backup.rs new file mode 100644 index 00000000000..1b222a9168c --- /dev/null +++ b/crates/catalog/src/backup.rs @@ -0,0 +1,522 @@ +//! Backing up a library's catalog: a dated folder that opens as the library it was taken of. +//! +//! A backup holds `catalog.snap`, the segments it lists (in `segments/`, as in the library), +//! `catalog.log` and the settings files beside them (not the photos, and not the caches). It is a library folder in its own right: +//! opening it shows the catalog as it was. +//! +//! **Each backup shares with the one before it the files that didn't change.** A segment is +//! never changed once written (a snapshot writes a changed one under a new name), so a segment +//! of the same name, size and CRC in the previous backup is the same file: it is hard-linked, +//! not copied. A backup of a large library after a day's work copies a few megabytes, and every +//! backup still stands on its own: removing an older one, or the library, takes nothing from it. +//! Where the folder can't hold hard links (another volume than the last backup's, a file system +//! without them), files are copied. A file is only shared once it was read and still has its +//! CRC: damage in an older backup is not handed on to the next (it is copied afresh from the +//! library instead). +//! +//! **A backup is one moment of the library, also while the library is in use.** The files are +//! read as they are on disk, without the journal's help: `catalog.snap` first, then the segments +//! it lists, then the log, then `catalog.snap` again. If it changed meanwhile (the library was +//! compacted), the backup starts over, keeping what it already has. Everything a snapshot lists +//! is checked against the size and CRC it states before it is kept. +//! +//! **A backup says what it holds.** Its marker file, `backup.json`, lists every file with its +//! size and CRC-32 (the segments' are also in `catalog.snap`). [`check`] reads a backup against +//! that list: a file that was edited, damaged, removed or added is named. +//! +//! **Nothing half-made counts.** A backup is written as `.partial` and renamed when it is +//! whole; a backup that fails or is cancelled removes it. One cut short by the program ending +//! stays as `.partial` (never taken for a backup) and is removed by a later backup to the +//! same folder, once it is an hour old. + +use std::collections::BTreeMap; +use std::io::Write; +use std::path::{Path, PathBuf}; + +use crate::journal::{LOG, SNAPSHOT}; +use crate::segments::{self, Segment}; + +/// The file that marks a finished backup: what it is of, as JSON. +pub const MARKER: &str = "backup.json"; +/// A backup being written is `.partial`. +const PARTIAL: &str = ".partial"; +/// How often a backup starts over because the library was compacted under it. +const ATTEMPTS: usize = 8; +/// How old a `.partial` folder is before a later backup removes it. +const STALE: std::time::Duration = std::time::Duration::from_secs(3600); + +#[derive(Debug, thiserror::Error)] +pub enum BackupError { + #[error("the backup was cancelled")] + Cancelled, + #[error("{0:?} can't be the name of a backup")] + Name(String), + #[error("there is a backup named {0} already")] + Exists(String), + /// The library can't be read as one: no catalog, a damaged or missing segment. + #[error("the library can't be backed up: {0}")] + Library(String), + /// A backup that was checked is not what it was when it was made ([`check`]). + #[error("the backup is not as it was made: {0}")] + Changed(String), + #[error("the backup can't be written: {0}")] + Io(String), +} + +/// How to back up. +#[derive(Clone, Copy, Debug)] +pub struct BackupOptions<'a> { + /// The backup's folder name (the time it is made). + pub name: &'a str, + /// Other files of the library folder to copy when they are there (presets, preferences): + /// plain file names, none of them the catalog's own. + pub also: &'a [&'a str], +} + +/// A backup that was made. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct BackupReport { + pub dir: PathBuf, + /// The op the backup's snapshot is of, and the photos that snapshot holds (changes since are + /// in the backup's log, and not counted here). + pub seq: u64, + pub photos: u64, + pub segments: u64, + /// Files in the backup; how many were copied, and how many are shared with the backup before. + pub files: u64, + pub copied: u64, + pub linked: u64, + /// Their size in all, and of the ones copied. + pub bytes: u64, + pub copied_bytes: u64, + /// Every file of the backup but the marker itself, by name: its size and CRC-32. + #[serde(default)] + pub contents: BTreeMap, +} + +/// A file of a backup, as its marker lists it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct Held { + pub bytes: u64, + pub crc: u32, +} + +/// Follows a backup as it is made, and can stop it. +pub trait Watch { + /// About to back up `name`; `done` of `total` bytes are. + fn progress(&self, name: &str, done: u64, total: u64) { + let _ = (name, done, total); + } + fn cancelled(&self) -> bool { + false + } +} + +impl Watch for () {} + +fn io(what: &str, path: &Path, e: std::io::Error) -> BackupError { + BackupError::Io(format!("{what} {}: {e}", path.display())) +} + +/// Counts the entries of a map without keeping them. +struct Count(u64); + +impl<'de> serde::Deserialize<'de> for Count { + fn deserialize>(d: D) -> Result { + struct Entries; + impl<'de> serde::de::Visitor<'de> for Entries { + type Value = Count; + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("the photos of a catalog") + } + fn visit_map>(self, mut map: A) -> Result { + let mut n = 0u64; + while map.next_entry::()?.is_some() { + n = n.saturating_add(1); + } + Ok(Count(n)) + } + } + d.deserialize_map(Entries) + } +} + +#[derive(serde::Deserialize)] +struct InlinePhotos { + photos: Count, +} + +/// What a backup needs to know of a `catalog.snap`. +#[derive(serde::Deserialize)] +struct Head { + format: String, + seq: u64, + #[serde(default)] + segments: Vec, + #[serde(default)] + photos: Option, + catalog: InlinePhotos, +} + +fn read_head(bytes: &[u8]) -> Result { + let head: Head = serde_json::from_slice(bytes).map_err(|e| BackupError::Library(format!("{SNAPSHOT}: {e}")))?; + if head.format != crate::journal::FORMAT { + return Err(BackupError::Library(format!("{SNAPSHOT} is not a LightCraft catalog (format {:?})", head.format))); + } + segments::check_list(&head.segments).map_err(|e| BackupError::Library(format!("{SNAPSHOT}: {e}")))?; + Ok(head) +} + +/// A name `options.also` may hold: a plain file name that isn't one of the catalog's or the +/// marker's (those are written by the backup itself, and a segment may be shared with another +/// backup: it is never written over). +fn valid_extra(name: &str) -> bool { + valid_name(name) && name != SNAPSHOT && name != LOG && name != MARKER && name != segments::SEGMENT_DIR +} + +/// The files of the folder `dir` that a backup may hold, by the names the catalog gives them: +/// the ones in it, and the ones in its segments folder (`segments/…`). An error names anything +/// else that is in it (another folder, a link). +fn held(dir: &Path) -> Result, String> { + let mut names = Vec::new(); + let entries = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + for entry in entries { + let entry = entry.map_err(|e| e.to_string())?; + let name = entry.file_name().to_string_lossy().into_owned(); + if regular(&entry.path()) { + names.push(name); + } else if name == segments::SEGMENT_DIR && std::fs::symlink_metadata(entry.path()).is_ok_and(|m| m.is_dir()) { + for inner in std::fs::read_dir(entry.path()).map_err(|e| format!("{name}: {e}"))? { + let inner = inner.map_err(|e| e.to_string())?; + let inner_name = format!("{}{}", segments::SEGMENT_PREFIX, inner.file_name().to_string_lossy()); + if !regular(&inner.path()) { + return Err(format!("{inner_name} is not a file")); + } + names.push(inner_name); + } + } else { + return Err(format!("{name} is not a file")); + } + } + Ok(names) +} + +/// Make the folder a file of a backup goes into (the segments folder, with its first file). +fn folder_for(path: &Path) -> Result<(), BackupError> { + match path.parent() { + Some(folder) if !folder.is_dir() => std::fs::create_dir_all(folder).map_err(|e| io("can't make the folder", folder, e)), + _ => Ok(()), + } +} + +fn valid_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 200 + && name != "." + && name != ".." + && !name.ends_with(PARTIAL) + && !name.chars().any(|c| c.is_control() || matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|')) +} + +/// A file's bytes; `None` when there is no such file. +fn read(path: &Path) -> Result>, BackupError> { + match std::fs::read(path) { + Ok(b) => Ok(Some(b)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(BackupError::Library(format!("{}: {e}", path.display()))), + } +} + +/// Write a new file and make it durable. Never over one that is there: a file of a backup may +/// be shared with another backup. +fn write(path: &Path, bytes: &[u8]) -> Result<(), BackupError> { + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(path).map_err(|e| io("can't create", path, e))?; + f.write_all(bytes).and_then(|()| f.sync_all()).map_err(|e| io("can't write", path, e)) +} + +fn sync_dir(dir: &Path) { + // (makes the names in it durable; a folder can't be opened on Windows, where renames are journaled) + if let Ok(d) = std::fs::File::open(dir) { + let _ = d.sync_all(); + } +} + +/// A regular file (not a link to one elsewhere). +fn regular(path: &Path) -> bool { + std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file()) +} + +/// The newest finished backup in `dest` (by when its marker was written, then by name), and the +/// segments its snapshot lists by name. +fn previous(dest: &Path) -> Option<(PathBuf, BTreeMap)> { + let mut found: Vec<(std::time::SystemTime, String)> = std::fs::read_dir(dest) + .ok()? + .filter_map(|e| e.ok()?.file_name().into_string().ok()) + .filter(|name| !name.ends_with(PARTIAL) && regular(&dest.join(name).join(MARKER))) + .map(|name| (std::fs::metadata(dest.join(&name).join(MARKER)).and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH), name)) + .collect(); + found.sort_unstable(); + found.into_iter().rev().find_map(|(_, name)| { + let dir = dest.join(&name); + let head = read_head(&std::fs::read(dir.join(SNAPSHOT)).ok()?).ok()?; + Some((dir, head.segments.into_iter().map(|s| (s.name.clone(), s)).collect())) + }) +} + +/// Remove what a backup that was cut short left in `dest`: folders `.partial` an hour old +/// or more (one being written now, by this or another program, is younger) that hold nothing +/// but what a backup holds. Anything else of that name is left alone. +fn sweep(dest: &Path, also: &[&str]) { + let Ok(entries) = std::fs::read_dir(dest) else { return }; + for entry in entries.flatten() { + let (Ok(name), path) = (entry.file_name().into_string(), entry.path()) else { continue }; + let old = std::fs::symlink_metadata(&path).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age >= STALE); + if !name.ends_with(PARTIAL) || !old || !std::fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir()) { + continue; + } + let ours = held(&path).is_ok_and(|names| { + names.iter().all(|n| n == SNAPSHOT || n == LOG || n == MARKER || also.contains(&n.as_str()) || segments::valid_name(n)) + }); + if ours && let Err(e) = std::fs::remove_dir_all(&path) { + log::warn!("backup: can't remove {}: {e}", path.display()); + } + } +} + +fn is(bytes: &[u8], segment: &Segment) -> bool { + bytes.len() as u64 == segment.bytes && crc32fast::hash(bytes) == segment.crc +} + +/// What one pass over the library's files came to. +enum Pass { + Done(BackupReport), + /// `catalog.snap` changed while its files were read: start over. + Again, +} + +struct Job<'a> { + library: &'a Path, + partial: &'a Path, + options: &'a BackupOptions<'a>, + watch: &'a dyn Watch, + previous: Option<&'a (PathBuf, BTreeMap)>, + /// Segment files in `partial` already: each as it is listed, and whether it is shared with + /// the backup before. + have: BTreeMap, +} + +impl Job<'_> { + /// Whether the library's `catalog.snap` is no longer `seen`. + fn changed(&self, seen: &[u8]) -> Result { + Ok(read(&self.library.join(SNAPSHOT))?.as_deref() != Some(seen)) + } + + fn pass(&mut self) -> Result { + let snapshot = read(&self.library.join(SNAPSHOT))? + .ok_or_else(|| BackupError::Library(format!("there is no {SNAPSHOT} in {}", self.library.display())))?; + let head = read_head(&snapshot)?; + // (sizes a snapshot states are not to be trusted: no sum of them may overflow) + let total = head.segments.iter().fold(snapshot.len() as u64, |sum, s| sum.saturating_add(s.bytes)); + let mut done = 0u64; + for segment in &head.segments { + if self.watch.cancelled() { + return Err(BackupError::Cancelled); + } + self.watch.progress(&segment.name, done, total); + done = done.saturating_add(segment.bytes); + let listed = Held { bytes: segment.bytes, crc: segment.crc }; + let to = self.partial.join(&segment.name); + folder_for(&to)?; + match self.have.get(&segment.name) { + Some((held, _)) if *held == listed => continue, + // (a file of that name from an earlier pass that isn't this one) + Some(_) => { + std::fs::remove_file(&to).map_err(|e| io("can't remove", &to, e))?; + self.have.remove(&segment.name); + } + None => {} + } + // the same file as in the backup before: shared with it, once it was read and is + // what it should be (damage in an older backup is not handed on) + if let Some((dir, before)) = self.previous + && before.get(&segment.name).is_some_and(|p| p.bytes == segment.bytes && p.crc == segment.crc) + { + let from = dir.join(&segment.name); + if regular(&from) && std::fs::read(&from).is_ok_and(|b| is(&b, segment)) && std::fs::hard_link(&from, &to).is_ok() { + self.have.insert(segment.name.clone(), (listed, true)); + continue; + } + } + let bytes = match read(&self.library.join(&segment.name))? { + Some(bytes) if is(&bytes, segment) => bytes, + // gone or different: because the library was compacted meanwhile, or damaged + found => { + if self.changed(&snapshot)? { + return Ok(Pass::Again); + } + let what = if found.is_some() { "is damaged" } else { "is missing" }; + return Err(BackupError::Library(format!("{} {what}", segment.name))); + } + }; + write(&to, &bytes)?; + self.have.insert(segment.name.clone(), (listed, false)); + } + self.watch.progress(LOG, done, total); + // the log after the segments, and then the snapshot once more: if it is still the one + // read first, the log is the one that goes with it + let log = read(&self.library.join(LOG))?; + if self.changed(&snapshot)? { + return Ok(Pass::Again); + } + if self.watch.cancelled() { + return Err(BackupError::Cancelled); + } + // what an earlier pass copied and this snapshot doesn't list + let listed: std::collections::BTreeSet<&str> = head.segments.iter().map(|s| s.name.as_str()).collect(); + let stale: Vec = self.have.keys().filter(|n| !listed.contains(n.as_str())).cloned().collect(); + for name in stale { + let path = self.partial.join(&name); + std::fs::remove_file(&path).map_err(|e| io("can't remove", &path, e))?; + self.have.remove(&name); + } + let mut report = BackupReport { + dir: PathBuf::new(), + seq: head.seq, + photos: head.photos.unwrap_or(head.catalog.photos.0), + segments: head.segments.len() as u64, + files: head.segments.len() as u64 + 1, + copied: 1, + linked: 0, + bytes: total, + copied_bytes: snapshot.len() as u64, + contents: BTreeMap::new(), + }; + report.contents.insert(SNAPSHOT.to_string(), Held { bytes: snapshot.len() as u64, crc: crc32fast::hash(&snapshot) }); + for segment in &head.segments { + report.contents.insert(segment.name.clone(), Held { bytes: segment.bytes, crc: segment.crc }); + match self.have.get(&segment.name) { + Some((_, true)) => report.linked += 1, + _ => { + report.copied += 1; + report.copied_bytes = report.copied_bytes.saturating_add(segment.bytes); + } + } + } + let mut small: Vec<(&str, Vec)> = Vec::new(); + if let Some(log) = log { + small.push((LOG, log)); + } + for name in self.options.also { + if let Some(bytes) = read(&self.library.join(name))? { + small.push((name, bytes)); + } + } + for (name, bytes) in &small { + report.contents.insert(name.to_string(), Held { bytes: bytes.len() as u64, crc: crc32fast::hash(bytes) }); + write(&self.partial.join(name), bytes)?; + report.files += 1; + report.copied += 1; + report.bytes = report.bytes.saturating_add(bytes.len() as u64); + report.copied_bytes = report.copied_bytes.saturating_add(bytes.len() as u64); + } + // the snapshot last: a folder with it has everything it lists + write(&self.partial.join(SNAPSHOT), &snapshot)?; + Ok(Pass::Done(report)) + } +} + +/// Back up the library in `library` as the folder `options.name` in `dest` (made if it isn't +/// there). See the module docs. +pub fn back_up(library: &Path, dest: &Path, options: &BackupOptions<'_>, watch: &dyn Watch) -> Result { + if !valid_name(options.name) { + return Err(BackupError::Name(options.name.to_string())); + } + if let Some(bad) = options.also.iter().find(|n| !valid_extra(n)) { + return Err(BackupError::Name(bad.to_string())); + } + if !library.join(SNAPSHOT).is_file() { + return Err(BackupError::Library(format!("there is no {SNAPSHOT} in {}", library.display()))); + } + std::fs::create_dir_all(dest).map_err(|e| io("can't make the folder", dest, e))?; + let dir = dest.join(options.name); + let partial = dest.join(format!("{}{PARTIAL}", options.name)); + if dir.exists() || partial.exists() { + return Err(BackupError::Exists(options.name.to_string())); + } + sweep(dest, options.also); + let previous = previous(dest); + std::fs::create_dir(&partial).map_err(|e| io("can't make the folder", &partial, e))?; + // (this run made the folder: nothing of a backup that isn't whole is left, also if what + // follows should panic) + struct Unfinished<'a>(Option<&'a Path>); + impl Drop for Unfinished<'_> { + fn drop(&mut self) { + if let Some(partial) = self.0 + && let Err(e) = std::fs::remove_dir_all(partial) + { + log::warn!("backup: can't remove {}: {e}", partial.display()); + } + } + } + let mut unfinished = Unfinished(Some(&partial)); + let mut job = Job { library, partial: &partial, options, watch, previous: previous.as_ref(), have: BTreeMap::new() }; + let made = (|| { + for _ in 0..ATTEMPTS { + if let Pass::Done(mut report) = job.pass()? { + report.dir = dir.clone(); + let marker = serde_json::to_vec_pretty(&report).map_err(|e| BackupError::Io(e.to_string()))?; + write(&partial.join(MARKER), &marker)?; + sync_dir(&partial.join(segments::SEGMENT_DIR)); + sync_dir(&partial); + std::fs::rename(&partial, &dir).map_err(|e| io("can't name the backup", &dir, e))?; + sync_dir(dest); + return Ok(report); + } + } + Err(BackupError::Library("it kept being saved while it was read; try again".into())) + })(); + if made.is_ok() { + // (renamed: there is no partial folder any more) + unfinished.0 = None; + } + made +} + +/// Read the backup in `dir` against what its marker lists: every file there, with the size and +/// CRC-32 it had when the backup was made, and no other file. The first thing that isn't so is +/// the error, naming the file. Returns the backup's report. +pub fn check(dir: &Path) -> Result { + let changed = BackupError::Changed; + let unreadable = |e: BackupError| BackupError::Changed(e.to_string()); + if !regular(&dir.join(MARKER)) { + return Err(changed(format!("{} is not a backup (it has no {MARKER})", dir.display()))); + } + let marker = read(&dir.join(MARKER)).map_err(unreadable)?.unwrap_or_default(); + let report: BackupReport = serde_json::from_slice(&marker).map_err(|e| changed(format!("{MARKER}: {e}")))?; + if report.contents.is_empty() { + return Err(changed(format!("{MARKER} doesn't list the backup's files"))); + } + for (name, held) in &report.contents { + // (only files of this folder: a marker is a file like any other, and may have been edited) + if !(valid_name(name) || segments::valid_name(name)) || name == MARKER { + return Err(changed(format!("{MARKER} lists {name:?}, which is not a file of the backup"))); + } + let path = dir.join(name); + if std::fs::symlink_metadata(&path).is_err() { + return Err(changed(format!("{name} is missing"))); + } + // (a file of its own, not a link to one elsewhere: the backup stands on its own) + let same = regular(&path) + && read(&path).map_err(unreadable)?.is_some_and(|bytes| bytes.len() as u64 == held.bytes && crc32fast::hash(&bytes) == held.crc); + if !same { + return Err(changed(format!("{name} is not as it was when the backup was made"))); + } + } + for name in held(dir).map_err(|e| changed(format!("{e}, and was not part of the backup")))? { + if name != MARKER && !report.contents.contains_key(&name) { + return Err(changed(format!("{name} was not part of the backup"))); + } + } + Ok(report) +} diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 79c17c284fa..3def262f8ed 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -100,7 +100,7 @@ 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"; +pub(crate) const FORMAT: &str = "lightcraft-catalog"; /// 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 { diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 3f13bf3c505..6d428f15ef0 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -13,6 +13,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod backup; pub mod dates; pub mod folders; mod index; @@ -1256,6 +1257,8 @@ mod tests_album_order; #[cfg(test)] mod tests_background; #[cfg(test)] +mod tests_backup; +#[cfg(test)] mod tests_folder_records; #[cfg(test)] mod tests_folders; diff --git a/crates/catalog/src/segments.rs b/crates/catalog/src/segments.rs index 400975a42b0..d5bb296eeca 100644 --- a/crates/catalog/src/segments.rs +++ b/crates/catalog/src/segments.rs @@ -231,7 +231,7 @@ fn fresh_name(first: PhotoId, seq: u64, taken: &std::collections::BTreeSet bool { +pub(crate) 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'-')) @@ -486,7 +486,7 @@ pub(crate) fn discard_unlisted(store: &mut dyn Store, segments: &[Segment]) { } /// A segment list a snapshot may state: this module's file names, each once, in id order. -fn check_list(segments: &[Segment]) -> Result<(), String> { +pub(crate) fn check_list(segments: &[Segment]) -> Result<(), String> { let mut names = std::collections::BTreeSet::new(); let mut last: Option = None; for s in segments { diff --git a/crates/catalog/src/tests_backup.rs b/crates/catalog/src/tests_backup.rs new file mode 100644 index 00000000000..b3eafabe8bd --- /dev/null +++ b/crates/catalog/src/tests_backup.rs @@ -0,0 +1,480 @@ +//! Backing up a library ([`crate::backup`]): a dated folder that opens as the library it was +//! taken of, and that shares with the backup before it the files that didn't change. + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + +use crate::backup::{self, BackupError, BackupOptions, BackupReport, Watch}; +use crate::journal::{LOG, SEGMENT_PREFIX, SNAPSHOT, segment_file}; +use crate::*; + +fn temp(name: &str) -> PathBuf { + static N: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!("lc-backup-{name}-{}-{}", std::process::id(), N.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +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", + ) +} + +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 folder of photos `1..=n` in segments of 4, compacted, with one change in its log +/// and a presets file beside the catalog. +fn library(dir: &Path, n: u64) -> (Journal, Catalog) { + 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..=n)); + j.snapshot(&c).unwrap(); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(1), rating: 3 }]); + std::fs::write(dir.join("presets.json"), b"[]").unwrap(); + (j, c) +} + +fn options(name: &str) -> BackupOptions<'_> { + BackupOptions { name, also: &["presets.json", "view.json"] } +} + +fn back_up(library: &Path, dest: &Path, name: &str) -> BackupReport { + backup::back_up(library, dest, &options(name), &()).unwrap() +} + +/// The catalog a folder opens as. +fn opened(dir: &Path) -> Catalog { + Journal::open(Box::new(FsStore::open(dir).unwrap())).unwrap().1 +} + +/// The files of a folder by the names the catalog gives them: the ones in it, and the ones in +/// its segments folder (`segments/…`). Other folders in it are named too (`Backups`). +fn files(dir: &Path) -> Vec { + let mut names = Vec::new(); + for entry in std::fs::read_dir(dir).unwrap() { + let entry = entry.unwrap(); + let name = entry.file_name().into_string().unwrap(); + if name == "segments" && entry.path().is_dir() { + names.extend(std::fs::read_dir(entry.path()).unwrap().map(|e| format!("segments/{}", e.unwrap().file_name().into_string().unwrap()))); + } else { + names.push(name); + } + } + names.sort(); + names +} + +/// A copy of a backup's (or library's) files, file by file (no links). +fn copy_of(from: &Path, name: &str) -> PathBuf { + let to = temp(name); + std::fs::create_dir_all(to.join("segments")).unwrap(); + for f in files(from) { + std::fs::copy(from.join(&f), to.join(&f)).unwrap(); + } + to +} + +fn segments(dir: &Path) -> Vec { + files(dir).into_iter().filter(|n| n.starts_with(SEGMENT_PREFIX)).collect() +} + +/// Whether two paths are the same file on disk (one a hard link of the other). +fn same_file(a: &Path, b: &Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let (a, b) = (std::fs::metadata(a).unwrap(), std::fs::metadata(b).unwrap()); + (a.dev(), a.ino()) == (b.dev(), b.ino()) + } + #[cfg(not(unix))] + { + let _ = (a, b); + true + } +} + +/// Given a library, when it is backed up, then the backup is a folder of its own that opens as +/// the library as it was, with its catalog, its log and the settings files beside them. +#[test] +fn a_backup_opens_as_the_library_it_was_taken_of() { + let (lib, dest) = (temp("lib"), temp("dest")); + let (j, c) = library(&lib, 12); + let report = back_up(&lib, &dest, "2026-10-10 12.00.00"); + assert_eq!(report.dir, dest.join("2026-10-10 12.00.00")); + assert_eq!((report.photos, report.segments, report.linked), (12, 3, 0)); + assert_eq!(report.copied, report.files); + let names = files(&report.dir); + assert!(names.contains(&SNAPSHOT.to_string()) && names.contains(&LOG.to_string()) && names.contains(&"presets.json".to_string()), "{names:?}"); + assert!(names.contains(&backup::MARKER.to_string())); + assert_eq!(segments(&report.dir), segments(&lib)); + assert_eq!( + report.bytes, + names.iter().filter(|n| *n != backup::MARKER).map(|n| std::fs::metadata(report.dir.join(n)).unwrap().len()).sum::() + ); + // the library is untouched and goes on + drop(j); + assert_eq!(opened(&lib).to_snapshot(), c.to_snapshot()); + // and the backup opens as it (its log's change included) + let back = opened(&report.dir); + assert_eq!(back.to_snapshot(), c.to_snapshot()); + assert_eq!(back.photo(PhotoId(1)).unwrap().rating, 3); + assert_eq!(files(&dest), ["2026-10-10 12.00.00"], "nothing else is left in the folder"); +} + +/// Given a backup, when the library changes a little and is backed up again, then the second +/// backup copies what changed and shares the rest with the first: the same files on disk. +#[test] +fn a_second_backup_shares_the_files_that_did_not_change() { + let (lib, dest) = (temp("lib"), temp("dest")); + let (mut j, mut c) = library(&lib, 12); + // (the change waiting in the log goes into its segment first, so only one changes below) + j.snapshot(&c).unwrap(); + let first = back_up(&lib, &dest, "2026-10-10 12.00.00"); + let then = c.clone(); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(6), rating: 5 }]); + j.snapshot(&c).unwrap(); + let second = back_up(&lib, &dest, "2026-10-11 12.00.00"); + assert_eq!((second.segments, second.linked), (3, 2), "{second:?}"); + // (`catalog.snap` is copied every time, and in a library this small it is most of the + // rest: it states the defaults of develop settings, 2.6 kB) + assert!(second.copied_bytes < first.copied_bytes * 3 / 4, "{} then {}", first.copied_bytes, second.copied_bytes); + let (old, new) = (segments(&first.dir), segments(&second.dir)); + let shared: Vec<&String> = new.iter().filter(|n| old.contains(n)).collect(); + assert_eq!(shared.len(), 2); + for name in shared { + assert!(same_file(&first.dir.join(name), &second.dir.join(name)), "{name} was copied"); + } + // each backup is the library of its day + assert_eq!(opened(&second.dir).to_snapshot(), c.to_snapshot()); + assert_eq!(opened(&first.dir).to_snapshot(), then.to_snapshot()); +} + +/// Backups don't depend on each other or on the library: removing an older backup, or the +/// library's own files, leaves a backup that still opens. +#[test] +fn a_backup_stands_on_its_own() { + let (lib, dest) = (temp("lib"), temp("dest")); + let (mut j, mut c) = library(&lib, 12); + let first = back_up(&lib, &dest, "a"); + run(&mut j, &mut c, vec![Op::SetRating { id: PhotoId(6), rating: 5 }]); + j.snapshot(&c).unwrap(); + let second = back_up(&lib, &dest, "b"); + let expected = c.to_snapshot(); + // the library moves on and replaces every segment; the first backup is thrown away + run(&mut j, &mut c, (1..=12).map(|id| Op::SetRating { id: PhotoId(id), rating: 1 }).collect()); + j.snapshot(&c).unwrap(); + drop(j); + std::fs::remove_dir_all(&first.dir).unwrap(); + std::fs::remove_dir_all(&lib).unwrap(); + assert_eq!(opened(&second.dir).to_snapshot(), expected); +} + +/// A watcher that does something to the library while it is being backed up. +struct Meanwhile { + at: F, + cancel: AtomicBool, +} + +impl Watch for Meanwhile { + fn progress(&self, name: &str, _done: u64, _total: u64) { + (self.at)(name); + } + fn cancelled(&self) -> bool { + self.cancel.load(Ordering::Relaxed) + } +} + +/// Given a library that is compacted while it is being backed up (the catalog changes under the +/// copy: new segments, old ones removed, the log reset), then the backup is still one moment of +/// the library: it opens, as the catalog before that compaction or after it. +#[test] +fn a_backup_taken_while_the_library_is_saved_is_one_moment_of_it() { + let (lib, dest) = (temp("lib"), temp("dest")); + let (j, c) = library(&lib, 40); + let before = c.to_snapshot(); + let state = Mutex::new((j, c, 0u32)); + let watch = Meanwhile { + at: |name: &str| { + let mut s = state.lock().unwrap(); + // as a segment is about to be copied, twice over, and then once more just before + // the log is read (the last moment a compaction can slip in): every segment is replaced + if (name.starts_with(SEGMENT_PREFIX) && s.2 < 2) || (name == LOG && s.2 == 2) { + s.2 += 1; + let (j, c, k) = &mut *s; + run(j, c, (1..=40).map(|id| Op::SetRating { id: PhotoId(id), rating: (*k % 5) as u8 + 1 }).collect()); + j.snapshot(c).unwrap(); + } + }, + cancel: AtomicBool::new(false), + }; + let report = backup::back_up(&lib, &dest, &options("live"), &watch).unwrap(); + let s = state.lock().unwrap(); + assert_eq!(s.2, 3); + let back = opened(&report.dir).to_snapshot(); + assert!(back == s.1.to_snapshot() || back == before, "the backup is neither the library before nor after"); + assert_eq!(back, s.1.to_snapshot(), "it was started over until the library held still"); + assert_eq!(segments(&report.dir), segments(&lib)); + assert_eq!(files(&dest), ["live"]); + // nothing of the passes that were started over is left in it + assert_eq!(backup::check(&report.dir).unwrap(), report); +} + +/// Given a backup that is cancelled, or that can't be finished, then no folder of it is left, +/// and the backups there were are as they were. +#[test] +fn a_backup_that_does_not_finish_leaves_nothing() { + let (lib, dest) = (temp("lib"), temp("dest")); + let (j, _c) = library(&lib, 12); + drop(j); + let first = back_up(&lib, &dest, "a"); + let kept = files(&first.dir); + + // cancelled after the first file + struct CancelAfterOne(AtomicU64); + impl Watch for CancelAfterOne { + fn progress(&self, _: &str, _: u64, _: u64) { + self.0.fetch_add(1, Ordering::Relaxed); + } + fn cancelled(&self) -> bool { + self.0.load(Ordering::Relaxed) >= 1 + } + } + let e = backup::back_up(&lib, &dest, &options("b"), &CancelAfterOne(AtomicU64::new(0))).unwrap_err(); + assert!(matches!(e, BackupError::Cancelled), "{e}"); + assert_eq!(files(&dest), ["a"]); + + // a segment of the library is damaged: no backup is made of a library that doesn't open + let name = segments(&lib).remove(1); + let mut bytes = std::fs::read(lib.join(&name)).unwrap(); + let at = bytes.windows(4).position(|w| w == b"4032").unwrap(); + bytes[at] = b'5'; + std::fs::write(lib.join(&name), &bytes).unwrap(); + // (a later backup would share the undamaged copy the first one holds, so make it a new library) + let fresh = temp("fresh-dest"); + let e = backup::back_up(&lib, &fresh, &options("c"), &()).unwrap_err(); + assert!(matches!(&e, BackupError::Library(msg) if msg.contains(&name)), "{e}"); + assert!(files(&fresh).is_empty()); + assert_eq!((files(&dest), files(&first.dir)), (vec!["a".to_string()], kept)); + + // a name that is taken is not written over + let e = backup::back_up(&lib, &dest, &options("a"), &()).unwrap_err(); + assert!(matches!(e, BackupError::Exists(_)), "{e}"); + assert_eq!(opened(&first.dir).len(), 12); +} + +/// What can't be a backup is refused with what is wrong: no library there, a name that is a +/// path, a folder that can't be made. +#[test] +fn what_cannot_be_backed_up_says_why() { + let (lib, dest) = (temp("lib"), temp("dest")); + let empty = temp("empty"); + let e = backup::back_up(&empty, &dest, &options("a"), &()).unwrap_err(); + assert!(matches!(&e, BackupError::Library(msg) if msg.contains(SNAPSHOT)), "{e}"); + let (j, _c) = library(&lib, 4); + drop(j); + for name in ["", ".", "..", "a/b", "a\\b", "../a"] { + let e = backup::back_up(&lib, &dest, &options(name), &()).unwrap_err(); + assert!(matches!(e, BackupError::Name(_)), "{name:?}: {e}"); + } + std::fs::write(dest.join("file"), b"x").unwrap(); + let e = backup::back_up(&lib, &dest.join("file"), &options("a"), &()).unwrap_err(); + assert!(matches!(e, BackupError::Io(_)), "{e}"); + assert_eq!(files(&dest), ["file"]); + // a snapshot that names files outside the library is not followed + let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(lib.join(SNAPSHOT)).unwrap()).unwrap(); + v["segments"][0]["name"] = "../presets.json".into(); + std::fs::write(lib.join(SNAPSHOT), serde_json::to_vec(&v).unwrap()).unwrap(); + let e = backup::back_up(&lib, &dest, &options("a"), &()).unwrap_err(); + assert!(matches!(e, BackupError::Library(_)), "{e}"); + assert_eq!(files(&dest), ["file"]); +} + +/// A library in one file (not yet in segments, or of a store without them) is backed up as it is. +#[test] +fn a_one_file_library_is_backed_up_too() { + let (lib, dest) = (temp("lib"), temp("dest")); + std::fs::write(lib.join(SNAPSHOT), include_str!("fixtures/v8-catalog.snap.json")).unwrap(); + std::fs::write(lib.join(LOG), include_str!("fixtures/v8-catalog.log.jsonl")).unwrap(); + let report = back_up(&lib, &dest, "a"); + assert_eq!((report.segments, report.photos), (0, 3)); + assert_eq!(std::fs::read(report.dir.join(SNAPSHOT)).unwrap(), std::fs::read(lib.join(SNAPSHOT)).unwrap()); + assert_eq!(std::fs::read(report.dir.join(LOG)).unwrap(), std::fs::read(lib.join(LOG)).unwrap()); + // the backup is the old format still; opening it upgrades the backup's copy, not the library + assert_eq!(opened(&report.dir).len(), 3); + assert!(std::str::from_utf8(&std::fs::read(lib.join(SNAPSHOT)).unwrap()).unwrap().contains(r#""version":8"#)); +} + +/// A file is shared with the backup before only once it was read and is what it should be: +/// one that was damaged there (a failing disk) is copied afresh from the library, so damage in +/// an old backup is never handed on to the next. +#[test] +fn a_damaged_file_in_the_backup_before_is_not_shared() { + let (lib, dest) = (temp("lib"), temp("dest")); + let (j, c) = library(&lib, 12); + drop(j); + let first = back_up(&lib, &dest, "a"); + let name = segments(&first.dir).remove(0); + let mut bytes = std::fs::read(first.dir.join(&name)).unwrap(); + let at = bytes.windows(4).position(|w| w == b"4032").unwrap(); + bytes[at] = b'5'; + std::fs::write(first.dir.join(&name), &bytes).unwrap(); + let second = back_up(&lib, &dest, "b"); + assert_eq!((second.linked, second.segments), (2, 3)); + assert!(!same_file(&first.dir.join(&name), &second.dir.join(&name))); + backup::check(&second.dir).unwrap(); + assert_eq!(opened(&second.dir).to_snapshot(), c.to_snapshot()); +} + +/// What counts as the backup before: the newest folder that is a finished backup. A folder +/// being written, one without a marker, and one whose snapshot lists a file of the same name +/// but another size or checksum share nothing. +#[test] +fn only_a_finished_backup_of_the_same_files_is_shared_with() { + let (lib, dest) = (temp("lib"), temp("dest")); + let (j, _c) = library(&lib, 12); + drop(j); + let first = back_up(&lib, &dest, "a"); + // copies of it that are not backups, with names that sort after it + for (name, marker) in [("z.partial", true), ("z-unmarked", false)] { + std::fs::create_dir_all(dest.join(name).join("segments")).unwrap(); + for f in files(&first.dir) { + if marker || f != backup::MARKER { + std::fs::copy(first.dir.join(&f), dest.join(name).join(&f)).unwrap(); + } + } + } + let second = back_up(&lib, &dest, "b"); + assert_eq!(second.linked, 3); + for name in segments(&second.dir) { + assert!(same_file(&first.dir.join(&name), &second.dir.join(&name)), "{name}"); + } + // a backup whose snapshot states another checksum for a file of the same name + let (other_lib, other_dest) = (temp("lib"), temp("dest")); + let (j, _c) = library(&other_lib, 12); + drop(j); + let made = back_up(&other_lib, &other_dest, "a"); + let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(made.dir.join(SNAPSHOT)).unwrap()).unwrap(); + v["segments"][0]["crc"] = 7.into(); + std::fs::write(made.dir.join(SNAPSHOT), serde_json::to_vec(&v).unwrap()).unwrap(); + let next = back_up(&other_lib, &other_dest, "b"); + assert_eq!(next.linked, 2); + assert_eq!(opened(&next.dir).len(), 12); +} + +/// A folder left by a backup that was cut short (`.partial`) is never taken for a backup, +/// is in nobody's way while it may still be written, and is removed by a later backup once it +/// is old. A folder of that name that holds anything else is not touched. +#[test] +fn what_a_backup_cut_short_left_is_cleared_away_later() { + let (lib, dest) = (temp("lib"), temp("dest")); + let (j, _c) = library(&lib, 12); + drop(j); + let old = |dir: &Path| { + let then = std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 3600); + std::fs::File::open(dir).unwrap().set_modified(then).unwrap(); + }; + let partial = |name: &str, extra: Option<&str>| { + let dir = dest.join(name); + std::fs::create_dir(&dir).unwrap(); + std::fs::create_dir(dir.join("segments")).unwrap(); + std::fs::write(dir.join(segment_file("1-1")), b"half").unwrap(); + if let Some(extra) = extra { + std::fs::write(dir.join(extra), b"mine").unwrap(); + } + dir + }; + let (stale, fresh, foreign) = (partial("x.partial", None), partial("y.partial", None), partial("z.partial", Some("thesis.txt"))); + old(&stale); + old(&foreign); + // a name whose partial folder is there is taken + assert!(matches!(backup::back_up(&lib, &dest, &options("y"), &()), Err(BackupError::Exists(_)))); + back_up(&lib, &dest, "a"); + assert!(!stale.exists(), "an old one is removed"); + assert!(fresh.exists(), "one that may be being written is not"); + assert!(foreign.join("thesis.txt").exists(), "a folder holding something else is not ours to remove"); +} + +/// Sizes a snapshot states are not trusted: ones that would overflow when added are an error +/// like any other damage, and leave nothing behind. +#[test] +fn absurd_sizes_in_a_snapshot_are_an_error() { + let (lib, dest) = (temp("lib"), temp("dest")); + let (j, _c) = library(&lib, 12); + drop(j); + let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(lib.join(SNAPSHOT)).unwrap()).unwrap(); + for k in 0..2 { + v["segments"][k]["bytes"] = u64::MAX.into(); + } + std::fs::write(lib.join(SNAPSHOT), serde_json::to_vec(&v).unwrap()).unwrap(); + assert!(matches!(backup::back_up(&lib, &dest, &options("a"), &()), Err(BackupError::Library(_)))); + assert!(files(&dest).is_empty()); + // and the other files to take along are plain names, none of them the catalog's own + for bad in ["../x", "a/b", SNAPSHOT, LOG, backup::MARKER, "segments/1-1.json", "segments", ""] { + let e = backup::back_up(&lib, &dest, &BackupOptions { name: "a", also: &[bad] }, &()).unwrap_err(); + assert!(matches!(e, BackupError::Name(_)), "{bad:?}: {e}"); + } +} + +/// A backup lists what it holds, and can be read against that list: a file that was edited by +/// hand (the snapshot, the log, a segment, a settings file), removed, or added since is named. +#[test] +fn a_backup_that_was_touched_is_found_out() { + let (lib, dest) = (temp("lib"), temp("dest")); + let (j, _c) = library(&lib, 12); + drop(j); + let made = back_up(&lib, &dest, "a"); + assert_eq!(backup::check(&made.dir).unwrap(), made); + assert_eq!(made.contents.len() as u64, made.files); + let segment = segments(&made.dir).remove(1); + for name in [SNAPSHOT, LOG, "presets.json", segment.as_str()] { + let copy = copy_of(&made.dir, "touched"); + // one character changed: still JSON, the same length + let mut bytes = std::fs::read(copy.join(name)).unwrap(); + let at = bytes.iter().position(|b| b.is_ascii_digit()).unwrap_or(0); + bytes[at] = if bytes[at] == b'7' { b'8' } else { b'7' }; + std::fs::write(copy.join(name), &bytes).unwrap(); + let e = backup::check(©).unwrap_err(); + assert!(matches!(&e, BackupError::Changed(msg) if msg.contains(name)), "{name}: {e}"); + // removed + std::fs::remove_file(copy.join(name)).unwrap(); + let e = backup::check(©).unwrap_err(); + assert!(matches!(&e, BackupError::Changed(msg) if msg.contains(name) && msg.contains("missing")), "{name}: {e}"); + } + // a file that wasn't there + let copy = copy_of(&made.dir, "added"); + std::fs::write(copy.join("notes.txt"), b"mine").unwrap(); + assert!(matches!(backup::check(©), Err(BackupError::Changed(msg)) if msg.contains("notes.txt"))); + // a link to the file elsewhere is not the file: the backup has to stand on its own + #[cfg(unix)] + { + let copy = copy_of(&made.dir, "linked"); + std::fs::remove_file(copy.join(&segment)).unwrap(); + std::os::unix::fs::symlink(made.dir.join(&segment), copy.join(&segment)).unwrap(); + assert!(matches!(backup::check(©), Err(BackupError::Changed(msg)) if msg.contains(&segment))); + } + // a folder that is no backup, and a marker that points outside it + assert!(matches!(backup::check(&lib), Err(BackupError::Changed(msg)) if msg.contains("not a backup"))); + let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(made.dir.join(backup::MARKER)).unwrap()).unwrap(); + v["contents"]["../x"] = serde_json::json!({"bytes": 1, "crc": 1}); + let copy = copy_of(&made.dir, "outside"); + std::fs::write(copy.join(backup::MARKER), serde_json::to_vec(&v).unwrap()).unwrap(); + assert!(matches!(backup::check(©), Err(BackupError::Changed(msg)) if msg.contains("not a file of the backup"))); +} diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 147d20f3a58..77585e9bb81 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -72,7 +72,7 @@ impl Unit { #[serde(rename_all = "camelCase")] pub struct TaskInfo { pub id: u64, - /// A stable id: `import`, `export`, `scan`, `previews`, `smartPreviews`, `lightroom`, `merge`, `download`, + /// A stable id: `import`, `export`, `scan`, `previews`, `smartPreviews`, `backup`, `lightroom`, `merge`, `download`, /// `faces`, `denoise`, `findMissing`, `applePhotos`, `cache`, `focus`. pub kind: &'static str, /// English; the frontend translates it. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 9b8dc3dbd28..2571ddf476b 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -5,6 +5,7 @@ //! `edit.*` (undo/redo), and queries (`catalog.query`, `photo.inspect`, `develop.get`…). mod activity; +pub mod backup; mod before; pub(crate) mod browse; mod color; @@ -151,6 +152,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(keywords::specs()); v.extend(manage::specs()); v.extend(previews::specs()); + v.extend(backup::specs()); v.extend(lut_profiles::specs()); v.extend(mask_effects::specs()); v.extend(cull::specs()); diff --git a/crates/engine/src/cmd/backup.rs b/crates/engine/src/cmd/backup.rs new file mode 100644 index 00000000000..2174fff33d6 --- /dev/null +++ b/crates/engine/src/cmd/backup.rs @@ -0,0 +1,256 @@ +//! `library.backup`: back up the library's catalog to a dated folder (see +//! [`lightcraft_catalog::backup`]): a folder that opens as the library it was taken of, and that +//! shares with the backup before it the files that didn't change. +//! +//! The backup reads the library's files as they are on disk, with a row in the activity stack. +//! It runs to its end before the command returns, or (`background`: what the app asks for) on a +//! worker thread while the library stays in use. Not the photos: the catalog, its log, and the +//! presets, view and preferences files. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use lightcraft_catalog::backup::{self, BackupOptions, BackupReport, Watch}; +use serde_json::{Value, json}; + +use super::{CommandSpec, always, bad, cmd}; +use crate::activity::{Cancel, TaskGuard, Unit}; +use crate::{Result, Session}; + +/// The folder in the library that backups go to unless another is asked for. +pub const BACKUPS: &str = "Backups"; +/// The library's other files a backup takes along. +const ALSO: &[&str] = &["presets.json", "view.json", "prefs.json"]; + +/// A backup under way, or the last one made. +#[derive(Default)] +pub struct BackupJob { + /// The library it is of. + pub library: PathBuf, + /// The folder it is made in. + pub dest: PathBuf, + /// Shared with the backup's row in the activity stack (its ✕ sets it). + pub cancel: Arc, + pub finished: AtomicBool, + /// How it ended. + pub outcome: std::sync::Mutex>>, +} + +impl BackupJob { + /// How it ended (`None` while it runs). + pub fn outcome(&self) -> Option> { + self.outcome.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone() + } + + pub fn json(&self) -> Value { + let outcome = self.outcome(); + let made = outcome.as_ref().is_some_and(|o| o.is_ok()); + json!({ + "running": !self.finished.load(Ordering::Relaxed), + // (stopped: not a backup that was whole before the stop was seen) + "cancelled": self.cancel.load(Ordering::Relaxed) && !made, + "library": self.library.to_string_lossy(), + "dest": self.dest.to_string_lossy(), + "report": outcome.as_ref().and_then(|o| o.as_ref().ok()).and_then(|r| serde_json::to_value(r).ok()), + "error": outcome.as_ref().and_then(|o| o.as_ref().err()), + }) + } +} + +/// Reports to the backup's row, and stops when its ✕ was pressed. +struct Row<'a> { + task: &'a TaskGuard, + cancel: &'a AtomicBool, +} + +impl Watch for Row<'_> { + fn progress(&self, name: &str, done: u64, total: u64) { + self.task.progress(done, total); + self.task.detail(name); + } + fn cancelled(&self) -> bool { + self.cancel.load(Ordering::Relaxed) + } +} + +/// A name for a backup made at `now` (ISO 8601; the session's clock is UTC, and the name says +/// so) that no folder in `dest` has. +fn free_name(dest: &Path, now: &str) -> String { + let time: String = now + .chars() + .take(19) + .map(|c| { + if c == 'T' { + ' ' + } else if c == ':' { + '.' + } else { + c + } + }) + .collect(); + let base = if time.trim().is_empty() { "backup".to_string() } else { format!("{time} UTC") }; + let taken = |name: &str| dest.join(name).exists() || dest.join(format!("{name}.partial")).exists(); + if !taken(&base) { + return base; + } + (2..1000u32).map(|n| format!("{base} ({n})")).find(|name| !taken(name)).unwrap_or(base) +} + +fn run(name: String, job: &BackupJob, task: &TaskGuard, hold: &AtomicBool) { + // However this ends, the job is over: also if something below should panic (it then says so, + // and the next backup is not refused as "already running"). + struct Over<'a>(&'a BackupJob); + impl Drop for Over<'_> { + fn drop(&mut self) { + let mut outcome = self.0.outcome.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if outcome.is_none() { + *outcome = Some(Err("the backup stopped on an internal error".into())); + } + self.0.finished.store(true, Ordering::Relaxed); + } + } + let _over = Over(job); + // (tests hold a backup here, to look at its row) + while hold.load(Ordering::SeqCst) && !job.cancel.load(Ordering::Relaxed) { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + let options = BackupOptions { name: &name, also: ALSO }; + let made = backup::back_up(&job.library, &job.dest, &options, &Row { task, cancel: &job.cancel }); + match &made { + Ok(r) => log::info!("library: backed up to {} ({} files, {} shared with the backup before)", r.dir.display(), r.files, r.linked), + Err(e) => log::warn!("library: backup: {e}"), + } + *job.outcome.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(made.map_err(|e| e.to_string())); +} + +/// A folder given as a parameter: an absolute path (a relative one would mean another folder to +/// the app, the command line and an agent). +fn folder(cmd: &str, value: &Value) -> Result { + match value.as_str().map(str::trim).filter(|d| !d.is_empty()).map(PathBuf::from) { + Some(dir) if dir.is_absolute() => Ok(dir), + Some(dir) => Err(bad(cmd, format!("`dir` must be an absolute path, not {}", dir.display()))), + None => Err(bad(cmd, "`dir` is a folder's path")), + } +} + +fn flag(cmd: &str, p: &Value, key: &str) -> Result { + match p.get(key) { + None | Some(Value::Null) => Ok(false), + Some(Value::Bool(b)) => Ok(*b), + Some(_) => Err(bad(cmd, format!("`{key}` is true or false"))), + } +} + +/// The backup of the open library that is under way, or the last one made of it. +pub fn status(s: &Session) -> Option<&Arc> { + let library = s.library.as_ref().map(|l| &l.dir)?; + s.backup.as_ref().filter(|b| b.library == *library) +} + +fn back_up(s: &mut Session, p: &Value) -> Result { + const C: &str = "library.backup"; + let Some(library) = s.library.as_ref().filter(|l| l.on_disk).map(|l| l.dir.clone()) else { + return Err(bad(C, "this library is not a folder on disk; there is nothing to back up to a folder")); + }; + if status(s).is_some_and(|b| !b.finished.load(Ordering::Relaxed)) { + return Err(bad(C, "a backup of this library is already running")); + } + let background = flag(C, p, "background")?; + let dest = match p.get("dir") { + None | Some(Value::Null) => s.backup_dir.clone().unwrap_or_else(|| library.join(BACKUPS)), + Some(dir) => folder(C, dir)?, + }; + // everything changed so far is in the log before it is read + s.persist()?; + let name = free_name(&dest, &(s.clock)()); + let job = Arc::new(BackupJob { library, dest, ..Default::default() }); + s.backup = Some(job.clone()); + let task = s.activity.start("backup", "Backing up the library", Cancel::Flag(job.cancel.clone())); + task.set_unit(Unit::Bytes); + let hold = s.backup_hold.clone(); + if !background || cfg!(target_arch = "wasm32") { + run(name, &job, &task, &hold); + return Ok(job.json()); + } + #[cfg(not(target_arch = "wasm32"))] + { + // the row stays while the worker runs (it is dropped with the closure, however that ends) + let worker = job.clone(); + if let Err(e) = std::thread::Builder::new().name("lc-backup".into()).spawn(move || run(name, &worker, &task, &hold)) { + *job.outcome.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Err(format!("could not start: {e}"))); + job.finished.store(true, Ordering::Relaxed); + return Err(bad(C, format!("could not start: {e}"))); + } + } + Ok(job.json()) +} + +fn preferences(s: &mut Session, p: &Value) -> Result { + if let Some(dir) = p.get("dir") { + s.backup_dir = match dir { + Value::Null => None, + dir => Some(folder("library.backupPreferences", dir)?), + }; + s.save_prefs()?; + } + Ok(json!({"dir": s.backup_dir.as_ref().map(|d| d.to_string_lossy())})) +} + +fn on_disk(s: &Session) -> std::result::Result<(), String> { + if s.library.as_ref().is_some_and(|l| l.on_disk) { Ok(()) } else { Err("the library is not a folder on disk".into()) } +} + +/// [`on_disk`], and no backup of the library under way. +fn can_back_up(s: &Session) -> std::result::Result<(), String> { + on_disk(s)?; + if status(s).is_some_and(|b| !b.finished.load(Ordering::Relaxed)) { Err("a backup of this library is running".into()) } else { Ok(()) } +} + +pub fn specs() -> Vec { + vec![ + cmd!(query + "library.backup", + "Back Up Library", + ["File"], + None, + "{dir?: absolute folder path, background?: bool} — back up the library's catalog (not the photos) to a folder named after the time (UTC) in `dir`, else in the library's backup folder (`library.backupPreferences`), else in Backups in the library folder. The backup opens as a library; files that didn't change since the backup before are shared with it (hard links, each read and checked first), so it copies what changed. Has a row in the activity stack (kind `backup`) that can stop it. Returns when the backup is made, or with `background` at once (then see `library.backupStatus`) → {running, cancelled, library, dest, report: {dir, seq, photos, segments, files, copied, linked, bytes, copiedBytes, contents: {file: {bytes, crc}}} | null, error}", + can_back_up, + back_up + ), + cmd!(query + "library.backupStatus", + "Backup Status", + [], + None, + "{} → the backup of the open library that is under way, or the last one made of it in this session, as `library.backup` returns it | null", + always, + |s, _| Ok(status(s).map_or(Value::Null, |b| b.json())) + ), + cmd!(query + "library.checkBackup", + "Check Backup", + [], + None, + "{dir: a backup's folder (absolute path)} — read the backup against what its marker (backup.json) lists: every file there with the size and CRC-32 it had when the backup was made, and no other → {ok: true, report} | {ok: false, error} naming the first file that was edited, damaged, removed or added. A backup that was opened as a library is no longer as it was made", + always, + |_, p| { + let dir = folder("library.checkBackup", p.get("dir").unwrap_or(&Value::Null))?; + Ok(match backup::check(&dir) { + Ok(report) => json!({"ok": true, "report": report}), + Err(e) => json!({"ok": false, "error": e.to_string()}), + }) + } + ), + cmd!( + "library.backupPreferences", + "Backup Preferences", + [], + None, + "{dir?: absolute folder path | null} — the folder the library's backups go to (saved with the library); null: Backups in the library folder → {dir}", + on_disk, + preferences + ), + ] +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index acaa1807009..33b58c52d66 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -389,6 +389,12 @@ pub struct Session { pub slideshow_export: Option>, /// The last (or running) Build Previews. pub preview_build: Option>, + /// The library backup under way, or the last one made (`library.backup`). + pub backup: Option>, + /// Where the library's backups go (a library preference; `None`: Backups in its folder). + pub backup_dir: Option, + /// Holds a backup before it starts reading (tests look at its row meanwhile). + pub(crate) backup_hold: std::sync::Arc, /// Develop defaults applied on import (persisted in prefs.json). pub import_defaults: import::ImportDefaults, /// Disk budget of the library's thumbnail cache in MB (0 = default; persisted in prefs.json). @@ -526,6 +532,9 @@ impl Session { activity: Default::default(), preview_build: None, slideshow_export: None, + backup: None, + backup_dir: None, + backup_hold: Default::default(), import_defaults: import::ImportDefaults::default(), cache_mb: 0, slideshow: slideshow::PlaybackSettings::default(), diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index e145ead2953..015cb443a72 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -208,6 +208,9 @@ impl Library { #[serde(default, rename_all = "camelCase")] struct PrefsFile { xmp: crate::sidecar::XmpPrefs, + /// Where the library's backups go (`library.backupPreferences`). + #[serde(skip_serializing_if = "Option::is_none")] + backup_dir: Option, /// Parameters of the last export (for Export with Previous). #[serde(alias = "last_export")] last_export: Option, @@ -528,6 +531,7 @@ impl Session { // preferences let prefs = settings.read::(files.as_mut(), "prefs.json").unwrap_or_default(); self.xmp = prefs.xmp; + self.backup_dir = prefs.backup_dir; self.last_export = prefs.last_export; self.last_merge = prefs.last_merge; self.export_presets = prefs.export_presets; @@ -809,6 +813,7 @@ impl Session { pub fn save_prefs(&mut self) -> Result<()> { let v = serde_json::to_vec_pretty(&PrefsFile { xmp: self.xmp, + backup_dir: self.backup_dir.clone(), last_export: self.last_export.clone(), last_merge: self.last_merge.clone(), export_presets: self.export_presets.clone(), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae03859d21f..2046c2e282d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5,6 +5,7 @@ use crate::{Selection, Session, command_specs}; mod album_order; mod album_remove; mod albums_local; +mod backup; mod color; mod constrain_crop; mod crop_angle; diff --git a/crates/engine/src/tests/backup.rs b/crates/engine/src/tests/backup.rs new file mode 100644 index 00000000000..f8feab65c42 --- /dev/null +++ b/crates/engine/src/tests/backup.rs @@ -0,0 +1,245 @@ +//! `library.backup`: a dated folder that opens as the library, sharing unchanged files with the +//! backup before; a row in the activity stack while it runs. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering; + +use serde_json::json; + +use crate::{EngineError, Session}; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-engine-backup-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d +} + +fn open(dir: &Path) -> Session { + let mut s = Session::new(); + s.open_library(dir, true).unwrap(); + s +} + +fn backups(dir: &Path) -> Vec { + let mut names: Vec = + std::fs::read_dir(dir).map(|d| d.filter_map(|e| e.ok()?.file_name().into_string().ok()).collect()).unwrap_or_default(); + names.sort(); + names +} + +/// Given a library with changes, when it is backed up, then `Backups/` in its folder +/// opens as the library as it is, and the library goes on as before. +#[test] +fn a_backup_opens_as_the_library() { + let dir = temp_dir("opens"); + let mut s = open(&dir); + let id = s.selection.active.unwrap(); + s.execute("photo.rate", &json!({"rating": 4})).unwrap(); + let r = s.execute("library.backup", &json!({})).unwrap(); + let made = PathBuf::from(r["report"]["dir"].as_str().unwrap()); + assert_eq!(made, dir.join("Backups").join("2026-09-30 12.00.00 UTC")); + assert_eq!((r["running"].as_bool(), r["error"].is_null()), (Some(false), true)); + assert_eq!(r["report"]["photos"].as_u64(), Some(s.catalog.len() as u64)); + assert!(s.activity.list().is_empty()); + let expect = s.catalog.to_snapshot(); + // the library goes on; the backup is what it was + s.execute("photo.rate", &json!({"rating": 1})).unwrap(); + let back = open(&made); + assert_eq!(back.catalog.to_snapshot(), expect); + assert_eq!(back.catalog.photo(id).unwrap().rating, 4); + assert_eq!(s.execute("library.backupStatus", &json!({})).unwrap()["report"]["dir"], r["report"]["dir"]); + drop((s, back)); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A second backup has a name of its own (also at the same time of day) and shares the files +/// that didn't change with the first. +#[test] +fn a_second_backup_shares_what_did_not_change() { + let dir = temp_dir("shares"); + let mut s = open(&dir); + let first = s.execute("library.backup", &json!({})).unwrap(); + let second = s.execute("library.backup", &json!({})).unwrap(); + assert_ne!(first["report"]["dir"], second["report"]["dir"]); + assert_eq!(backups(&dir.join("Backups")), ["2026-09-30 12.00.00 UTC", "2026-09-30 12.00.00 UTC (2)"]); + assert_eq!(second["report"]["linked"], second["report"]["segments"]); + assert!(second["report"]["segments"].as_u64().unwrap() >= 1); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The folder backups go to: one given with the command, or the library's own (a preference +/// saved with it), else `Backups` in the library folder. +#[test] +fn backups_go_to_the_folder_asked_for() { + let (dir, there, elsewhere) = (temp_dir("where"), temp_dir("where-there"), temp_dir("where-else")); + let mut s = open(&dir); + let r = s.execute("library.backup", &json!({"dir": there.to_string_lossy()})).unwrap(); + assert!(PathBuf::from(r["report"]["dir"].as_str().unwrap()).starts_with(&there)); + assert!(backups(&dir.join("Backups")).is_empty(), "given for one backup, not remembered"); + // the library's own folder for them, kept with the library + let p = s.execute("library.backupPreferences", &json!({"dir": elsewhere.to_string_lossy()})).unwrap(); + assert_eq!(p["dir"].as_str(), Some(&*elsewhere.to_string_lossy())); + s.close_library().unwrap(); + drop(s); + let mut s = open(&dir); + assert_eq!(s.execute("library.backupPreferences", &json!({})).unwrap()["dir"].as_str(), Some(&*elsewhere.to_string_lossy())); + s.execute("library.backup", &json!({})).unwrap(); + assert_eq!(backups(&elsewhere).len(), 1); + // and back to the default + assert!(s.execute("library.backupPreferences", &json!({"dir": null})).unwrap()["dir"].is_null()); + s.execute("library.backup", &json!({})).unwrap(); + assert_eq!(backups(&dir.join("Backups")).len(), 1); + drop(s); + for d in [dir, there, elsewhere] { + let _ = std::fs::remove_dir_all(d); + } +} + +/// While a backup runs it has a row in the activity stack that can stop it; stopped, it leaves +/// no folder, says so, and the row is gone. +#[test] +fn a_running_backup_shows_in_the_activity_stack_and_can_be_stopped() { + let dir = temp_dir("row"); + let mut s = open(&dir); + s.backup_hold.store(true, Ordering::SeqCst); + let r = s.execute("library.backup", &json!({"background": true})).unwrap(); + assert_eq!(r["running"].as_bool(), Some(true)); + let rows = s.activity.list(); + assert_eq!(rows.len(), 1, "{rows:?}"); + assert_eq!((rows[0].kind, rows[0].label.as_str(), rows[0].cancellable), ("backup", "Backing up the library", true)); + assert_eq!(rows[0].unit, crate::activity::Unit::Bytes); + // one at a time (the menu item is off meanwhile) + assert!(matches!(s.execute("library.backup", &json!({})), Err(EngineError::Disabled { .. } | EngineError::BadParams { .. }))); + s.activity.cancel(rows[0].id).unwrap(); + s.backup_hold.store(false, Ordering::SeqCst); + let t0 = std::time::Instant::now(); + while !s.activity.list().is_empty() && t0.elapsed() < std::time::Duration::from_secs(20) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(s.activity.list().is_empty()); + let status = s.execute("library.backupStatus", &json!({})).unwrap(); + assert_eq!((status["running"].as_bool(), status["cancelled"].as_bool()), (Some(false), Some(true))); + assert!(status["report"].is_null() && status["error"].as_str().is_some_and(|e| e.contains("cancelled")), "{status}"); + assert!(backups(&dir.join("Backups")).is_empty()); + // and the next one runs, and says how far it got + s.backup_hold.store(true, Ordering::SeqCst); + s.execute("library.backup", &json!({"background": true})).unwrap(); + s.backup_hold.store(false, Ordering::SeqCst); + let t0 = std::time::Instant::now(); + while s.execute("library.backupStatus", &json!({})).unwrap()["running"] == json!(true) && t0.elapsed() < std::time::Duration::from_secs(20) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let done = s.execute("library.backupStatus", &json!({})).unwrap(); + assert!(done["error"].is_null() && done["cancelled"] == json!(false), "{done}"); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// What can't be backed up says why: a library that isn't a folder, or no library. +#[test] +fn a_library_without_a_folder_is_not_backed_up() { + let mut s = Session::with_demo(); + let e = s.execute("library.backup", &json!({})).unwrap_err(); + assert!(e.to_string().contains("folder"), "{e}"); + assert!(s.activity.list().is_empty()); + // a folder that can't be written to is the backup's error, not a panic; nothing is left + let dir = temp_dir("bad-dest"); + let mut s = open(&dir); + std::fs::write(dir.join("not-a-folder"), b"x").unwrap(); + let r = s.execute("library.backup", &json!({"dir": dir.join("not-a-folder").to_string_lossy()})).unwrap(); + assert!(r["report"].is_null() && r["error"].as_str().is_some(), "{r}"); + assert!(s.activity.list().is_empty()); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A backup can be checked against what it listed when it was made: untouched it is sound; a +/// file edited by hand is named. +#[test] +fn a_backup_is_checked_against_its_own_list() { + let dir = temp_dir("check"); + let mut s = open(&dir); + let r = s.execute("library.backup", &json!({})).unwrap(); + let made = PathBuf::from(r["report"]["dir"].as_str().unwrap()); + let sound = s.execute("library.checkBackup", &json!({"dir": made.to_string_lossy()})).unwrap(); + assert_eq!((sound["ok"].as_bool(), &sound["report"]["dir"]), (Some(true), &r["report"]["dir"])); + let snap = made.join("catalog.snap"); + let edited = std::fs::read_to_string(&snap).unwrap().replacen("\"seq\":", "\"seq\": ", 1); + std::fs::write(&snap, edited).unwrap(); + let touched = s.execute("library.checkBackup", &json!({"dir": made.to_string_lossy()})).unwrap(); + assert_eq!(touched["ok"].as_bool(), Some(false)); + assert!(touched["error"].as_str().unwrap().contains("catalog.snap"), "{touched}"); + assert!(s.execute("library.checkBackup", &json!({})).is_err()); + assert_eq!( + s.execute("library.checkBackup", &json!({"dir": dir.to_string_lossy()})).unwrap()["ok"].as_bool(), + Some(false), + "a library is not a backup" + ); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A backup holds every change made so far, also one that was not yet written to the library's +/// log when the backup was asked for; and the library's settings files. +#[test] +fn a_backup_holds_what_was_not_saved_yet() { + let dir = temp_dir("unsaved"); + let mut s = open(&dir); + let id = s.selection.active.unwrap(); + s.execute("library.backupPreferences", &json!({"dir": null})).unwrap(); + // (committed, not yet persisted: commands persist as they return, this does not) + s.commit("Rate", lightcraft_catalog::Op::SetRating { id, rating: 5 }).unwrap(); + let r = s.execute("library.backup", &json!({})).unwrap(); + let made = PathBuf::from(r["report"]["dir"].as_str().unwrap()); + for name in ["catalog.snap", "prefs.json", "backup.json"] { + assert!(made.join(name).is_file(), "{name}"); + } + drop(s); + assert_eq!(open(&made).catalog.photo(id).unwrap().rating, 5); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Parameters that aren't what they should be are an error, not a backup somewhere else: a +/// folder that isn't a path, a relative one, a flag that isn't one. +#[test] +fn bad_parameters_are_refused() { + let dir = temp_dir("params"); + let mut s = open(&dir); + for p in [json!({"dir": 5}), json!({"dir": ["x"]}), json!({"dir": ""}), json!({"dir": "relative/there"}), json!({"background": "yes"})] { + assert!(matches!(s.execute("library.backup", &p), Err(EngineError::BadParams { .. })), "{p}"); + } + assert!(matches!(s.execute("library.backupPreferences", &json!({"dir": "relative"})), Err(EngineError::BadParams { .. }))); + assert!(matches!(s.execute("library.checkBackup", &json!({"dir": "relative"})), Err(EngineError::BadParams { .. }))); + assert!(backups(&dir.join("Backups")).is_empty() && s.activity.list().is_empty()); + // a name taken by a backup that was cut short is stepped around + std::fs::create_dir_all(dir.join("Backups").join("2026-09-30 12.00.00 UTC.partial")).unwrap(); + let r = s.execute("library.backup", &json!({})).unwrap(); + assert!(r["report"]["dir"].as_str().unwrap().ends_with("2026-09-30 12.00.00 UTC (2)"), "{r}"); + drop(s); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A backup belongs to the library it is of: another library opened in the session has no +/// backup status, and can be backed up while the first one's still runs. +#[test] +fn a_backup_is_its_librarys() { + let (a, b) = (temp_dir("lib-a"), temp_dir("lib-b")); + let mut s = open(&a); + s.backup_hold.store(true, Ordering::SeqCst); + s.execute("library.backup", &json!({"background": true})).unwrap(); + s.open_library(&b, true).unwrap(); + assert!(s.execute("library.backupStatus", &json!({})).unwrap().is_null()); + s.backup_hold.store(false, Ordering::SeqCst); + let r = s.execute("library.backup", &json!({})).unwrap(); + assert!(PathBuf::from(r["report"]["dir"].as_str().unwrap()).starts_with(b.join("Backups")), "{r}"); + let t0 = std::time::Instant::now(); + while !s.activity.list().is_empty() && t0.elapsed() < std::time::Duration::from_secs(20) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(backups(&a.join("Backups")).len(), 1); + drop(s); + for d in [a, b] { + let _ = std::fs::remove_dir_all(d); + } +} diff --git a/crates/ui-egui/locales/cs-formats.json b/crates/ui-egui/locales/cs-formats.json index 1eb882f09d4..f0f09e9e8f0 100644 --- a/crates/ui-egui/locales/cs-formats.json +++ b/crates/ui-egui/locales/cs-formats.json @@ -203,6 +203,8 @@ "{name} opened in the other editor": "{name} otevřeno v druhém editoru", "{n} originals opened in the other editor": "Originály otevřené v druhém editoru: {n}", "· {in_source} identical copies": "· shodné kopie: {in_source}", + "Backed up the library to {}": "Knihovna zálohována do {}", + "The library was not backed up: {}": "Knihovna nebyla zálohována: {}", "{n} photo{}": "fotografií: {n}{:.0}", "{n} photo{} match · updates automatically as photos change": "Odpovídající fotografie: {n}{:.0} · aktualizuje se automaticky při změnách fotografií", "{n} photo{} now · updates automatically as photos change": "Aktuální fotografie: {n}{:.0} · aktualizuje se automaticky při změnách fotografií", diff --git a/crates/ui-egui/locales/cs.json b/crates/ui-egui/locales/cs.json index 52ca94a524d..7d22bc2ebc7 100644 --- a/crates/ui-egui/locales/cs.json +++ b/crates/ui-egui/locales/cs.json @@ -175,6 +175,11 @@ "1 raw can now be developed from its raw data": "1 soubor RAW lze nyní vyvolat z dat RAW", "This raw is now developed from its raw data": "Tento soubor RAW se nyní vyvolává z dat RAW", "This raw variant still can't be decoded": "Tuto variantu RAW stále nelze dekódovat", + "Back Up Library": "Zálohovat knihovnu", + "Backing up the library": "Zálohování knihovny", + "Backup Status": "Stav zálohy", + "Check Backup": "Zkontrolovat zálohu", + "Backup Preferences": "Předvolby zálohování", "Adding to Apple Photos…": "Přidávání do Apple Photos…", "Advanced search…": "Rozšířené hledání…", "After": "Po", diff --git a/crates/ui-egui/locales/de-formats.json b/crates/ui-egui/locales/de-formats.json index 79390f13647..0ac925f1221 100644 --- a/crates/ui-egui/locales/de-formats.json +++ b/crates/ui-egui/locales/de-formats.json @@ -268,6 +268,8 @@ "{name} opened in the other editor": "{name} im anderen Editor geöffnet", "{n} originals opened in the other editor": "{n} Originale im anderen Editor geöffnet", "· {in_source} identical copies": "· {in_source} identische Kopien", + "Backed up the library to {}": "Bibliothek gesichert nach {}", + "The library was not backed up: {}": "Die Bibliothek wurde nicht gesichert: {}", "{count} more warnings.": "{count} weitere Warnungen.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} Katalogbilder wurden nicht importiert, weil ihre Einträge im Katalog unvollständig sind.", "{photos} catalog records processed; {collections} collections.": "{photos} Katalogeinträge verarbeitet; {collections} Sammlungen.", diff --git a/crates/ui-egui/locales/de.json b/crates/ui-egui/locales/de.json index e2205db782f..8c3ebdbb18a 100644 --- a/crates/ui-egui/locales/de.json +++ b/crates/ui-egui/locales/de.json @@ -2205,6 +2205,11 @@ "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "Kein Grafikprozessor gefunden: LightCraft rendert auf der CPU, was viel langsamer ist. Details unter Hilfe → Systeminformationen.", "On NixOS, start it from `nix develop`.": "Unter NixOS startest du es aus `nix develop`.", "Files with the same content as another file in this import: only the first is imported.": "Dateien mit demselben Inhalt wie eine andere Datei dieses Imports: Nur die erste wird importiert.", + "Back Up Library": "Bibliothek sichern", + "Backing up the library": "Bibliothek wird gesichert", + "Backup Status": "Sicherungsstatus", + "Check Backup": "Sicherung prüfen", + "Backup Preferences": "Sicherungseinstellungen", "Lightroom Catalog Import": "Lightroom-Katalogimport", "Destination library": "Zielbibliothek", "Show in Library": "In Bibliothek anzeigen", diff --git a/crates/ui-egui/locales/es-formats.json b/crates/ui-egui/locales/es-formats.json index 33e5f52fc6e..1c4ecb58d76 100644 --- a/crates/ui-egui/locales/es-formats.json +++ b/crates/ui-egui/locales/es-formats.json @@ -268,6 +268,8 @@ "{name} opened in the other editor": "{name} abierto en el otro editor", "{n} originals opened in the other editor": "{n} originales abiertos en el otro editor", "· {in_source} identical copies": "· {in_source} copias idénticas", + "Backed up the library to {}": "Copia de seguridad de la biblioteca guardada en {}", + "The library was not backed up: {}": "No se hizo la copia de seguridad de la biblioteca: {}", "{count} more warnings.": "{count} advertencias más.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "No se importaron {skipped} imágenes del catálogo porque sus registros en el catálogo están incompletos.", "{photos} catalog records processed; {collections} collections.": "{photos} registros del catálogo procesados; {collections} colecciones.", diff --git a/crates/ui-egui/locales/es.json b/crates/ui-egui/locales/es.json index 888af077ff2..7b1b24da8a8 100644 --- a/crates/ui-egui/locales/es.json +++ b/crates/ui-egui/locales/es.json @@ -2208,6 +2208,11 @@ "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "No se encontró ningún procesador gráfico: LightCraft renderiza en la CPU, lo que es mucho más lento. Detalles en Ayuda → Información del sistema.", "On NixOS, start it from `nix develop`.": "En NixOS, inícielo desde `nix develop`.", "Files with the same content as another file in this import: only the first is imported.": "Archivos con el mismo contenido que otro archivo de esta importación: solo se importa el primero.", + "Back Up Library": "Hacer copia de seguridad de la biblioteca", + "Backing up the library": "Haciendo copia de seguridad de la biblioteca", + "Backup Status": "Estado de la copia de seguridad", + "Check Backup": "Comprobar copia de seguridad", + "Backup Preferences": "Preferencias de copia de seguridad", "Lightroom Catalog Import": "Importación de catálogo de Lightroom", "These photos are only in memory. Open a library on disk and import the catalog again to save them.": "Estas fotos solo están en memoria. Abre una biblioteca en disco e importa el catálogo de nuevo para guardarlas.", "Show in Library": "Mostrar en la biblioteca", diff --git a/crates/ui-egui/locales/fr-formats.json b/crates/ui-egui/locales/fr-formats.json index 294273781e0..b261a502e74 100644 --- a/crates/ui-egui/locales/fr-formats.json +++ b/crates/ui-egui/locales/fr-formats.json @@ -268,6 +268,8 @@ "{name} opened in the other editor": "{name} ouvert dans l’autre éditeur", "{n} originals opened in the other editor": "{n} originaux ouverts dans l’autre éditeur", "· {in_source} identical copies": "· {in_source} copies identiques", + "Backed up the library to {}": "Bibliothèque sauvegardée dans {}", + "The library was not backed up: {}": "La bibliothèque n’a pas été sauvegardée : {}", "{count} more warnings.": "{count} avertissements supplémentaires.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} images du catalogue n’ont pas été importées, car leurs entrées dans le catalogue sont incomplètes.", "{photos} catalog records processed; {collections} collections.": "{photos} entrées du catalogue traitées ; {collections} collections.", diff --git a/crates/ui-egui/locales/fr.json b/crates/ui-egui/locales/fr.json index 3278d6ccda6..cfaaae66b47 100644 --- a/crates/ui-egui/locales/fr.json +++ b/crates/ui-egui/locales/fr.json @@ -2204,6 +2204,11 @@ "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "Aucun processeur graphique trouvé : LightCraft effectue le rendu sur le processeur, ce qui est beaucoup plus lent. Détails dans Aide → Informations système.", "On NixOS, start it from `nix develop`.": "Sous NixOS, lancez-le depuis `nix develop`.", "Files with the same content as another file in this import: only the first is imported.": "Fichiers au contenu identique à un autre fichier de cette importation : seul le premier est importé.", + "Back Up Library": "Sauvegarder la bibliothèque", + "Backing up the library": "Sauvegarde de la bibliothèque", + "Backup Status": "État de la sauvegarde", + "Check Backup": "Vérifier la sauvegarde", + "Backup Preferences": "Préférences de sauvegarde", "Lightroom Catalog Import": "Importation de catalogue Lightroom", "These photos are only in memory. Open a library on disk and import the catalog again to save them.": "Ces photos sont uniquement en mémoire. Ouvrez une bibliothèque sur disque et importez à nouveau le catalogue pour les enregistrer.", "Show in Library": "Afficher dans la bibliothèque", diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 7efae90e945..5d8ab3fd617 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -264,6 +264,26 @@ "Keywords of {n} selected photos": "Parole chiave delle foto selezionate: {n}", "new, inside {parent}": "nuova, dentro {parent}", "Delete these {n} effect presets?": "Eliminare questi preset effetto ({n})?", + "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.", + "{name} opened in the other editor": "{name} opened in the other editor", + "{s} s of AV1 video": "{s} s of AV1 video", + "Delete {n} effect preset{}? This can't be undone.": "Delete {n} effect preset{}? This can't be undone.", + "{count} more warnings.": "{count} more warnings.", + "· {in_source} identical copies": "· {in_source} identical copies", + "Backed up the library to {}": "Libreria salvata in {}", + "The library was not backed up: {}": "Il backup della libreria non è stato eseguito: {}", + "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})", + "{n} preset{}": "{n} preset{}", + " — kept but not applied: {}": " — kept but not applied: {}", + "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has", + "Saved template {name}": "Saved template {name}", + "LightCraft stopped unexpectedly: {e}": "LightCraft stopped unexpectedly: {e}", + "Renames {n} face{} across the library. The files are not changed.": "Renames {n} face{} across the library. The files are not changed.", + " · {n} skipped (could not be rendered)": " · {n} skipped (could not be rendered)", + "Delete “{name}”?": "Delete “{name}”?", + "Keywords of {n} selected photos": "Keywords of {n} selected photos", + "new, inside {parent}": "new, inside {parent}", + "Delete these {n} effect presets?": "Delete these {n} effect presets?", "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", "{photos} catalog records processed; {collections} collections.": "Record del catalogo elaborati: {photos}; raccolte: {collections}.", "Skipped {problem}": "Saltato: {problem}", diff --git a/crates/ui-egui/locales/ja-formats.json b/crates/ui-egui/locales/ja-formats.json index 99c14bf16dc..440790e54b4 100644 --- a/crates/ui-egui/locales/ja-formats.json +++ b/crates/ui-egui/locales/ja-formats.json @@ -272,6 +272,8 @@ "{name} opened in the other editor": "{name}を別のエディタで開きました", "{n} originals opened in the other editor": "{n}個の元ファイルを別のエディタで開きました", "· {in_source} identical copies": "・同一のコピー {in_source} 件", + "Backed up the library to {}": "ライブラリを {} にバックアップしました", + "The library was not backed up: {}": "ライブラリをバックアップできませんでした: {}", "{count} more warnings.": "ほかに{count}件の警告があります。", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "カタログ内のレコードが不完全なため、{skipped}件の画像を読み込めませんでした。", "{photos} catalog records processed; {collections} collections.": "カタログの{photos}件のレコードを処理しました。コレクションは{collections}件です。", diff --git a/crates/ui-egui/locales/ja.json b/crates/ui-egui/locales/ja.json index e1834555bd7..447d1b2bd0b 100644 --- a/crates/ui-egui/locales/ja.json +++ b/crates/ui-egui/locales/ja.json @@ -2206,6 +2206,11 @@ "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "グラフィックプロセッサが見つかりません。LightCraftはCPUで描画するため、かなり遅くなります。詳細は「ヘルプ → システム情報」を参照してください。", "On NixOS, start it from `nix develop`.": "NixOSでは `nix develop` から起動してください。", "Files with the same content as another file in this import: only the first is imported.": "この読み込み内の別のファイルと内容が同じファイルです。最初のファイルだけが読み込まれます。", + "Back Up Library": "ライブラリをバックアップ", + "Backing up the library": "ライブラリをバックアップ中", + "Backup Status": "バックアップの状態", + "Check Backup": "バックアップを確認", + "Backup Preferences": "バックアップの環境設定", "Lightroom Catalog Import": "Lightroomカタログの読み込み", "These photos are only in memory. Open a library on disk and import the catalog again to save them.": "これらの写真はメモリ内にのみあります。ディスク上のライブラリを開き、カタログを再度読み込んで保存してください。", "Show in Library": "ライブラリに表示", diff --git a/crates/ui-egui/locales/ka-formats.json b/crates/ui-egui/locales/ka-formats.json index 46036826186..12ca829e11f 100644 --- a/crates/ui-egui/locales/ka-formats.json +++ b/crates/ui-egui/locales/ka-formats.json @@ -243,6 +243,8 @@ "{} — show their photos": "{} — მისი ფოტოების ჩვენება", "· {dups} already in the library": "· უკვე ბიბლიოთეკაშია: {dups}", "· {in_source} identical copies": "· იდენტური ასლები: {in_source}", + "Backed up the library to {}": "ბიბლიოთეკის სარეზერვო ასლი შეიქმნა: {}", + "The library was not backed up: {}": "ბიბლიოთეკის სარეზერვო ასლი ვერ შეიქმნა: {}", "· {n} photo{}": "· ფოტო: {n}{:.0}", "· {trashed} in Recently Deleted": "· ახლახან წაშლილებში: {trashed}", "“{parent}” has a “{name}” already. Merge the two?": "„{parent}“-ში „{name}“ უკვე არსებობს. გაერთიანდეს ორივე?", diff --git a/crates/ui-egui/locales/ka.json b/crates/ui-egui/locales/ka.json index 32c40770018..7b1b2018219 100644 --- a/crates/ui-egui/locales/ka.json +++ b/crates/ui-egui/locales/ka.json @@ -770,6 +770,11 @@ "File ▸ Open Recent Library lists the last 8 libraries; ones that are gone (moved, drive disconnected) are greyed": "ფაილი → ბოლოს გახსნილი ბიბლიოთეკის გახსნა ბოლო 8 ბიბლიოთეკას აჩვენებს; გამქრალი (გადატანილი, დისკი გამორთულია) ბიბლიოთეკები", "Filename": "ფაილის სახელი", "Files with the same content as another file in this import: only the first is imported.": "ფაილები, რომელთა შიგთავსი ამ იმპორტის სხვა ფაილს ემთხვევა: იმპორტდება მხოლოდ პირველი.", + "Back Up Library": "ბიბლიოთეკის სარეზერვო ასლი", + "Backing up the library": "ბიბლიოთეკის სარეზერვო ასლის შექმნა", + "Backup Status": "სარეზერვო ასლის მდგომარეობა", + "Check Backup": "სარეზერვო ასლის შემოწმება", + "Backup Preferences": "სარეზერვო ასლის პარამეტრები", "Fill": "შევსება", "Fill Edges": "კიდეების შევსება", "Fill Location": "მდებარეობის შევსება", diff --git a/crates/ui-egui/locales/pl-formats.json b/crates/ui-egui/locales/pl-formats.json index 20c7f840d6e..19c03b4aab5 100644 --- a/crates/ui-egui/locales/pl-formats.json +++ b/crates/ui-egui/locales/pl-formats.json @@ -247,6 +247,8 @@ "{n} originals opened in the other editor": "Oryginały otwarte w innym edytorze: {n}", "{n} photos opened for editing; each is stacked with its original": "Zdjęcia otwarte do edycji: {n}; każde połączono w stos z oryginałem", "· {in_source} identical copies": "· identyczne kopie: {in_source}", + "Backed up the library to {}": "Utworzono kopię zapasową biblioteki w {}", + "The library was not backed up: {}": "Nie utworzono kopii zapasowej biblioteki: {}", "· {trashed} in Recently Deleted": "· w Ostatnio usuniętych: {trashed}", " in {g} group{}": " w grupach: {g}{:.0}", " · kept, not applied: {}": " · zachowane, niezastosowane: {}", diff --git a/crates/ui-egui/locales/pl.json b/crates/ui-egui/locales/pl.json index adac22e62ad..acc305ec078 100644 --- a/crates/ui-egui/locales/pl.json +++ b/crates/ui-egui/locales/pl.json @@ -2077,6 +2077,11 @@ "Faces": "Twarze", "Faces of a Person": "Twarze osoby", "Files with the same content as another file in this import: only the first is imported.": "Pliki o tej samej zawartości co inny plik w tym imporcie: importowany jest tylko pierwszy.", + "Back Up Library": "Utwórz kopię zapasową biblioteki", + "Backing up the library": "Tworzenie kopii zapasowej biblioteki", + "Backup Status": "Stan kopii zapasowej", + "Check Backup": "Sprawdź kopię zapasową", + "Backup Preferences": "Preferencje kopii zapasowych", "Fill Location": "Uzupełnij lokalizację", "Fill Location from GPS": "Uzupełnij lokalizację z GPS", "Fill empty City, State and Country from GPS (offline GeoNames place names)": "Uzupełnij puste pola Miasto, Region i Kraj na podstawie GPS (nazwy miejsc GeoNames, offline)", diff --git a/crates/ui-egui/locales/pt-br-formats.json b/crates/ui-egui/locales/pt-br-formats.json index f17f2c0fd4b..f1e5dcb7e26 100644 --- a/crates/ui-egui/locales/pt-br-formats.json +++ b/crates/ui-egui/locales/pt-br-formats.json @@ -272,6 +272,8 @@ "{name} opened in the other editor": "{name} aberto no outro editor", "{n} originals opened in the other editor": "{n} originais abertos no outro editor", "· {in_source} identical copies": "· {in_source} cópias idênticas", + "Backed up the library to {}": "Backup da biblioteca salvo em {}", + "The library was not backed up: {}": "O backup da biblioteca não foi feito: {}", "{count} more warnings.": "Mais {count} avisos.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "{skipped} imagens do catálogo não foram importadas porque seus registros no catálogo estão incompletos.", "{photos} catalog records processed; {collections} collections.": "{photos} registros do catálogo processados; {collections} coleções.", diff --git a/crates/ui-egui/locales/pt-br.json b/crates/ui-egui/locales/pt-br.json index e84fb7615b7..e3963f6bccf 100644 --- a/crates/ui-egui/locales/pt-br.json +++ b/crates/ui-egui/locales/pt-br.json @@ -2046,6 +2046,11 @@ "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "Nenhum processador gráfico encontrado: o LightCraft renderiza na CPU, o que é muito mais lento. Detalhes em Ajuda → Informações do sistema.", "On NixOS, start it from `nix develop`.": "No NixOS, inicie-o a partir de `nix develop`.", "Files with the same content as another file in this import: only the first is imported.": "Arquivos com o mesmo conteúdo de outro arquivo desta importação: apenas o primeiro é importado.", + "Back Up Library": "Fazer backup da biblioteca", + "Backing up the library": "Fazendo backup da biblioteca", + "Backup Status": "Status do backup", + "Check Backup": "Verificar backup", + "Backup Preferences": "Preferências de backup", "Lightroom Catalog Import": "Importação de catálogo do Lightroom", "These photos are only in memory. Open a library on disk and import the catalog again to save them.": "Estas fotos estão apenas na memória. Abra uma biblioteca no disco e importe o catálogo novamente para salvá-las.", "Show in Library": "Mostrar na biblioteca", diff --git a/crates/ui-egui/locales/ru-formats.json b/crates/ui-egui/locales/ru-formats.json index 76b7af42764..4398df041aa 100644 --- a/crates/ui-egui/locales/ru-formats.json +++ b/crates/ui-egui/locales/ru-formats.json @@ -268,6 +268,8 @@ "{name} opened in the other editor": "{name} открыт в другом редакторе", "{n} originals opened in the other editor": "Открыто оригиналов в другом редакторе: {n}", "· {in_source} identical copies": "· идентичных копий: {in_source}", + "Backed up the library to {}": "Резервная копия библиотеки сохранена в {}", + "The library was not backed up: {}": "Резервная копия библиотеки не создана: {}", "{count} more warnings.": "Других предупреждений: {count}.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Не импортированы изображения каталога: {skipped}. Их записи в каталоге неполные.", "{photos} catalog records processed; {collections} collections.": "Обработано записей каталога: {photos}; коллекций: {collections}.", diff --git a/crates/ui-egui/locales/ru.json b/crates/ui-egui/locales/ru.json index 306804df045..45e8a6ba6c1 100644 --- a/crates/ui-egui/locales/ru.json +++ b/crates/ui-egui/locales/ru.json @@ -2199,6 +2199,11 @@ "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "Графический процессор не найден: LightCraft выполняет рендеринг на CPU, а это намного медленнее. Подробности: Справка → Сведения о системе.", "On NixOS, start it from `nix develop`.": "В NixOS запускайте его из `nix develop`.", "Files with the same content as another file in this import: only the first is imported.": "Файлы с тем же содержимым, что и другой файл этого импорта: импортируется только первый.", + "Back Up Library": "Резервная копия библиотеки", + "Backing up the library": "Резервное копирование библиотеки", + "Backup Status": "Состояние резервной копии", + "Check Backup": "Проверить резервную копию", + "Backup Preferences": "Настройки резервного копирования", "Lightroom Catalog Import": "Импорт каталога Lightroom", "Destination library": "Библиотека назначения", "Show in Library": "Показать в библиотеке", diff --git a/crates/ui-egui/locales/uk-formats.json b/crates/ui-egui/locales/uk-formats.json index 36022ac1a25..93ac5dc67f8 100644 --- a/crates/ui-egui/locales/uk-formats.json +++ b/crates/ui-egui/locales/uk-formats.json @@ -268,6 +268,8 @@ "{name} opened in the other editor": "{name} відкрито в іншому редакторі", "{n} originals opened in the other editor": "Відкрито оригіналів в іншому редакторі: {n}", "· {in_source} identical copies": "· ідентичних копій: {in_source}", + "Backed up the library to {}": "Резервну копію бібліотеки збережено в {}", + "The library was not backed up: {}": "Резервну копію бібліотеки не створено: {}", "{count} more warnings.": "Інших попереджень: {count}.", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "Не імпортовано зображення каталогу: {skipped}. Їхні записи в каталозі неповні.", "{photos} catalog records processed; {collections} collections.": "Оброблено записів каталогу: {photos}; колекцій: {collections}.", diff --git a/crates/ui-egui/locales/uk.json b/crates/ui-egui/locales/uk.json index ee694ed4fe0..c3ef48b4358 100644 --- a/crates/ui-egui/locales/uk.json +++ b/crates/ui-egui/locales/uk.json @@ -2204,6 +2204,11 @@ "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "Графічний процесор не знайдено: LightCraft виконує рендеринг на ЦП, а це набагато повільніше. Докладніше: Довідка → Інформація про систему.", "On NixOS, start it from `nix develop`.": "У NixOS запускайте його з `nix develop`.", "Files with the same content as another file in this import: only the first is imported.": "Файли з тим самим вмістом, що й інший файл цього імпорту: імпортується лише перший.", + "Back Up Library": "Створити резервну копію бібліотеки", + "Backing up the library": "Створення резервної копії бібліотеки", + "Backup Status": "Стан резервної копії", + "Check Backup": "Перевірити резервну копію", + "Backup Preferences": "Параметри резервного копіювання", "Lightroom Catalog Import": "Імпорт каталогу Lightroom", "Destination library": "Бібліотека призначення", "Show in Library": "Показати в бібліотеці", diff --git a/crates/ui-egui/locales/zh-hans-formats.json b/crates/ui-egui/locales/zh-hans-formats.json index 7406c39b866..c6aa6c7af52 100644 --- a/crates/ui-egui/locales/zh-hans-formats.json +++ b/crates/ui-egui/locales/zh-hans-formats.json @@ -272,6 +272,8 @@ "{name} opened in the other editor": "已在其他编辑器中打开 {name}", "{n} originals opened in the other editor": "已在其他编辑器中打开 {n} 个原始文件", "· {in_source} identical copies": "· {in_source} 个相同副本", + "Backed up the library to {}": "已将图库备份到 {}", + "The library was not backed up: {}": "未能备份图库:{}", "{count} more warnings.": "另有 {count} 条警告。", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "有 {skipped} 张图像未导入,因为它们在目录中的记录不完整。", "{photos} catalog records processed; {collections} collections.": "已处理 {photos} 条目录记录;{collections} 个收藏集。", diff --git a/crates/ui-egui/locales/zh-hans.json b/crates/ui-egui/locales/zh-hans.json index 270af8a6251..3569f4b74b9 100644 --- a/crates/ui-egui/locales/zh-hans.json +++ b/crates/ui-egui/locales/zh-hans.json @@ -2039,6 +2039,11 @@ "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "未找到图形处理器:LightCraft 改用 CPU 渲染,速度会慢很多。详情见“帮助 → 系统信息”。", "On NixOS, start it from `nix develop`.": "在 NixOS 上,请从 `nix develop` 启动。", "Files with the same content as another file in this import: only the first is imported.": "与本次导入中另一个文件内容相同的文件:只导入第一个。", + "Back Up Library": "备份图库", + "Backing up the library": "正在备份图库", + "Backup Status": "备份状态", + "Check Backup": "检查备份", + "Backup Preferences": "备份偏好设置", "Lightroom Catalog Import": "Lightroom 目录导入", "These photos are only in memory. Open a library on disk and import the catalog again to save them.": "这些照片仅保存在内存中。请打开磁盘上的图库并再次导入目录以保存照片。", "Show in Library": "在图库中显示", diff --git a/crates/ui-egui/locales/zh-hant-formats.json b/crates/ui-egui/locales/zh-hant-formats.json index d5c4eb279a2..373f8682b45 100644 --- a/crates/ui-egui/locales/zh-hant-formats.json +++ b/crates/ui-egui/locales/zh-hant-formats.json @@ -272,6 +272,8 @@ "{name} opened in the other editor": "已在其他編輯器中開啟 {name}", "{n} originals opened in the other editor": "已在其他編輯器中開啟 {n} 個原始檔案", "· {in_source} identical copies": "· {in_source} 個相同副本", + "Backed up the library to {}": "已將照片庫備份到 {}", + "The library was not backed up: {}": "未能備份照片庫:{}", "{count} more warnings.": "另有 {count} 則警告。", "{skipped} catalog images were not imported because their records in the catalog are incomplete.": "有 {skipped} 張影像未匯入,因為它們在目錄中的記錄不完整。", "{photos} catalog records processed; {collections} collections.": "已處理 {photos} 筆目錄記錄;{collections} 個收藏集。", diff --git a/crates/ui-egui/locales/zh-hant.json b/crates/ui-egui/locales/zh-hant.json index 0408e23ec87..a9e38d516ec 100644 --- a/crates/ui-egui/locales/zh-hant.json +++ b/crates/ui-egui/locales/zh-hant.json @@ -2007,6 +2007,11 @@ "No graphics processor found: LightCraft renders on the CPU, which is much slower. Details in Help → System Info.": "找不到圖形處理器:LightCraft 改用 CPU 算繪,速度會慢很多。詳情請見「說明 → 系統資訊」。", "On NixOS, start it from `nix develop`.": "在 NixOS 上,請從 `nix develop` 啟動。", "Files with the same content as another file in this import: only the first is imported.": "與本次匯入中另一個檔案內容相同的檔案:只匯入第一個。", + "Back Up Library": "備份照片庫", + "Backing up the library": "正在備份照片庫", + "Backup Status": "備份狀態", + "Check Backup": "檢查備份", + "Backup Preferences": "備份偏好設定", "Lightroom Catalog Import": "Lightroom 目錄匯入", "These photos are only in memory. Open a library on disk and import the catalog again to save them.": "這些相片僅保存在記憶體中。請開啟磁碟上的照片庫並再次匯入目錄以儲存相片。", "Show in Library": "在照片庫中顯示", diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index fa10210f0a3..e01a71f525d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -361,6 +361,28 @@ impl LightcraftApp { panels::slideshow::tick(self, ctx, now); } + /// Announce the end of a library backup: where it went, or why there is none. + fn backup_status(&mut self, ctx: &egui::Context) { + let Some(b) = self.session.backup.clone() else { return }; + let key = std::sync::Arc::as_ptr(&b) as usize; + if self.ui.backup_seen == Some(key) { + return; + } + match b.outcome() { + Some(outcome) => { + self.ui.backup_seen = Some(key); + let msg = match outcome { + Ok(report) => crate::i18n::tr_format!("Backed up the library to {}", report.dir.display()), + Err(e) => crate::i18n::tr_format!("The library was not backed up: {}", e), + }; + // (long enough to read a path, or what went wrong) + self.toast_for(ctx, msg, 8.0); + } + // The activity stack shows the backup while it runs; poll for the end. + None => ctx.request_repaint_after(std::time::Duration::from_millis(250)), + } + } + /// Announce the end of a Build Previews run. fn preview_build_status(&mut self, ctx: &egui::Context) { use std::sync::atomic::Ordering; diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 6e92091c780..4cec8f71103 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -71,6 +71,7 @@ impl LightcraftApp { tasks::poll(self, ctx); updates_ui::tick(self, ctx); self.preview_build_status(ctx); + self.backup_status(ctx); self.save_status(ctx); self.ai_mask_detail(ctx, now); self.place_names_outcome(ctx); diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index 5c1bcb9fc1c..6ea6b3b91c8 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -136,6 +136,7 @@ const LAYOUT: &[(&str, &[&str])] = &[ "@Open Recent Library", "file.backupLibrary", "file.restoreLibrary", + "library.backup", "---", "dialog.newAlbum", "dialog.newFolder", @@ -361,6 +362,8 @@ fn host_supports(app: &LightcraftApp, id: &str) -> bool { match id { "file.backupLibrary" => app.services.backup_library.is_some(), "file.restoreLibrary" => app.services.restore_library.is_some(), + // a library that is a folder on disk is backed up to a folder (the browser's has its own backup, above) + "library.backup" => app.session.library.as_ref().is_some_and(|l| l.on_disk), "photo.restore" | "photo.deletePermanently" => selection_deleted(app), "photo.delete" => !selection_deleted(app), // only in an album that holds its photos (not a smart one) diff --git a/crates/ui-egui/src/menus/menubar/tests.rs b/crates/ui-egui/src/menus/menubar/tests.rs index 1e2fe388dde..b3743849d9b 100644 --- a/crates/ui-egui/src/menus/menubar/tests.rs +++ b/crates/ui-egui/src/menus/menubar/tests.rs @@ -198,6 +198,24 @@ fn file_menu_starts_with_the_import_entry_points() { assert!(!text.contains("Add Folder") && !text.contains("\"Add Photos"), "no add-folder wording left in the menus"); } +/// File ▸ Back Up Library is for a library that is a folder on disk: in its menu and +/// backing it up; absent where the library has no folder (the browser's has its own backup). +#[test] +fn back_up_library_is_offered_for_a_library_on_disk() { + let all = |app: &LightcraftApp| -> Vec { menu_bar(app).into_iter().flat_map(|(_, v)| v).collect() }; + assert!(find(&all(&app()), "library.backup").is_none(), "the demo library has no folder"); + let dir = std::env::temp_dir().join(format!("lc-menubar-backup-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut session = lightcraft_engine::Session::new(); + session.open_library(&dir, true).unwrap(); + let mut on_disk = LightcraftApp::new(session, crate::Services::default()); + assert!(matches!(find(&all(&on_disk), "library.backup"), Some(MenuNode::Item { enabled: true, .. }))); + let r = run_item(&mut on_disk, "library.backup", json!({"background": false})).unwrap(); + assert!(r["error"].is_null() && std::path::Path::new(r["report"]["dir"].as_str().unwrap()).starts_with(dir.join("Backups")), "{r}"); + drop(on_disk); + let _ = std::fs::remove_dir_all(&dir); +} + /// Back Up / Restore Library are the browser build's (its library lives in browser storage): /// absent from the desktop's menus, present and wired to the host where it provides them. #[test] diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index c88a502078d..ce3922513c7 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -149,6 +149,14 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option f(&mut app.session), - None => Err("not available here: on the desktop the library is a folder; back it up with your other files".into()), + None => { + Err("not available here: on the desktop the library is a folder; File ▸ Back Up Library (`library.backup`) backs up its catalog" + .into()) + } } } "view.filmstrip" => { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 38b50902c50..08250b93bb4 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -36,6 +36,8 @@ pub struct UiState { /// The Build Previews run last announced (its identity, finished?). #[serde(skip)] pub preview_build_seen: Option<(usize, bool)>, + /// The library backup whose end was announced (see `backup_status`). + pub backup_seen: Option, /// Saving the library is failing (announced with a toast; the top bar shows a warning until /// a later save succeeds). #[serde(skip)] @@ -362,6 +364,7 @@ impl Default for UiState { docking_version: crate::docking::DOCKING_VERSION, language: crate::i18n::default_language(), preview_build_seen: None, + backup_seen: None, unsaved_seen: false, frame_rate: std::env::var("LIGHTCRAFT_FPS").is_ok_and(|v| matches!(v.trim(), "1" | "on" | "true" | "yes")), luminance_map_restore: None, diff --git a/docs/web.md b/docs/web.md index f6d7158a8ef..213d931cdc2 100644 --- a/docs/web.md +++ b/docs/web.md @@ -120,7 +120,8 @@ are the same in every version, so serve them with `Cache-Control: no-cache` (not entry's checksum is verified, and each restored original must match its content hash) and only then switches to it (`active-library` names the folder in use) and reloads: the previous library stays in storage. Both are web-only (`file.backupLibrary`, `file.restoreLibrary`; the - desktop library is a folder). + desktop library is a folder, whose catalog File ▸ Back Up Library, `library.backup`, backs up to a + folder: `docs/catalog-persistence.md` → Backups). - A failed save (quota exceeded, storage cleared) is not silent: the catalog then refuses new writes, so commands report `saved in memory but not written`, the top bar shows the unsaved warning (as on the desktop, see `docs/control-protocol.md`), and saving is retried every From c2bde11787500eda678d27f0e2876a31380a5fff Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 11 Oct 2026 09:15:52 -0400 Subject: [PATCH 23/61] Catalog: the library's own files are one list, and backups take all of it The files a library keeps beside its catalog were named in three places: the list a backup takes along, the list the browser build reads at start-up, and the strings library.rs reads and writes. A new file had to be remembered in each, or backups would silently leave it out. library::SettingsFile is now the one list. Backup and restore take SETTINGS_FILES, the browser build's list is made from it (a test holds that it has every one), and the library's file store refuses to write a file that is not listed, with an error that says where to list it: the change that adds a file meets that in its first test. Co-Authored-By: Claude Opus 5.5 --- apps/lightcraft-web/src/files.rs | 15 ++++- crates/engine/src/cmd/backup.rs | 4 +- crates/engine/src/library.rs | 102 ++++++++++++++++++++++++++---- crates/engine/src/tests/backup.rs | 38 +++++++++++ 4 files changed, 142 insertions(+), 17 deletions(-) diff --git a/apps/lightcraft-web/src/files.rs b/apps/lightcraft-web/src/files.rs index 4712e2c83e0..5e9877d5e8f 100644 --- a/apps/lightcraft-web/src/files.rs +++ b/apps/lightcraft-web/src/files.rs @@ -17,6 +17,7 @@ use std::io; use std::sync::{Arc, Mutex}; use lightcraft_engine::catalog::Store; +use lightcraft_engine::library::SettingsFile; /// What has to be written for a dirty file. #[derive(Clone, Debug, PartialEq)] @@ -199,8 +200,10 @@ impl Store for FilesStore { } } -/// Names of the library files read at start-up. -pub const LIBRARY_FILES: [&str; 6] = ["catalog.snap", "catalog.log", "presets.json", "view.json", "prefs.json", "ui.json"]; +/// Names of the library files read at start-up: the catalog, the library's own files (every one +/// of `SettingsFile::ALL`; a test holds that), and the interface's. +pub const LIBRARY_FILES: [&str; 6] = + ["catalog.snap", "catalog.log", SettingsFile::Presets.name(), SettingsFile::View.name(), SettingsFile::Prefs.name(), "ui.json"]; /// Is a browser storage error, by its `DOMException` name, "the entry doesn't exist"? Only /// `NotFoundError` is; anything else (security, type mismatch, an unreadable store) is a failure. @@ -230,6 +233,14 @@ mod tests { use lightcraft_engine::library::LibraryStores; use serde_json::json; + /// Every file the library has is read at start-up (and so saved and backed up by the page). + #[test] + fn every_file_of_the_library_is_read_at_start_up() { + for file in SettingsFile::ALL { + assert!(LIBRARY_FILES.contains(&file.name()), "{}", file.name()); + } + } + /// Apply flush ops to a "disk" map, as the backend would. fn flush(files: &Files, disk: &mut BTreeMap>) { for op in files.take_dirty() { diff --git a/crates/engine/src/cmd/backup.rs b/crates/engine/src/cmd/backup.rs index 2174fff33d6..022bbe817eb 100644 --- a/crates/engine/src/cmd/backup.rs +++ b/crates/engine/src/cmd/backup.rs @@ -20,8 +20,8 @@ use crate::{Result, Session}; /// The folder in the library that backups go to unless another is asked for. pub const BACKUPS: &str = "Backups"; -/// The library's other files a backup takes along. -const ALSO: &[&str] = &["presets.json", "view.json", "prefs.json"]; +/// The library's other files a backup takes along: every one it has. +const ALSO: &[&str] = &crate::library::SETTINGS_FILES; /// A backup under way, or the last one made. #[derive(Default)] diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 015cb443a72..c7c9bfb8cd9 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -76,8 +76,8 @@ pub struct Library { /// cached in `thumbs/`. pub on_disk: bool, journal: Journal, - /// presets.json, view.json, prefs.json. - files: Box, + /// The library's own files beside the catalog ([`SettingsFile`]). + pub(crate) files: Box, /// What happened when the catalog was loaded. pub report: LoadReport, /// Last persistence error (shown by the UI; ops stay pending and are retried). @@ -106,13 +106,88 @@ pub struct Library { lock: Option, } +/// One of the library's own files beside the catalog: what it remembers that is not in the +/// catalog. This is the one list of them. A file the library writes there is a file its backups +/// take along (`cmd::backup`) and the browser build reads at start-up, so the library's file +/// store writes no file that is not here ([`Listed`]): add a variant, and both follow. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SettingsFile { + /// User presets and favourites. + Presets, + /// What the library shows: source, sort, filter. + View, + /// Preferences that belong to the library. + Prefs, +} + +impl SettingsFile { + pub const ALL: [SettingsFile; 3] = [SettingsFile::Presets, SettingsFile::View, SettingsFile::Prefs]; + + pub const fn name(self) -> &'static str { + match self { + SettingsFile::Presets => "presets.json", + SettingsFile::View => "view.json", + SettingsFile::Prefs => "prefs.json", + } + } +} + +/// The names of [`SettingsFile::ALL`]. +pub const SETTINGS_FILES: [&str; 3] = [SettingsFile::Presets.name(), SettingsFile::View.name(), SettingsFile::Prefs.name()]; + +const PRESETS: &str = SettingsFile::Presets.name(); +const VIEW: &str = SettingsFile::View.name(); +const PREFS: &str = SettingsFile::Prefs.name(); + +/// The library's file store, writing only the files the library lists ([`SettingsFile`]), and +/// one of those set aside under its own name (`prefs.json.corrupt-…`). +struct Listed(Box); + +impl Listed { + fn check(name: &str) -> std::io::Result<()> { + let listed = SETTINGS_FILES.iter().any(|file| name.strip_prefix(file).is_some_and(|rest| rest.is_empty() || rest.starts_with('.'))); + if listed { + return Ok(()); + } + Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!("{name} is not one of the library's files: list it in library::SettingsFile, so that backups take it along"), + )) + } +} + +impl Store for Listed { + fn read(&mut self, name: &str) -> std::io::Result>> { + self.0.read(name) + } + fn write_atomic(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + Listed::check(name)?; + self.0.write_atomic(name, data) + } + fn append(&mut self, name: &str, data: &[u8]) -> std::io::Result<()> { + Listed::check(name)?; + self.0.append(name, data) + } + fn truncate(&mut self, name: &str, len: u64) -> std::io::Result<()> { + Listed::check(name)?; + self.0.truncate(name, len) + } + fn remove(&mut self, name: &str) -> std::io::Result<()> { + Listed::check(name)?; + self.0.remove(name) + } + fn describe(&self) -> String { + self.0.describe() + } +} + /// Where a library's files live (see [`Session::open_library_in`]). pub struct LibraryStores { /// Shown as the library's location (`library.info`). pub dir: PathBuf, /// The catalog journal (`catalog.snap`, `catalog.log`). pub catalog: Box, - /// presets.json, view.json, prefs.json. + /// The library's own files beside the catalog ([`SettingsFile`]). pub files: Box, /// `dir` is a real directory (enables `Originals/` copies and the `thumbs/` disk cache). pub on_disk: bool, @@ -483,7 +558,8 @@ impl Session { /// Open `stores`; the new library takes `lock` once nothing can fail any more. fn open_stores(&mut self, stores: LibraryStores, seed_demo: bool, lock: &mut Option) -> Result<()> { - let LibraryStores { dir, catalog, mut files, on_disk } = stores; + let LibraryStores { dir, catalog, files, on_disk } = stores; + let mut files: Box = Box::new(Listed(files)); self.media.smart_dir = on_disk.then(|| crate::smart::dir(&dir)); // the current library may be these same files: let its background snapshot land first if let Some(old) = self.library.as_mut() @@ -529,7 +605,7 @@ impl Session { } let mut settings = SettingsLoad::default(); // preferences - let prefs = settings.read::(files.as_mut(), "prefs.json").unwrap_or_default(); + let prefs = settings.read::(files.as_mut(), PREFS).unwrap_or_default(); self.xmp = prefs.xmp; self.backup_dir = prefs.backup_dir; self.last_export = prefs.last_export; @@ -561,7 +637,7 @@ impl Session { self.media.smart_dir = Some(d.clone()); } // presets - if let Some(f) = settings.read::(files.as_mut(), "presets.json") { + if let Some(f) = settings.read::(files.as_mut(), PRESETS) { for p in &mut self.presets { p.favorite = p.builtin && f.favorites.contains(&p.id) || (!p.builtin && p.favorite); } @@ -576,7 +652,7 @@ impl Session { self.profile_recent = f.profile_recent.into_iter().filter(known).take(crate::presets::RECENT_PROFILES).collect(); } // view state - if let Some(v) = settings.read::(files.as_mut(), "view.json") { + if let Some(v) = settings.read::(files.as_mut(), VIEW) { self.source = v.source; self.browse = v.browse; self.library_folder = v.library_folder.filter(|f| !f.trim().is_empty()); @@ -686,7 +762,7 @@ impl Session { log::error!("library: compaction: {e}"); lib.last_error = Some(format!("compaction: {e}")); } - let due = self.library.as_ref().is_some_and(|l| l.presets_saved.differs(self) && !l.blocked.contains(&"presets.json")); + let due = self.library.as_ref().is_some_and(|l| l.presets_saved.differs(self) && !l.blocked.contains(&PRESETS)); if !due { return Ok(()); } @@ -697,7 +773,7 @@ impl Session { if state.hash == lib.presets_saved.hash { lib.presets_saved = state; lib.presets_error = None; - } else if let Err(e) = lib.files.write_atomic("presets.json", presets.as_bytes()) { + } else if let Err(e) = lib.files.write_atomic(PRESETS, presets.as_bytes()) { // the state stays stale: retried by the next command and the frame loop (backing off); // meanwhile the presets count as unsaved, so the UI warns and a backup refuses log::error!("library: presets: {e}"); @@ -801,8 +877,8 @@ impl Session { } let v = self.view_json(); let Some(lib) = self.library.as_mut() else { return }; - if v != lib.view_written && !lib.blocked.contains(&"view.json") { - match lib.files.write_atomic("view.json", &v) { + if v != lib.view_written && !lib.blocked.contains(&VIEW) { + match lib.files.write_atomic(VIEW, &v) { Ok(()) => lib.view_written = v, Err(e) => log::error!("library: view: {e}"), } @@ -840,12 +916,12 @@ impl Session { }) .unwrap_or_default(); let Some(lib) = self.library.as_mut() else { return Ok(()) }; - if lib.blocked.contains(&"prefs.json") { + if lib.blocked.contains(&PREFS) { return Err(EngineError::Other( "prefs: prefs.json couldn't be read when the library opened, so it isn't overwritten; reopen the library to save preferences".into(), )); } - lib.files.write_atomic("prefs.json", &v).map_err(|e| EngineError::Other(format!("prefs: {e}"))) + lib.files.write_atomic(PREFS, &v).map_err(|e| EngineError::Other(format!("prefs: {e}"))) } /// Warnings about the open library not handed out yet: its settings files, and a lock that diff --git a/crates/engine/src/tests/backup.rs b/crates/engine/src/tests/backup.rs index f8feab65c42..c43f6058beb 100644 --- a/crates/engine/src/tests/backup.rs +++ b/crates/engine/src/tests/backup.rs @@ -243,3 +243,41 @@ fn a_backup_is_its_librarys() { let _ = std::fs::remove_dir_all(d); } } + +/// Given a library with every one of its own files (presets, view, preferences), when it is +/// backed up, then the backup has each of them, as it is in the library. +#[test] +fn a_backup_takes_every_file_of_the_library() { + use crate::library::SettingsFile; + let dir = temp_dir("every-file"); + let mut s = open(&dir); + for file in SettingsFile::ALL { + std::fs::write(dir.join(file.name()), format!("{{\"file\":\"{}\"}}", file.name())).unwrap(); + } + let made = s.execute("library.backup", &json!({})).unwrap(); + let backup = PathBuf::from(made["report"]["dir"].as_str().unwrap()); + for file in SettingsFile::ALL { + assert_eq!(std::fs::read(backup.join(file.name())).unwrap(), std::fs::read(dir.join(file.name())).unwrap(), "{}", file.name()); + } + assert_eq!(crate::library::SETTINGS_FILES.to_vec(), SettingsFile::ALL.map(SettingsFile::name).to_vec()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Given an open library, when something writes a file beside the catalog that the library does +/// not list, then it is refused, and the error says where to list it: a file the library writes +/// is a file its backups take along, so there is no writing one without listing it. A listed +/// file, and a damaged one set aside under its name, are written. +#[test] +fn the_library_writes_only_the_files_it_lists() { + let dir = temp_dir("listed-files"); + let mut s = open(&dir); + let files = &mut s.library.as_mut().unwrap().files; + let e = files.write_atomic("locations.json", b"{}").unwrap_err(); + assert!(e.to_string().contains("locations.json") && e.to_string().contains("SettingsFile"), "{e}"); + assert!(files.append("locations.json", b"{}").is_err()); + assert!(!dir.join("locations.json").exists()); + files.write_atomic("view.json", b"{}").unwrap(); + files.write_atomic("prefs.json.corrupt-1", b"{").unwrap(); + assert!(dir.join("view.json").exists() && dir.join("prefs.json.corrupt-1").exists()); + let _ = std::fs::remove_dir_all(&dir); +} From fdb46e3800d4f98cd28aad5ac2b72ef721d54bda Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 18 Oct 2026 11:14:31 -0400 Subject: [PATCH 24/61] Catalog: a backup ignores what the OS writes into its folder, and a menu's default is the menu's MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - backup::check and the .partial sweep skip .DS_Store, Thumbs.db, desktop.ini and ._ files (also in segments/): looking at a backup in Finder or Explorer made a sound backup fail its check. - The background default of File ▸ Back Up Library is in menubar::run_item (and the in-app key dispatch), not in run_ui_command: a script's or the control channel's backup returns when it is made, as the command says. - The sweep takes a .partial folder for stale only when its segments folder is an hour old too; tests' same_file is None where hard links can't be told; UiState.backup_seen is not saved. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/backup.rs | 19 +++++++++--- crates/catalog/src/tests_backup.rs | 37 +++++++++++++++++------ crates/ui-egui/src/menus/menubar.rs | 13 ++++++++ crates/ui-egui/src/menus/menubar/tests.rs | 25 +++++++++++++++ crates/ui-egui/src/menus/run.rs | 8 ----- crates/ui-egui/src/shortcuts.rs | 12 ++++++-- crates/ui-egui/src/state.rs | 4 ++- crates/ui-egui/src/state/settings.rs | 12 ++++++++ 8 files changed, 103 insertions(+), 27 deletions(-) diff --git a/crates/catalog/src/backup.rs b/crates/catalog/src/backup.rs index 1b222a9168c..6f560435354 100644 --- a/crates/catalog/src/backup.rs +++ b/crates/catalog/src/backup.rs @@ -264,19 +264,28 @@ fn previous(dest: &Path) -> Option<(PathBuf, BTreeMap)> { }) } +/// A file an operating system writes into a folder that somebody looked at (Finder, Explorer): not +/// the backup's, and no change to it, so it does not make a sound backup fail its check. +fn os_metadata(name: &str) -> bool { + let name = name.rsplit('/').next().unwrap_or(name); + matches!(name, ".DS_Store" | "Thumbs.db" | "desktop.ini") || name.starts_with("._") +} + /// Remove what a backup that was cut short left in `dest`: folders `.partial` an hour old -/// or more (one being written now, by this or another program, is younger) that hold nothing -/// but what a backup holds. Anything else of that name is left alone. +/// or more (one being written now, by this or another program, is younger: the folder or its +/// `segments` folder, which is where a backup writes most, was changed less than an hour ago) +/// that hold nothing but what a backup holds. Anything else of that name is left alone. fn sweep(dest: &Path, also: &[&str]) { let Ok(entries) = std::fs::read_dir(dest) else { return }; + let age = |p: &Path| std::fs::symlink_metadata(p).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()); for entry in entries.flatten() { let (Ok(name), path) = (entry.file_name().into_string(), entry.path()) else { continue }; - let old = std::fs::symlink_metadata(&path).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age >= STALE); + let old = age(&path).is_some_and(|a| a >= STALE) && age(&path.join(segments::SEGMENT_DIR)).is_none_or(|a| a >= STALE); if !name.ends_with(PARTIAL) || !old || !std::fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir()) { continue; } let ours = held(&path).is_ok_and(|names| { - names.iter().all(|n| n == SNAPSHOT || n == LOG || n == MARKER || also.contains(&n.as_str()) || segments::valid_name(n)) + names.iter().all(|n| n == SNAPSHOT || n == LOG || n == MARKER || also.contains(&n.as_str()) || segments::valid_name(n) || os_metadata(n)) }); if ours && let Err(e) = std::fs::remove_dir_all(&path) { log::warn!("backup: can't remove {}: {e}", path.display()); @@ -514,7 +523,7 @@ pub fn check(dir: &Path) -> Result { } } for name in held(dir).map_err(|e| changed(format!("{e}, and was not part of the backup")))? { - if name != MARKER && !report.contents.contains_key(&name) { + if name != MARKER && !report.contents.contains_key(&name) && !os_metadata(&name) { return Err(changed(format!("{name} was not part of the backup"))); } } diff --git a/crates/catalog/src/tests_backup.rs b/crates/catalog/src/tests_backup.rs index b3eafabe8bd..cd0d154bc8f 100644 --- a/crates/catalog/src/tests_backup.rs +++ b/crates/catalog/src/tests_backup.rs @@ -96,18 +96,19 @@ fn segments(dir: &Path) -> Vec { files(dir).into_iter().filter(|n| n.starts_with(SEGMENT_PREFIX)).collect() } -/// Whether two paths are the same file on disk (one a hard link of the other). -fn same_file(a: &Path, b: &Path) -> bool { +/// Whether two paths are the same file on disk (one a hard link of the other): `None` where that +/// can't be told (not on Unix), so that an assertion on it is skipped there, not passed. +fn same_file(a: &Path, b: &Path) -> Option { #[cfg(unix)] { use std::os::unix::fs::MetadataExt; let (a, b) = (std::fs::metadata(a).unwrap(), std::fs::metadata(b).unwrap()); - (a.dev(), a.ino()) == (b.dev(), b.ino()) + Some((a.dev(), a.ino()) == (b.dev(), b.ino())) } #[cfg(not(unix))] { let _ = (a, b); - true + None } } @@ -160,7 +161,7 @@ fn a_second_backup_shares_the_files_that_did_not_change() { let shared: Vec<&String> = new.iter().filter(|n| old.contains(n)).collect(); assert_eq!(shared.len(), 2); for name in shared { - assert!(same_file(&first.dir.join(name), &second.dir.join(name)), "{name} was copied"); + assert_ne!(same_file(&first.dir.join(name), &second.dir.join(name)), Some(false), "{name} was copied"); } // each backup is the library of its day assert_eq!(opened(&second.dir).to_snapshot(), c.to_snapshot()); @@ -338,7 +339,7 @@ fn a_damaged_file_in_the_backup_before_is_not_shared() { std::fs::write(first.dir.join(&name), &bytes).unwrap(); let second = back_up(&lib, &dest, "b"); assert_eq!((second.linked, second.segments), (2, 3)); - assert!(!same_file(&first.dir.join(&name), &second.dir.join(&name))); + assert_ne!(same_file(&first.dir.join(&name), &second.dir.join(&name)), Some(true)); backup::check(&second.dir).unwrap(); assert_eq!(opened(&second.dir).to_snapshot(), c.to_snapshot()); } @@ -364,7 +365,7 @@ fn only_a_finished_backup_of_the_same_files_is_shared_with() { let second = back_up(&lib, &dest, "b"); assert_eq!(second.linked, 3); for name in segments(&second.dir) { - assert!(same_file(&first.dir.join(&name), &second.dir.join(&name)), "{name}"); + assert_ne!(same_file(&first.dir.join(&name), &second.dir.join(&name)), Some(false), "{name}"); } // a backup whose snapshot states another checksum for a file of the same name let (other_lib, other_dest) = (temp("lib"), temp("dest")); @@ -380,16 +381,19 @@ fn only_a_finished_backup_of_the_same_files_is_shared_with() { } /// A folder left by a backup that was cut short (`.partial`) is never taken for a backup, -/// is in nobody's way while it may still be written, and is removed by a later backup once it +/// is in nobody's way while it may still be written (the folder, or its `segments` folder where a +/// backup writes most, changed less than an hour ago), and is removed by a later backup once it /// is old. A folder of that name that holds anything else is not touched. #[test] fn what_a_backup_cut_short_left_is_cleared_away_later() { let (lib, dest) = (temp("lib"), temp("dest")); let (j, _c) = library(&lib, 12); drop(j); + let then = || std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 3600); + let old_top = |dir: &Path| std::fs::File::open(dir).unwrap().set_modified(then()).unwrap(); let old = |dir: &Path| { - let then = std::time::SystemTime::now() - std::time::Duration::from_secs(2 * 3600); - std::fs::File::open(dir).unwrap().set_modified(then).unwrap(); + old_top(&dir.join("segments")); + old_top(dir); }; let partial = |name: &str, extra: Option<&str>| { let dir = dest.join(name); @@ -402,13 +406,17 @@ fn what_a_backup_cut_short_left_is_cleared_away_later() { dir }; let (stale, fresh, foreign) = (partial("x.partial", None), partial("y.partial", None), partial("z.partial", Some("thesis.txt"))); + // one whose folder is quiet but whose segments are being written now (another backup, to the same place) + let writing = partial("w.partial", None); old(&stale); old(&foreign); + old_top(&writing); // a name whose partial folder is there is taken assert!(matches!(backup::back_up(&lib, &dest, &options("y"), &()), Err(BackupError::Exists(_)))); back_up(&lib, &dest, "a"); assert!(!stale.exists(), "an old one is removed"); assert!(fresh.exists(), "one that may be being written is not"); + assert!(writing.join("segments").exists(), "one whose segments are being written is not"); assert!(foreign.join("thesis.txt").exists(), "a folder holding something else is not ours to remove"); } @@ -462,6 +470,15 @@ fn a_backup_that_was_touched_is_found_out() { let copy = copy_of(&made.dir, "added"); std::fs::write(copy.join("notes.txt"), b"mine").unwrap(); assert!(matches!(backup::check(©), Err(BackupError::Changed(msg)) if msg.contains("notes.txt"))); + // what a file manager writes into a folder somebody looked at is no change of the backup, + // beside it and among its segments; a file that is none of those is + let copy = copy_of(&made.dir, "looked-at"); + for name in [".DS_Store", "Thumbs.db", "desktop.ini", "._catalog.snap", "segments/.DS_Store"] { + std::fs::write(copy.join(name), b"os").unwrap(); + } + assert_eq!(backup::check(©).unwrap(), made); + std::fs::write(copy.join("segments/notes.txt"), b"mine").unwrap(); + assert!(matches!(backup::check(©), Err(BackupError::Changed(msg)) if msg.contains("notes.txt"))); // a link to the file elsewhere is not the file: the backup has to stand on its own #[cfg(unix)] { diff --git a/crates/ui-egui/src/menus/menubar.rs b/crates/ui-egui/src/menus/menubar.rs index 6ea6b3b91c8..58c0150dd8b 100644 --- a/crates/ui-egui/src/menus/menubar.rs +++ b/crates/ui-egui/src/menus/menubar.rs @@ -915,10 +915,23 @@ pub fn menu_bar(app: &LightcraftApp) -> Vec<(String, Vec)> { bar } +/// What a menu item asks for that the command's own default does not: from a menu a backup runs +/// while the library stays in use (its row is in the activity stack, and a toast says how it +/// ended). Only here: the engine's own default, which a script or the control channel gets, is to +/// return when the backup is made. +pub(crate) fn menu_defaults(id: &str, params: &mut Value) { + if id == "library.backup" + && let Some(p) = params.as_object_mut() + { + p.entry("background").or_insert(Value::Bool(true)); + } +} + /// Run a menu item. Rating, flag and label items behave like their keys (the active photo only in /// Compare/Survey; Auto Advance moves on). pub fn run_item(app: &mut LightcraftApp, id: &str, params: Value) -> Result { let mut params = if params.is_null() { json!({}) } else { params }; + menu_defaults(id, &mut params); let culling_cmd = matches!( id, "photo.rate" diff --git a/crates/ui-egui/src/menus/menubar/tests.rs b/crates/ui-egui/src/menus/menubar/tests.rs index b3743849d9b..b0af46fb9f1 100644 --- a/crates/ui-egui/src/menus/menubar/tests.rs +++ b/crates/ui-egui/src/menus/menubar/tests.rs @@ -216,6 +216,31 @@ fn back_up_library_is_offered_for_a_library_on_disk() { let _ = std::fs::remove_dir_all(&dir); } +/// A backup from a menu runs in the background unless it says otherwise; one asked for by a +/// script or the control channel (not through a menu) is the engine's own: it returns when +/// the backup is made. +#[test] +fn only_a_menu_backup_defaults_to_the_background() { + let mut p = json!({}); + menu_defaults("library.backup", &mut p); + assert_eq!(p, json!({"background": true})); + let mut p = json!({"background": false}); + menu_defaults("library.backup", &mut p); + assert_eq!(p, json!({"background": false})); + let mut p = json!({}); + menu_defaults("library.restore", &mut p); + assert_eq!(p, json!({})); + let dir = std::env::temp_dir().join(format!("lc-menubar-script-backup-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut session = lightcraft_engine::Session::new(); + session.open_library(&dir, true).unwrap(); + let mut app = LightcraftApp::new(session, crate::Services::default()); + let r = app.run("library.backup", json!({})).unwrap(); + assert!(r["running"] == json!(false) && r["report"]["dir"].is_string(), "{r}"); + drop(app); + let _ = std::fs::remove_dir_all(&dir); +} + /// Back Up / Restore Library are the browser build's (its library lives in browser storage): /// absent from the desktop's menus, present and wired to the host where it provides them. #[test] diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index ce3922513c7..f89534e31c3 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -149,14 +149,6 @@ pub fn run_ui_command(app: &mut LightcraftApp, id: &str, p: &Value) -> Option, - /// The library backup whose end was announced (see `backup_status`). + /// The library backup whose end was announced (see `backup_status`): an address, only good + /// for this run. + #[serde(skip)] pub backup_seen: Option, /// Saving the library is failing (announced with a toast; the top bar shows a warning until /// a later save succeeds). diff --git a/crates/ui-egui/src/state/settings.rs b/crates/ui-egui/src/state/settings.rs index fff943b4cfc..f093bca448c 100644 --- a/crates/ui-egui/src/state/settings.rs +++ b/crates/ui-egui/src/state/settings.rs @@ -448,6 +448,18 @@ mod loupe_info_tests { assert!(!newer.film_names, "the rest of the settings are still read"); } + /// The backup whose end was announced is an address in this run: a settings file never keeps + /// it (it could silence the next run's first backup announcement). + #[test] + fn the_announced_backup_is_not_saved() { + use crate::state::UiState; + let ui = UiState { backup_seen: Some(0x1234), ..UiState::default() }; + let saved = serde_json::to_string(&ui).unwrap(); + assert!(!saved.contains("backupSeen") && !saved.contains("backup_seen"), "{saved}"); + let read: UiState = serde_json::from_str(&saved).unwrap(); + assert_eq!(read.backup_seen, None); + } + /// Show message when loading or rendering photos is on until it is turned off, and is saved /// with the app's settings. #[test] From 5e38caf673dce499b5d891e59b3838360ffcbbd0 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 18 Oct 2026 11:39:36 -0400 Subject: [PATCH 25/61] Catalog: sweep takes only a missing segments folder for quiet, and the check's docs name the ignored OS files A segments folder whose time is yet to come (clock skew) is not old. Test: a stale .partial that Finder visited is swept. Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/backup.rs | 14 +++++++++++--- crates/catalog/src/tests_backup.rs | 2 ++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/crates/catalog/src/backup.rs b/crates/catalog/src/backup.rs index 6f560435354..026ff876072 100644 --- a/crates/catalog/src/backup.rs +++ b/crates/catalog/src/backup.rs @@ -22,7 +22,8 @@ //! //! **A backup says what it holds.** Its marker file, `backup.json`, lists every file with its //! size and CRC-32 (the segments' are also in `catalog.snap`). [`check`] reads a backup against -//! that list: a file that was edited, damaged, removed or added is named. +//! that list: a file that was edited, damaged, removed or added is named (not what Finder or +//! Explorer write into a folder somebody looked at: `.DS_Store`, `Thumbs.db`, `desktop.ini`, `._…`). //! //! **Nothing half-made counts.** A backup is written as `.partial` and renamed when it is //! whole; a backup that fails or is cancelled removes it. One cut short by the program ending @@ -277,10 +278,16 @@ fn os_metadata(name: &str) -> bool { /// that hold nothing but what a backup holds. Anything else of that name is left alone. fn sweep(dest: &Path, also: &[&str]) { let Ok(entries) = std::fs::read_dir(dest) else { return }; + // None: no age to go by (a time yet to come, or unreadable): not old. A folder that is not + // there has no age either, and is told apart below. let age = |p: &Path| std::fs::symlink_metadata(p).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()); + let quiet = |p: &Path| match std::fs::symlink_metadata(p) { + Err(e) if e.kind() == std::io::ErrorKind::NotFound => true, + _ => age(p).is_some_and(|a| a >= STALE), + }; for entry in entries.flatten() { let (Ok(name), path) = (entry.file_name().into_string(), entry.path()) else { continue }; - let old = age(&path).is_some_and(|a| a >= STALE) && age(&path.join(segments::SEGMENT_DIR)).is_none_or(|a| a >= STALE); + let old = age(&path).is_some_and(|a| a >= STALE) && quiet(&path.join(segments::SEGMENT_DIR)); if !name.ends_with(PARTIAL) || !old || !std::fs::symlink_metadata(&path).is_ok_and(|m| m.is_dir()) { continue; } @@ -493,7 +500,8 @@ pub fn back_up(library: &Path, dest: &Path, options: &BackupOptions<'_>, watch: } /// Read the backup in `dir` against what its marker lists: every file there, with the size and -/// CRC-32 it had when the backup was made, and no other file. The first thing that isn't so is +/// CRC-32 it had when the backup was made, and no other file (but what a file manager writes into +/// a folder somebody looked at: `.DS_Store`, `Thumbs.db`, `desktop.ini`, `._…`). The first thing that isn't so is /// the error, naming the file. Returns the backup's report. pub fn check(dir: &Path) -> Result { let changed = BackupError::Changed; diff --git a/crates/catalog/src/tests_backup.rs b/crates/catalog/src/tests_backup.rs index cd0d154bc8f..e9a760b3bb3 100644 --- a/crates/catalog/src/tests_backup.rs +++ b/crates/catalog/src/tests_backup.rs @@ -408,6 +408,8 @@ fn what_a_backup_cut_short_left_is_cleared_away_later() { let (stale, fresh, foreign) = (partial("x.partial", None), partial("y.partial", None), partial("z.partial", Some("thesis.txt"))); // one whose folder is quiet but whose segments are being written now (another backup, to the same place) let writing = partial("w.partial", None); + // (one that Finder visited is still ours) + std::fs::write(stale.join(".DS_Store"), b"os").unwrap(); old(&stale); old(&foreign); old_top(&writing); From b98cb851db69461312d9d789275d9d9d8e4d9ed3 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 18 Oct 2026 12:04:19 -0400 Subject: [PATCH 26/61] Catalog: the sweep test that sets folder times is for Unix Co-Authored-By: Claude Opus 5.5 --- crates/catalog/src/tests_backup.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/catalog/src/tests_backup.rs b/crates/catalog/src/tests_backup.rs index e9a760b3bb3..1ccaaa21c60 100644 --- a/crates/catalog/src/tests_backup.rs +++ b/crates/catalog/src/tests_backup.rs @@ -384,6 +384,8 @@ fn only_a_finished_backup_of_the_same_files_is_shared_with() { /// is in nobody's way while it may still be written (the folder, or its `segments` folder where a /// backup writes most, changed less than an hour ago), and is removed by a later backup once it /// is old. A folder of that name that holds anything else is not touched. +// (a folder's time is set through a handle on the folder, which Windows does not give to File::open) +#[cfg(unix)] #[test] fn what_a_backup_cut_short_left_is_cleared_away_later() { let (lib, dest) = (temp("lib"), temp("dest")); From 3dd8fc4694e84897d486e879bf0a3de84464c760 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Thu, 22 Oct 2026 05:35:18 -0400 Subject: [PATCH 27/61] Locales: fi, id, sv and vi for the backup labels; Parity: summary refreshed --- crates/ui-egui/locales/fi-formats.json | 4 ++- crates/ui-egui/locales/fi.json | 7 +++- crates/ui-egui/locales/id-formats.json | 4 ++- crates/ui-egui/locales/id.json | 7 +++- crates/ui-egui/locales/it-formats.json | 18 ----------- crates/ui-egui/locales/it.json | 7 +++- crates/ui-egui/locales/sv-formats.json | 4 ++- crates/ui-egui/locales/sv.json | 7 +++- crates/ui-egui/locales/vi-formats.json | 4 ++- crates/ui-egui/locales/vi.json | 7 +++- docs/catalog-persistence.md | 44 ++++++++++++++++++++++++++ docs/parity-checklist.md | 7 ++-- docs/whats-new.md | 8 +++++ 13 files changed, 98 insertions(+), 30 deletions(-) diff --git a/crates/ui-egui/locales/fi-formats.json b/crates/ui-egui/locales/fi-formats.json index 1daab3dab9f..3e32bcf2d50 100644 --- a/crates/ui-egui/locales/fi-formats.json +++ b/crates/ui-egui/locales/fi-formats.json @@ -305,5 +305,7 @@ "Drop to import {n} preset{}": "Pudota tuodaksesi esiasetuksia: {n}{:.0}", "Drop to review {n} item{} for import": "Pudota tarkistaaksesi ennen tuontia (kohteita: {n}){:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Minne Lightroom-luettelo ”{catalog}” tuodaan?", - "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Yhdistä avoimeen kirjastoon ”{library}” (kuvia: {count}{:.0})", + "Backed up the library to {}": "Kirjasto varmuuskopioitu kohteeseen {}", + "The library was not backed up: {}": "Kirjastoa ei varmuuskopioitu: {}" } diff --git a/crates/ui-egui/locales/fi.json b/crates/ui-egui/locales/fi.json index e0a8c622a36..8eaf6d5417f 100644 --- a/crates/ui-egui/locales/fi.json +++ b/crates/ui-egui/locales/fi.json @@ -2327,5 +2327,10 @@ "Drop to open the face model": "Pudota avataksesi kasvomallin", "Dropped Files": "Pudotetut tiedostot", "Finish Lightroom catalog import before adding photos": "Viimeistele Lightroom-luettelon tuonti ennen kuvien lisäämistä", - "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta" + "Import dropped files without review": "Tuo pudotetut tiedostot ilman tarkistusta", + "Back Up Library": "Varmuuskopioi kirjasto", + "Backing up the library": "Kirjastoa varmuuskopioidaan", + "Backup Status": "Varmuuskopion tila", + "Check Backup": "Tarkista varmuuskopio", + "Backup Preferences": "Varmuuskopioinnin asetukset" } diff --git a/crates/ui-egui/locales/id-formats.json b/crates/ui-egui/locales/id-formats.json index 7fc3255221e..5f83216cbd7 100644 --- a/crates/ui-egui/locales/id-formats.json +++ b/crates/ui-egui/locales/id-formats.json @@ -305,5 +305,7 @@ "Drop to review {n} item{} for import": "Jatuhkan untuk meninjau {n} item sebelum impor{:.0}", "Inside: {names}": "Di dalam: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Ke mana katalog Lightroom “{catalog}” diimpor?", - "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Gabungkan ke pustaka yang terbuka “{library}” ({count} foto{:.0})", + "Backed up the library to {}": "Pustaka dicadangkan ke {}", + "The library was not backed up: {}": "Pustaka tidak dicadangkan: {}" } diff --git a/crates/ui-egui/locales/id.json b/crates/ui-egui/locales/id.json index 0d6da9b8fb8..65defd3ff3d 100644 --- a/crates/ui-egui/locales/id.json +++ b/crates/ui-egui/locales/id.json @@ -2339,5 +2339,10 @@ "Drop to open the face model": "Jatuhkan untuk membuka model wajah", "Dropped Files": "File yang dijatuhkan", "Finish Lightroom catalog import before adding photos": "Selesaikan impor katalog Lightroom sebelum menambahkan foto", - "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan" + "Import dropped files without review": "Impor file yang dijatuhkan tanpa tinjauan", + "Back Up Library": "Cadangkan pustaka", + "Backing up the library": "Mencadangkan pustaka", + "Backup Status": "Status cadangan", + "Check Backup": "Periksa cadangan", + "Backup Preferences": "Preferensi pencadangan" } diff --git a/crates/ui-egui/locales/it-formats.json b/crates/ui-egui/locales/it-formats.json index 5d8ab3fd617..7dd08ddd744 100644 --- a/crates/ui-egui/locales/it-formats.json +++ b/crates/ui-egui/locales/it-formats.json @@ -264,26 +264,8 @@ "Keywords of {n} selected photos": "Parole chiave delle foto selezionate: {n}", "new, inside {parent}": "nuova, dentro {parent}", "Delete these {n} effect presets?": "Eliminare questi preset effetto ({n})?", - "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.": "{missing} originals are missing. Their catalog records are available; use Find Missing Photos to relink them.", - "{name} opened in the other editor": "{name} opened in the other editor", - "{s} s of AV1 video": "{s} s of AV1 video", - "Delete {n} effect preset{}? This can't be undone.": "Delete {n} effect preset{}? This can't be undone.", - "{count} more warnings.": "{count} more warnings.", - "· {in_source} identical copies": "· {in_source} identical copies", "Backed up the library to {}": "Libreria salvata in {}", "The library was not backed up: {}": "Il backup della libreria non è stato eseguito: {}", - "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})": "{what} merge added at {mp}, the largest a panorama can be (its full size is {full})", - "{n} preset{}": "{n} preset{}", - " — kept but not applied: {}": " — kept but not applied: {}", - "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has": "{what} merge added at {mp}: its full size, {full}, needs more memory than this computer has", - "Saved template {name}": "Saved template {name}", - "LightCraft stopped unexpectedly: {e}": "LightCraft stopped unexpectedly: {e}", - "Renames {n} face{} across the library. The files are not changed.": "Renames {n} face{} across the library. The files are not changed.", - " · {n} skipped (could not be rendered)": " · {n} skipped (could not be rendered)", - "Delete “{name}”?": "Delete “{name}”?", - "Keywords of {n} selected photos": "Keywords of {n} selected photos", - "new, inside {parent}": "new, inside {parent}", - "Delete these {n} effect presets?": "Delete these {n} effect presets?", "Imported {e} mask effect{} (Masking ▸ Effect)": "Imported {e} mask effect{} (Masking → Effect)", "{photos} catalog records processed; {collections} collections.": "Record del catalogo elaborati: {photos}; raccolte: {collections}.", "Skipped {problem}": "Saltato: {problem}", diff --git a/crates/ui-egui/locales/it.json b/crates/ui-egui/locales/it.json index e159fd47d15..6d63a4dc1d7 100644 --- a/crates/ui-egui/locales/it.json +++ b/crates/ui-egui/locales/it.json @@ -2361,5 +2361,10 @@ "Import dropped files without review": "Importa i file rilasciati senza revisione", "An import is running": "Un'importazione è in corso", "An import is running. Drop photos when it has finished": "Un'importazione è in corso. Trascina le foto quando è finita", - "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto" + "Finish Lightroom catalog import before adding photos": "Termina l'importazione del catalogo Lightroom prima di aggiungere foto", + "Back Up Library": "Esegui backup della libreria", + "Backing up the library": "Backup della libreria in corso", + "Backup Status": "Stato del backup", + "Check Backup": "Verifica backup", + "Backup Preferences": "Preferenze di backup" } diff --git a/crates/ui-egui/locales/sv-formats.json b/crates/ui-egui/locales/sv-formats.json index 9a71a0288c4..84f446fa629 100644 --- a/crates/ui-egui/locales/sv-formats.json +++ b/crates/ui-egui/locales/sv-formats.json @@ -305,5 +305,7 @@ "Drop to review {n} item{} for import": "Släpp för att granska {n} objekt före import{:.0}", "Inside: {names}": "Inuti: {names}", "Where should the Lightroom catalog “{catalog}” go?": "Vart ska Lightroom-katalogen ”{catalog}” importeras?", - "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Slå samman med det öppna biblioteket ”{library}” ({count} foto{:.0})", + "Backed up the library to {}": "Biblioteket säkerhetskopierades till {}", + "The library was not backed up: {}": "Biblioteket säkerhetskopierades inte: {}" } diff --git a/crates/ui-egui/locales/sv.json b/crates/ui-egui/locales/sv.json index 66e69b7ba5d..e33baa9e35a 100644 --- a/crates/ui-egui/locales/sv.json +++ b/crates/ui-egui/locales/sv.json @@ -2429,5 +2429,10 @@ "Drop to open the face model": "Släpp för att öppna ansiktsmodellen", "Dropped Files": "Släppta filer", "Finish Lightroom catalog import before adding photos": "Slutför importen av Lightroom-katalogen innan du lägger till foton", - "Import dropped files without review": "Importera släppta filer utan granskning" + "Import dropped files without review": "Importera släppta filer utan granskning", + "Back Up Library": "Säkerhetskopiera bibliotek", + "Backing up the library": "Säkerhetskopierar biblioteket", + "Backup Status": "Säkerhetskopians status", + "Check Backup": "Kontrollera säkerhetskopian", + "Backup Preferences": "Inställningar för säkerhetskopiering" } diff --git a/crates/ui-egui/locales/vi-formats.json b/crates/ui-egui/locales/vi-formats.json index d5e28bff060..93b525a4cca 100644 --- a/crates/ui-egui/locales/vi-formats.json +++ b/crates/ui-egui/locales/vi-formats.json @@ -305,5 +305,7 @@ "Drop to import {n} preset{}": "Thả để nhập {n} thiết lập sẵn{:.0}", "Drop to review {n} item{} for import": "Thả để xem lại {n} mục trước khi nhập{:.0}", "Where should the Lightroom catalog “{catalog}” go?": "Nhập danh mục Lightroom «{catalog}» vào đâu?", - "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})" + "Merge into the open library “{library}” ({count} photo{})": "Gộp vào thư viện đang mở «{library}» ({count} ảnh{:.0})", + "Backed up the library to {}": "Đã sao lưu thư viện vào {}", + "The library was not backed up: {}": "Thư viện chưa được sao lưu: {}" } diff --git a/crates/ui-egui/locales/vi.json b/crates/ui-egui/locales/vi.json index e4fb8feb81c..a1833c0f9a8 100644 --- a/crates/ui-egui/locales/vi.json +++ b/crates/ui-egui/locales/vi.json @@ -2235,5 +2235,10 @@ "Drop to open the face model": "Thả để mở mô hình khuôn mặt", "Dropped Files": "Tệp đã thả", "Finish Lightroom catalog import before adding photos": "Hoàn tất nhập danh mục Lightroom trước khi thêm ảnh", - "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại" + "Import dropped files without review": "Nhập các tệp đã thả mà không xem lại", + "Back Up Library": "Sao lưu thư viện", + "Backing up the library": "Đang sao lưu thư viện", + "Backup Status": "Trạng thái sao lưu", + "Check Backup": "Kiểm tra bản sao lưu", + "Backup Preferences": "Tùy chọn sao lưu" } diff --git a/docs/catalog-persistence.md b/docs/catalog-persistence.md index 9fffb2bccb4..6c346c3cd41 100644 --- a/docs/catalog-persistence.md +++ b/docs/catalog-persistence.md @@ -154,6 +154,50 @@ what changed, and opening a library reads its segments on several threads. - **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. +## Backups + +File ▸ Back Up Library (`library.backup`) makes a folder named after the time (UTC) that holds `catalog.snap`, the +segments it lists, `catalog.log` and the presets, view and preferences files: the catalog, not the photos or the +caches (`crates/catalog/src/backup.rs`). It goes to `Backups` in the library folder, to the folder set for the library +(`library.backupPreferences`), or to the one given with the command. The app makes it in the background and says in a +toast where it went or why there is none; the command itself returns when the backup is made (`background: true` for +the other). + +- **A backup takes every file the library has.** The library's own files beside the catalog are one list + (`SettingsFile` in `crates/engine/src/library.rs`), which is what a backup takes along and what the browser build + reads at start-up. The library's file store refuses to write a file that is not on it, so a new one can't be added + without being backed up. Not in a backup: the files an upgrade kept (`catalog.snap.v…`), a damaged log set aside, + previews and caches. +- **A backup is a library.** Opening its folder shows the catalog as it was. To go back to it, copy the folder and + open the copy, or copy its files over the library's. Opening the backup itself turns it into a library in use: it is + changed from then on, no longer passes `library.checkBackup`, and (it holds the library's preferences) sends its own + backups to the same folder as the original's. +- **Each backup shares with the one before it the files that didn't change.** A segment is never changed once + written, so one of the same name, size and CRC in the previous backup is the same file, and is hard-linked instead + of copied. Every backup still stands on its own: removing an older one, or the library, takes nothing from it. + Where hard links aren't possible (another volume than the last backup's), files are copied. A file is shared only + once it was read and still has its CRC, so damage in an older backup is not handed on: that file is copied afresh + from the library. +- **Made while the library is in use.** The files are read as they are on disk: `catalog.snap`, the segments it + lists, the log, then `catalog.snap` again. If it changed meanwhile (a compaction), the backup starts over, keeping + what it has. Every segment is checked against the size and CRC the snapshot states; a library with a damaged or + missing segment is not backed up, and the error names the file. +- **Nothing half-made counts.** A backup is written as `.partial` and renamed when whole; one that fails or is + stopped (its row in the activity stack) removes it. One cut short by the program ending stays as `.partial`, + is never taken for a backup, and is removed by a later backup to the same folder once it is an hour old. +- **A backup says what it holds.** Its marker, `backup.json`, lists every file with its size and CRC-32. + `library.checkBackup` reads a backup against that list and names the first file that was edited, damaged, removed or + added since (not what Finder or Explorer write into a folder somebody looked at: `.DS_Store`, `Thumbs.db`, + `desktop.ini`, `._…`). + +A backup on the same disk as the library guards against a damaged catalog or a mistake, not against losing the disk: +set the library's backup folder to another drive for that. + +One million photos (414 MB of catalog, 123 segments of up to 8,192 photos, as measured before segments were cut +to 4,096 photos and about 2 MB, so a backup now copies less after the same edits; Apple M1 Max): the first backup took 1.0 s; one after 1000 +edits in one place copied 3.4 MB and shared 122 files, in about 0.15 s (most of it reading the files it shares); +checking a backup took 64 ms. Three backups together took 398 MB on disk, where the library takes 395 MB. + ## Measurements: only the changed segments are written (format 11) `cargo run --release -p lightcraft-catalog --example persist_bench -- 300000`, one run of each on an diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f60..c4aa53848c2 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -52,10 +52,10 @@ cited here still exists. Formerly docs/parity.md. | X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | | Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 78 | 4 | 2 | 1 | 49/52 (94%) | 24/26 (92%) | -| Lightroom Classic extras | 41 | 25 | 21 | 8 | — | 24/26 (92%) | -| **Total** | 421 | 65 | 57 | 35 | 196/203 (97%) | 146/161 (91%) | +| Lightroom Classic extras | 41 | 26 | 21 | 8 | — | 24/27 (89%) | +| **Total** | 421 | 66 | 57 | 35 | 196/203 (97%) | 146/162 (90%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.5%** of 543 in-scope rows — P0 98.3% of 203 · P1 94.4% of 161 · P2 56.7% of 178. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **83.5%** of 544 in-scope rows — P0 98.3% of 203 · P1 94.1% of 162 · P2 56.7% of 178. ## Top gaps and shortcut notes @@ -702,6 +702,7 @@ From `08-lightroom-classic-extras.md` (Classic-only features) and part 2 of `06- | LRC-LIB-CATALOG-IMPORT | Native Lightroom Classic catalog import | P1 | 🟡 | `cmd:library.inspectLightroom`, `cmd:library.importLightroom`, `cmd:file.importLightroom`, `crates/engine/src/lightroom_catalog.rs`, `crates/ui-egui/src/dialogs/lightroom_destination.rs`, `crates/ui-egui/src/tests/lightroom_destination.rs`, `docs/lightroom-catalog-import.md` | before the import starts, File ▸ Import Lightroom Catalog… asks where the catalog goes: merge into the open library (named, with its photo count; preselected when it is empty) or create a new library (named after the catalog file, next to the open library, both editable), which is made and opened following File ▸ New Library…'s rules before the import; Cancel does nothing; Settings ▸ General ▸ "When importing a Lightroom catalog" (Ask where to import it / Always merge into the open library) or the window's "Don't ask again" turns it off; `file.importLightroom` takes `into` (`open` / `new`), `name`, `location` to choose without the window; a session in memory merges without asking (issue #2672); read-only `.lrcat` plus committed WAL pages (also WAL-only tables with main schema format 0), in-tree read-only Rust SQLite B-tree reader; on-demand main-file pages up to 16 GiB with existing table/record bounds (WAL still capped at 1 GiB, issue #798); background inspection/import with progress/cancellation, per-open library identity checks; persistent result with destination library, offline-original counts and Show in Library, dismissed when switching libraries; offline Local records are promoted without probing missing files; originals in place, ratings/flags/labels, XMP, hierarchical keywords, collection sets/regular collections, virtual copies, mapped develop settings; stable reimport identities, undo, missing-file placeholders, a root folder not found at its recorded path looked up relative to the catalog (Lightroom's `relativePathFromCatalog`, so a project folder copied from another computer stays linked; reported as a warning), existing edits preserved. Best-effort deduplicated recovery archives retain settings/history/snapshots/collection rules (32 MiB each, eight archives/128 MiB aggregate); archive limits/write failures and optional-table limits warn without blocking photo import; unrelated unsupported tables and opaque SQL BLOBs skipped. Custom white balance on relative-WB raws (`RAW` in Lightroom's terms) stays As Shot and is reported, since the catalog keeps no as-shot white to shift from (issue #510). An image whose file, folder or root folder record is missing from the catalog, or whose original path is empty, is skipped with its virtual copies instead of failing the whole import; the report lists them as data (`skipped`: image id and reason) and the result window counts them in the UI language (PR #2230). Adobe rendering, AI data and native history replay remain incomplete; no writes to Lightroom catalogs. Open Library given a Lightroom catalog folder, an `.lrdata` / `.lrcat-data` folder or the `.lrcat` makes no library there and offers this import with the catalog found (`cmd:app.openLibrary`, `crates/engine/src/lightroom_folder.rs`; issue #891) | | LRC-LIB-CATALOG-LOCK | Catalog open in one program at a time | P1 | ✅ | `cmd:app.openLibrary`, `crates/catalog/src/lock.rs`, `crates/engine/src/library.rs` (`open_library`) | exclusive OS lock on `catalog.lock` for the session (app and `lightcraft-cli --library`); a second opener is refused with who has it (`catalog.lock.owner`: program, process, computer); released by the OS on a crash, so never stale; file systems without locks open unprotected with a warning (the app's notices, `library.info` → `settingsWarnings`, and the CLI's stderr; issue #171); no read-only mode; the browser build (OPFS) has no guard across tabs yet. A library that can't be opened at launch (locked, unreadable, newer format, drive missing) shows a window — Try Again, Choose Another Library…, Continue Without Saving (then a banner; nothing written), Quit — instead of a silent demo session (`crates/ui-egui/src/panels/library_problem.rs`); the lock is released explicitly when the library closes, not by letting its file handle close, so a program another thread is starting at that moment (which holds a copy of every file handle until it is launched) cannot keep the library "already open" for a moment (issue #680) | | LRC-LIB-CATALOG-SWITCH | New / Open Recent catalog, catalog name shown | P1 | ✅ | `cmd:app.newLibrary`, `cmd:app.openLibrary`, `cmd:app.recentLibraries`, `cmd:app.clearRecentLibraries`, `crates/ui-egui/src/dialogs/settings.rs`, `crates/ui-egui/src/panels/left.rs`, `crates/ui-egui/src/panels/library_problem.rs` (`launch_plan`, `show_chooser`), `crates/ui-egui/src/tests/launch_library.rs` | File ▸ New Library… (name, then location), File ▸ Open Recent Library (last 8; missing ones greyed out, dropped when opened; Remove from List ▸ one entry, or `app.recentLibraries {remove}`, which forgets only the path; Clear), the open library's name under My Photos and in the window title (issue #902); Open/New refused during imports and their folder scans; a library that can't be opened leaves the current one and its reference pin intact; a successful switch clears the catalog-local reference pin; ⌘O (Ctrl+O on Windows and Linux) runs Open Library… and asks for a folder once (`crates/ui-egui/src/tests/keymap.rs`: `cmd_o_opens_the_library_picker_once`); a dialog or a text field with the focus keeps the key; Settings ▸ General ▸ At launch: Open the last library (default) or Ask me, a window listing the recent libraries (name, folder, when last opened; missing, unreadable or no-longer-library ones greyed out with the reason, checked read-only — nothing is locked or written, so a library another program has open is reported, with who has it, when Open is pressed; the last one selected; Open, Open Another…, New Library…, Remove from List, Quit; ↑ ↓ Return Esc), also shown once when Alt/Option is held in the first 2 s after the window appears (macOS reports an Option key held since before launch only once it changes); `--library` and `LIGHTCRAFT_LIBRARY` come first and `lightcraft-cli` never asks (issue #1290) | +| LRC-LIB-CATALOG-BACKUP | Catalog backup [Classic] | P1 | 🟡 | `cmd:library.backup`, `cmd:library.backupStatus`, `cmd:library.backupPreferences`, `cmd:library.checkBackup`, `crates/catalog/src/backup.rs`, `crates/engine/src/cmd/backup.rs`, `docs/catalog-persistence.md` | File ▸ Back Up Library: the catalog, its log and the presets / view / preferences files (not the photos) as a folder named after the time (UTC) in Backups in the library folder, or in the folder set for the library or given with the command. A backup opens as a library; files that didn't change since the backup before are shared with it (hard links, each read and checked first), so a backup copies what changed and each still stands on its own. Made in the background while the library is in use (activity stack, cancellable; a toast says where it went or why not), from the files as they are on disk, each checked against its size and CRC; a backup that fails or is stopped leaves nothing, one cut short by a crash is cleared away by a later backup. A backup lists every file with its size and CRC, and `library.checkBackup` reads it against that list (a file edited, damaged, removed or added is named). No schedule (Classic backs up on exit every day / week / month), no restore command (copy the backup and open the copy), no choice of folder in the UI, no pruning of old backups, names in UTC (no local time yet) | | LRC-LIB-FOLDERS | Disk folder tree | P1 | ✅ | `cmd:library.browse`, `cmd:folder.rename`, `cmd:folder.move`, `crates/ui-egui/src/panels/left.rs` (`local_section`, `folder_tree`) | standard places + the browsed folder + Browse Folder…, each an expandable tree of subfolders, breadcrumb navigation; context menu: Rename Folder…, Move Folder To…, Show in Finder (on disk, photos relinked; one undo step each: undo / redo move the folder back and forth, refused when the destination is taken) | | LRC-LIB-LIBFOLDERS | Library folders | P1 | ✅ | `cmd:library.folders`, `cmd:library.source` (`libraryFolder`), `cmd:library.filter` (`libraryFolder`), `cmd:library.removeFolder`, `cmd:folder.rename`, `cmd:folder.move`, `cmd:folder.label`, `cmd:folder.create`, `cmd:photo.moveToFolder`, `cmd:folder.scanChanges`, `cmd:folder.synchronize`, `crates/catalog/src/folders.rs`, `crates/engine/src/sync.rs`, `crates/ui-egui/src/sync.rs`, `crates/ui-egui/src/panels/left.rs` (`folders_section`, `folder_menu_for_library`, `row_menu`), `crates/ui-egui/src/tests/panels.rs` | sidebar Folders: the folders the library's photos were imported from, with photo counts (subfolders included), as another way to explore the library next to By Date and Keywords; Local stays the way to browse any folder on disk. Each disk is a row of its own and starts open: a drive letter, a Windows share (`\\server\share`, `\\?\UNC\…`, `\\wsl$\…`), a macOS share or disk (`/Volumes/tokyo`), a Linux mount (`/media`, `/run/media`, `/mnt`, gvfs `smb-share:…`, `/net/`), NFS (`/Network/Servers/`), else “This Computer” — told apart from the stored paths alone, so an offline share lists like a mounted one and the sidebar never waits on a network. Only folders that hold imported photos are listed (browsed, deleted and demo photos don't count); every folder is a row of its own (`Users` → `me` → `Pictures`), and a folder that holds nothing itself and leads to one folder starts open; every level indents one step more than its parent however deep it goes (16 pt while the deepest open row of any sidebar tree fits the panel with room for its name and count; narrower in bands of 14, 12, 10 and 8 pt when it would not, the same for every tree, chosen from the last frame; issue #2298): past 8 pt the whole sidebar (Albums, Local, By Date, Folders, Keywords) scrolls sideways when its widest row is wider than the panel (rows are measured one frame behind; Create Album and the counts stay at the visible edge); a name that does not fit ends in an ellipsis at the count (the full name on hover; a row asks for room for at most 140 pt of its name, so depth, not one long name, makes the sidebar scroll), as does the grid title; selection and hover bars end at the panel's edge; click makes the folder the source, like an album or a Local folder (its photos and those of the folders inside it fill the grid, titled “photos/travel”; the filter bar narrows it further; `library.source` `libraryFolder` + `path`; kept with the library's view), and its row is always opened into view; the shown folder follows a rename or move and their undo (engine-tested; the sidebar test covers rename), is dropped back to All Photos when it is removed or no longer holds a photo, and a smart album made from the view keeps it, also when its rules are edited (the editor has no folder field). Only a folder that shows exactly its own photos can be shown (not the startup disk, not `/Volumes`-like folders above disks, not an empty one). A row that would cover other disks' photos too (the startup disk, `/Volumes`, `/mnt`…) only opens. Right-click (row or triangle): Rename Folder…, Move Folder To…, New Folder on Disk… (`folder.create`; one undo step, undo removes it while empty), Move Selected Photos Here (`photo.moveToFolder`, also *Move to Folder…* in the photo context menu, and photos dragged from the grid onto a Folders row: the row lights up, the dragged label says “Move 3 photos to “Trip””, a closed folder held under the pointer opens, a row covering several disks and Local photos are refused with the reason, photos already there say so; a drop asks first (“Move 2 photos to “Porto”?”, Don't ask again, Settings → Confirm before moving photos to another folder on disk), and photos that leave the view leave the selection; files and XMP sidecars move, virtual copies follow, across volumes copied (streamed) and verified before the source goes, a name taken in the destination refuses the whole move, one undo step; an undo with the share offline or read-only is refused with the reason and kept until it can run, nothing deleted), Show in Finder (on disk, photos relinked, as in Local), Set Color Label ▸ (the five colours with their custom names, None, Edit Label Names…; `folder.label`, one undo step; the row shows the label's dot before its count and says it with its name; kept in the catalog as a folder record under the folder's identity, so it follows Rename / Move and their undo and redo, the folders inside going along), Synchronize Folder… (the dialog opens at once and scans the folder and the folders inside it on a worker thread — the look for new files beside parallel checks of the library's photos — then offers Import new photos (checked; files only browsed in Local count as new), Relink photos whose file was renamed or moved within the folder (checked; matched by content — a Duplicate's too — or, for a photo with no hash on record such as one from a Lightroom catalog, by file size and dimensions when exactly one file agrees), Remove missing photos from the library (to Recently Deleted) and Read metadata updates from XMP sidecars (saved after the photo came in or was last edited here, and saying something the library doesn't; the sidecar wins), with counts and skipped duplicates / unreadable files; a folder with none of these changes only says the library is up to date with it, with one Close and no choices, and closing it starts no job; `folder.scanChanges` / `folder.synchronize`, which acts on exactly the scan shown — a scan whose folder's photos changed meanwhile is refused and made again in the background — and is one undo step, also with a full history; a folder that isn't there (an unplugged disk) is reported as such, not as every photo missing; a whole disk or a folder holding disks needs `disk: true`; Esc stops the scan; Synchronize hands everything to a worker thread — the import, the checks that moved and missing files are still as found, the sidecar reads — and commits its steps between frames, shown in the activity stack with ✕ to stop, so no file is touched on the UI thread) and Remove from Library… (asks; moves the folder's photos to Recently Deleted, one undo step, no file touched); a disk row (not the startup disk) offers Set Color Label ▸, Synchronize Folder… and Remove Disk from Library… (the command needs `disk: true` for a whole disk or a folder spanning several). Limits: names are compared as written (macOS `/Volumes/tokyo` vs `/Volumes/TOKYO` are two disks; `/Volumes/Macintosh HD/…` and `/…` two rows); no disk capacity / online status; no “include subfolders” switch (a folder always includes the ones inside it); photos can't yet be dragged onto a folder row (use the menus); a name clash on moving photos is refused rather than renamed -1, -2; folders can't be filtered or sorted by label, and a label stays with the old path when the folder is moved outside LightCraft (Find Missing relinks photos, not folder records); Synchronize has no “show import dialog first” or “show missing photos” option, and only knows when a photo came in or was last developed here: a rating, label or metadata change made here (auto-write off) after another app saved the sidecar is listed as an update, and reading it restores the sidecar's older value (reading is never the default); the walk for new files stops when the scan is cancelled, and its depth/entry limits are only logged | | LRC-LIB-COLLECTIONS | Collections & sets | P1 | ✅ | `cmd:album.create`, `cmd:album.createSmart`, `cmd:album.toggleTarget`, `cmd:album.setTarget`, `cmd:album.clearQuick` | albums + folders (sets), smart albums (rule editor; rules incl. File Path — the whole string, either separator, case-insensitive), Quick Collection and target album (B in the grids adds / removes the selection; album menu ▸ Set as Target Album; the target is marked +) | diff --git a/docs/whats-new.md b/docs/whats-new.md index 176a4ec7974..4cc4e268735 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -22,6 +22,14 @@ - Segment files that a crash left beside a library are removed the next time it is opened, and a library folder that has segment files but no `catalog.snap` (a folder copied in part, or a `catalog.snap` that was removed) is no longer opened as a new, empty library: LightCraft says that the snapshot is missing and changes nothing. +- File ▸ Back Up Library backs up the catalog (not the photos) to a folder named after the time (UTC) in the folder the + library's backups go to (Backups in the library folder unless another is set with `library.backupPreferences`), while you go on working, and says where it went when it is done. A backup opens as a library of + its own. Each one shares with the one before it the files that didn't change (hard links, where the folder can hold them: on + another volume than the last backup's, or a file system without links, they are copied), so a backup of a large + library after a day's work copies a few megabytes where it can share, and removing an older backup takes nothing from a newer one. Agents: + `library.backup` (`dir`; returns when the backup is made, or at once with `background`), `library.backupStatus`, + `library.backupPreferences` (the folder a library's backups go to), `library.checkBackup` (reads a backup against + the list of files it was made with, and names one that was edited or damaged since). - 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. A library from before format 10 whose upgrade can't be written (a full disk, a folder that can't be written From 8332b4d7b8b3109c5f3491fd81f8c873feabd717 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sat, 10 Oct 2026 19:33:57 -0400 Subject: [PATCH 28/61] Catalog: restore a library from a backup, and keep what it replaces `library.restore {dir}` makes the open library what a backup holds and goes on in it; with `to` it restores into another folder (one that is empty or a library nothing has open) and opens nothing. `library.backups` lists a folder's backups, newest first. - Only a sound backup is restored: read against its marker, each file again as it is copied, and refused when its catalog or log is a newer LightCraft's. The backup is only read: nothing is shared with it or made in its folder. - What the library held, with every change up to that moment, is moved to Replaced/ in the library folder, a library folder itself. - All or nothing: the backup is copied into restore.partial, a note (restore.json) is written, then files are moved, the snapshot first out and last in. Files that can't all be moved out are moved back; a restore cut short after the note is completed when the library is next opened. The note is not trusted: it moves a catalog's files by plain name between folders of the library's own, never through a link. - A restored catalog that doesn't open is taken back, and the session goes on in the library as it was. If a restore can neither go on nor go back, the session changes and writes nothing until the library is opened again. - A backup folder is no longer opened as a library where it is: working in it changed it. No menu item yet. Restore runs in the command, with a row in the activity stack. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/catalog/src/backup.rs | 52 +- crates/catalog/src/journal.rs | 27 ++ crates/catalog/src/lib.rs | 3 + crates/catalog/src/restore.rs | 633 ++++++++++++++++++++++++ crates/catalog/src/tests_backup.rs | 24 +- crates/catalog/src/tests_restore.rs | 722 ++++++++++++++++++++++++++++ crates/engine/Cargo.toml | 2 + crates/engine/src/cmd/backup.rs | 229 ++++++++- crates/engine/src/lib.rs | 12 + crates/engine/src/library.rs | 65 ++- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/backup.rs | 12 +- crates/engine/src/tests/restore.rs | 586 ++++++++++++++++++++++ crates/ui-egui/locales/cs.json | 3 + crates/ui-egui/locales/de.json | 3 + crates/ui-egui/locales/es.json | 3 + crates/ui-egui/locales/fr.json | 3 + crates/ui-egui/locales/it.json | 3 + crates/ui-egui/locales/ja.json | 3 + crates/ui-egui/locales/ka.json | 3 + crates/ui-egui/locales/pl.json | 3 + crates/ui-egui/locales/pt-br.json | 3 + crates/ui-egui/locales/ru.json | 3 + crates/ui-egui/locales/uk.json | 3 + crates/ui-egui/locales/zh-hans.json | 3 + crates/ui-egui/locales/zh-hant.json | 3 + docs/catalog-persistence.md | 47 +- docs/web.md | 2 +- 29 files changed, 2417 insertions(+), 40 deletions(-) create mode 100644 crates/catalog/src/restore.rs create mode 100644 crates/catalog/src/tests_restore.rs create mode 100644 crates/engine/src/tests/restore.rs diff --git a/Cargo.lock b/Cargo.lock index 17f738ea5e2..e7c798b1279 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3689,6 +3689,7 @@ dependencies = [ "ab_glyph", "chrono", "craft-docpath", + "crc32fast", "harfrust 0.13.3", "jxl-oxide", "libc", diff --git a/crates/catalog/src/backup.rs b/crates/catalog/src/backup.rs index 026ff876072..fe45703ded2 100644 --- a/crates/catalog/src/backup.rs +++ b/crates/catalog/src/backup.rs @@ -1,8 +1,9 @@ //! Backing up a library's catalog: a dated folder that opens as the library it was taken of. //! //! A backup holds `catalog.snap`, the segments it lists (in `segments/`, as in the library), -//! `catalog.log` and the settings files beside them (not the photos, and not the caches). It is a library folder in its own right: -//! opening it shows the catalog as it was. +//! `catalog.log` and the settings files beside them (not the photos, and not the caches). Its +//! files are a library folder's, so it reads as the catalog as it was; to work in that again it is +//! restored ([`crate::restore`]), not opened where it is, which would change it. //! //! **Each backup shares with the one before it the files that didn't change.** A segment is //! never changed once written (a snapshot writes a changed one under a new name), so a segment @@ -60,6 +61,9 @@ pub enum BackupError { /// A backup that was checked is not what it was when it was made ([`check`]). #[error("the backup is not as it was made: {0}")] Changed(String), + /// A library can't be restored from a backup ([`crate::restore`]). + #[error("the library can't be restored: {0}")] + Restore(String), #[error("the backup can't be written: {0}")] Io(String), } @@ -116,7 +120,7 @@ pub trait Watch { impl Watch for () {} -fn io(what: &str, path: &Path, e: std::io::Error) -> BackupError { +pub(crate) fn io(what: &str, path: &Path, e: std::io::Error) -> BackupError { BackupError::Io(format!("{what} {}: {e}", path.display())) } @@ -172,14 +176,14 @@ fn read_head(bytes: &[u8]) -> Result { /// A name `options.also` may hold: a plain file name that isn't one of the catalog's or the /// marker's (those are written by the backup itself, and a segment may be shared with another /// backup: it is never written over). -fn valid_extra(name: &str) -> bool { +pub(crate) fn valid_extra(name: &str) -> bool { valid_name(name) && name != SNAPSHOT && name != LOG && name != MARKER && name != segments::SEGMENT_DIR } /// The files of the folder `dir` that a backup may hold, by the names the catalog gives them: /// the ones in it, and the ones in its segments folder (`segments/…`). An error names anything /// else that is in it (another folder, a link). -fn held(dir: &Path) -> Result, String> { +pub(crate) fn held(dir: &Path) -> Result, String> { let mut names = Vec::new(); let entries = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?; for entry in entries { @@ -204,14 +208,14 @@ fn held(dir: &Path) -> Result, String> { } /// Make the folder a file of a backup goes into (the segments folder, with its first file). -fn folder_for(path: &Path) -> Result<(), BackupError> { +pub(crate) fn folder_for(path: &Path) -> Result<(), BackupError> { match path.parent() { Some(folder) if !folder.is_dir() => std::fs::create_dir_all(folder).map_err(|e| io("can't make the folder", folder, e)), _ => Ok(()), } } -fn valid_name(name: &str) -> bool { +pub(crate) fn valid_name(name: &str) -> bool { !name.is_empty() && name.len() <= 200 && name != "." @@ -221,7 +225,7 @@ fn valid_name(name: &str) -> bool { } /// A file's bytes; `None` when there is no such file. -fn read(path: &Path) -> Result>, BackupError> { +pub(crate) fn read(path: &Path) -> Result>, BackupError> { match std::fs::read(path) { Ok(b) => Ok(Some(b)), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), @@ -231,12 +235,12 @@ fn read(path: &Path) -> Result>, BackupError> { /// Write a new file and make it durable. Never over one that is there: a file of a backup may /// be shared with another backup. -fn write(path: &Path, bytes: &[u8]) -> Result<(), BackupError> { +pub(crate) fn write(path: &Path, bytes: &[u8]) -> Result<(), BackupError> { let mut f = std::fs::OpenOptions::new().write(true).create_new(true).open(path).map_err(|e| io("can't create", path, e))?; f.write_all(bytes).and_then(|()| f.sync_all()).map_err(|e| io("can't write", path, e)) } -fn sync_dir(dir: &Path) { +pub(crate) fn sync_dir(dir: &Path) { // (makes the names in it durable; a folder can't be opened on Windows, where renames are journaled) if let Ok(d) = std::fs::File::open(dir) { let _ = d.sync_all(); @@ -244,7 +248,7 @@ fn sync_dir(dir: &Path) { } /// A regular file (not a link to one elsewhere). -fn regular(path: &Path) -> bool { +pub(crate) fn regular(path: &Path) -> bool { std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file()) } @@ -499,6 +503,32 @@ pub fn back_up(library: &Path, dest: &Path, options: &BackupOptions<'_>, watch: made } +/// The finished backups in `dest`, newest first (by when their markers were written, then by +/// name): each as its marker reports it, with the folder it is in now. Folders whose marker +/// can't be read are left out. +pub fn list(dest: &Path) -> Vec { + let Ok(entries) = std::fs::read_dir(dest) else { return Vec::new() }; + let mut found: Vec<(std::time::SystemTime, String, BackupReport)> = entries + .filter_map(|e| e.ok()?.file_name().into_string().ok()) + .filter(|name| !name.ends_with(PARTIAL) && regular(&dest.join(name).join(MARKER))) + .filter_map(|name| { + let marker = dest.join(&name).join(MARKER); + let made = std::fs::metadata(&marker).and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH); + let mut report: BackupReport = serde_json::from_slice(&std::fs::read(&marker).ok()?).ok()?; + report.dir = dest.join(&name); + Some((made, name, report)) + }) + .collect(); + found.sort_unstable_by(|a, b| (b.0, &b.1).cmp(&(a.0, &a.1))); + found.into_iter().map(|(_, _, report)| report).collect() +} + +/// Whether `dir` is a backup: it has a backup's marker (whatever that is: a folder with +/// something of that name is not worked in as a library). +pub fn is_backup(dir: &Path) -> bool { + std::fs::symlink_metadata(dir.join(MARKER)).is_ok() +} + /// Read the backup in `dir` against what its marker lists: every file there, with the size and /// CRC-32 it had when the backup was made, and no other file (but what a file manager writes into /// a folder somebody looked at: `.DS_Store`, `Thumbs.db`, `desktop.ini`, `._…`). The first thing that isn't so is diff --git a/crates/catalog/src/journal.rs b/crates/catalog/src/journal.rs index 3def262f8ed..62655f3d10f 100644 --- a/crates/catalog/src/journal.rs +++ b/crates/catalog/src/journal.rs @@ -612,6 +612,33 @@ struct SnapHeader { defaults: Option, } +/// Whether this version reads the `catalog.snap` in `bytes`, going by its header: a LightCraft +/// catalog, of a format that isn't newer than [`VERSION`]. The error says what it is instead. +pub(crate) fn readable(bytes: &[u8]) -> std::result::Result<(), String> { + let h: SnapHeader = serde_json::from_slice(bytes).map_err(|e| format!("{SNAPSHOT}: {e}"))?; + if h.format != FORMAT { + return Err(format!("{SNAPSHOT} is not a LightCraft catalog (format {:?})", h.format)); + } + if h.version > VERSION { + return Err(format!("{SNAPSHOT} is catalog format v{}, written by a newer LightCraft than this one (v{VERSION})", h.version)); + } + Ok(()) +} + +/// Whether this version reads the `catalog.log` in `bytes`: no record in it holds a change this +/// version doesn't know (what a newer LightCraft wrote; damage is another matter, and is dealt +/// with when the log is opened). +pub(crate) fn log_readable(bytes: &[u8]) -> std::result::Result<(), String> { + for line in bytes.split(|b| *b == b'\n') { + if let Ok(line) = std::str::from_utf8(line) + && let Line::Newer(seq) = decode_line(line.trim_end_matches('\r')) + { + return Err(format!("{LOG} record {seq} holds a change this version doesn't know (a newer LightCraft wrote it)")); + } + } + Ok(()) +} + /// The whole `catalog.snap` (after [`SnapHeader`] was checked; `format` and `version` are ignored). #[derive(serde::Deserialize)] struct SnapFile { diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 6d428f15ef0..d2b32852861 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -23,6 +23,7 @@ pub mod local; pub mod lock; pub mod model; pub mod query; +pub mod restore; pub mod rules; pub mod safe_file; pub mod segments; @@ -1275,6 +1276,8 @@ mod tests_lock; #[cfg(test)] mod tests_repair; #[cfg(test)] +mod tests_restore; +#[cfg(test)] mod tests_scale; #[cfg(test)] mod tests_segments; diff --git a/crates/catalog/src/restore.rs b/crates/catalog/src/restore.rs new file mode 100644 index 00000000000..b0b915ce58c --- /dev/null +++ b/crates/catalog/src/restore.rs @@ -0,0 +1,633 @@ +//! Restoring a library's catalog from a backup ([`crate::backup`]). +//! +//! **The library becomes what the backup holds**: `catalog.snap`, its segments, `catalog.log` +//! and the settings files asked for. The backup itself is only read: its files are copied, never +//! shared, since a library goes on changing. +//! +//! **Nothing is restored from a backup that isn't what it was when it was made**, or that this +//! version can't open. The backup is read against its marker first ([`crate::backup::check`]), +//! and every file again as it is copied; a snapshot or a log record of a newer LightCraft is +//! refused there, with the library untouched. +//! +//! **What the library was is kept.** The files a restore replaces are moved to +//! `Replaced/` in the library folder, which is a library folder in its own right: a +//! restore can be taken back by opening it, or by moving its files back ([`take_back`]). +//! +//! **A restore is all or nothing, also when it is cut short.** The backup is first copied into +//! `restore.partial` in the library folder, with the library untouched. Only then are files +//! moved, and before the first of them a note of what is to be done is written (`restore.json`). +//! A restore that stops after that is completed by [`finish`], which whoever opens the library +//! calls first: the library is never opened as some files of one catalog and some of another. +//! The snapshot is the first file moved out and the last moved in, so a folder with a +//! `catalog.snap` and no note is always a whole library. Where the library's files can't all be +//! moved out, or the copy of the backup is no longer whole, the ones that were are moved back, +//! and the library is as it was. +//! +//! **The note is a file like any other.** It may have been edited, or be what is left of +//! something else: it moves files of the library folder itself, by plain name, between that +//! folder, `Replaced` and `restore.partial`, which must be folders of the library's own (not +//! links); never another folder, a lock file or a backup's marker. A note that asks for anything +//! else is not followed, and nothing is moved. + +use std::path::{Path, PathBuf}; + +use crate::backup::{self, BackupError, Watch}; +use crate::journal::{LOG, SNAPSHOT}; +use crate::segments::{self, SEGMENT_DIR}; + +/// The note of a restore under way, in the library folder. +pub const PENDING: &str = "restore.json"; +/// The folder in the library folder that holds what restores replaced. +pub const REPLACED: &str = "Replaced"; +/// The backup's files, copied into the library folder before any is moved into place. +const STAGED: &str = "restore.partial"; + +/// How to restore. +#[derive(Clone, Copy, Debug)] +pub struct RestoreOptions<'a> { + /// Other files of the backup to restore besides the catalog's (presets, preferences): plain + /// file names. A file of the backup that isn't named here stays out, and the library's own + /// file of that name stays where it is. + pub also: &'a [&'a str], + /// The name of the folder in `Replaced` that takes what the restore replaces (the time). + pub aside: &'a str, +} + +/// A restore that was made. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct RestoreReport { + pub backup: PathBuf, + pub library: PathBuf, + /// Where what the library was went; `None` when there was nothing to replace. + pub aside: Option, + /// The op the restored snapshot is of, and the photos it holds (as the backup reports them). + pub seq: u64, + pub photos: u64, + /// Files restored, and their size in all. + pub files: u64, + pub bytes: u64, + /// Files of the backup that were not asked for, and so not restored. + pub skipped: Vec, + /// What the restore put into the library folder, and what it moved out of it to `aside`, by + /// name there (`segments`: the folder). + pub placed: Vec, + pub replaced: Vec, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +enum Phase { + /// What the library holds is being moved to `Replaced/