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:
Alby96 committed 2026-10-27 13:53:41 +01:00
1 parent a133306fb0
commit 4518ffe655
29 files changed
+856 -162

No files matched your search

@@ -4,6 +4,7 @@ using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
@@ -274,6 +275,73 @@ public sealed class LibraryTests(TestContext context)
Assert.Null(await server.Database.Sequences.GetAsync(t));
}
[Test]
public async Task ARestoreSaysWhichPhotosStayedAndWhy()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (editor, _, _) = await server.UserAsync("alberto", "editor");
var admin = await server.AdminAsync();
Guid id = default;
for (var i = 0; i < 4; i++) id = (await Uploads.UploadAsync(editor, Photo(120 + i), $"IMG_{i + 1:0000}.JPG", sessionKey: "kept")).SequenceId;
await UntilIdleAsync(server);
var frames = await server.Database.Frames.ListBySequenceAsync(id);
string name;
using (var deleted = await editor.PostAsJsonAsync($"/api/v1/sequences/{id}/frames/delete", new FrameDeleteRequest([frames[1].Id, frames[2].Id], null, false),
ProtocolJson.Default.FrameDeleteRequest))
name = Assert.NotNull((await deleted.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
await UntilIdleAsync(server);
var trashed = Path.Combine(PhotoEntryFolder(server, name), "originals", Path.GetFileName(frames[2].RelativePath));
var bytes = await File.ReadAllBytesAsync(trashed, context.Cancellation);
bytes[^10] ^= 0x01;
await File.WriteAllBytesAsync(trashed, bytes, context.Cancellation);
using var restored = await admin.PostAsync($"/api/v1/archive/trash/{name}/restore", null);
var result = await restored.ReadAsync(ProtocolJson.Default.TrashRestoreDto);
Assert.Equal(1, result.Photos);
Assert.SequenceEqual([frames[2].OriginalFileName!], result.Kept);
Assert.SequenceEqual(["mismatch"], Assert.NotNull(result.KeptReasons));
Assert.Equal(KeptPhoto.Sentence(KeptReason.Mismatch, 1, System.Globalization.CultureInfo.GetCultureInfo("en")), result.Message);
}
[Test]
[WindowsOnly]
public async Task APhotoNeverHashedIsDeletedUnlessItCannotBeRead()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
// Photos copied into the archive by hand and scanned: adopted, never hashed.
var shoot = Path.Combine(server.Options.ArchivePath, "Shoot");
Directory.CreateDirectory(shoot);
for (var i = 0; i < 3; i++) await File.WriteAllBytesAsync(Path.Combine(shoot, $"IMG_{i + 1:0000}.JPG"), Photo(130 + i), context.Cancellation);
var archives = server.Services.GetRequiredService<ArchiveService>();
await archives.Indexer.ScanAsync(server.Services.GetRequiredService<ServerArchive>().Current, ScanMode.Incremental, null, _ => ValueTask.CompletedTask,
context.Cancellation);
await UntilIdleAsync(server);
var id = (await server.Database.Sequences.ListLocationsAsync(server.Services.GetRequiredService<ServerArchive>().Id)).Single(l => l.Folder == "Shoot").Id;
var frames = await server.Database.Frames.ListBySequenceAsync(id);
Assert.True(frames.All(f => f.Sha256 is null), "adopted, not verified");
var url = $"/api/v1/sequences/{id}/frames/delete";
// Another program holds one: it cannot be hashed for its tombstone, and the answer names it (no frames_conflict loop).
var held = Path.Combine(server.Options.ArchivePath, frames[1].RelativePath);
using (new FileStream(held, FileMode.Open, FileAccess.Read, FileShare.None))
{
using var refused = await admin.PostAsJsonAsync(url, new FrameDeleteRequest([frames[1].Id], null, false), ProtocolJson.Default.FrameDeleteRequest);
var error = await refused.ExpectErrorAsync(HttpStatusCode.Conflict, "photo_unreadable");
Assert.Equal("1", error.Details);
Assert.Contains("IMG_0002.JPG", error.Message);
}
Assert.FileExists(held);
// One whose original is gone has nothing left to hash: it goes, without a tombstone.
File.Delete(Path.Combine(server.Options.ArchivePath, frames[2].RelativePath));
using (var gone = await admin.PostAsJsonAsync(url, new FrameDeleteRequest([frames[2].Id], null, false), ProtocolJson.Default.FrameDeleteRequest))
Assert.NotNull((await gone.ReadAsync(ProtocolJson.Default.FrameDeleteResultDto)).TrashEntry);
Assert.Empty(await server.Database.FrameRemovals.ListBySequenceAsync(id));
Assert.SequenceEqual([frames[0].Id, frames[1].Id], (await server.Database.Frames.ListBySequenceAsync(id)).Select(f => f.Id));
}
[Test]
public async Task APhotoDeleteTakesAsManyIdsAsItsLimit()
{
@@ -8,6 +8,7 @@ using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
@@ -228,6 +229,42 @@ public sealed class BrowserUploadTests(TestContext context)
Assert.SequenceEqual([keeper.FrameId], (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
}
[Test]
public async Task APhotoDeletedBetweenTheCompletionsCheckAndItsCommitIsNotFiled()
{
// The completion asks the index first; a deletion that lands after that and before the commit is caught by the
// ingest itself, which asks the sidecar's tombstones under the lease the deletion takes.
GatedIngest? gate = null;
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = Chunk, s =>
{
ArchiveModule.Register(s);
s.AddSingleton<IArchiveIngest>(sp => gate = new GatedIngest(sp.GetRequiredService<ArchiveService>().Ingest));
});
var browser = await Browser.SignInAsync(server);
var sequence = await CreateAsync(browser, "Roof");
var photo = Photo(17);
var sha = Uploads.Sha(photo);
var keeper = await UploadAsync(browser, sequence.Id, "IMG_0000.JPG", Photo(18));
var first = await UploadAsync(browser, sequence.Id, "IMG_0001.JPG", photo);
await UntilIdleAsync(server);
var frame = Assert.NotNull(await server.Database.Frames.GetAsync(first.FrameId));
File.Delete(Path.Combine(server.Options.ArchivePath, frame.RelativePath));
var repair = await StartAsync(browser, sequence.Id, "IMG_0001.JPG", photo, HttpStatusCode.Created);
var id = Assert.NotNull(repair.UploadId);
await SendChunksAsync(browser, id, photo);
Assert.NotNull(gate).BeforeCommit = () => DeleteAsync(server, browser, sequence.Id, first.FrameId);
using (var complete = await CompleteAsync(browser, id))
await complete.ExpectErrorAsync(HttpStatusCode.Conflict, UploadErrors.PhotoRemoved);
Assert.SequenceEqual([keeper.FrameId], (await server.Database.Frames.ListBySequenceAsync(sequence.Id)).Select(f => f.Id));
Assert.True(await server.Database.FrameRemovals.IsRemovedAsync(sequence.Id, sha), "the tombstone stays");
Assert.False(server.Services.GetRequiredService<UploadStore>().Exists(id), "the partial file is gone");
Assert.FileMissing(Path.Combine(server.Options.StagingPath, id.ToString("N") + ".jpg"));
using (var late = await CompleteAsync(browser, id))
await late.ExpectErrorAsync(HttpStatusCode.Conflict, "upload_state");
}
[Test]
public async Task AStaleTombstoneBesideAFrameOfTheSameContentRefusesNoRepair()
{
@@ -426,6 +463,22 @@ public sealed class BrowserUploadTests(TestContext context)
}
}
/// <summary>The archive's ingest with a step run once before the next commit (what lands between the completion's checks and it).</summary>
private sealed class GatedIngest(IArchiveIngest inner) : IArchiveIngest
{
public Func<Task>? BeforeCommit { get; set; }
public async Task<IngestResult> CommitAsync(IngestRequest request, CancellationToken cancellationToken = default)
{
if (BeforeCommit is { } step)
{
BeforeCommit = null;
await step();
}
return await inner.CommitAsync(request, cancellationToken);
}
}
/// <summary>A JPEG of a few chunks: noise does not compress below the chunk size.</summary>
private static byte[] Photo(int seed)
{