Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
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: 3 additions & 1 deletion crates/catalog/src/journal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,9 @@ impl Journal {
report.stale += 1;
}
Some((seq, op)) if j.seq.checked_add(1) == Some(seq) => {
if catalog.apply(op).is_err() {
// (a batch that was only partly taken back when it was applied is logged as it was: replaying it is
// not damage, see `Catalog::replay_op`)
if catalog.replay_op(op).is_err() {
report.failed += 1;
} else {
report.replayed += 1;
Expand Down
82 changes: 59 additions & 23 deletions crates/catalog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ pub enum CatalogError {
/// version doesn't know). Nothing was read into the session and nothing was modified.
#[error("this library was written by a newer version of LightCraft ({0}); update LightCraft to open it. The library was left unchanged.")]
Newer(String),
/// A batch failed, and rolling back what it had applied failed too: the catalog is not as it was, and part of
/// the batch stays. `remaining` is what is left of the rollback (applied in order, it takes the catalog back to
/// where it was before the batch), so the change can still be undone, and the batch itself is the record to keep
/// of it: replaying the batch from the same catalog fails the same way and leaves the same changes.
#[error("{cause}; the change was only partly taken back, so part of it stays")]
PartlyApplied { cause: Box<CatalogError>, remaining: Box<Op> },
}

pub type Result<T> = std::result::Result<T, CatalogError>;
Expand Down Expand Up @@ -298,8 +304,8 @@ pub struct Catalog {
/// references and clears the table when a snapshot is read.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
grids: Vec<String>,
/// Increments on every applied op, and when a batch fails and its rollback cannot undo it whole (the catalog
/// changed, so what is keyed by the revision is out of date).
/// Increments on every applied op, and when a batch fails and part of it stays ([`CatalogError::PartlyApplied`]): the
/// catalog changed, so what is keyed by the revision is out of date.
#[serde(skip)]
pub revision: u64,
/// Which photos the latest ops touched ([`Catalog::touched_since`]).
Expand Down Expand Up @@ -412,8 +418,10 @@ struct Changes {
/// outside (a library just loaded takes a range of its own, so that nothing kept from another library is
/// taken for this one's): nothing is known of how the catalog got to where it is.
seen: u64,
/// A batch that failed could not be rolled back whole: what it changed stays, so what it noted must too.
torn: bool,
/// The inverses of a failed batch's ops that could not be applied when it was rolled back, in the order they
/// are to be applied (see [`CatalogError::PartlyApplied`]). Empty unless a rollback is under way or has just
/// failed; [`Catalog::apply`] hands it out.
leftover: Vec<Op>,
}

impl PartialEq for Changes {
Expand All @@ -423,6 +431,14 @@ impl PartialEq for Changes {
}
}

/// `op` and, when it is a batch, the ops in it (nested batches too), each alone and in the order the batch lists them.
fn unbatch(op: Op, out: &mut Vec<Op>) {
match op {
Op::Batch { ops } => ops.into_iter().for_each(|op| unbatch(op, out)),
op => out.push(op),
}
}

impl Catalog {
pub fn new() -> Catalog {
Catalog { next_photo: 1, next_album: 1, next_stack: 1, ..Default::default() }
Expand Down Expand Up @@ -726,37 +742,37 @@ impl Catalog {
}

/// Apply an op; returns its inverse. On error the catalog is as it was, the revision included, and nothing is
/// remembered of the op in what the latest ops touched. The one exception is a batch whose rollback fails: the
/// catalog did change, so the revision advances and anything may be taken to have changed.
/// remembered of the op in what the latest ops touched. The one exception is a batch that fails and cannot be rolled
/// back whole: it is [`CatalogError::PartlyApplied`], the catalog did change (the revision advances and anything may
/// be taken to have changed), and the caller must record the op.
pub fn apply(&mut self, op: Op) -> Result<Op> {
if self.changes.seen != self.revision {
// the revision was set from outside: what is remembered is of another past
self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() };
}
let broad = self.changes.broad;
self.changes.torn = false;
let inv = match self.apply_inner(op) {
Ok(inv) => inv,
Err(e) => {
Err(cause) => {
let made = self.revision.saturating_add(1);
if self.changes.torn {
// (a batch the rollback of which failed changed something and says not what: it makes a
// revision, so what is kept for the one before is dropped, and anything may have changed, as
// after an op of a wider reach)
self.changes.torn = false;
self.changes.broad = made;
self.revision = made;
self.changes.seen = made;
} else {
let left = std::mem::take(&mut self.changes.leftover);
if left.is_empty() {
// (everything the failed op, or the rollback of a batch, noted was made for the revision it
// would have made: nothing earlier has that one. A note the cap already dropped stays
// dropped, which only says less than is known, as the cap does.)
while self.changes.touched.back().is_some_and(|(r, _, _)| *r == made) {
self.changes.touched.pop_back();
}
self.changes.broad = broad;
return Err(cause);
}
return Err(e);
// (a batch the rollback of which failed changed something and says not what: it makes a revision, so
// what is kept for the one before is dropped, and anything may have changed, as after an op of a
// wider reach)
self.changes.broad = made;
self.revision = made;
self.changes.seen = made;
return Err(CatalogError::PartlyApplied { cause: Box::new(cause), remaining: Box::new(Op::Batch { ops: left }) });
}
};
self.revision += 1;
Expand Down Expand Up @@ -1151,12 +1167,21 @@ impl Catalog {
match self.apply_inner(op) {
Ok(inv) => inverses.push(inv),
Err(e) => {
// roll back what was applied
for inv in inverses.into_iter().rev() {
if self.apply_inner(inv).is_err() {
self.changes.torn = true;
// roll back what was applied: first what a batch inside this one could not take back
// (it was done last), then the inverses, newest first. A batch among them (the inverse
// of one that went through) goes op by op, in the order it lists them: as a whole it would
// stop at the first op that cannot go yet and be kept whole, to stop there again at the
// retry, while its later ops (the one that makes the first possible) never ran.
let mut todo = Vec::new();
let leftover = std::mem::take(&mut self.changes.leftover);
leftover.into_iter().chain(inverses.into_iter().rev()).for_each(|inv| unbatch(inv, &mut todo));
let mut left = Vec::new();
for inv in todo {
if self.apply_inner(inv.clone()).is_err() {
left.push(inv);
}
}
self.changes.leftover = left;
return Err(e);
}
}
Expand Down Expand Up @@ -1345,7 +1370,7 @@ impl Catalog {
for (i, line) in lines.iter().enumerate() {
match serde_json::from_str::<Op>(line) {
Ok(op) => {
self.apply(op)?;
self.replay_op(op)?;
n += 1;
}
Err(e) if i + 1 == lines.len() => {
Expand All @@ -1358,6 +1383,17 @@ impl Catalog {
Ok(n)
}

/// Apply one op of a saved log: the one place that says which failures of a logged op are the log being replayed, not
/// damage (`Journal::open` and [`Self::replay`] both go through it). A batch that was only partly taken back when it
/// was applied is logged as it was ([`CatalogError::PartlyApplied`]) and fails the same way again, leaving the same
/// changes, so replaying it counts as done; any other error is the caller's to handle.
pub(crate) fn replay_op(&mut self, op: Op) -> Result<()> {
match self.apply(op) {
Ok(_) | Err(CatalogError::PartlyApplied { .. }) => Ok(()),
Err(e) => Err(e),
}
}

pub fn op_to_log_line(op: &Op) -> String {
let mut s = serde_json::to_string(op).unwrap_or_default();
s.push('\n');
Expand Down
103 changes: 103 additions & 0 deletions crates/catalog/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1128,3 +1128,106 @@ fn a_batch_that_cannot_be_rolled_back_whole_makes_earlier_changes_unknown() {
assert_eq!(c.touched_since(start), None, "so nothing is said of what changed");
assert_eq!(c.touched_since(c.revision), Some(vec![]), "from after it, it is known again");
}

/// A batch that fails, and whose rollback fails halfway, says so and hands out what is left of the rollback.
#[test]
fn a_batch_that_cannot_be_rolled_back_whole_hands_out_what_is_left_of_the_rollback() {
let mut c = Catalog::default();
let mut ids = Vec::new();
for name in ["a.jpg", "b.jpg"] {
let id = c.alloc_photo_id();
let photo = Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00");
c.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();
ids.push(id);
}
let stack = c.alloc_stack_id();
c.apply(Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap();
let before = c.to_snapshot();
let missing = PhotoId(9_999);
// the photo goes, then its stack, then an op fails: putting the stack back needs the photo, which comes later
let torn = |ops: Vec<Op>| Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }].into_iter().chain(ops).collect() };
let fail = Op::SetRating { id: missing, rating: 1 };

let revision = c.revision;
let e = c.apply(torn(vec![fail.clone()])).unwrap_err();
assert_eq!(c.revision, revision + 1, "the catalog changed, so what is derived from its revision is out of date");
assert_eq!(c.touched_since(revision), None, "and nothing is said of what changed");
let CatalogError::PartlyApplied { cause, remaining } = e else { panic!("expected a partly applied batch, got {e:?}") };
assert_eq!(*cause, CatalogError::NoPhoto(missing));
assert_ne!(c.to_snapshot(), before, "the rollback went only part of the way");
// what is left finishes the rollback
c.apply(*remaining).unwrap();
assert_eq!(c.to_snapshot(), before);

// a batch in a batch: what the inner one could not take back is taken back by the outer one's rollback, when it can
let nested = Op::Batch { ops: vec![Op::SetRating { id: ids[1], rating: 5 }, torn(vec![fail.clone()])] };
assert_eq!(c.apply(nested), Err(CatalogError::NoPhoto(missing)));
assert_eq!(c.to_snapshot(), before);

// an op that fails plainly is not partly applied, and leaves nothing for the next op to hand out
assert_eq!(c.apply(fail), Err(CatalogError::NoPhoto(missing)));
assert_eq!(c.to_snapshot(), before);
}

/// A batch that succeeded inside a batch that fails is taken back by its inverse, which is a batch too. When that inverse
/// cannot go through as a whole (the stack is put back before the photo it holds), its ops are taken back one by one,
/// so that what is handed out for a retry is only what still has to be done and the retry can finish.
#[test]
fn the_inverse_of_a_nested_batch_is_taken_back_op_by_op() {
let mut c = Catalog::default();
let mut ids = Vec::new();
for name in ["a.jpg", "b.jpg"] {
let id = c.alloc_photo_id();
let photo = Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00");
c.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();
ids.push(id);
}
let stack = c.alloc_stack_id();
c.apply(Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap();
let before = c.to_snapshot();
let missing = PhotoId(9_999);
// the inner batch goes through (the photo goes, then its stack); the outer one fails after it
let inner = Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }] };
let outer = Op::Batch { ops: vec![inner, Op::SetRating { id: missing, rating: 1 }] };
let e = c.apply(outer).unwrap_err();
let CatalogError::PartlyApplied { cause, remaining } = e else { panic!("expected a partly applied batch, got {e:?}") };
assert_eq!(*cause, CatalogError::NoPhoto(missing));
assert!(c.photo(ids[0]).is_some(), "the photo came back: only what could not yet be done is left");
let Op::Batch { ops: left } = remaining.as_ref() else { panic!("a batch of what is left") };
assert!(matches!(left.as_slice(), [Op::AddStack { .. }]), "just the stack, on its own: {left:?}");
// what is left finishes the rollback
c.apply(*remaining).unwrap();
assert_eq!(c.to_snapshot(), before);
}

/// A batch that was only partly taken back is logged as it was and leaves the same changes when the log is replayed: the
/// replay counts it and goes on with the records after it (the journal's open does the same).
#[test]
fn replaying_a_log_goes_on_after_a_partly_applied_batch() {
let mut c = Catalog::default();
let mut ids = Vec::new();
for name in ["a.jpg", "b.jpg"] {
let id = c.alloc_photo_id();
let photo = Photo::new(id, Source::File { path: format!("/p/{name}") }, name, "JPEG", 60, 40, "2026-01-01T10:00:00");
c.apply(Op::AddPhoto { photo: Box::new(photo) }).unwrap();
ids.push(id);
}
let stack = c.alloc_stack_id();
c.apply(Op::AddStack { stack: Stack { id: stack, photos: ids.clone(), collapsed: false } }).unwrap();
let start = c.clone();
// the photo goes, then its stack, then an op fails: putting the stack back needs the photo, which comes later
let torn =
Op::Batch { ops: vec![Op::RemovePhoto { id: ids[0] }, Op::RemoveStack { id: stack }, Op::SetRating { id: PhotoId(9_999), rating: 1 }] };
let rate = Op::SetRating { id: ids[1], rating: 4 };
assert!(matches!(c.apply(torn.clone()), Err(CatalogError::PartlyApplied { .. })));
c.apply(rate.clone()).unwrap();

let log = format!("{}{}", Catalog::op_to_log_line(&torn), Catalog::op_to_log_line(&rate));
let mut replayed = start;
assert_eq!(replayed.replay(&log).unwrap(), 2, "both records were replayed");
assert_eq!(replayed.to_snapshot(), c.to_snapshot(), "the log gives what the session had");

// an op that fails plainly still stops the replay
let bad = Op::SetRating { id: PhotoId(9_999), rating: 1 };
assert_eq!(replayed.replay(&Catalog::op_to_log_line(&bad)), Err(CatalogError::NoPhoto(PhotoId(9_999))));
}
4 changes: 4 additions & 0 deletions crates/engine/src/cmd/browse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,10 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result:
let label = if renamed { format!("Rename Folder to “{name}”") } else { format!("Move Folder “{name}”") };
let folder = crate::FolderMove { from: to.to_string(), to: from.to_string() };
if let Err(e) = s.commit_with_folder(&label, Op::Batch { ops }, folder) {
if matches!(e, crate::EngineError::Catalog(lightcraft_catalog::CatalogError::PartlyApplied { .. })) {
// part of it stays, and the undo step that takes it back renames the folder: it stays where it is
return Err(e.to_string());
}
// the catalog didn't take it: put the folder back where the photos still point
let back = rename_folder_on_disk(to, from).err().map(|b| format!("; moving it back failed too: {b}")).unwrap_or_default();
return Err(format!("{e}{back}"));
Expand Down
Loading
Loading