merge: proxy and decode-tier fixes (V-1, V-24, V-25, V-26, V-27, V-28)

Merge branch fix2/proxies-tiers into the verification branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 16:54:07 +00:00
commit e9870f4e88
28 files changed
+1049 -92

No files matched your search

+146 -34
View File
@@ -1,3 +1,4 @@
using System.Collections.Concurrent;
using System.Diagnostics;
using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
@@ -10,7 +11,9 @@ using Titano.Core.Model;
namespace Titano.Data.Archiving;
/// <summary>Frames processed by one thumbnail or proxy pass over a sequence.</summary>
public sealed record ImagePassResult(int Built, int Reused, int Undecodable);
/// <param name="Waiting">Frames of a proxy pass whose originals this host cannot decode and whose proxy it waits for from a
/// client or render node that can (BRIEF §2.3): unlike <paramref name="Undecodable"/> ones, nothing is wrong with them.</param>
public sealed record ImagePassResult(int Built, int Reused, int Undecodable, int Waiting = 0);
/// <summary>What became of a proxy sent by a client or render node (<see cref="ArchiveImages.StoreProxy"/>).</summary>
public enum ProxyStoreResult
@@ -45,9 +48,26 @@ public sealed class ArchiveImages
private const int CommitFrames = 200;
private const int ProbeLongEdge = 64;
/// <summary>Proxy headers kept at most (<see cref="Headers"/>): some 30 MB, the proxies of a few large sequences.</summary>
private const int MaxHeaders = 1 << 17;
private static readonly TimeSpan CommitInterval = TimeSpan.FromSeconds(10);
/// <summary>
/// Age of a proxy file under which its header is not kept: a file system's clock may give a file written again at
/// once (with the same length) the same write time, at a granularity of up to two seconds.
/// </summary>
private static readonly TimeSpan Settling = TimeSpan.FromSeconds(3);
private static readonly ImageDecoder ServerDecoders = DecoderFactory.CreateServer();
/// <summary>
/// The capture time and size of proxies read lately, by path, while the file keeps its length and write time: the
/// server's manifests and tier records check every proxy of a sequence, so an unchanged one costs a stat.
/// </summary>
private static readonly ConcurrentDictionary<string, ProxyHeader> Headers = new(StringComparer.Ordinal);
private readonly TitanoDatabase _db;
private readonly SequenceWriter _writer;
private readonly ArchiveIndexer _indexer;
@@ -86,6 +106,21 @@ public sealed class ArchiveImages
/// </summary>
public static bool ServerNeedsProxy(ImageFileFormat format) => NeedsProxy(ServerDecoders, format);
/// <summary>
/// Whether the file at <paramref name="proxy"/> (a sequence's <c>proxies/0001.jpg</c>) is the proxy of the frame
/// captured at <paramref name="capturedAt"/>, of <paramref name="width"/> × <paramref name="height"/>: its Exif capture
/// time is the frame's to the microsecond (the index's precision), or the frame has none to compare with; and, for a
/// frame whose original this host takes from its proxy (<paramref name="policy"/> given: the archive's), it is not
/// smaller than the policy's (<see cref="TooSmall"/>: one an earlier version made from an embedded preview). Proxies
/// are named by frame index, so one left by a frame renumbered since (frames inserted before it) is another photo's.
/// Renders, analyses, decode tiers and the server's manifests and downloads treat a proxy that fails this as missing,
/// and the proxy pass removes it (<see cref="BuildProxiesAsync"/>).
/// </summary>
/// <param name="policy">The archive's proxy policy for a frame whose original this host cannot decode (its proxy comes
/// from a client or render node); null for one this host decodes and makes the proxy of itself.</param>
public static bool IsProxyOf(string proxy, DateTime? capturedAt, int width, int height, ProxyPolicy? policy) =>
Check(proxy, capturedAt, width, height, policy).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
/// <summary>
/// A proxy of the original at <paramref name="path"/> for a server that cannot decode it (<see cref="StoreProxy"/>):
/// at <paramref name="longEdge"/> (0 = full size) and <paramref name="quality"/>, with <paramref name="frame"/>'s capture
@@ -140,25 +175,30 @@ public sealed class ArchiveImages
if (frame.CapturedAt is { } captured)
{
using var stream = new MemoryStream(jpeg, writable: false);
if (MetadataReader.Read(stream, "proxy.jpg").CapturedAt != captured) return ProxyStoreResult.WrongFrame;
if (!SameCapture(MetadataReader.Read(stream, "proxy.jpg").CapturedAt, captured)) return ProxyStoreResult.WrongFrame;
}
var folder = paths.Sequence(sequence.Folder);
Directory.CreateDirectory(folder.Proxies);
AtomicFile.WriteAllBytes(folder.Proxy(frame.Index), jpeg);
var path = folder.Proxy(frame.Index);
AtomicFile.WriteAllBytes(path, jpeg);
Headers.TryRemove(path, out _);
return ProxyStoreResult.Stored;
}
/// <param name="startFrame">Resume point inside the sequence (frames before it were done by an earlier run).</param>
/// <param name="startFrame">Resume point inside the sequence (frames before it were done by an earlier run: the
/// sequence's built status counts them as they are now).</param>
/// <param name="checkpoint">Called with the next frame index whenever the pack has been committed.</param>
public async Task<ImagePassResult> BuildThumbnailsAsync(Archive archive, Sequence sequence, bool force, int startFrame,
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
{
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ThumbnailPolicy;
var archiveManifest = ManifestStore.ReadArchive(paths.ManifestPath);
var policy = archiveManifest.ThumbnailPolicy;
var folder = paths.Sequence(sequence.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
int built = 0, reused = 0, undecodable = 0;
var complete = true;
var tiers = new Dictionary<Guid, FileTier>();
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
// Thumbnail writers exclude each other only; ingest keeps committing meanwhile.
@@ -166,6 +206,12 @@ public sealed class ArchiveImages
_writer.Options.LeaseDuration, cancellationToken).ConfigureAwait(false))
using (var pack = ThumbPackWriter.Open(folder.ThumbsPackPath))
{
for (var i = 0; i < startFrame && i < manifest.Frames.Count; i++)
{
var frame = manifest.Frames[i];
complete &= pack.Entries.GetValueOrDefault(frame.I) is { } entry
&& entry.SourceHash.AsSpan().SequenceEqual(ThumbPack.Fingerprint(frame.Sha256, frame.File, frame.Size));
}
var cadence = new Cadence();
for (var i = startFrame; i < manifest.Frames.Count; i++)
{
@@ -178,9 +224,9 @@ public sealed class ArchiveImages
// A frame this host cannot decode shows its proxy once one arrived; until then its original's embedded
// preview, whose smaller thumbnail the proxy's replaces.
var fromProxy = false;
if (NeedsProxy(frame.Format) && !(current && edge >= FrameImageRenderer.ThumbnailLongEdge)
&& ReadProxy(folder.Proxy(frame.I), frame) is { Check: ProxyCheck.Current or ProxyCheck.Unverifiable } proxy)
fromProxy = !current || edge < System.Math.Min(FrameImageRenderer.ThumbnailLongEdge, proxy.LongEdge);
if (NeedsProxy(frame.Format) && !(current && edge >= policy.LongEdge)
&& Check(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H, archiveManifest.ProxyPolicy) is { Check: ProxyCheck.Current or ProxyCheck.Unverifiable } proxy)
fromProxy = !current || edge < System.Math.Min(policy.LongEdge, proxy.LongEdge);
if (current && !fromProxy)
{
reused++;
@@ -208,12 +254,18 @@ public sealed class ArchiveImages
}
pack.Commit();
}
await _tiers.RecordAsync(archive, sequence, tiers, cancellationToken).ConfigureAwait(false);
await MarkAsync(archive, paths, sequence, SequenceStatus.ThumbsBuilt, undecodable == 0, cancellationToken).ConfigureAwait(false);
await _tiers.RecordAsync(archive, sequence, tiers, proxies: false, cancellationToken).ConfigureAwait(false);
await MarkAsync(archive, paths, sequence, SequenceStatus.ThumbsBuilt, complete && undecodable == 0, cancellationToken).ConfigureAwait(false);
return new ImagePassResult(built, reused, undecodable);
}
/// <inheritdoc cref="BuildThumbnailsAsync"/>
/// <remarks>
/// <see cref="SequenceStatus.ProxiesBuilt"/> is set only when every frame has its proxy: a server asks clients and
/// render nodes for none while it is set (BRIEF §2.3), so a pass resumed at <paramref name="startFrame"/> checks the
/// proxies of the frames an earlier run did again (their headers only). The <see cref="FrameFlags.PreviewOnly"/> flag
/// of frames this host reads through their proxies follows whether they have one (<see cref="FrameTiers"/>).
/// </remarks>
public async Task<ImagePassResult> BuildProxiesAsync(Archive archive, Sequence sequence, bool force, int startFrame,
Func<int, int, ValueTask> checkpoint, CancellationToken cancellationToken = default)
{
@@ -224,33 +276,38 @@ public sealed class ArchiveImages
var folder = paths.Sequence(sequence.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
Directory.CreateDirectory(folder.Proxies);
int built = 0, reused = 0, undecodable = 0;
int built = 0, reused = 0, undecodable = 0, waiting = 0;
var complete = true;
var tiers = new Dictionary<Guid, FileTier>();
var companions = await GprCompanions.FindAsync(_db, archive, manifest.Frames, cancellationToken).ConfigureAwait(false);
var cadence = new Cadence();
for (var i = startFrame; i < manifest.Frames.Count; i++)
for (var i = 0; i < manifest.Frames.Count; i++)
{
cancellationToken.ThrowIfCancellationRequested();
var frame = manifest.Frames[i];
var path = folder.Proxy(frame.I);
var done = i < startFrame;
if (NeedsProxy(frame.Format))
{
// Only a client or render node that decodes the original makes this proxy: a preview would make one the
// size of a thumbnail here. One left from a frame renumbered since goes, so it is asked for again, and so
// does one smaller than the policy's (made here from a preview by an earlier version).
var (check, longEdge) = ReadProxy(path, frame);
if (check is ProxyCheck.Current or ProxyCheck.Unverifiable && TooSmall(longEdge, frame.W, frame.H, policy)) check = ProxyCheck.Stale;
if (check is ProxyCheck.Current or ProxyCheck.Unverifiable)
{
reused++;
}
else
{
if (check == ProxyCheck.Stale) File.Delete(path);
undecodable++;
}
var check = Check(path, frame.CapturedAt, frame.W, frame.H, policy).Check;
var usable = check is ProxyCheck.Current or ProxyCheck.Unverifiable;
if (check == ProxyCheck.Stale) Delete(path);
complete &= usable;
if (done) continue;
if (usable) reused++;
else if ((frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0) undecodable++;
else waiting++;
}
else if (!force && ReadProxy(path, frame).Check == ProxyCheck.Current)
else if (done)
{
// Made by the earlier run, unless the frame did not decode then.
complete &= ReadProxy(path, frame.CapturedAt).Check is ProxyCheck.Current or ProxyCheck.Unverifiable;
continue;
}
else if (!force && ReadProxy(path, frame.CapturedAt).Check == ProxyCheck.Current)
{
reused++;
continue;
@@ -259,17 +316,19 @@ public sealed class ArchiveImages
() => _renderer.Proxy(folder, frame, manifest.Camera, policy, cancellationToken, companions.GetValueOrDefault(frame.Id))) is { } image)
{
AtomicFile.WriteAllBytes(path, image.Jpeg);
Headers.TryRemove(path, out _);
built++;
}
else
{
undecodable++;
complete = false;
}
if (cadence.Due()) await checkpoint(i + 1, manifest.Frames.Count).ConfigureAwait(false);
}
await _tiers.RecordAsync(archive, sequence, tiers, cancellationToken).ConfigureAwait(false);
await MarkAsync(archive, paths, sequence, SequenceStatus.ProxiesBuilt, undecodable == 0, cancellationToken).ConfigureAwait(false);
return new ImagePassResult(built, reused, undecodable);
await _tiers.RecordAsync(archive, sequence, tiers, proxies: true, cancellationToken).ConfigureAwait(false);
await MarkAsync(archive, paths, sequence, SequenceStatus.ProxiesBuilt, complete, cancellationToken).ConfigureAwait(false);
return new ImagePassResult(built, reused, undecodable, waiting);
}
/// <summary>Where a frame's proxy stands; only a capture time tells whether it is the frame's.</summary>
@@ -283,27 +342,80 @@ public sealed class ArchiveImages
/// <summary>The frame has no capture time to compare with.</summary>
Unverifiable,
/// <summary>Made from another frame (frames were renumbered since).</summary>
/// <summary>Made from another frame (frames were renumbered since), or too small (<see cref="Check"/>).</summary>
Stale,
}
/// <summary>Where the proxy at <paramref name="proxy"/> stands for <paramref name="frame"/>, and its long edge.</summary>
private static (ProxyCheck Check, int LongEdge) ReadProxy(string proxy, SidecarFrame frame)
/// <summary>A proxy's Exif capture time and oriented long edge, read when the file had this length and write time.</summary>
private readonly record struct ProxyHeader(long Length, long WriteTicks, DateTime? CapturedAt, int LongEdge);
/// <summary>
/// Where the proxy at <paramref name="proxy"/> stands for the frame captured at <paramref name="capturedAt"/>, of
/// <paramref name="width"/> × <paramref name="height"/>, and its long edge: <see cref="ProxyCheck.Stale"/> also when
/// <paramref name="policy"/> is given and the proxy is <see cref="TooSmall"/> for it (<see cref="IsProxyOf"/>).
/// </summary>
private static (ProxyCheck Check, int LongEdge) Check(string proxy, DateTime? capturedAt, int width, int height, ProxyPolicy? policy)
{
var (check, longEdge) = ReadProxy(proxy, capturedAt);
if (check is ProxyCheck.Current or ProxyCheck.Unverifiable && policy is not null && TooSmall(longEdge, width, height, policy)) check = ProxyCheck.Stale;
return (check, longEdge);
}
/// <summary>Where the proxy at <paramref name="proxy"/> stands for the frame captured at <paramref name="capturedAt"/>, and its long edge.</summary>
private static (ProxyCheck Check, int LongEdge) ReadProxy(string proxy, DateTime? capturedAt)
{
if (ReadHeader(proxy) is not { } header) return (ProxyCheck.Missing, 0);
var check = capturedAt is not { } captured ? ProxyCheck.Unverifiable : SameCapture(header.CapturedAt, captured) ? ProxyCheck.Current : ProxyCheck.Stale;
return (check, header.LongEdge);
}
/// <summary>
/// The header of the proxy at <paramref name="proxy"/>; null when there is none or it cannot be read. Kept in
/// <see cref="Headers"/> while the file's length and write time stay as they were when it was read (taken first, so
/// a file replaced meanwhile is read again next time), once the file is older than <see cref="Settling"/>; a full
/// cache starts over.
/// </summary>
private static ProxyHeader? ReadHeader(string proxy)
{
if (!File.Exists(proxy)) return (ProxyCheck.Missing, 0);
try
{
var file = new FileInfo(proxy);
if (!file.Exists) return null;
var (length, written) = (file.Length, file.LastWriteTimeUtc);
if (Headers.TryGetValue(proxy, out var cached) && cached.Length == length && cached.WriteTicks == written.Ticks) return cached;
var metadata = MetadataReader.Read(proxy);
var (width, height) = metadata.OrientedSize;
var check = frame.CapturedAt is null ? ProxyCheck.Unverifiable : metadata.CapturedAt == frame.CapturedAt ? ProxyCheck.Current : ProxyCheck.Stale;
return (check, System.Math.Max(width, height));
var header = new ProxyHeader(length, written.Ticks, metadata.CapturedAt, System.Math.Max(width, height));
if (DateTime.UtcNow - written < Settling)
{
Headers.TryRemove(proxy, out _);
return header;
}
if (Headers.Count >= MaxHeaders) Headers.Clear();
Headers[proxy] = header;
return header;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return (ProxyCheck.Missing, 0);
return null;
}
}
/// <summary>
/// Whether a proxy's Exif capture time is the frame's <paramref name="captured"/> to the microsecond: the index keeps
/// capture times to the microsecond, sidecars and Exif to the 100 ns tick, so a proxy made from either record of the
/// frame (here from the sidecar, by a client from the server's index) matches both.
/// </summary>
private static bool SameCapture(DateTime? proxy, DateTime captured) =>
proxy is { } time && time.Ticks / TimeSpan.TicksPerMicrosecond == captured.Ticks / TimeSpan.TicksPerMicrosecond;
/// <summary>Removes the proxy at <paramref name="path"/> and what is known of it.</summary>
private static void Delete(string path)
{
File.Delete(path);
Headers.TryRemove(path, out _);
}
/// <summary>
/// Whether a proxy whose long edge is <paramref name="longEdge"/> falls short of the policy's for a frame of
/// <paramref name="width"/> × <paramref name="height"/> (the policy's long edge, or the frame's own when smaller or
+27 -10
View File
@@ -12,7 +12,9 @@ namespace Titano.Data.Archiving;
/// shows a warning at once; its next light analysis lists them. Tiers describe the host that probed or decoded the files
/// last. Only a file in a format this host decodes natively is flagged undecodable (it is damaged); one beyond this
/// host's decoders (HEIF or an unsupported RAW without a preview on the server) keeps its tier but no flag, so render
/// nodes and proxies can still provide its pixels, and a host that decodes a flagged frame clears the flag.
/// nodes and proxies can still provide its pixels, and a host that decodes a flagged frame clears the flag. A frame whose
/// original this host reads through its proxy (<see cref="ArchiveImages.NeedsProxy(ImageFileFormat)"/>) is preview-only
/// only while it has none: with its proxy it is not rendered from the embedded preview, so it caps nothing.
/// </summary>
internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, ArchiveIndexer indexer)
{
@@ -50,17 +52,25 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
}
/// <summary>
/// Records <paramref name="tiers"/> (by frame id) where they change what the sidecar says, and returns the frames that
/// changed as they are now. Frames no longer in the sequence are ignored.
/// Records <paramref name="tiers"/> (by frame id) where they change what the sidecar says, and returns the sequence's
/// frames as the sidecar has them afterwards (none when there was nothing to record). Frames no longer in the
/// sequence are ignored. The <see cref="FrameFlags.PreviewOnly"/> flag of a frame whose original this host reads
/// through its proxy follows whether its own proxy is there when the sidecar is written
/// (<see cref="ArchiveImages.IsProxyOf"/>, <see cref="SequenceFrames.WithProxy"/>), not when the caller looked: proxies
/// arrive while analyses and renders run, and another worker may have recorded them already.
/// </summary>
/// <param name="proxies">Whether every such frame follows its proxy even where no tier is recorded (analyses and the
/// proxy pass); otherwise only the frames in <paramref name="tiers"/> do.</param>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
public async Task<IReadOnlyList<SidecarFrame>> RecordAsync(Archive archive, Sequence sequence, IReadOnlyDictionary<Guid, FileTier> tiers,
CancellationToken cancellationToken)
bool proxies, CancellationToken cancellationToken)
{
if (tiers.Count == 0) return [];
if (tiers.Count == 0 && !proxies) return [];
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
var changed = new List<SidecarFrame>();
ProxyPolicy? policy = null;
var manifest = await writer.UpdateAsync(paths, sequence.Id, sequence.Folder, m =>
{
changed.Clear();
@@ -70,8 +80,16 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
{
var frame = m.Frames[i];
frames[i] = frame;
if (!tiers.TryGetValue(frame.Id, out var tier)) continue;
var updated = SequenceFrames.WithTier(frame, tier, DecodesNatively(frame.Format));
var tier = tiers.GetValueOrDefault(frame.Id);
if (tier is null && !proxies) continue;
bool? proxied = (frame.Flags & FrameFlags.Missing) == 0 && ArchiveImages.NeedsProxy(writer.Options.Decoder, frame.Format)
? ArchiveImages.IsProxyOf(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H,
policy ??= ManifestStore.ReadArchive(paths.ManifestPath).ProxyPolicy)
: null;
SidecarFrame updated;
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)
continue;
gained |= (updated.Flags & ~frame.Flags & FrameFlags.Undecodable) != 0;
@@ -86,14 +104,13 @@ internal sealed class FrameTiers(TitanoDatabase db, SequenceWriter writer, Archi
UpdatedAt = DateTimeOffset.UtcNow,
};
}, cancellationToken).ConfigureAwait(false);
if (changed.Count == 0) return [];
if (changed.Count == 0) return manifest.Frames;
await db.Frames.UpdateTiersAsync(changed.ConvertAll(f => new FrameTierFields(f.Id, f.Flags, f.PreviewW ?? 0, f.PreviewH ?? 0)), cancellationToken)
.ConfigureAwait(false);
var folder = paths.Sequence(sequence.Folder);
if (await db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false) is { } existing)
await db.Sequences.UpsertAsync(SequenceMapping.ToSequence(manifest, archive.Id, folder, existing), cancellationToken).ConfigureAwait(false);
await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
return changed;
return manifest.Frames;
}
/// <summary>
@@ -34,7 +34,9 @@ internal sealed class ImageJobHandler(TitanoDatabase db, ArchiveImages images, J
var result = kind == JobKind.Thumbs
? await images.BuildThumbnailsAsync(archive, sequence, force, start, Checkpoint, context.Cancellation).ConfigureAwait(false)
: await images.BuildProxiesAsync(archive, sequence, force, start, Checkpoint, context.Cancellation).ConfigureAwait(false);
context.Log(Loc.L("Archive.Log.ImagesDone", sequence.DisplayTitle, result.Built, result.Reused, result.Undecodable));
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);
}
}