fix: stalled jobs, editor cancellation stops and GoPro DNG decoding

Owner review 1, phase 1 (docs/requests/2026-10-15-owner-review-1.md).

Thumbnail and proxy jobs over several sequences counted sequences while
they checkpointed inside one: the rate decayed until the time left
overflowed TimeSpan, the job failed while publishing progress and again
while saving it, and stayed Running. The throughput is now seeded by the
first window with progress, the time left is bounded (JobEta), saving
progress never throws, image passes count frames, and job speeds use the
right unit (bytes for verify and import).

The debugger stops in WicDecoderProvider.cs when presets changed were
cancelled preview decodes leaving synchronous thread-pool delegates; the
editor's sources, LatestRunner and the render node's proxy task now keep
them in their own tasks, and a cancellation is never an unreadable frame.

GoPro DNGs converted by Adobe software were classified GPR and read only
through their 8-bit preview, and Windows' preview-only DNG decoder was
reported as a native decode. A DNG is GPR only when its raw image is
VC-5, WIC decodes RAW only through the Raw Image Extension and never DNG,
analyses and previews take an adequate embedded preview by choice while
renders develop natively, and frames already indexed as GPR are
reclassified by the next light analysis.

Also records the owner's request (docs/requests), the BRIEF amendments
(§8.1, §8.2, new §24), DECISIONS, CHANGELOG, STATUS and ARCHITECTURE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-16 10:20:26 +02:00
1 parent 19265b36c2
commit 34d03051f5
77 files changed
+785 -94

No files matched your search

+3 -1
View File
@@ -36,7 +36,9 @@ public sealed class LatestRunner(TimeSpan delay) : IDisposable
try
{
if (wait > TimeSpan.Zero) await Task.Delay(wait, token).ConfigureAwait(false);
await Task.Run(() => work(token), token).ConfigureAwait(false);
// An async delegate: a work item that throws on cancellation before returning its task (synchronous work) is
// caught here, in user code, instead of in the thread pool, where a debugger with Just My Code stops (R4).
await Task.Run(async () => await work(token).ConfigureAwait(false), token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
+18 -3
View File
@@ -118,20 +118,35 @@ public sealed class LocalSequenceSource : ISequenceSource
if ((uint)index >= (uint)_files.Length || _files[index] is not { } file) return null;
var companions = _companions;
var companion = (uint)index < (uint)companions.Length ? companions[index] : null;
return await Task.Run(() =>
var pixels = await Task.Run(() =>
{
try
{
// Thumbnails take an embedded preview when it is large enough (no RAW development for a filmstrip cell).
var request = new DecodeRequest(file, maxLongEdge, purpose, ForcePreview: purpose == DecodePurpose.Thumbnail, Companion: companion);
// Thumbnails take an embedded preview when it is large enough (no RAW development for a filmstrip cell); the
// preview and its corrections take an adequate embedded preview of a RAW too, developing only without one (R4).
var request = new DecodeRequest(file, maxLongEdge, purpose, ForcePreview: purpose == DecodePurpose.Thumbnail, Companion: companion,
PreferPreview: true);
return _decoder.Decode(request, cancellationToken)?.Pixels;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
// Superseded by a newer edit: end here, so the cancellation never crosses into the thread pool (a debugger
// with Just My Code stops there, R4); it is reported below.
return null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("editor", $"Frame {file} could not be read", ex);
return null;
}
}, cancellationToken);
// A cancelled decode is a cancellation for the caller, never an unreadable frame.
if (cancellationToken.IsCancellationRequested)
{
pixels?.Dispose();
cancellationToken.ThrowIfCancellationRequested();
}
return pixels;
}
public Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
@@ -140,7 +140,8 @@ public sealed class RemoteSequenceSource : ISequenceSource
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
if ((uint)index >= (uint)_remote.Frames.Count) return null;
return await Task.Run(() => _pixels.LoadAsync(index, maxLongEdge, cancellationToken).AsTask(), cancellationToken);
// The loader decodes synchronously: an async delegate keeps a superseded decode's cancellation in user code (R4).
return await Task.Run(async () => await _pixels.LoadAsync(index, maxLongEdge, cancellationToken).ConfigureAwait(false), cancellationToken);
}
public async Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
@@ -283,7 +284,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
ProgressDone = progress.Done,
ProgressTotal = progress.Total,
ItemsPerSecond = progress.ItemsPerSecond,
Eta = progress.EtaSeconds is { } eta ? TimeSpan.FromSeconds(eta) : null,
Eta = JobEta.FromSeconds(progress.EtaSeconds),
});
break;
case JobStateEvent state when !_foreign.ContainsKey(state.JobId):
+11 -6
View File
@@ -12,13 +12,18 @@ public static class JobText
/// <summary>True for jobs whose items are frames, so their speed reads in fps.</summary>
public static bool CountsFrames(JobKind kind) =>
kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Verify;
kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.DeepAnalyse;
/// <summary>"11.3 fps" for frame jobs, "41/s" otherwise; empty when unknown.</summary>
public static string Speed(JobKind kind, double? perSecond) =>
perSecond is > 0 and var rate
? Loc.L(CountsFrames(kind) ? "Jobs.Speed.Fps" : "Jobs.Speed.PerSecond", Formatting.Rate(rate))
: string.Empty;
/// <summary>True for jobs whose progress counts bytes (hash verification, card import).</summary>
public static bool CountsBytes(JobKind kind) => kind is JobKind.Verify or JobKind.Import;
/// <summary>"11.3 fps" for frame jobs, "57 MB/s" for byte jobs, "41/s" otherwise; empty when unknown.</summary>
public static string Speed(JobKind kind, double? perSecond) => perSecond switch
{
> 0 and var rate when CountsBytes(kind) => Loc.L("Jobs.Speed.Bytes", Formatting.Bytes((long)rate)),
> 0 and var rate => Loc.L(CountsFrames(kind) ? "Jobs.Speed.Fps" : "Jobs.Speed.PerSecond", Formatting.Rate(rate)),
_ => string.Empty,
};
/// <summary>"1,240 / 3,600"; empty while the total is unknown.</summary>
public static string Counter(long done, long total) =>
@@ -18,6 +18,13 @@ namespace Titano.Core.Windows.Wic;
/// Sources whose native format is floating or fixed point (scRGB: JPEG XR, HDR) are requested as 128bppRGBAFloat
/// and copied unchanged, keeping highlights above 1. Alpha is discarded. The Exif orientation is applied while
/// de-interleaving (<see cref="OrientationMap"/>).
/// <para>
/// WIC picks the decoder itself, and for a camera RAW only the Raw Image Extension develops the sensor data: Windows'
/// in-box DNG decoder reads only the embedded JPEG preview, and the TIFF decoder would read a TIFF-based RAW's thumbnail.
/// So a RAW decodes here only when the decoder WIC chose is the Raw Image Extension (checked per file by CLSID), DNG never
/// (the managed decoder develops it at 16 bits, the Raw Image Extension at 8), and a request that prefers the embedded
/// preview is left to the managed decoder, which reads it without developing anything (R4, owner review 1).
/// </para>
/// </remarks>
public sealed class WicDecoderProvider : IImageDecoderProvider
{
@@ -44,7 +51,7 @@ public sealed class WicDecoderProvider : IImageDecoderProvider
/// <summary>Detects the codecs again (after a Store extension was installed); decodes that start afterwards use them.</summary>
public CodecInventory Refresh() => _inventory = CodecInventory.Detect(refresh: true);
public DecodeTier? TierFor(ImageFileFormat format) => Inventory.IsNative(format) ? DecodeTier.Native : null;
public DecodeTier? TierFor(ImageFileFormat format) => format != ImageFileFormat.Dng && Inventory.IsNative(format) ? DecodeTier.Native : null;
/// <summary>
/// Decodes the first frame. Returns null when WIC cannot natively decode this format here, when the request
@@ -54,7 +61,8 @@ public sealed class WicDecoderProvider : IImageDecoderProvider
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(request);
if (request.ForcePreview || TierFor(ImageFormatInfo.FromPath(request.Path).Format) is null) return null;
var format = ImageFormatInfo.FromPath(request.Path);
if (request.ForcePreview || (request.PreferPreview && format.IsRaw) || TierFor(format.Format) is null) return null;
cancellationToken.ThrowIfCancellationRequested();
Win32Com.EnsureInitialized();
@@ -69,6 +77,7 @@ public sealed class WicDecoderProvider : IImageDecoderProvider
var hr = factory.CreateDecoderFromStream(stream, 0, WicDecodeOptions.MetadataCacheOnDemand, out decoder);
if (hr == WINCODEC_ERR_COMPONENTNOTFOUND) return null;
Marshal.ThrowExceptionForHR(hr);
if (format.IsRaw && DecoderClsid(decoder!) != WicGuids.RawDecoder) return null;
frame = decoder!.GetFrame(0);
frame.GetSize(out var width, out var height);
var orientation = request.ApplyOrientation ? ReadOrientation(frame) : 1;
@@ -103,6 +112,23 @@ public sealed class WicDecoderProvider : IImageDecoderProvider
}
}
/// <summary>CLSID of the decoder WIC chose for the stream, or <see cref="Guid.Empty"/> when it does not say.</summary>
private static Guid DecoderClsid(IWICBitmapDecoder decoder)
{
if (decoder.GetDecoderInfo(out var pointer) < 0 || pointer == 0) return Guid.Empty;
object? info = null;
try
{
info = Marshal.GetObjectForIUnknown(pointer);
return info is IWICBitmapDecoderInfo decoderInfo ? decoderInfo.GetCLSID() : Guid.Empty;
}
finally
{
Marshal.Release(pointer);
Win32Com.Release(info);
}
}
/// <summary>Size after fitting the long edge into <paramref name="maxLongEdge"/> (never upscales; 0 = native).</summary>
internal static (uint Width, uint Height) TargetSize(uint width, uint height, int maxLongEdge)
{
@@ -59,8 +59,11 @@ public static class SequenceFrames
/// tier is kept and <see cref="FrameFlags.Undecodable"/> is left as it was.</param>
/// <param name="proxied">Whether the host takes the frame's pixels from its proxy (an original it cannot decode, whose
/// proxy is there): see <see cref="WithProxy"/>.</param>
/// <remarks>A probe reads the file's signature again: the format it found replaces a stored one that is out of date
/// (GoPro DNGs converted by Adobe software were stored as GPR before owner review 1).</remarks>
public static SidecarFrame WithTier(SidecarFrame frame, FileTier tier, bool damaged = true, bool proxied = false)
{
if (tier.Format != ImageFileFormat.Unknown && tier.Format != frame.Format) frame = frame with { Format = tier.Format };
var flags = frame.Flags & ~(FrameFlags.PreviewOnly | FrameFlags.Undecodable);
if (tier.Tier == DecodeTier.EmbeddedPreview) flags |= proxied ? FrameFlags.None : FrameFlags.PreviewOnly;
else if (tier.Tier == DecodeTier.Unavailable) flags |= damaged ? FrameFlags.Undecodable : frame.Flags & FrameFlags.Undecodable;
+13
View File
@@ -97,6 +97,19 @@ internal static class DngReader
if (total * 8 < samples) throw new InvalidDataException("DNG: image data too short for the raster");
}
/// <summary>
/// True when the full-resolution raw image of the DNG <paramref name="r"/> reads is VC-5 compressed (Compression 9,
/// GoPro's GPR), which no managed decoder handles; false for every other DNG, a GoPro one converted by Adobe software
/// (lossless JPEG or lossy LinearRaw) included, and when no raw image is found.
/// </summary>
internal static bool IsVc5(TiffReader r)
{
var chain = r.ReadChain();
return chain.Count > 0 && FindRawIfd(r, chain) is { } raw && r.GetUInt(raw, TiffTags.Compression) == Vc5Compression;
}
private const uint Vc5Compression = 9;
/// <summary>First IFD with NewSubfileType 0 and a CFA/LinearRaw photometric: IFD0, its SubIFDs (two levels), the chain.</summary>
private static Ifd? FindRawIfd(TiffReader r, IReadOnlyList<Ifd> chain)
{
@@ -166,6 +166,9 @@ public sealed class ManagedDecoderProvider : IImageDecoderProvider
private static DecodedImage? Raw(Stream stream, ImageFileFormat format, DecodeRequest request, CancellationToken cancellationToken)
{
if (request.PreferPreview && !request.ForcePreview && request.MaxLongEdge > 0 && RawDecoder.Formats.Contains(format)
&& Preview(stream, request, adequateOnly: true, cancellationToken) is { } quick)
return quick.AsChoice();
if (!request.ForcePreview && RawDecoder.Formats.Contains(format))
{
try
+17 -2
View File
@@ -32,6 +32,10 @@ public enum DecodePurpose
/// <param name="ForcePreview">Use the embedded preview even when native decode is possible (fast paths).</param>
/// <param name="Companion">The JPEG a GoPro wrote with this GPR when it is kept elsewhere than beside it (an import puts
/// it in a sequence of its own); null looks beside the file. Other formats ignore it.</param>
/// <param name="PreferPreview">For a RAW file: use an embedded preview whose long edge reaches <paramref name="MaxLongEdge"/>
/// when there is one, and decode natively otherwise. Analyses, thumbnails, proxies and the editor's preview ask for it
/// (fast); renders never do. The result is marked <see cref="DecodedImage.ByChoice"/>, so it never makes the frame
/// preview-only (R4, owner review 1).</param>
public sealed record DecodeRequest(
string Path,
int MaxLongEdge = 0,
@@ -39,14 +43,22 @@ public sealed record DecodeRequest(
bool ApplyOrientation = true,
bool AllowPreview = true,
bool ForcePreview = false,
string? Companion = null);
string? Companion = null,
bool PreferPreview = false);
/// <summary>Decoded pixels plus how they were produced. Dispose to return the buffer to the pool.</summary>
public sealed class DecodedImage(ImageBuffer pixels, DecodeTier tier, string decoder, int sourceWidth, int sourceHeight) : IDisposable
public sealed class DecodedImage(ImageBuffer pixels, DecodeTier tier, string decoder, int sourceWidth, int sourceHeight, bool byChoice = false) : IDisposable
{
public ImageBuffer Pixels { get; } = pixels;
public DecodeTier Tier { get; } = tier;
/// <summary>
/// The pixels come from an embedded preview the request preferred (<see cref="DecodeRequest.PreferPreview"/>) although
/// the file may decode natively: <see cref="Tier"/> says how these pixels were made, not what the frame can give, so it
/// is not recorded as the frame's tier.
/// </summary>
public bool ByChoice { get; } = byChoice;
/// <summary>Short provider/decoder name for logs ("wic", "managed-jpeg", "managed-dng").</summary>
public string Decoder { get; } = decoder;
@@ -56,6 +68,9 @@ public sealed class DecodedImage(ImageBuffer pixels, DecodeTier tier, string dec
public int SourceHeight { get; } = sourceHeight;
public void Dispose() => Pixels.Dispose();
/// <summary>The same pixels marked <see cref="ByChoice"/> (the returned image owns them; do not dispose this one).</summary>
internal DecodedImage AsChoice() => new(Pixels, Tier, Decoder, SourceWidth, SourceHeight, byChoice: true);
}
/// <summary>Tier a provider would use for one specific file, with the reason when it is not native.</summary>
+3 -1
View File
@@ -119,8 +119,10 @@ public static class ImageSignature
var reader = TiffReader.Open(stream);
var ifd0 = reader?.ReadIfd(reader.FirstIfdOffset);
var make = reader is not null && ifd0 is not null ? IfdValue.String(reader, ifd0, TiffTags.Make) : null;
// A GoPro DNG is GPR only when its raw image is VC-5: one converted by Adobe software (Lightroom, DNG Converter) is
// an ordinary DNG the managed DNG decoder develops (R4, owner review 1).
if (ifd0?.Has(TiffTags.DngVersion) == true)
return extension == ImageFileFormat.Gpr || make?.StartsWith("GoPro", StringComparison.OrdinalIgnoreCase) == true ? ImageFileFormat.Gpr : ImageFileFormat.Dng;
return extension == ImageFileFormat.Gpr || Codecs.Dng.DngReader.IsVc5(reader!) ? ImageFileFormat.Gpr : ImageFileFormat.Dng;
if (extension == ImageFileFormat.Tiff) return ImageFileFormat.Tiff;
var byMake = ByMake(make, extension);
if (byMake != ImageFileFormat.Unknown) return byMake;
+15 -4
View File
@@ -22,7 +22,9 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
/// The tier of every frame of <paramref name="manifest"/> whose tier is not known yet, that decodes only through a
/// preview whose size is not known (the output cap needs it), or that is a GPR whose JPEG in another sequence
/// (<see cref="GprCompanions"/>; an upload may index it after the GPR was probed) is larger than its stored preview,
/// probed with the host's decoders without decoding pixels; missing and unreadable files are left for later.
/// or that is stored as GPR without the .gpr extension (indexed before GoPro DNGs converted by Adobe software counted as
/// DNG; R4, owner review 1), probed with the host's decoders without decoding pixels; missing and unreadable files are
/// left for later.
/// </summary>
public async Task<Dictionary<Guid, FileTier>> ProbeUnknownAsync(Archive archive, SequencePaths folder, SequenceManifest manifest,
CancellationToken cancellationToken)
@@ -30,7 +32,7 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
var tiers = new Dictionary<Guid, FileTier>();
var present = manifest.Frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
var companions = await GprCompanions.FindWithSizesAsync(db, archive, present, cancellationToken).ConfigureAwait(false);
var unknown = present.Where(f => f.Tier == 0 || (f.Tier == DecodeTier.EmbeddedPreview && f.PreviewW is null)
var unknown = present.Where(f => f.Tier == 0 || (f.Tier == DecodeTier.EmbeddedPreview && f.PreviewW is null) || IsStaleGpr(f)
|| (companions.TryGetValue(f.Id, out var jpeg)
&& int.Max(f.PreviewW ?? 0, f.PreviewH ?? 0) < int.Max(jpeg.Width, jpeg.Height)));
foreach (var frame in unknown)
@@ -97,7 +99,8 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
if (tier is not null) updated = SequenceFrames.WithTier(frame, tier, DecodesNatively(frame.Format), proxied == true);
else if (proxied is { } own) updated = SequenceFrames.WithProxy(frame, own);
else continue;
if (updated.Tier == frame.Tier && updated.Flags == frame.Flags && updated.PreviewW == frame.PreviewW && updated.PreviewH == frame.PreviewH)
if (updated.Tier == frame.Tier && updated.Flags == frame.Flags && updated.PreviewW == frame.PreviewW && updated.PreviewH == frame.PreviewH
&& updated.Format == frame.Format)
continue;
gained |= (updated.Flags & ~frame.Flags & FrameFlags.Undecodable) != 0;
frames[i] = updated;
@@ -118,7 +121,7 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
// for these frames while this waits for the row, and PostgreSQL would abort one of them.
await tx.Sequences.RecordTiersAsync(sequence.Id, gained ? SequenceStatus.HasWarnings : SequenceStatus.None,
frames.Count(f => (f.Flags & FrameFlags.PreviewOnly) != 0), cancellationToken).ConfigureAwait(false);
await tx.Frames.UpdateTiersAsync(changed.ConvertAll(f => new FrameTierFields(f.Id, f.Flags, f.PreviewW ?? 0, f.PreviewH ?? 0)), cancellationToken)
await tx.Frames.UpdateTiersAsync(changed.ConvertAll(f => new FrameTierFields(f.Id, f.Flags, f.PreviewW ?? 0, f.PreviewH ?? 0, f.Format)), cancellationToken)
.ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
@@ -127,6 +130,14 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
}
}
/// <summary>
/// A frame stored as GPR whose file is not a .gpr: before owner review 1 every DNG with Make=GoPro counted as GPR, so
/// Adobe-converted GoPro DNGs were recorded preview-only; probing reads its signature again (<see cref="SequenceFrames.WithTier"/>
/// then stores the format found).
/// </summary>
internal static bool IsStaleGpr(SidecarFrame frame) =>
frame.Format == ImageFileFormat.Gpr && !frame.File.EndsWith(".gpr", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Whether this host decodes <paramref name="format"/> natively, so a file of it that yields no pixels is damaged
/// rather than beyond this host (JPEG always: the managed JPEG decoder is part of every host).
@@ -6,8 +6,9 @@ using Titano.Data.Jobs;
namespace Titano.Data.Archiving.Jobs;
/// <summary>
/// <see cref="JobKind.Thumbs"/> and <see cref="JobKind.Proxies"/> over the target sequences. Progress counts
/// sequences; checkpoint: <c>sequence:frame</c>.
/// <see cref="JobKind.Thumbs"/> and <see cref="JobKind.Proxies"/> over the target sequences. Progress counts frames
/// across all targets, so the speed and time left follow the photos even inside a long sequence; checkpoint:
/// <c>sequence:frame</c>.
/// </summary>
internal sealed class ImageJobHandler(TitanoDatabase db, ArchiveImages images, JobKind kind) : IJobHandler
{
@@ -18,18 +19,29 @@ internal sealed class ImageJobHandler(TitanoDatabase db, ArchiveImages images, J
var force = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.ImageJobParameters, new ImageJobParameters(false)).Force;
var (first, firstFrame) = Parse(context.Checkpoint);
var targets = context.Job.TargetIds;
var sequences = new Sequence?[targets.Count];
long total = 0;
for (var s = 0; s < targets.Count; s++)
{
sequences[s] = await db.Sequences.GetAsync(targets[s], context.Cancellation).ConfigureAwait(false);
total += sequences[s]?.FrameCount ?? 0;
}
long before = 0;
for (var s = 0; s < Math.Min(first, targets.Count); s++) before += sequences[s]?.FrameCount ?? 0;
for (var s = first; s < targets.Count; s++)
{
context.Cancellation.ThrowIfCancellationRequested();
if (await db.Sequences.GetAsync(targets[s], context.Cancellation).ConfigureAwait(false) is not { } sequence
if (sequences[s] is not { } sequence
|| await db.Archives.GetAsync(sequence.ArchiveId, context.Cancellation).ConfigureAwait(false) is not { } archive)
{
context.Log(Loc.L("Archive.Log.SequenceMissing", targets[s]));
before += sequences[s]?.FrameCount ?? 0;
continue;
}
var index = s;
var offset = before;
ValueTask Checkpoint(int nextFrame, int frames) =>
context.CheckpointAsync(string.Create(CultureInfo.InvariantCulture, $"{index}:{nextFrame}"), index, targets.Count);
context.CheckpointAsync(string.Create(CultureInfo.InvariantCulture, $"{index}:{nextFrame}"), Math.Min(total, offset + nextFrame), total);
var start = s == first ? firstFrame : 0;
var result = kind == JobKind.Thumbs
? await images.BuildThumbnailsAsync(archive, sequence, force, start, Checkpoint, context.Cancellation).ConfigureAwait(false)
@@ -37,7 +49,8 @@ internal sealed class ImageJobHandler(TitanoDatabase db, ArchiveImages images, J
context.Log(kind == JobKind.Thumbs
? Loc.L("Archive.Log.ImagesDone", sequence.DisplayTitle, result.Built, result.Reused, result.Undecodable)
: Loc.L("Archive.Log.ProxiesDone", sequence.DisplayTitle, result.Built, result.Reused, result.Undecodable, result.Waiting));
await context.CheckpointAsync(string.Create(CultureInfo.InvariantCulture, $"{s + 1}:0"), s + 1, targets.Count).ConfigureAwait(false);
before += sequence.FrameCount;
await context.CheckpointAsync(string.Create(CultureInfo.InvariantCulture, $"{s + 1}:0"), Math.Min(total, before), total).ConfigureAwait(false);
}
}
+27 -7
View File
@@ -23,6 +23,9 @@ public sealed record JobEngineOptions
/// <summary>Finished jobs older than this are purged (BRIEF §14.6: 90 days).</summary>
public TimeSpan HistoryRetention { get; init; } = TimeSpan.FromDays(90);
/// <summary>Clock of the throughput windows and the checkpoint interval (tests pass their own).</summary>
public TimeProvider Time { get; init; } = TimeProvider.System;
}
/// <summary>
@@ -182,17 +185,29 @@ public sealed class JobEngine : IAsyncDisposable
_shutdown.Dispose();
}
/// <summary>Broadcasts live progress. A subscriber that throws never fails the job it watches (logged once per job).</summary>
internal void PublishProgress(JobContext context)
{
var (rate, eta) = context.Rate();
Progress?.Invoke(new JobProgressInfo(context.Job.Id, context.Job.Kind, context.Job.TargetLabel, context.Done, context.Total, rate, eta, context.Message));
}
internal async Task<bool> PersistAsync(JobContext context)
{
var (rate, eta) = context.Rate();
try
{
var (rate, eta) = context.Rate();
Progress?.Invoke(new JobProgressInfo(context.Job.Id, context.Job.Kind, context.Job.TargetLabel, context.Done, context.Total, rate, eta, context.Message));
}
catch (Exception ex)
{
if (context.FirstProgressFailure()) Log.Warning("jobs", $"Progress of {context.Job.Kind} job {context.Job.Id} not published", ex);
}
}
/// <summary>
/// Saves progress, checkpoint and log tail; false when the job no longer runs here (cancelled or paused elsewhere).
/// Saving is best effort and never throws: a failure is logged and the job goes on, so its final state is always written.
/// </summary>
internal async Task<bool> PersistAsync(JobContext context)
{
try
{
var (rate, eta) = context.Rate();
return await _db.Jobs.UpdateProgressAsync(context.Job.Id, context.Done, context.Total, rate, eta, context.Checkpoint, context.LogTail, CancellationToken.None)
.ConfigureAwait(false);
}
@@ -201,6 +216,11 @@ public sealed class JobEngine : IAsyncDisposable
Log.Warning("jobs", "Progress not saved (transient database error)", ex);
return true;
}
catch (Exception ex)
{
Log.Warning("jobs", $"Progress of {context.Job.Kind} job {context.Job.Id} not saved", ex);
return true;
}
}
/// <summary>True when this engine claims jobs of <paramref name="kind"/> (it has a handler and the kind is not filtered out).</summary>
+17 -25
View File
@@ -1,4 +1,3 @@
using System.Diagnostics;
using System.Text;
using Titano.Core.Model;
@@ -39,23 +38,26 @@ public sealed class JobContext
{
private const int LogTailLines = 40;
private readonly JobEngine _engine;
private readonly Stopwatch _clock = Stopwatch.StartNew();
private readonly TimeProvider _time;
private readonly long _started;
private readonly Queue<string> _log = new();
private readonly Lock _gate = new();
private long _lastPersistTicks;
private long _rateDone;
private double _rateSeconds;
private double? _rate;
private readonly JobThroughput _throughput;
private long _lastPersist;
private int _progressFailures;
internal JobContext(JobEngine engine, Job job, CancellationToken cancellation)
{
_engine = engine;
_time = engine.Options.Time;
_started = _time.GetTimestamp();
_lastPersist = _started;
Job = job;
Cancellation = cancellation;
Checkpoint = job.Checkpoint;
Done = job.ProgressDone;
Total = job.ProgressTotal;
_rateDone = Done;
_throughput = new JobThroughput(Done);
if (job.LogTail is { Length: > 0 } tail)
{
foreach (var line in tail.Split('\n')) _log.Enqueue(line);
@@ -122,35 +124,25 @@ public sealed class JobContext
}
}
/// <summary>Throughput as a moving average over windows of at least two seconds, and the time left at that rate.</summary>
/// <summary>Throughput and time left (<see cref="JobThroughput"/>); never throws, whatever the progress reported.</summary>
internal (double? Rate, TimeSpan? Eta) Rate()
{
lock (_gate)
{
var seconds = _clock.Elapsed.TotalSeconds;
var span = seconds - _rateSeconds;
if (span >= 2 && Done >= _rateDone)
{
var sample = (Done - _rateDone) / span;
_rate = _rate is { } previous ? previous * 0.7 + sample * 0.3 : sample;
_rateDone = Done;
_rateSeconds = seconds;
}
TimeSpan? eta = _rate is > 0 && Total > Done ? TimeSpan.FromSeconds((Total - Done) / _rate.Value) : null;
return (_rate, eta);
}
lock (_gate) return _throughput.Sample(_time.GetElapsedTime(_started).TotalSeconds, Done, Total);
}
/// <summary>True the first time publishing this job's progress failed, so the failure is logged once.</summary>
internal bool FirstProgressFailure() => Interlocked.Increment(ref _progressFailures) == 1;
private async ValueTask ReportCoreAsync(long done, long total, string? message, bool force)
{
Done = done;
Total = total;
Message = message;
var now = _clock.ElapsedTicks;
var due = now - Interlocked.Read(ref _lastPersistTicks) >= _engine.Options.CheckpointInterval.TotalSeconds * Stopwatch.Frequency;
var now = _time.GetTimestamp();
var due = _time.GetElapsedTime(Interlocked.Read(ref _lastPersist), now) >= _engine.Options.CheckpointInterval;
_engine.PublishProgress(this);
if (!force && !due) return;
Interlocked.Exchange(ref _lastPersistTicks, now);
Interlocked.Exchange(ref _lastPersist, now);
if (!await _engine.PersistAsync(this).ConfigureAwait(false))
_engine.StopJob(Job.Id); // cancelled or paused by someone else
}
+58
View File
@@ -0,0 +1,58 @@
namespace Titano.Data.Jobs;
/// <summary>
/// Time left of a job: unknown (null) when nothing remains, the rate is unknown, or the result is not a finite duration
/// of at most <see cref="Max"/>. Every conversion of a stored or reported time left goes through here, so a stalled job
/// shows no time left instead of overflowing <see cref="TimeSpan"/>.
/// </summary>
public static class JobEta
{
/// <summary>Longest time left worth showing; beyond it the job reads as stalled.</summary>
public static readonly TimeSpan Max = TimeSpan.FromDays(365);
/// <summary>The time <paramref name="remaining"/> items take at <paramref name="perSecond"/>.</summary>
public static TimeSpan? Of(long remaining, double? perSecond) =>
remaining > 0 && perSecond is > 0 and var rate ? FromSeconds(remaining / rate) : null;
/// <summary>A stored or reported number of seconds as a time left, or null when it is not a usable one.</summary>
public static TimeSpan? FromSeconds(double? seconds) =>
seconds is { } s && double.IsFinite(s) && s >= 0 && s <= Max.TotalSeconds ? TimeSpan.FromSeconds(s) : null;
}
/// <summary>
/// Throughput of a running job as a moving average over windows of at least two seconds. The first window that saw
/// progress seeds the average; each later window weighs 30 %. A window without progress lowers the rate, which tends to
/// zero without reaching it: below <see cref="MinRate"/> it reads as unknown, and the time left with it.
/// </summary>
internal sealed class JobThroughput(long done)
{
private const double WindowSeconds = 2;
/// <summary>Items per second below which a job counts as stalled.</summary>
internal const double MinRate = 1e-6;
private long _done = done;
private double _seconds;
private double? _rate;
/// <summary>Takes a sample at <paramref name="seconds"/> since the job started and returns the rate and time left.</summary>
public (double? Rate, TimeSpan? Eta) Sample(double seconds, long done, long total)
{
if (done < _done)
{
// Progress went back (a handler restarted its count): start a new window there.
_done = done;
_seconds = seconds;
}
else if (seconds - _seconds >= WindowSeconds)
{
var sample = (done - _done) / (seconds - _seconds);
if (_rate is { } previous) _rate = previous * 0.7 + sample * 0.3;
else if (sample > 0) _rate = sample;
_done = done;
_seconds = seconds;
}
var rate = _rate is >= MinRate ? _rate : null;
return (rate, JobEta.Of(total - done, rate));
}
}
+1 -1
View File
@@ -48,7 +48,7 @@ public static class JobWire
ProgressDone = dto.ProgressDone,
ProgressTotal = dto.ProgressTotal,
ItemsPerSecond = dto.ItemsPerSecond,
Eta = dto.EtaSeconds is { } eta ? TimeSpan.FromSeconds(eta) : null,
Eta = JobEta.FromSeconds(dto.EtaSeconds),
LogTail = dto.LogTail,
NodeId = dto.NodeId,
Attempts = dto.Attempts,
@@ -40,10 +40,14 @@ internal static class AnalysisFollowUp
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
}
/// <summary>Sequences of <paramref name="archiveId"/> without a current light analysis (new, adopted, or with frames a scan added).</summary>
/// <summary>
/// Sequences of <paramref name="archiveId"/> without a current light analysis (new, adopted, or with frames a scan added),
/// and those with frames stored as GPR that are DNGs: the light analysis probes them again and records the DNG format
/// and its native tier (R4, owner review 1).
/// </summary>
public static async Task<List<Guid>> UnanalysedAsync(TitanoDatabase db, Guid archiveId, CancellationToken cancellationToken)
{
var ids = new List<Guid>();
var ids = new List<Guid>(await db.Frames.ListSequencesWithStaleGprAsync(archiveId, cancellationToken).ConfigureAwait(false));
var query = new SequenceQuery { ArchiveId = archiveId, WithoutStatus = SequenceStatus.AnalyzedLight, Sort = SequenceSort.Oldest, Limit = 1000 };
do
{
@@ -52,6 +56,6 @@ internal static class AnalysisFollowUp
query = query with { Cursor = page.NextCursor };
}
while (query.Cursor is not null);
return ids;
return [.. ids.Distinct()];
}
}
@@ -300,8 +300,11 @@ public sealed class RenderNodeClient : IAsyncDisposable
}
try
{
var jpeg = await Task.Run(() => ArchiveImages.MakeProxy(_processing.Archive.Decoder, original, frame, camera, spec.LongEdge, spec.Quality,
cancellationToken), cancellationToken).ConfigureAwait(false);
var jpeg = await Task.Run(async () =>
{
await Task.Yield();
return ArchiveImages.MakeProxy(_processing.Archive.Decoder, original, frame, camera, spec.LongEdge, spec.Quality, cancellationToken);
}, cancellationToken).ConfigureAwait(false);
if (jpeg is null)
{
unsent++;
@@ -191,7 +191,9 @@ internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IA
try
{
var companion = proxied ? null : Companions?.GetValueOrDefault(frame.Id);
decoded = _decoder.Decode(new DecodeRequest(file, maxLongEdge, purpose, Companion: companion), cancellationToken);
// Analyses and previews take an adequate embedded preview of a RAW (fast); renders develop it (R4, owner review 1).
decoded = _decoder.Decode(new DecodeRequest(file, maxLongEdge, purpose, Companion: companion, PreferPreview: purpose != DecodePurpose.Render),
cancellationToken);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
@@ -200,7 +202,8 @@ internal sealed class SequenceFrameSource : IFrameSource, IRenderFrameSource, IA
return null;
}
// A file that vanished is missing, not undecodable (a verify flags it); only what decoding found is recorded.
if (Originals && !proxied && (decoded is not null || File.Exists(file)))
// A preview taken by choice says how these pixels were made, not what the file can give.
if (Originals && !proxied && decoded is not { ByChoice: true } && (decoded is not null || File.Exists(file)))
{
_observed[index] = decoded switch
{
+23 -12
View File
@@ -23,7 +23,7 @@ public sealed record DuplicateFrame(string Sha256, Guid FrameId, Guid SequenceId
public readonly record struct FrameLightStats(Guid FrameId, double? MeanLogLuminance, double? ClipLow, double? ClipHigh);
/// <summary>Decode-tier fields of one frame (BRIEF §8.2): its flags and the stored size of its largest embedded preview.</summary>
public readonly record struct FrameTierFields(Guid FrameId, FrameFlags Flags, int PreviewWidth, int PreviewHeight);
public readonly record struct FrameTierFields(Guid FrameId, FrameFlags Flags, int PreviewWidth, int PreviewHeight, ImageFileFormat Format);
/// <summary>Per-format totals and flagged-frame counts of one sequence.</summary>
public sealed record SequenceFrameStats(IReadOnlyList<FormatBucket> ByFormat, long Missing, long Corrupt, long Duplicate, long Excluded);
@@ -175,19 +175,20 @@ public sealed class FrameRepository
for (var start = 0; start < frames.Count; start += Batch)
{
var count = Math.Min(Batch, frames.Count - start);
var sql = new StringBuilder("UPDATE frames AS f SET flags = v.fl, preview_width = v.w, preview_height = v.h FROM (VALUES ");
var args = new DbParam[count * 4];
var sql = new StringBuilder("UPDATE frames AS f SET flags = v.fl, preview_width = v.w, preview_height = v.h, format = v.fmt FROM (VALUES ");
var args = new DbParam[count * 5];
for (var i = 0; i < count; i++)
{
var f = frames[start + i];
sql.Append(i > 0 ? ", (" : "(").Append('$').Append(4 * i + 1).Append(", $").Append(4 * i + 2)
.Append(", $").Append(4 * i + 3).Append(", $").Append(4 * i + 4).Append(')');
args[4 * i] = f.FrameId;
args[4 * i + 1] = (int)f.Flags;
args[4 * i + 2] = f.PreviewWidth;
args[4 * i + 3] = f.PreviewHeight;
sql.Append(i > 0 ? ", (" : "(").Append('$').Append(5 * i + 1).Append(", $").Append(5 * i + 2)
.Append(", $").Append(5 * i + 3).Append(", $").Append(5 * i + 4).Append(", $").Append(5 * i + 5).Append(')');
args[5 * i] = f.FrameId;
args[5 * i + 1] = (int)f.Flags;
args[5 * i + 2] = f.PreviewWidth;
args[5 * i + 3] = f.PreviewHeight;
args[5 * i + 4] = (int)f.Format;
}
sql.Append(") AS v(id, fl, w, h) WHERE f.id = v.id");
sql.Append(") AS v(id, fl, w, h, fmt) WHERE f.id = v.id");
updated += await session.ExecuteAsync(sql.ToString(), args, cancellationToken).ConfigureAwait(false);
}
}
@@ -195,8 +196,8 @@ public sealed class FrameRepository
{
foreach (var f in frames)
{
updated += await session.ExecuteAsync("UPDATE frames SET flags = $2, preview_width = $3, preview_height = $4 WHERE id = $1",
[f.FrameId, (int)f.Flags, f.PreviewWidth, f.PreviewHeight], cancellationToken).ConfigureAwait(false);
updated += await session.ExecuteAsync("UPDATE frames SET flags = $2, preview_width = $3, preview_height = $4, format = $5 WHERE id = $1",
[f.FrameId, (int)f.Flags, f.PreviewWidth, f.PreviewHeight, (int)f.Format], cancellationToken).ConfigureAwait(false);
}
}
return updated;
@@ -263,6 +264,16 @@ public sealed class FrameRepository
"ORDER BY f.sha256, s.first_capture, f.sequence_id, f.idx",
[archiveId], r => new DuplicateFrame(r.GetString(0), r.GetGuid(1), r.GetGuid(2), r.GetInt32(3), r.GetString(4)), cancellationToken);
/// <summary>
/// Sequences of an archive with frames stored as GPR whose file is not a .gpr: indexed before GoPro DNGs converted by
/// Adobe software counted as DNG (R4, owner review 1); their next light analysis probes them again.
/// </summary>
public Task<IReadOnlyList<Guid>> ListSequencesWithStaleGprAsync(Guid archiveId, CancellationToken cancellationToken = default) =>
_db.ListAsync(
"SELECT DISTINCT f.sequence_id FROM frames f JOIN sequences s ON s.id = f.sequence_id " +
"WHERE s.archive_id = $1 AND f.format = $2 AND lower(f.file_name) NOT LIKE '%.gpr'",
[archiveId, (int)ImageFileFormat.Gpr], r => r.GetGuid(0), cancellationToken);
/// <summary>Frames of an archive that carry every bit of <paramref name="flags"/>.</summary>
public Task<IReadOnlyList<FrameRef>> ListFlaggedAsync(Guid archiveId, FrameFlags flags, CancellationToken cancellationToken = default) =>
_db.ListAsync(
@@ -1,5 +1,6 @@
using System.Globalization;
using Titano.Core.Model;
using Titano.Data.Jobs;
namespace Titano.Data.Repositories;
@@ -209,7 +210,7 @@ public sealed class JobRepository
ProgressDone = r.GetInt64(7),
ProgressTotal = r.GetInt64(8),
ItemsPerSecond = r.GetDoubleOrNull(9),
Eta = r.GetDoubleOrNull(10) is { } seconds ? TimeSpan.FromSeconds(seconds) : null,
Eta = JobEta.FromSeconds(r.GetDoubleOrNull(10)),
Checkpoint = r.GetStringOrNull(11),
LogTail = r.GetStringOrNull(12),
CreatedBy = r.GetGuidOrNull(13),
+6 -4
View File
@@ -2,6 +2,7 @@ using System.Globalization;
using System.Text.Json;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Jobs;
using Titano.Data.Repositories;
using Titano.Protocol;
using Titano.Server.Api;
@@ -99,13 +100,14 @@ public sealed class RenderNodeService(
{
if (await OwnedNodeAsync(caller, nodeId, cancellationToken) is not { } node) return Outcome<bool>.Fail(404, "not_found", "node");
if (await AssignedJobAsync(node, jobId, cancellationToken) is not { } job) return Outcome<bool>.Fail(409, "job_not_assigned");
double? eta = progress.ItemsPerSecond is > 0 && progress.Total > progress.Done ? (progress.Total - progress.Done) / progress.ItemsPerSecond.Value : null;
// A node reports any rate (a tiny one when it stalls): only a usable time left is stored and broadcast.
var rate = progress.ItemsPerSecond is { } r && double.IsFinite(r) && r > 0 ? r : (double?)null;
var eta = JobEta.Of(progress.Total - progress.Done, rate);
var tail = AppendLog(job.LogTail, progress.LogLine);
if (!await db.Jobs.UpdateNodeProgressAsync(jobId, NodeKey(node), progress.Done, progress.Total, progress.ItemsPerSecond,
eta is { } seconds ? TimeSpan.FromSeconds(seconds) : null, tail, cancellationToken))
if (!await db.Jobs.UpdateNodeProgressAsync(jobId, NodeKey(node), progress.Done, progress.Total, rate, eta, tail, cancellationToken))
return Outcome<bool>.Fail(409, "job_not_assigned");
await TouchAsync(node, cancellationToken);
events.Publish(new JobProgressEvent(jobId, progress.Done, progress.Total, progress.ItemsPerSecond, eta));
events.Publish(new JobProgressEvent(jobId, progress.Done, progress.Total, rate, eta?.TotalSeconds));
return true;
}