fix(archive): convert job applies exactly the confirmed plan, resumes safely and watches its space

The convert job planned every sequence again when it ran and checked only the frames
version, so a verify, a repaired upload or a tier change between the dry run and the job
let it replace photos the confirmed plan had listed as staying unchanged.

- Each sequence of a convert job now carries the digest of the photos it converts, each
  with its SHA-256 (ConvertSequencePlan.Digest, also in the plan's fingerprint). Under the
  sequence's lease, its sidecar settled, the job plans it again and goes on only while the
  digest matches; it then pins those photos (convert-<job>.pins), so photos that come in
  or are verified later stay as they are, a retry included. Stage B checks under the lease
  that every pinned photo still holds the content converted instead of holding the frames
  version, so a sequence still receiving uploads converts what was confirmed.
- A resumed job settles the journals a crash left in a sequence (a half-done replacement
  among them) before it plans, and reports a sequence its replacement completed as
  Converted, never Nothing or a partial swap.
- The passes a converted or new sequence needs are queued as soon as its outcome is
  journaled; the journal records the statuses they follow from and whether they were
  queued, so a pause, yield, stop or crash no longer loses them.
- Staged conversions of a blocked or failed sequence are kept for the retry, which
  re-verifies and takes them; maintenance keeps a convert job's staging while the job is
  queued, running or paused, and removes its journal and staging once the job is done or
  gone from the history.
- A dry run counts the sequences of a queued conversion as busy, so the same conversion
  cannot be confirmed twice.
- New sequence copies are owned by the source's owner, else by the requesting user's id
  (never the user name); a staged copy that vanished fails the sequence instead of leaving
  its photo out; the job log states how many photos stayed in the source alone.
- Free space is measured where the conversion writes: the server takes the tighter of the
  space path's volume and the archive's own (Unraid cache), the desktop asks Windows
  (GetDiskFreeSpaceEx), which also measures UNC archives; the job checks again before each
  sequence and each photo, scaling estimates by the files staged so far, and stops before
  the volume fills with what it staged kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 2d7d461c33b9f257bf57793cc7cf331d0425c14e)
This commit is contained in:
Alby96 committed 2026-10-27 22:06:55 +01:00
1 parent f86a151a5d
commit 67a6d51cbe
17 files changed
+1222 -236

No files matched your search

@@ -453,6 +453,8 @@ public sealed class AppServices : IAsyncDisposable
var archive = new ArchiveServiceOptions
{
Decoder = DecoderFactory.CreateClient(_wic),
// Measured by Windows itself, so an archive on a network share (UNC) is measured too: a conversion checks its space.
FreeSpace = Chronos.Core.Windows.Devices.VolumeInfo.FreeBytesAt,
Parallelism = () => Parallelism,
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
// The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10).
@@ -70,6 +70,26 @@ public sealed record VolumeInfo(
}
}
/// <summary>
/// Free bytes available to the current user on the volume holding the folder <paramref name="folder"/>, quotas counted: a
/// network share's (UNC) too, which <see cref="DriveInfo"/> cannot measure. Null when the folder cannot be reached or measured.
/// </summary>
public static long? FreeBytesAt(string folder)
{
ArgumentException.ThrowIfNullOrEmpty(folder);
// A share's folder must end with a separator.
var directory = Path.EndsInDirectorySeparator(folder) ? folder : folder + Path.DirectorySeparatorChar;
VolumeNative.SetThreadErrorMode(VolumeNative.SEM_FAILCRITICALERRORS, out var previousMode);
try
{
return VolumeNative.GetDiskFreeSpaceEx(directory, out var free, out _, out _) ? (long)Math.Min(free, long.MaxValue) : null;
}
finally
{
VolumeNative.SetThreadErrorMode(previousMode, out _);
}
}
/// <summary>Every ready fixed or removable volume, enumerated through <see cref="DriveInfo"/> (network and optical drives are skipped).</summary>
public static IReadOnlyList<VolumeInfo> ListLocal()
{
+30 -8
View File
@@ -43,7 +43,7 @@ public enum ConvertSkip
/// <summary>Why a whole sequence is not converted now; nothing of it is touched.</summary>
public enum ConvertBlock
{
/// <summary>A running or paused job works on the sequence or its whole archive.</summary>
/// <summary>A running or paused job works on the sequence or its whole archive, or a conversion of it waits in the queue.</summary>
Busy,
/// <summary>The archive is offline or read-only.</summary>
@@ -52,15 +52,21 @@ public enum ConvertBlock
/// <summary>The sequence's sidecar cannot be read, or belongs to another sequence.</summary>
Unreadable,
/// <summary>The sequence's frames changed after the plan was made (found by the job, which then leaves it as it is).</summary>
/// <summary>
/// The photos the sequence converts are no longer those of the plan confirmed (found by the job, which then leaves it as
/// it is).
/// </summary>
FramesChanged,
}
/// <summary>Frames of a sequence that are not converted, and why.</summary>
public sealed record ConvertSkipped(ConvertSkip Reason, int Frames);
/// <summary>One frame a conversion converts: its id and index, its file and format, its size and the converted file's estimated size.</summary>
public sealed record ConvertFramePlan(Guid FrameId, int Index, string File, ImageFileFormat Format, long Size, long EstimatedBytes);
/// <summary>
/// One frame a conversion converts: its id and index, its file and format, its size, the converted file's estimated size,
/// and the SHA-256 of the content converted.
/// </summary>
public sealed record ConvertFramePlan(Guid FrameId, int Index, string File, ImageFileFormat Format, long Size, long EstimatedBytes, string? Sha256 = null);
/// <summary>
/// One sequence of a conversion plan: the frames converted, those skipped with why, the frames version the plan was made at,
@@ -79,6 +85,21 @@ public sealed record ConvertSequencePlan(Guid SequenceId, string Title, string F
public long BytesAfter => Frames.Sum(f => f.EstimatedBytes);
public int SkippedFrames => Skipped.Sum(s => s.Frames);
/// <summary>
/// A digest of the photos the sequence converts: each frame in order with the SHA-256 of the content converted. A
/// conversion job converts the sequence only while its plan there still has the digest the user confirmed.
/// </summary>
public string Digest() => DigestOf(Frames.Select(f => (f.FrameId, f.Sha256)));
/// <summary>The digest of frames, each with the SHA-256 of its content, in order (<see cref="Digest"/>).</summary>
public static string DigestOf(IEnumerable<(Guid FrameId, string? Sha256)> frames)
{
ArgumentNullException.ThrowIfNull(frames);
var text = new StringBuilder();
foreach (var (id, sha) in frames) text.Append(CultureInfo.InvariantCulture, $"{id:N}|{sha?.ToLowerInvariant()}\n");
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(text.ToString())));
}
}
/// <summary>
@@ -108,15 +129,16 @@ public sealed record ConvertPlan(Guid ArchiveId, ConvertOptions Options, Convert
public int Skipped => Sequences.Sum(s => s.SkippedFrames);
/// <summary>
/// A digest of what the plan converts (options, mode, and each sequence in order with its frames version, the frames
/// converted and skipped, and what blocks it), the same for two plans of the same archive state.
/// A digest of what the plan converts (options, mode, and each sequence in order with its frames version, the photos
/// converted with their content (<see cref="ConvertSequencePlan.Digest"/>), those skipped, and what blocks it), the
/// same for two plans of the same archive state.
/// </summary>
public string Fingerprint()
{
var text = new StringBuilder().Append(Options.Key).Append('|').Append(Mode).Append('\n');
foreach (var s in Sequences)
{
text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FramesVersion}|{s.Frames.Count}|{s.BytesBefore}|");
text.Append(CultureInfo.InvariantCulture, $"{s.SequenceId:N}|{s.FramesVersion}|{s.Frames.Count}|{s.BytesBefore}|{s.Digest()}|");
foreach (var skipped in s.Skipped) text.Append(CultureInfo.InvariantCulture, $"{skipped.Reason}:{skipped.Frames};");
foreach (var blocked in s.Blocked) text.Append(blocked).Append(';');
text.Append('\n');
@@ -180,7 +202,7 @@ public static class ConvertPlanner
skipped[reason] = skipped.GetValueOrDefault(reason) + 1;
continue;
}
frames.Add(new ConvertFramePlan(frame.Id, frame.I, frame.File, frame.Format, frame.Size, EstimateBytes(options, frame.W, frame.H)));
frames.Add(new ConvertFramePlan(frame.Id, frame.I, frame.File, frame.Format, frame.Size, EstimateBytes(options, frame.W, frame.H), frame.Sha256));
}
return new ConvertSequencePlan(manifest.Id, title, folder.RelativeFolder, manifest.Versions.Frames, frames,
[.. skipped.OrderBy(s => s.Key).Select(s => new ConvertSkipped(s.Key, s.Value))], []);
@@ -40,6 +40,12 @@ public sealed class ArchiveMaintenance
/// <summary>Staged copies older than this belong to no running import.</summary>
private static readonly TimeSpan StagingAge = TimeSpan.FromHours(24);
/// <summary>
/// The journal of a conversion job this index does not know (another host's, or one its history forgot) is left alone
/// until it has not been written for this long: the job history keeps finished jobs as long by default.
/// </summary>
private static readonly TimeSpan JournalAge = TimeSpan.FromDays(Housekeeping.CleanupSteps.DefaultHistoryDays);
/// <summary>Temporary files of atomic writes older than this were left by a crash.</summary>
private static readonly TimeSpan TempAge = TimeSpan.FromHours(1);
@@ -141,7 +147,7 @@ public sealed class ArchiveMaintenance
leases = LeaseFile.CleanupStale(paths.LocksDirectory, dryRun);
break;
case 1:
temps = PurgeTemporaryFiles(paths, locations, dryRun);
temps = await PurgeTemporaryFilesAsync(paths, locations, dryRun, cancellationToken).ConfigureAwait(false);
break;
case 2:
packs = await CompactPacksAsync(paths, locations, dryRun, cancellationToken).ConfigureAwait(false);
@@ -172,20 +178,66 @@ public sealed class ArchiveMaintenance
return (space.ReclaimableBytes, long.Max(0, before.FileBytes - after.FileBytes));
}
/// <summary>Staging copies and atomic-write temporaries left behind by crashes (never originals).</summary>
private static List<string> PurgeTemporaryFiles(ArchivePaths paths, IReadOnlyList<SequenceLocation> locations, bool dryRun)
/// <summary>
/// Staging copies and atomic-write temporaries left behind by crashes (never originals), and what a conversion job left
/// (<see cref="ConvertJournal"/>): its staged conversions stay while the job is queued, running or paused, however old, go
/// as soon as it is done, and otherwise once none of them was written for a day (a retry then converts again); its journal
/// stays while a retry can use it, and goes once the job is done, or unknown to this index and untouched for as long as
/// the job history keeps jobs.
/// </summary>
private async Task<List<string>> PurgeTemporaryFilesAsync(ArchivePaths paths, IReadOnlyList<SequenceLocation> locations, bool dryRun,
CancellationToken cancellationToken)
{
var now = DateTime.UtcNow;
var found = new List<string>();
var conversions = new List<string>();
var states = new Dictionary<Guid, JobState?>();
async Task<JobState?> StateAsync(Guid job)
{
if (!states.TryGetValue(job, out var state)) states[job] = state = (await _db.Jobs.GetAsync(job, cancellationToken).ConfigureAwait(false))?.State;
return state;
}
bool Old(string file, TimeSpan age) => now - File.GetLastWriteTimeUtc(file) > age;
void Collect(string directory, string pattern, TimeSpan age, bool recursive)
{
if (!Directory.Exists(directory)) return;
foreach (var file in Directory.EnumerateFiles(directory, pattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
{
if (now - File.GetLastWriteTimeUtc(file) > age) found.Add(file);
if (Old(file, age)) found.Add(file);
}
}
if (Directory.Exists(paths.StagingDirectory))
{
foreach (var file in Directory.EnumerateFiles(paths.StagingDirectory))
{
if (Old(file, StagingAge)) found.Add(file);
}
foreach (var directory in Directory.EnumerateDirectories(paths.StagingDirectory))
{
if (ConvertJournal.JobOf(Path.GetFileName(directory)) is not { } job)
{
Collect(directory, "*", StagingAge, recursive: true);
continue;
}
var state = await StateAsync(job).ConfigureAwait(false);
if (state is JobState.Queued or JobState.Running or JobState.Paused) continue;
var files = Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories).ToList();
if (state == JobState.Done || files.All(f => Old(f, StagingAge)))
{
found.AddRange(files);
conversions.Add(directory);
}
}
}
if (Directory.Exists(paths.JournalDirectory))
{
foreach (var file in Directory.EnumerateFiles(paths.JournalDirectory, ConvertJournal.Prefix + "*"))
{
if (ConvertJournal.JobOf(Path.GetFileName(file)) is not { } job) continue;
var state = await StateAsync(job).ConfigureAwait(false);
if (state == JobState.Done || state is null && Old(file, JournalAge)) found.Add(file);
}
}
Collect(paths.StagingDirectory, "*", StagingAge, recursive: true);
Collect(paths.MetaDirectory, ".*.tmp", TempAge, recursive: false);
foreach (var location in locations)
{
@@ -206,6 +258,7 @@ public sealed class ArchiveMaintenance
Log.Warning("archive", $"Could not remove {file}", ex);
}
}
foreach (var directory in conversions) MassConverter.DeleteStaging(directory);
}
return found.ConvertAll(paths.ToRelative);
}
+4 -3
View File
@@ -697,15 +697,16 @@ public static class ArchiveJobs
/// <summary>
/// <see cref="JobKind.Convert"/>: applies the conversion <paramref name="plan"/> (<see cref="ArchiveService.PlanConvertAsync"/>)
/// as confirmed (owner review 2, R7): the sequences it converts, in its order with their frames versions, are the job's
/// targets, so jobs that would touch them wait. A sequence that changed before it ran is left as it is and reported.
/// as confirmed (owner review 2, R7): the sequences it converts, in its order with their frames versions and the digest of
/// the photos each converts (<see cref="ConvertSequencePlan.Digest"/>), are the job's targets, so jobs that would touch
/// them wait. A sequence whose photos to convert are no longer those when the job comes to it is left as it is and reported.
/// </summary>
/// <exception cref="ArgumentException">The plan converts nothing.</exception>
public static ArchiveJobRequest Convert(Archive archive, ConvertPlan plan)
{
ArgumentNullException.ThrowIfNull(archive);
ArgumentNullException.ThrowIfNull(plan);
var sequences = plan.Converted.Select(s => new ConvertSequence(s.SequenceId, s.FramesVersion)).ToList();
var sequences = plan.Converted.Select(s => new ConvertSequence(s.SequenceId, s.FramesVersion, s.Digest())).ToList();
if (sequences.Count == 0) throw new ArgumentException("The plan converts nothing.", nameof(plan));
var label = sequences.Count == 1 ? plan.Converted.First().Title : archive.Name;
return new(JobKind.Convert, [.. sequences.Select(s => s.Id)], label,
@@ -55,14 +55,18 @@ public sealed record MoveSequence(Guid Id);
/// <summary>
/// <see cref="JobKind.Convert"/> (owner review 2, R7): targets = the sequences converted, so the jobs that would touch them
/// wait; the archive, the target format and JPEG quality, the mode chosen for this run, the sequences of the confirmed plan
/// in its order with the frames version each was planned at, and the plan's fingerprint
/// (<see cref="ConvertPlan.Fingerprint"/>). A sequence whose frames changed since is left as it is and reported.
/// in its order, each with what it converts, and the plan's fingerprint (<see cref="ConvertPlan.Fingerprint"/>). A sequence
/// whose photos to convert are no longer those confirmed is left as it is and reported.
/// </summary>
public sealed record ConvertJobParameters(Guid ArchiveId, ConvertTarget Target, int Quality, ConvertMode Mode, IReadOnlyList<ConvertSequence> Sequences,
string Fingerprint);
/// <summary>A sequence of a <see cref="ConvertJobParameters"/> and the frames version it was planned at.</summary>
public sealed record ConvertSequence(Guid Id, int FramesVersion);
/// <summary>
/// A sequence of a <see cref="ConvertJobParameters"/>: the frames version it was planned at and the digest of the photos it
/// converts, each with its content (<see cref="ConvertSequencePlan.Digest"/>), which the job checks under the sequence's
/// lease before it converts anything; null in a job an earlier build queued, which checks the frames version only.
/// </summary>
public sealed record ConvertSequence(Guid Id, int FramesVersion, string? Frames = null);
/// <summary>A job ready to enqueue.</summary>
public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets, string? Label, string? ParametersJson, JobPriority Priority);
@@ -80,6 +84,7 @@ public sealed record ArchiveJobRequest(JobKind Kind, IReadOnlyList<Guid> Targets
[JsonSerializable(typeof(ConvertJobParameters))]
[JsonSerializable(typeof(ConvertJournal))]
[JsonSerializable(typeof(StagedLine))]
[JsonSerializable(typeof(PinnedSequence))]
[JsonSerializable(typeof(CardProfile))]
internal sealed partial class ArchiveJobJson : JsonSerializerContext
{
@@ -8,13 +8,14 @@ namespace Chronos.Data.Archiving.Jobs;
/// <summary>
/// <see cref="JobKind.Convert"/>: a mass conversion (owner review 2, R7; BRIEF §12.5) of the sequences of a confirmed plan
/// (<see cref="ConvertJobParameters"/>) through <see cref="MassConverter"/>, which plans again, refuses when the archive's
/// volume lacks the space, and converts one sequence at a time, each all or nothing; its journal makes every stage
/// (<see cref="ConvertJobParameters"/>) through <see cref="MassConverter"/>, which settles what a crash left half-way, refuses
/// when the volume lacks the space (measured again before each sequence and each photo), and converts one sequence at a
/// time, each all or nothing and only while the photos it converts are those confirmed; its journal makes every stage
/// resumable. Progress counts photos; the checkpoint only marks a resume, the journal says where. Each sequence whose frames
/// were replaced is told as <c>converted</c>, each new sequence as <c>created</c> (<see cref="ArchiveServiceOptions.SequenceChanged"/>),
/// as soon as it is done; the passes they need (light analysis, a deep one when the source had it, thumbnails and
/// proxies) are queued as follow-ups. Sequences left as they were (changed after the plan, busy, a photo that failed) are
/// logged and fail the job at the end, after the others are converted; a retry tries them again.
/// and the passes it needs (light analysis, a deep one when the source had it, thumbnails and proxies) are queued as
/// follow-ups, as soon as it is done. Sequences left as they were (changed after the plan, busy, a photo that failed) are
/// logged and fail the job at the end, after the others are converted; a retry tries them again with what they staged.
/// </summary>
internal sealed class ConvertJobHandler(ChronosDatabase db, MassConverter converter, Func<Guid, string, CancellationToken, Task>? sequenceChanged) : IJobHandler
{
@@ -35,22 +36,24 @@ internal sealed class ConvertJobHandler(ChronosDatabase db, MassConverter conver
if (parameters.Fingerprint.Length == 0) throw new InvalidOperationException($"Convert job {context.Job.Id} has no confirmed plan.");
var archive = await db.Archives.GetAsync(parameters.ArchiveId, context.Cancellation).ConfigureAwait(false)
?? throw new InvalidOperationException($"Convert job {context.Job.Id} does not name a known archive.");
var by = context.Job.CreatedBy is { } user ? (await db.Users.GetAsync(user, context.Cancellation).ConfigureAwait(false))?.Username : null;
var result = await converter.RunAsync(archive, parameters, context.Job.Id, by, new ConvertCallbacks(
var name = context.Job.CreatedBy is { } user ? (await db.Users.GetAsync(user, context.Cancellation).ConfigureAwait(false))?.Username : null;
var result = await converter.RunAsync(archive, parameters, context.Job.Id, new ConvertRequester(name, context.Job.CreatedBy), new ConvertCallbacks(
(done, total) => context.ReportAsync(done, total),
(done, total) => context.CheckpointAsync(Checkpoint, done, total),
context.Log, TellAsync), context.Cancellation).ConfigureAwait(false);
await QueueAsync(context, result).ConfigureAwait(false);
context.Log, TellAsync, requests => QueueAsync(context, requests)), context.Cancellation).ConfigureAwait(false);
context.Log(Loc.L("Archive.Log.ConvertDone", result.Sequences.Count(s => s.Outcome == ConvertOutcome.Converted),
result.Sequences.Count(s => s.Outcome == ConvertOutcome.Created), result.Frames));
var kept = result.Kept.Count();
if (kept > 0) throw new InvalidOperationException(Loc.Plural("Archive.Error.ConvertKept", kept));
}
/// <summary>Queues what the converted sequences need, each kind once per sequence; a failure is logged, never passed on.</summary>
private async Task QueueAsync(JobContext context, ConvertResult result)
/// <summary>
/// Queues what a sequence converted or made needs as soon as its outcome is journaled, each kind once per sequence; a
/// failure is logged, never passed on.
/// </summary>
private async ValueTask QueueAsync(JobContext context, IReadOnlyList<ArchiveJobRequest> requests)
{
foreach (var request in result.FollowUps)
foreach (var request in requests)
{
try
{
File diff suppressed because it is too large. Load diff
+5 -3
View File
@@ -63,9 +63,11 @@ public sealed record ArchiveServiceOptions
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
/// <summary>
/// The free bytes of the volume an archive root lies on, as the host counts them (a server measures its space volume,
/// owner review 2, R2); null: the volume of the root itself. A conversion checks its estimate against it (R7). The
/// function returns null when the space cannot be measured.
/// The free bytes a write under a folder of an archive (its root, its staging folder) may count on, as the host counts
/// them: a server takes the tighter of its space volume (owner review 2, R2) and the folder's own volume, the desktop asks
/// Windows, which measures a network share too; null: the folder's drive (<see cref="DriveInfo"/>). A conversion checks its
/// estimate against it before it starts, before each sequence and before each photo (R7). The function returns null when
/// the space cannot be measured.
/// </summary>
public Func<string, long?>? FreeSpace { get; init; }
+4 -2
View File
@@ -42,8 +42,10 @@ public static class ArchiveModule
events.Publish(new SequenceChangedEvent(id, change, sequence.FramesVersion, sequence.SettingsVersion));
},
Decoder = DecoderFactory.CreateServer(),
// What the panel shows as the archive's free space (owner review 2, R2): a conversion's estimate is checked against it.
FreeSpace = volumes is null ? null : root => volumes.Report(root).Space?.FreeBytes,
// Where a conversion writes (owner review 2, R7): the tighter of what the panel shows as the archive's free space
// (R2: the space path's volume) and the volume the archive's folders are on, which takes every byte it stages
// and files (on Unraid the cache, until the mover runs).
FreeSpace = volumes is null ? null : volumes.WritableFree,
Owner = Owner,
ImagesAfterScan = true,
Parallelism = () => options.Parallelism,
+11
View File
@@ -47,6 +47,17 @@ public class VolumeSpace(ServerOptions options, ILogger<VolumeSpace> logger)
}
}
/// <summary>
/// The free bytes a write under the folder <paramref name="path"/> of the archive may count on (a conversion checks its
/// estimate against it, owner review 2, R7): the tighter of the space volume and the volume the folder is on, which on
/// Unraid is the cache a share writes to until the mover runs; null when neither can be measured.
/// </summary>
public long? WritableFree(string path)
{
var report = Report(path);
return report.Space is { } space && report.Write is { } write ? Math.Min(space.FreeBytes, write.FreeBytes) : report.Space?.FreeBytes;
}
/// <summary>
/// The storage figures of the archive at <paramref name="archiveRoot"/>: of the space path when one is set and can be
/// measured, else of the archive root (a space path that cannot be measured is logged once, until it can again).