feat: owner review 2 phase 4b: mass conversion after import (#13)
CI / Build and test (push) Failing after 3m1s
CI / PostgreSQL 16 integration (push) Skipped
CI / PostgreSQL 17 integration (push) Skipped
CI / Docker image (push) Skipped
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 10s
Release / Build, test and publish (push) Successful in 15m31s
Release / Server image (push) Successful in 1m13s

Convert photos already in the archive to JPEG, TIFF-16 or Linear DNG, from the panel's Library and the desktop's Archive and Library. Each run asks Replace (same frames, originals to the trash, recoverable) or New sequence. A dry run lists what converts, what is skipped and why, size before and after, and free space; the job converts exactly the confirmed photos, resumes, and commits all or nothing per sequence. A conversion never changes what Chronos reads from a photo. Replaced originals are erased only on the archive's own word that their conversion is gone. Desktop TIFFs that WIC showed black or as noise now go to the managed reader; the Edit picker no longer spins a core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #13.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-03 10:41:50 +01:00
1 parent 7e4a3b481d
commit efa87f68ce
354 files changed
+24530 -843

No files matched your search

+177 -62
View File
@@ -21,8 +21,71 @@ public sealed record TrashEmptyPlan(Guid ArchiveId, IReadOnlyList<TrashEntry> En
public int Photos => Entries.Sum(e => e.Frames);
}
/// <summary>What an emptying erased, and the entries it kept (a replacement that no longer matches, an entry changed since the plan).</summary>
public sealed record TrashEmptyResult(int Erased, long Bytes, IReadOnlyList<string> Refused);
/// <summary>What an emptying erased, and the entries it kept, each with why (<see cref="TrashKept"/>).</summary>
public sealed record TrashEmptyResult(int Erased, long Bytes, IReadOnlyList<TrashKept> Refused);
/// <summary>An entry an emptying kept in the trash: its title and why.</summary>
public sealed record TrashKept(string Title, TrashKeptReason Reason)
{
/// <summary>
/// "Kept in the trash, changed after the plan: Etna", a job log line in the current culture; where something settles the
/// reason, the line says what.
/// </summary>
public string LogLine => Loc.L(Reason switch
{
TrashKeptReason.Mismatch => "Archive.Log.TrashKeptMismatch",
TrashKeptReason.Unknown => "Archive.Log.TrashKeptUnknown",
TrashKeptReason.Busy => "Archive.Log.TrashKeptBusy",
TrashKeptReason.Unhashed => "Archive.Log.TrashKeptUnhashed",
TrashKeptReason.Unreadable => "Archive.Log.TrashKeptUnreadable",
TrashKeptReason.StaleIndex => "Archive.Log.TrashKeptStaleIndex",
_ => "Archive.Log.TrashKept",
}, Title);
}
/// <summary>
/// Why an emptying kept an entry in the trash. For an entry of replaced originals (owner review 2, R7), all but
/// <see cref="Changed"/> and <see cref="Busy"/> are about where the archive shows their conversions: they are erased only
/// while each conversion is there and matches, or once the archive itself shows it deleted, as the dry run said.
/// </summary>
public enum TrashKeptReason
{
/// <summary>The entry changed since the emptying was planned (restored, or deleted again, meanwhile), or is gone.</summary>
Changed,
/// <summary>
/// A conversion of its originals no longer matches its content, in its sequence or in the trash, or its frame holds other
/// content now (its file changed since the conversion).
/// </summary>
Mismatch,
/// <summary>
/// The archive does not show what became of a conversion of its originals: its sequence's sidecar holds none of it and no
/// tombstone says it was deleted (a sidecar rebuilt from the photos keeps only what one index knew), or the sequence is
/// nowhere in the archive and the trash has no record of erasing it. Nothing in the archive settles it: restoring the
/// entry keeps its photos.
/// </summary>
Unknown,
/// <summary>Its sequence is busy: another writer holds it, or a change to it is not settled yet.</summary>
Busy,
/// <summary>A frame of its sequence that may hold a conversion of its originals was never hashed: a verify of the sequence settles it.</summary>
Unhashed,
/// <summary>
/// A sidecar where its sequence may be cannot be read, or photos there have none: a scan of the archive rebuilds or adopts
/// it (what the new sidecar shows then decides).
/// </summary>
Unreadable,
/// <summary>
/// This index lists its sequence in a folder that no longer holds it, the archive holds it nowhere else and the trash has no
/// record of erasing it: a rebuild of the index drops that row (restoring the entry then brings its photos back as a new
/// sequence).
/// </summary>
StaleIndex,
}
/// <summary>The trash changed after the emptying was planned (an entry came, went or changed); nothing was erased.</summary>
public sealed class StaleTrashPlanException() : InvalidOperationException(Loc.L("Archive.Error.TrashChanged"));
@@ -37,12 +100,20 @@ public sealed partial class SequenceTrash
/// <summary>
/// The dry run of emptying the trash: <paramref name="names"/> of the entries to erase (null: every entry), each
/// measured on disk, and the plan's fingerprint (<see cref="Fingerprint"/>). Reads only.
/// measured on disk, each replaced entry whose conversion was deleted since said so (<see cref="TrashEntry.ConversionDeleted"/>),
/// and the plan's fingerprint (<see cref="Fingerprint"/>). Reads only.
/// </summary>
public async Task<TrashEmptyPlan> PlanEmptyAsync(Archive archive, IReadOnlyList<string>? names = null, CancellationToken cancellationToken = default)
public Task<TrashEmptyPlan> PlanEmptyAsync(Archive archive, IReadOnlyList<string>? names = null, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(archive);
var paths = new ArchivePaths(archive.RootPath);
return PlanEmptyAsync(archive, paths, names, new SidecarWalk(paths), cancellationToken);
}
/// <summary>The dry run, finding the sequences of replaced entries that moved through <paramref name="walk"/> (made at most once).</summary>
private async Task<TrashEmptyPlan> PlanEmptyAsync(Archive archive, ArchivePaths paths, IReadOnlyList<string>? names, SidecarWalk walk,
CancellationToken cancellationToken)
{
var listed = await ListAsync(archive, cancellationToken).ConfigureAwait(false);
var wanted = names?.ToHashSet(StringComparer.Ordinal);
var chosen = wanted is null ? listed : [.. listed.Where(e => wanted.Contains(e.Name))];
@@ -52,6 +123,9 @@ public sealed partial class SequenceTrash
var (files, bytes) = Directory.Exists(folder) ? Measure(folder, cancellationToken) : (0, 0L);
return e with { Files = files, Bytes = bytes };
}).ToList(), cancellationToken).ConfigureAwait(false);
// The sequences of replaced entries, found once for the whole plan.
var located = new Dictionary<Guid, Located>();
for (var i = 0; i < measured.Count; i++) measured[i] = await PlannedAsync(archive, paths, measured[i], located, walk, cancellationToken).ConfigureAwait(false);
var unknown = names?.Where(n => !listed.Any(e => e.Name == n)).Distinct(StringComparer.Ordinal).ToList() ?? [];
return new TrashEmptyPlan(archive.Id, measured, measured.Sum(e => e.Bytes), Fingerprint(measured), unknown);
}
@@ -68,11 +142,15 @@ public sealed partial class SequenceTrash
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
}
/// <summary>What identifies one entry as planned: its kind, name, files and bytes on disk, and when it was deleted.</summary>
/// <summary>
/// What identifies one entry as planned: its kind, name, files and bytes on disk, when it was deleted, and for a replaced
/// entry whether its conversion was deleted (<see cref="TrashEntry.ConversionDeleted"/>), which the dry run says.
/// </summary>
public static string EntryFingerprint(TrashEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
return string.Create(CultureInfo.InvariantCulture, $"{entry.Kind}|{entry.Name}|{entry.Files}|{entry.Bytes}|{entry.DeletedAt.UtcTicks}");
var planned = string.Create(CultureInfo.InvariantCulture, $"{entry.Kind}|{entry.Name}|{entry.Files}|{entry.Bytes}|{entry.DeletedAt.UtcTicks}");
return entry.ConversionDeleted ? planned + "|conversion-deleted" : planned;
}
/// <summary>
@@ -81,8 +159,13 @@ public sealed partial class SequenceTrash
/// hold exactly the planned entries (<see cref="EmptyTrashParameters.Fingerprint"/>), else nothing is erased; a run
/// resumed after a stop checks each remaining entry against its own fingerprint, keeps one that changed and skips one
/// that is gone, and each entry is checked against its fingerprint once more under its lease, just before it goes. A
/// <see cref="TrashKind.Replaced"/> entry is erased only while every replacement still matches its
/// SHA-256 in the sequence (re-hashed now); otherwise it is kept. Leftovers of an interrupted erase are deleted first.
/// <see cref="TrashKind.Replaced"/> entry is weighed under its sequence's lease as well, against the archive as it is then
/// (<see cref="Survey"/>): it is erased only while every conversion of its originals still matches its SHA-256 where the
/// archive shows it (re-hashed now: in the sequence, or a copy the trash holds when its conversion was deleted, as the
/// dry run said); otherwise, or when the archive cannot tell, it is kept, with why. Leftovers of an interrupted erase are
/// deleted first; the sequences of replaced entries that moved are looked up in one walk of the archive for the whole run
/// (<see cref="SidecarWalk"/>), and the records of erased sequences no replaced entry needs any more go at the end
/// (<see cref="SweepErasures"/>).
/// </summary>
/// <param name="progress">Entries done so far (the resume point) and their number.</param>
/// <exception cref="StaleTrashPlanException">The trash no longer holds exactly the planned entries; nothing was erased.</exception>
@@ -95,9 +178,10 @@ public sealed partial class SequenceTrash
ArchiveVolume.EnsureWritable(paths);
SweepErasing(paths);
var items = parameters.Entries;
var current = await PlanEmptyAsync(archive, [.. items.Skip(start).Select(i => i.Name)], cancellationToken).ConfigureAwait(false);
var walk = new SidecarWalk(paths);
var current = await PlanEmptyAsync(archive, paths, [.. items.Skip(start).Select(i => i.Name)], walk, cancellationToken).ConfigureAwait(false);
if (start == 0 && (current.Fingerprint != parameters.Fingerprint || current.Unknown.Count > 0)) throw new StaleTrashPlanException();
var refused = new List<string>();
var refused = new List<TrashKept>();
int erased = 0;
long bytes = 0;
for (var i = start; i < items.Count; i++)
@@ -108,94 +192,125 @@ public sealed partial class SequenceTrash
{
if (EntryFingerprint(entry) != item.Fingerprint)
{
refused.Add(entry.Title);
refused.Add(new TrashKept(entry.Title, TrashKeptReason.Changed));
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
}
else if (await EraseAsync(paths, entry, item.Fingerprint, cancellationToken).ConfigureAwait(false))
else if (await EraseAsync(archive, paths, entry, item.Fingerprint, walk, cancellationToken).ConfigureAwait(false) is { } reason)
{
refused.Add(new TrashKept(entry.Title, reason));
}
else
{
erased++;
bytes += entry.Bytes;
}
else
{
refused.Add(entry.Title);
}
}
await progress(i + 1, items.Count).ConfigureAwait(false);
}
SweepErasures(archive, paths, cancellationToken);
return new TrashEmptyResult(erased, bytes, refused);
}
/// <summary>
/// Erases one entry under its lease, once its record read and its folder measured again under it still give the
/// planned <paramref name="fingerprint"/> (another host sharing the archive may have restored the entry and deleted the
/// same sequence again since); false (logged) when it changed, or a replaced entry's replacements no longer match.
/// same sequence again since). A replaced entry is weighed under its sequence's lease too, so no writer of the sequence
/// moves its conversions meanwhile, and only once what a writer left unsettled in the sequence is settled (an undo whose
/// completion waited for this entry's lease takes photos out of it): the archive must tell where each conversion is (as
/// the dry run said, which the fingerprint holds), and each must still match. A deleted sequence that a replaced entry
/// still in the trash came from leaves a record of its erasing (<see cref="RecordErasureAsync"/>). Returns null once erased,
/// else why the entry is kept (logged).
/// </summary>
private async Task<bool> EraseAsync(ArchivePaths paths, TrashEntry entry, string fingerprint, CancellationToken cancellationToken)
private async Task<TrashKeptReason?> EraseAsync(Archive archive, ArchivePaths paths, TrashEntry entry, string fingerprint, SidecarWalk walk,
CancellationToken cancellationToken)
{
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, EntryLease(entry.Name), _writer.Options.Owner, _writer.Options.LeaseWait,
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
{
var (folder, record) = Location(paths, entry);
if (!Directory.Exists(folder) || !File.Exists(record)) return false;
if (Reread(paths, entry, cancellationToken) is not { } now || EntryFingerprint(now) != fingerprint)
if (!Directory.Exists(folder) || !File.Exists(record)) return TrashKeptReason.Changed;
IAsyncDisposable? sequence = null;
if (entry.Kind == TrashKind.Replaced)
{
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
return false;
try
{
sequence = await _writer.LockAsync(paths, entry.SequenceId, cancellationToken).ConfigureAwait(false);
}
catch (LeaseUnavailableException ex)
{
Log.Warning("archive", $"Trash entry {entry.Name} is kept: its sequence is busy", ex);
return TrashKeptReason.Busy;
}
}
if (entry.Kind == TrashKind.Replaced && !await ReplacementsHoldAsync(paths, entry, cancellationToken).ConfigureAwait(false))
await using (sequence)
{
Log.Warning("archive", $"Trash entry {entry.Name} is kept: a replacement of its originals no longer matches");
return false;
// Settled before the entry is read again, so what is read is what an erase takes.
var located = sequence is null ? null : await LocateAsync(archive, paths, entry, walk, EntryLease(entry.Name), cancellationToken).ConfigureAwait(false);
var (now, survey) = Reread(archive, paths, entry, located, cancellationToken);
if (survey?.Kept is { } kept)
{
Log.Warning("archive", $"Trash entry {entry.Name} is kept ({kept}): the archive does not show the conversions of its originals whole");
return kept;
}
if (now is null || EntryFingerprint(now) != fingerprint)
{
Log.Warning("archive", $"Trash entry {entry.Name} changed since the emptying was planned; it is kept");
return TrashKeptReason.Changed;
}
if (survey is not null && !await MatchAsync(survey, cancellationToken).ConfigureAwait(false))
{
Log.Warning("archive", $"Trash entry {entry.Name} is kept: a conversion of its originals no longer matches");
return TrashKeptReason.Mismatch;
}
var aside = Path.Combine(TrashDirectory(paths), ErasingFolder, Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Path.GetDirectoryName(aside)!);
// Before the folder goes: once it has, the archive alone tells a replaced entry of that sequence what became of it.
if (entry.Kind == TrashKind.Sequence) await RecordErasureAsync(archive, paths, now, walk, cancellationToken).ConfigureAwait(false);
Directory.Move(folder, aside);
File.Delete(record);
Erase(aside);
Log.Info("archive", $"Trash entry {entry.Name} ({entry.Title}, {entry.Files} files, {entry.Bytes} bytes) erased"
+ (now.ConversionDeleted ? "; the conversion of its originals had been deleted" : string.Empty));
return null;
}
var aside = Path.Combine(TrashDirectory(paths), ErasingFolder, Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(Path.GetDirectoryName(aside)!);
Directory.Move(folder, aside);
File.Delete(record);
Erase(aside);
Log.Info("archive", $"Trash entry {entry.Name} ({entry.Title}, {entry.Files} files, {entry.Bytes} bytes) erased");
return true;
}
}
/// <summary>
/// Whether every photo of a replaced entry still has its replacement in the sequence: a frame holding the replacement's
/// SHA-256 whose file hashes to it now. The originals are erased only then (a later phase's conversion).
/// An entry as the trash lists it and an erase plans it, from its record and folder as they are now, and a replaced
/// entry's survey against where its sequence was found under its lease (<paramref name="located"/>, which says whether the
/// conversion of one of its photos was deleted, <see cref="TrashEntry.ConversionDeleted"/>); a null entry when its record
/// cannot be read or its folder is gone.
/// </summary>
private async Task<bool> ReplacementsHoldAsync(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
{
if (FrameTrash.ReadEntry(paths, entry.Name) is not { } record) return false;
foreach (var photo in record.Photos)
{
if (photo.Replacement is not { } replacement) return false;
var holders = (await _db.Frames.FindBySha256Async(replacement.ToLowerInvariant(), cancellationToken).ConfigureAwait(false))
.Where(f => f.SequenceId == record.SequenceId).ToList();
var verified = false;
foreach (var frame in holders)
{
var file = paths.FromRelative(frame.RelativePath);
if (!File.Exists(file)) continue;
if (string.Equals(await ContentHash.Sha256Async(file, null, cancellationToken).ConfigureAwait(false), replacement, StringComparison.OrdinalIgnoreCase))
{
verified = true;
break;
}
}
if (!verified) return false;
}
return true;
}
/// <summary>An entry as the trash lists it, from its record and folder as they are now; null when its record cannot be read.</summary>
private static TrashEntry? Reread(ArchivePaths paths, TrashEntry entry, CancellationToken cancellationToken)
private static (TrashEntry? Entry, ConversionSurvey? Survey) Reread(Archive archive, ArchivePaths paths, TrashEntry entry, Located? located,
CancellationToken cancellationToken)
{
var (folder, recordPath) = Location(paths, entry);
var now = FrameTrash.IsPhotoEntry(entry.Name)
? FrameTrash.ReadListed(paths, entry.ArchiveId, entry.Name)
: ReadRecord(recordPath) is { } record ? Entry(entry.ArchiveId, Path.GetFileName(entry.Name), record) : null;
if (now is null) return null;
if (now is null || !Directory.Exists(folder)) return (null, null);
var (files, bytes) = Measure(folder, cancellationToken);
return now with { Files = files, Bytes = bytes };
now = now with { Files = files, Bytes = bytes };
if (located is null) return (now, null);
if (FrameTrash.ReadEntry(paths, entry.Name) is not { } photos) return (null, null);
var survey = Survey(archive, paths, entry.Name, photos, located, cancellationToken);
return (survey.Deleted ? now with { ConversionDeleted = true } : now, survey);
}
/// <summary>
/// <paramref name="entry"/> as an emptying plans it: a replaced entry is <see cref="TrashEntry.ConversionDeleted"/> when the
/// archive shows the conversion of one of its photos deleted (<see cref="Survey"/>), so the dry run says so. Its sequence
/// is found once per plan (<paramref name="located"/>, through <paramref name="walk"/> when it moved). Reads sidecars and
/// records; hashes nothing.
/// </summary>
private async Task<TrashEntry> PlannedAsync(Archive archive, ArchivePaths paths, TrashEntry entry, Dictionary<Guid, Located> located, SidecarWalk walk,
CancellationToken cancellationToken)
{
if (entry.Kind != TrashKind.Replaced || FrameTrash.ReadEntry(paths, entry.Name) is not { } record) return entry;
if (!located.TryGetValue(entry.SequenceId, out var where))
located[entry.SequenceId] = where = await LocateAsync(archive, paths, entry, walk, null, cancellationToken).ConfigureAwait(false);
return Survey(archive, paths, entry.Name, record, where, cancellationToken).Deleted ? entry with { ConversionDeleted = true } : entry;
}
/// <summary>The folder and record of an entry of either kind.</summary>