Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
36c15f2
Catalog: compact stored records and compaction by snapshot size (form…
nledford Oct 10, 2026
df1fea0
Catalog: compact records are format 10, and the formats are one list
nledford Oct 11, 2026
f9cdabd
Catalog: an upgrade keeps the files it replaces
nledford Oct 11, 2026
179af6e
Catalog: a library states what its missing develop settings read as
nledford Oct 11, 2026
8ba8ba8
Catalog: every upgrade keeps its copy, and a library that can't be up…
nledford Oct 11, 2026
592bd77
Catalog: a library states every develop default, also the ones never …
nledford Oct 11, 2026
8dbf901
Catalog: an upgrade that can't be checked keeps its copy, and a damag…
nledford Oct 11, 2026
9e8a438
Catalog: each format says whether it adds an op, and the guard reads …
nledford Oct 14, 2026
eb19437
Catalog: develop defaults are stated from format 10, kept files are n…
nledford Oct 18, 2026
612b08c
Catalog: the bench does not snapshot twice when the last batch alread…
nledford Oct 18, 2026
fa93655
Catalog: the bench counts the final snapshot only when it takes one
nledford Oct 18, 2026
beab8ef
Catalog: the snapshot in segments (format 11)
nledford Oct 10, 2026
e88dd50
Catalog: segments are JSON files in a segments folder
nledford Oct 10, 2026
3797a99
Catalog: the segments folder is a folder of the library's own
nledford Oct 10, 2026
b6ebbd1
Catalog: the format 11 fixture is a library in segments, and going ba…
nledford Oct 11, 2026
70afc20
Catalog: the segment warning in What's New is for libraries in a fold…
nledford Oct 18, 2026
168aab2
Catalog: What's New states the compaction rule of format 11
nledford Oct 18, 2026
3f01ff8
Catalog: segments no longer listed are removed only under a lock that…
nledford Oct 18, 2026
d9459d9
Catalog: a library whose upgrade was put off is not compacted into th…
nledford Oct 18, 2026
78e8c33
Catalog: rustfmt
nledford Oct 18, 2026
c9843bc
Catalog: compacting a library whose upgrade was put off keeps its old…
nledford Oct 18, 2026
2d8a8f4
Catalog: a compaction that failed after its commit keeps the old file…
nledford Oct 18, 2026
44753af
Catalog: a snapshot committed despite an error advances the journal's…
nledford Oct 18, 2026
9a1c886
Catalog: a snapshot committed despite an error does not advance the j…
nledford Oct 18, 2026
6cc1c12
Catalog: the bench counts the final snapshot once; closing a library …
nledford Oct 18, 2026
4a78c3f
Catalog: a compaction by hand ends the put-off upgrade, tested
nledford Oct 18, 2026
dc07670
Catalog: the bench says "and a last one" only when a last compaction ran
nledford Oct 18, 2026
b2df124
Catalog: segments of about 2 MB and at most 4096 photos
nledford Oct 10, 2026
2e2feca
Catalog: going back names each kept file, also the damaged log and a …
nledford Oct 18, 2026
e2ff14f
Catalog: the 1 million photo segment table says its counts do not equ…
nledford Oct 18, 2026
d7be8d0
Catalog: a failed sync of the segments folder fails the snapshot, and…
nledford Oct 18, 2026
06cbd82
Catalog: an atomic write fails when its folder can't be synced on POSIX
nledford Oct 18, 2026
6b48b9f
Catalog: a file system that can't sync folders does not fail saves
nledford Oct 18, 2026
267cd4a
Catalog: macOS's EOPNOTSUPP (102) is also "can't sync folders"
nledford Oct 18, 2026
604d743
Catalog: the "not supported" errno of a folder sync is the platform's…
nledford Oct 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/lightcraft-web/src/files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
Expand Down
176 changes: 152 additions & 24 deletions crates/catalog/examples/persist_bench.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
//! Catalog persistence costs on large synthetic catalogs (issue #37): log append, compaction
//! (snapshot serialise / write+fsync / log reset), synchronous and on the background worker, load,
//! and a catalog clone.
//! Catalog persistence costs on large synthetic catalogs (issue #37): an import that compacts as
//! the app does (how often, and how much it writes in all), log append, compaction (snapshot
//! serialise / write+fsync / log reset), synchronous and on the background worker, load, and a
//! catalog clone.
//!
//! ```text
//! cargo run --release -p lightcraft-catalog --example persist_bench -- <dir> [photos…]
//! ```
//!
//! `<dir>` is a scratch directory (wiped per size). Default sizes: 1000 10000 85000. 90 % of the
//! photos are Local browse records, the rest library photos with a few edits and history steps.
//! photos are Local browse records, the rest library photos with a few edits and history steps;
//! `PERSIST_BENCH_MIX=library` makes them all unedited JPEGs of a library, with a title;
//! `PERSIST_BENCH_MIX=edited` makes them all edited raws with 20 history steps each.
//! Peak memory: run under `/usr/bin/time -l` (macOS) / `-v` (Linux) with one size;
//! `PERSIST_BENCH_NO_LOAD=1` skips the final load, so the peak is building + compacting.

Expand All @@ -21,7 +24,47 @@ fn ms(t: Instant) -> f64 {
t.elapsed().as_secs_f64() * 1e3
}

/// `PERSIST_BENCH_MIX=library`: an imported JPEG nobody edited.
fn library_photo(c: &mut Catalog, i: u64) -> Photo {
let id = c.alloc_photo_id();
let name = format!("IMG_{i:08}.jpg");
let path = format!("/Volumes/Photos/Library/Archive/2019/2019-07 Summer/Trip to the coast/Day {:05}/extra/{name}", i / 500);
let mut p = Photo::new(id, Source::File { path }, &name, "JPEG", 4032, 3024, "2026-09-30T12:00:00");
p.file_size = 3_400_000 + i;
p.captured = Some(format!("2019-07-{:02}T10:{:02}:{:02}", 1 + i % 28, i % 60, (i / 60) % 60));
p.content_hash = Some(format!("{:032x}", i.wrapping_mul(0x9e37_79b9_7f4a_7c15)));
p.meta.title = format!("IMG_{i:07}");
p
}

/// `PERSIST_BENCH_MIX=edited`: a raw with 20 edits, each a history step with its own settings.
fn edited_photo(c: &mut Catalog, i: u64) -> Photo {
let mut p = library_photo(c, i);
p.kind = MediaKind::Raw;
p.format = "CR3".into();
p.as_shot_wb = Some((5200.0, 3.0));
let mut d = p.import_defaults();
for step in 0..20u64 {
match step % 4 {
0 => d.light.exposure = (i % 7) as f64 * 0.1 + step as f64 * 0.01,
1 => d.light.contrast = step as f64,
2 => d.wb.tint = (i % 11) as f64 + step as f64,
_ => d.detail.sharpen_amount = 40.0 + step as f64,
}
p.history.push(HistoryStep { label: "Edit".into(), settings: Arc::new(d.clone()) });
}
p.develop = p.history.last().map(|s| s.settings.clone()).unwrap_or_default();
p.edited = Some("2026-09-30T12:00:00".into());
p.rating = (i % 6) as u8;
p
}

fn photo(c: &mut Catalog, i: u64) -> Photo {
match std::env::var("PERSIST_BENCH_MIX").as_deref() {
Ok("library") => return library_photo(c, i),
Ok("edited") => return edited_photo(c, i),
_ => {}
}
let id = c.alloc_photo_id();
let mut p = Photo::new(
id,
Expand Down Expand Up @@ -61,6 +104,20 @@ fn photo(c: &mut Catalog, i: u64) -> Photo {
p
}

/// Log rating changes (2000 per append) until the journal asks for a compaction.
fn fill_until_due(j: &mut Journal, cat: &mut Catalog, ids: &[PhotoId]) -> std::result::Result<(), Box<dyn std::error::Error>> {
while !j.wants_snapshot() {
let ops: Vec<Op> = (0..2000u64)
.map(|k| Op::SetRating { id: ids.get((k as usize) % ids.len().max(1)).copied().unwrap_or(PhotoId(1)), rating: ((j.seq() + k) % 6) as u8 })
.collect();
for op in &ops {
cat.apply(op.clone())?;
}
j.append(&ops)?;
}
Ok(())
}

fn stats(mut v: Vec<f64>) -> String {
v.sort_by(f64::total_cmp);
let pick = |q: f64| v.get(((v.len() as f64 - 1.0) * q).round() as usize).copied().unwrap_or(0.0);
Expand All @@ -78,17 +135,55 @@ fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
let _ = std::fs::remove_dir_all(&dir);
let (mut j, _, _) = Journal::open(Box::new(FsStore::open(&dir)?))?;
let mut cat = Catalog::new();
// bulk-add (as one import would) and log it, so the first compaction is an import's
// an import: photos added one op each, the log compacted whenever the journal asks for
// it (as the app does; synchronously here, so the numbers don't depend on timing)
let t = Instant::now();
let (mut compactions, mut written, mut log_written) = (0u64, 0u64, 0u64);
for chunk in (0..n).collect::<Vec<_>>().chunks(500) {
let ops: Vec<Op> = chunk.iter().map(|i| Op::AddPhoto { photo: Box::new(photo(&mut cat, *i)) }).collect();
for op in &ops {
cat.apply(op.clone())?;
}
let before = j.log_bytes();
j.append(&ops)?;
log_written += j.log_bytes() - before;
if j.wants_snapshot() {
j.snapshot(&cat)?;
compactions += 1;
written += j.stats().last_snapshot.bytes;
}
}
let log_left = j.log_bytes();
// (a last batch that reached a threshold was snapshotted already: not again)
if log_left > 0 {
j.snapshot(&cat)?;
written += j.stats().last_snapshot.bytes;
}
let import_ms = ms(t);
let size = j.snapshot_bytes();
println!(
"== {n} photos ({} local): snapshot {:.1} MB ({:.0} B per photo)",
cat.photos().filter(|p| p.local).count(),
size as f64 / 1e6,
size as f64 / n.max(1) as f64
);
let last = if log_left > 0 { " (and a last one)" } else { "" };
println!(
" import: {compactions} compactions{last} wrote {:.1} MB of snapshots ({:.1}x the final one) + {:.1} MB of log in {:.1} s; {:.1} MB of log left for the last",
written as f64 / 1e6,
written as f64 / size.max(1) as f64,
log_written as f64 / 1e6,
import_ms / 1e3,
log_left as f64 / 1e6
);
if std::env::var_os("PERSIST_BENCH_NO_LOAD").is_none() {
let t = Instant::now();
let (_, loaded, _) = Journal::open(Box::new(FsStore::open(&dir)?))?;
println!(" open (the whole catalog from its snapshot): {:.1} ms", ms(t));
if loaded.len() != cat.len() {
return Err("reloaded catalog differs".into());
}
}
j.snapshot(&cat)?;
let first = j.stats().last_snapshot;
println!("== {n} photos ({} local): snapshot {:.1} MB", cat.photos().filter(|p| p.local).count(), first.bytes as f64 / 1e6);

let t = Instant::now();
let copy = cat.clone();
Expand All @@ -107,14 +202,10 @@ fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
println!(" append (1 op, fsync): {}", stats(appends));

// compactions at the default threshold crossing
// compactions when the journal asks for them
let mut totals = Vec::new();
for _ in 0..3 {
while !j.wants_snapshot() {
let op = Op::SetRating { id: ids.first().copied().unwrap_or(PhotoId(1)), rating: (j.seq() % 6) as u8 };
cat.apply(op.clone())?;
j.append(&[op])?;
}
fill_until_due(&mut j, &mut cat, &ids)?;
j.snapshot(&cat)?;
let s = j.stats().last_snapshot;
println!(
Expand All @@ -125,14 +216,10 @@ fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
println!(" compaction total: {}", stats(totals));

// the same at the threshold, written by the worker while single-op appends go on
// the same, written by the worker while single-op appends go on
let mut blocking = Vec::new();
for _ in 0..3 {
while !j.wants_snapshot() {
let op = Op::SetRating { id: ids.first().copied().unwrap_or(PhotoId(1)), rating: (j.seq() % 6) as u8 };
cat.apply(op.clone())?;
j.append(&[op])?;
}
fill_until_due(&mut j, &mut cat, &ids)?;
let t = Instant::now();
j.snapshot_in_background(&cat)?;
let start_ms = ms(t);
Expand All @@ -158,6 +245,26 @@ fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
println!(" background compaction blocking: {}", stats(blocking));

// changes all over the library (a rating on every 50th photo), then one compaction
let spread: Vec<PhotoId> = cat.photos().map(|p| p.id).step_by(50).collect();
let ops: Vec<Op> = 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<Op> = 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<String> = cat.photos().filter(|p| p.local).filter_map(|p| folder_of(p)).collect();
Expand All @@ -175,7 +282,7 @@ fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
}
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);
Expand All @@ -187,7 +294,7 @@ fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
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(),
Expand All @@ -205,11 +312,32 @@ fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
continue;
}
let t = Instant::now();
let (_, loaded, _) = Journal::open(Box::new(FsStore::open(&dir)?))?;
println!(" open (load snapshot + replay): {:.1} ms", ms(t));
let (mut j, mut loaded, _) = Journal::open(Box::new(FsStore::open(&dir)?))?;
let open_ms = ms(t);
println!(" open (after forgetting; load snapshot + replay): {open_ms:.1} ms");
if loaded.len() != cat.len() {
return Err("reloaded catalog differs".into());
}
// a long log (never compacted here): what replaying it costs when the library is opened
let ids: Vec<PhotoId> = loaded.photos().map(|p| p.id).take(1000).collect();
const REPLAYED: u64 = 200_000;
for batch in 0..REPLAYED / 2000 {
let ops: Vec<Op> = (0..2000u64)
.map(|k| Op::SetRating {
id: ids.get((k as usize) % ids.len().max(1)).copied().unwrap_or(PhotoId(1)),
rating: ((batch + k) % 6) as u8,
})
.collect();
for op in &ops {
loaded.apply(op.clone())?;
}
j.append(&ops)?;
}
let log_mb = j.log_bytes() as f64 / 1e6;
drop(j);
let t = Instant::now();
let (_, _, report) = Journal::open(Box::new(FsStore::open(&dir)?))?;
println!(" open with {} more log records ({log_mb:.1} MB): {:.1} ms ({:.1} ms more)", report.replayed, ms(t), ms(t) - open_ms);
}
let _ = std::fs::remove_dir_all(&dir);
Ok(())
Expand Down
7 changes: 7 additions & 0 deletions crates/catalog/proptest-regressions/tests_segments.txt
Original file line number Diff line number Diff line change
@@ -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)]
Loading
Loading