fix(archive): settle trash journals under their leases and say why restored photos stayed
Second fix round of owner review 2, phase 3 (engine, server, desktop). - A photo never hashed whose original is missing can be deleted again: it goes into its trash record without a file and without a tombstone (nothing is left to name), stays listed until Empty erases it, and a restore keeps it with the reason "no file". FrameDeleteBlock.Unhashable now blocks only a present original that cannot be read; the API answers it as 409 photo_unreadable naming the photo, and every block has its own code and message. - Deleting a whole sequence first settles an interrupted photo deletion, restore or ingest of it (ReadLocked under its lease), so no journal or half entry travels into the sequence's trash entry; it refuses while a restore into it waits for its busy entry. - FrameTrash.Settle takes the photo entry's lease and leaves the journal for later while the entry is busy (an emptying), so it never races EraseAsync; meanwhile no other restore writes its journal over it and scans do not adopt its files. - The hashes computed for frames that stay (to find a twin of a deleted photo) go into the sidecar and index, and only a frame whose first and last 64 KiB match a deleted photo's is read whole. - A restore into a new sequence rewrites its record after each photo filed, so a crash or a database failure never leaves filed photos listed. - An upload completion no longer has a window before the commit: the ingest checks the sidecar's tombstones under the sequence lease a deletion takes (IngestRequest.RefuseRemoved), unless the upload asked to bring it back. - A restore reports each kept photo with its reason (no longer matches its record, could not be moved back, already in the sequence, had no file); the desktop line and the API message say so in en and it, and the tooltip holds the whole sentence. The desktop tells TrashMismatchException by its type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit 1858f1f450a35fb8383ede8d80ce5f8de9b7ceac)
This commit is contained in:
1 parent
a133306fb0
commit
4518ffe655
29 files changed
+856
-162
No files matched your search
@@ -258,7 +258,7 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
|
||||
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
|
||||
|
||||
Assert.Equal(1, restored.Photos);
|
||||
Assert.SequenceEqual([frames[2].OriginalFileName!], restored.Kept);
|
||||
Assert.SequenceEqual([new KeptPhoto(frames[2].OriginalFileName!, KeptReason.Mismatch)], restored.Kept);
|
||||
Assert.SequenceEqual([frames[0].Id, frames[1].Id, frames[3].Id], (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
|
||||
Assert.SequenceEqual([frames[2].Sha256], (await fx.Db.FrameRemovals.ListBySequenceAsync(sequence.Id)).Select(r => r.Sha256));
|
||||
var left = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == deleted.Entry.Name);
|
||||
@@ -705,7 +705,7 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
|
||||
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct);
|
||||
|
||||
Assert.Equal(0, restored.Photos);
|
||||
Assert.SequenceEqual([frames[1].OriginalFileName!], restored.Kept);
|
||||
Assert.SequenceEqual([new KeptPhoto(frames[1].OriginalFileName!, KeptReason.NotMoved)], restored.Kept);
|
||||
Assert.FileMissing(photo);
|
||||
Assert.FileMissing(folder.RestoreJournalPath);
|
||||
var entryFolder = EntryFolder(fx, deleted.Entry);
|
||||
@@ -806,13 +806,92 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
|
||||
Assert.True(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, sha));
|
||||
Assert.Equal(sha, Sha(Path.Combine(EntryFolder(fx, deleted.Entry), "originals", Path.GetFileName(frames[1].RelativePath))));
|
||||
|
||||
// One whose original is gone as well could leave none: the plan refuses it, and says which.
|
||||
// One whose original is gone as well has no content left to name: it goes without a file and without a tombstone,
|
||||
// and its record stays in the trash, listed until Empty erases it (nothing can bring it back).
|
||||
var third = Sha(fx.Paths.FromRelative(frames[2].RelativePath));
|
||||
File.Delete(fx.Paths.FromRelative(frames[3].RelativePath));
|
||||
var row = (await fx.Db.Sequences.GetAsync(sequence.Id))!;
|
||||
var refused = await fx.Service.FrameTrash.PlanDeleteAsync(sequence.Id, [frames[2].Id, frames[3].Id], row.FramesVersion, fx.Ct);
|
||||
Assert.SequenceEqual([FrameDeleteBlock.Unhashable], refused.Blocked);
|
||||
Assert.SequenceEqual([frames[3].Id], refused.Unhashable.Select(f => f.Id));
|
||||
await Assert.ThrowsAsync<StaleDeletePlanException>(() => fx.Service.FrameTrash.DeleteAsync(refused, null, null, fx.Ct));
|
||||
var gone = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[2], frames[3]);
|
||||
|
||||
Assert.Equal((2, 1), (gone.Entry.Frames, gone.Entry.Files));
|
||||
Assert.SequenceEqual(new[] { sha, third }.Order(), Assert.NotNull(ManifestStore.ReadSequence(folder.ManifestPath).Removed).Select(r => r.Sha256).Order());
|
||||
Assert.SequenceEqual([frames[0].Id], ManifestStore.ReadSequence(folder.ManifestPath).Frames.Select(f => f.Id));
|
||||
|
||||
var restored = await fx.Service.RestoreEntryAsync(fx.Archive.Id, gone.Entry.Name, null, fx.Ct);
|
||||
Assert.Equal(1, restored.Photos);
|
||||
Assert.SequenceEqual([KeptReason.NoFile], restored.Kept.Select(k => k.Reason));
|
||||
var left = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Name == gone.Entry.Name);
|
||||
Assert.Equal((1, 0), (left.Frames, left.Files));
|
||||
await Assert.ThrowsAsync<TrashMismatchException>(() => fx.Service.RestoreEntryAsync(fx.Archive.Id, gone.Entry.Name, null, fx.Ct));
|
||||
|
||||
var plan = await fx.Service.PlanEmptyTrashAsync(fx.Archive.Id, [gone.Entry.Name], fx.Ct);
|
||||
var items = plan.Entries.Select(e => new EmptyTrashItem(e.Name, SequenceTrash.EntryFingerprint(e))).ToList();
|
||||
var emptied = await fx.Service.Trash.EmptyAsync(fx.Archive, new EmptyTrashParameters(items, plan.Fingerprint), 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
|
||||
Assert.Equal(1, emptied.Erased);
|
||||
Assert.DoesNotContain(gone.Entry.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Name));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public async Task APhotoNeverHashedThatCannotBeReadWaitsUntilItCan()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (sequence, frames) = await AdoptedAsync(fx, "Shoot", 3);
|
||||
var original = fx.Paths.FromRelative(frames[1].RelativePath);
|
||||
var sha = Sha(original);
|
||||
|
||||
// Another program holds it: it could not be hashed for its tombstone, so the plan refuses it and says which.
|
||||
using (new FileStream(original, FileMode.Open, FileAccess.Read, FileShare.None))
|
||||
{
|
||||
var refused = await fx.Service.FrameTrash.PlanDeleteAsync(sequence.Id, [frames[1].Id], sequence.FramesVersion, fx.Ct);
|
||||
Assert.SequenceEqual([FrameDeleteBlock.Unhashable], refused.Blocked);
|
||||
Assert.SequenceEqual([frames[1].Id], refused.Unhashable.Select(f => f.Id));
|
||||
await Assert.ThrowsAsync<StaleDeletePlanException>(() => fx.Service.FrameTrash.DeleteAsync(refused, null, null, fx.Ct));
|
||||
}
|
||||
|
||||
Assert.Equal(sha, Sha(original));
|
||||
await DeleteAsync(fx, sequence, frames[1]);
|
||||
Assert.True(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, sha));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AFrameThatStaysHashedToFindATwinKeepsItsHashAndOnlyLikelyTwinsAreReadWhole()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var shoot = Path.Combine(fx.Archive.RootPath, "Raw");
|
||||
Directory.CreateDirectory(shoot);
|
||||
// Originals of one size, as uncompressed raw files are: only one whose first and last 64 KiB match a deleted photo's
|
||||
// is read whole.
|
||||
const int Size = 300_000;
|
||||
static byte[] Padded(int seed)
|
||||
{
|
||||
var bytes = new byte[Size];
|
||||
Photos.Jpeg(Start, seed).CopyTo(bytes, 0);
|
||||
return bytes;
|
||||
}
|
||||
var deleted = Padded(1);
|
||||
var near = (byte[])deleted.Clone();
|
||||
near[Size / 2] ^= 0xFF;
|
||||
File.WriteAllBytes(Path.Combine(shoot, "IMG_0001.JPG"), Padded(2));
|
||||
File.WriteAllBytes(Path.Combine(shoot, "IMG_0002.JPG"), deleted);
|
||||
File.WriteAllBytes(Path.Combine(shoot, "IMG_0003.JPG"), deleted);
|
||||
File.WriteAllBytes(Path.Combine(shoot, "IMG_0004.JPG"), near);
|
||||
await fx.ScanAsync();
|
||||
var id = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single(l => l.Folder == "Raw").Id;
|
||||
var frames = await fx.Db.Frames.ListBySequenceAsync(id);
|
||||
Assert.True(frames.All(f => f.Sha256 is null), "adopted, not verified");
|
||||
|
||||
await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(id))!, frames.Single(f => f.RelativePath.EndsWith("IMG_0002.JPG", StringComparison.Ordinal)));
|
||||
|
||||
var sidecar = ManifestStore.ReadSequence(fx.Paths.Sequence("Raw").ManifestPath);
|
||||
Assert.Null(sidecar.Removed, "its twin stays");
|
||||
string? InSidecar(string name) => sidecar.Frames.Single(f => f.File.EndsWith(name, StringComparison.Ordinal)).Sha256;
|
||||
Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(deleted)), InSidecar("IMG_0003.JPG"));
|
||||
Assert.Equal(Convert.ToHexStringLower(SHA256.HashData(near)), InSidecar("IMG_0004.JPG"));
|
||||
Assert.Null(InSidecar("IMG_0001.JPG"), "its first 64 KiB differ: never read whole");
|
||||
// The index holds the hashes too, so a later deletion does not read those files again.
|
||||
var now = await fx.Db.Frames.ListBySequenceAsync(id);
|
||||
Assert.Equal(InSidecar("IMG_0003.JPG"), now.Single(f => f.RelativePath.EndsWith("IMG_0003.JPG", StringComparison.Ordinal)).Sha256);
|
||||
Assert.Null(now.Single(f => f.RelativePath.EndsWith("IMG_0001.JPG", StringComparison.Ordinal)).Sha256);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -974,6 +1053,148 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
|
||||
Assert.FileExists(Path.Combine(SequenceTrash.TrashDirectory(fx.Paths), names[1], "added.bin"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ASequenceDeletedAfterAnInterruptedPhotoDeletionTakesNoHalfEntryAlong()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (sequence, frames) = await UploadedAsync(fx, 3);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
// As a photo deletion leaves it when the process dies after its first move: journal, pending record, one file moved.
|
||||
var name = $"{sequence.Id:N}-20261027120000";
|
||||
var entry = Path.Combine(FrameTrash.Directory(fx.Paths), name);
|
||||
var record = entry + ".json";
|
||||
var sidecar = ManifestStore.ReadSequence(folder.ManifestPath).Frames.Take(2).ToList();
|
||||
var files = sidecar.Select(f => new TrashedFile(f.File, "originals/" + Path.GetFileName(f.File), f.Size, f.Sha256)).ToList();
|
||||
Directory.CreateDirectory(Path.Combine(entry, "originals"));
|
||||
File.WriteAllText(FrameRemovalJournal.PendingRecord(record), JsonSerializer.Serialize(new PhotoTrashRecord(TrashKind.Photos, sequence.Id, sequence.DisplayTitle,
|
||||
sequence.Folder, [.. sidecar.Zip(files, (f, t) => new TrashedPhoto(f, [t], null))], files.Sum(f => f.Size), DateTimeOffset.UtcNow, "alberto"),
|
||||
TrashJson.Default.PhotoTrashRecord));
|
||||
var moves = files.Select(f => new FrameRemovalMove(f.From, fx.Paths.ToRelative(Path.Combine(entry, f.Path)))).ToList();
|
||||
FrameRemovalJournal.Write(folder, new FrameRemovalJournal(fx.Paths.ToRelative(record), fx.Paths.ToRelative(entry), [.. sidecar.Select(f => f.Id)], moves));
|
||||
File.Move(folder.File(moves[0].From), fx.Paths.FromRelative(moves[0].To));
|
||||
|
||||
await DeleteSequenceAsync(fx, sequence.Id);
|
||||
|
||||
// The deletion was undone first: every photo went with its sequence, and neither its journal nor half an entry is left.
|
||||
var deleted = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.Kind == TrashKind.Sequence);
|
||||
var trashed = fx.Paths.Sequence(".chronos/trash/" + deleted.Name);
|
||||
Assert.FileMissing(trashed.RemovalJournalPath);
|
||||
foreach (var frame in frames) Assert.Equal(frame.Sha256, Sha(trashed.File(frame.RelativePath[(sequence.Folder.Length + 1)..])));
|
||||
Assert.False(Directory.Exists(entry));
|
||||
Assert.FileMissing(FrameRemovalJournal.PendingRecord(record));
|
||||
Assert.DoesNotContain(TrashKind.Photos, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Select(e => e.Kind));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARestoreWhoseEntryIsBusyWaitsAndNothingGoesOnOverIt()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (sequence, frames) = await UploadedAsync(fx, 5);
|
||||
var folder = fx.Paths.Sequence(sequence.Folder);
|
||||
var deleted = await DeleteAsync(fx, sequence, frames[1], frames[2]);
|
||||
var other = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[3]);
|
||||
// A restore died after moving one original back, before the sidecar; the entry is being emptied meanwhile.
|
||||
var journal = RestoreJournal(fx, deleted.Entry);
|
||||
journal.Write(folder);
|
||||
var moved = journal.Photos[0].Moves[0];
|
||||
File.Move(fx.Paths.FromRelative(moved.To), folder.File(moved.From));
|
||||
|
||||
using (Assert.NotNull(LeaseFile.TryAcquire(fx.Paths.LocksDirectory, SequenceTrash.EntryLease(deleted.Entry.Name), "other")))
|
||||
{
|
||||
// Another writer leaves the journal for later: it never moves a file into an entry being erased.
|
||||
await fx.Service.SetSequenceInfoAsync(sequence.Id, "Harbour", [], 0, null, fx.Ct);
|
||||
Assert.FileExists(folder.RestoreJournalPath);
|
||||
Assert.FileExists(folder.File(moved.From));
|
||||
Assert.FileMissing(fx.Paths.FromRelative(moved.To));
|
||||
// A scan does not adopt the photo that restore moved in.
|
||||
File.SetLastWriteTimeUtc(folder.File(moved.From), DateTime.UtcNow);
|
||||
await fx.ScanAsync();
|
||||
Assert.Count(2, await fx.Db.Frames.ListBySequenceAsync(sequence.Id));
|
||||
// Neither a restore of another entry into the sequence nor the sequence's deletion goes on over it.
|
||||
await Assert.ThrowsAsync<LeaseUnavailableException>(() => fx.Service.RestoreEntryAsync(fx.Archive.Id, other.Entry.Name, null, fx.Ct));
|
||||
await Assert.ThrowsAsync<LeaseUnavailableException>(() => DeleteSequenceAsync(fx, sequence.Id));
|
||||
Assert.FileExists(folder.RestoreJournalPath);
|
||||
Assert.FileExists(folder.ManifestPath);
|
||||
}
|
||||
|
||||
// Once the entry is free, the next writer settles it: the original goes back into its entry, and both entries come back.
|
||||
await fx.Service.SetSequenceInfoAsync(sequence.Id, "Harbour", [], 0, null, fx.Ct);
|
||||
Assert.FileMissing(folder.RestoreJournalPath);
|
||||
Assert.Equal(frames[1].Sha256, Sha(fx.Paths.FromRelative(moved.To)));
|
||||
Assert.FileMissing(folder.File(moved.From));
|
||||
Assert.Equal(2, (await fx.Service.RestoreEntryAsync(fx.Archive.Id, deleted.Entry.Name, null, fx.Ct)).Photos);
|
||||
Assert.Equal(1, (await fx.Service.RestoreEntryAsync(fx.Archive.Id, other.Entry.Name, null, fx.Ct)).Photos);
|
||||
Assert.SequenceEqual(frames.Select(f => f.Id), (await fx.Db.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARestoreIntoANewSequenceStoppedBetweenPhotosKeepsItsRecordTrue()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (sequence, frames) = await UploadedAsync(fx, 4);
|
||||
var first = await DeleteAsync(fx, sequence, frames[1]);
|
||||
var second = await DeleteAsync(fx, (await fx.Db.Sequences.GetAsync(sequence.Id))!, frames[2], frames[3]);
|
||||
await DeleteSequenceAsync(fx, sequence.Id);
|
||||
var made = await fx.Service.RestoreEntryAsync(fx.Archive.Id, first.Entry.Name, null, fx.Ct);
|
||||
Assert.True(made.NewSequence);
|
||||
var entryFolder = EntryFolder(fx, second.Entry);
|
||||
var staged = Path.Combine(entryFolder, ".restoring", "originals", Path.GetFileName(frames[2].RelativePath));
|
||||
using var cancel = CancellationTokenSource.CreateLinkedTokenSource(fx.Ct);
|
||||
|
||||
// The new sequence is held while the first photo waits to be filed into it, and the restore is cancelled meanwhile.
|
||||
Task restore;
|
||||
using (Assert.NotNull(LeaseFile.TryAcquire(fx.Paths.LocksDirectory, $"seq-{made.Sequence.Id:N}", "other")))
|
||||
{
|
||||
restore = fx.Service.RestoreEntryAsync(fx.Archive.Id, second.Entry.Name, null, cancel.Token);
|
||||
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
|
||||
while (!File.Exists(staged))
|
||||
{
|
||||
Assert.True(DateTime.UtcNow < until, "the first photo was never staged");
|
||||
await Task.Delay(10, fx.Ct);
|
||||
}
|
||||
cancel.Cancel();
|
||||
}
|
||||
await Assert.ThrowsAsync<OperationCanceledException>(() => restore);
|
||||
|
||||
// The first photo is filed, the second stays, and the record lists exactly what is left.
|
||||
Assert.SequenceEqual([frames[1].Sha256, frames[2].Sha256], (await fx.Db.Frames.ListBySequenceAsync(made.Sequence.Id)).Select(f => f.Sha256));
|
||||
var record = Assert.NotNull(FrameTrash.ReadEntry(fx.Paths, second.Entry.Name));
|
||||
Assert.SequenceEqual([frames[3].Id], record.Photos.Select(p => p.Frame.Id));
|
||||
Assert.Equal(frames[3].Size, record.Bytes);
|
||||
Assert.Equal(frames[3].Sha256, Sha(Path.Combine(entryFolder, "originals", Path.GetFileName(frames[3].RelativePath))));
|
||||
Assert.False(Directory.Exists(Path.Combine(entryFolder, ".restoring")));
|
||||
|
||||
var rest = await fx.Service.RestoreEntryAsync(fx.Archive.Id, second.Entry.Name, null, fx.Ct);
|
||||
Assert.Equal((1, made.Sequence.Id), (rest.Photos, rest.Sequence.Id));
|
||||
Assert.Empty(rest.Kept);
|
||||
Assert.False(Directory.Exists(entryFolder));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnIngestThatRefusesRemovedContentChecksTheTombstonesUnderTheLease()
|
||||
{
|
||||
var fx = await FixtureAsync();
|
||||
var (sequence, frames) = await UploadedAsync(fx, 3);
|
||||
await DeleteAsync(fx, sequence, frames[1]);
|
||||
// The same photo staged again (an upload whose completion checked the index before the deletion landed).
|
||||
var (path, size, sha) = fx.Stage(Start.AddSeconds(10), 101);
|
||||
Assert.Equal(frames[1].Sha256, sha);
|
||||
var request = new IngestRequest(fx.Archive.Id, sequence.Id, null, null, path, frames[1].OriginalFileName!, size, sha, null, null, RefuseRemoved: true);
|
||||
|
||||
var refused = await Assert.ThrowsAsync<PhotoRemovedException>(() => fx.Service.Ingest.CommitAsync(request, fx.Ct));
|
||||
|
||||
Assert.Equal(sequence.Id, refused.SequenceId);
|
||||
Assert.FileExists(path);
|
||||
Assert.Count(2, ManifestStore.ReadSequence(fx.Paths.Sequence(sequence.Folder).ManifestPath).Frames);
|
||||
Assert.True(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, sha));
|
||||
|
||||
// Asked back, it is filed and its tombstone goes.
|
||||
var back = await fx.Service.Ingest.CommitAsync(request with { RefuseRemoved = false }, fx.Ct);
|
||||
Assert.False(back.Duplicate);
|
||||
Assert.False(await fx.Db.FrameRemovals.IsRemovedAsync(sequence.Id, sha));
|
||||
Assert.Count(3, await fx.Db.Frames.ListBySequenceAsync(sequence.Id));
|
||||
}
|
||||
|
||||
/// <summary>An entry of originals a conversion replaced (a later phase), its one photo replaced by <paramref name="replacement"/>.</summary>
|
||||
private static string WriteReplaced(ArchiveFixture fx, Sequence sequence, string stamp, string replacement)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user