merge: fourth-pass analysis and sync fixes (Y-1, Y-2, Y-7)

Merge branch fix4/analysis-sync 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 22:09:58 +00:00
commit 8e8f802f93
14 files changed
+433 -28

No files matched your search

@@ -13,15 +13,15 @@ namespace Titano.Data.Processing;
/// </summary>
internal static class AnalysisFollowUp
{
/// <summary>Queues one light analysis of <paramref name="sequenceIds"/> (labelled like the job that found them).</summary>
public static async Task QueueAsync(TitanoDatabase db, JobContext context, IReadOnlyCollection<Guid> sequenceIds)
/// <summary>Queues one light analysis of <paramref name="sequenceIds"/>, labelled <paramref name="label"/> (by default like the job that found them).</summary>
public static async Task QueueAsync(TitanoDatabase db, JobContext context, IReadOnlyCollection<Guid> sequenceIds, string? label = null)
{
if (sequenceIds.Count == 0) return;
var waiting = (await db.Jobs.ListQueuedAsync([JobKind.LightAnalyse], 1000, context.Cancellation).ConfigureAwait(false))
.SelectMany(j => j.TargetIds).ToHashSet();
var targets = sequenceIds.Where(id => !waiting.Contains(id)).Distinct().ToList();
if (targets.Count == 0) return;
var request = ProcessingJobs.LightAnalysis(targets, context.Job.TargetLabel);
var request = ProcessingJobs.LightAnalysis(targets, label ?? context.Job.TargetLabel);
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
}
@@ -44,6 +44,7 @@ internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser anal
var outcome = await analyser.AnalyseAsync(targets[i], deep, progress, context.Cancellation).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
if (outcome is null) context.Log(Loc.L("Archive.Log.SequenceMissing", targets[i]));
else if (outcome.FramesChanged != FramesChange.None) await NotRecordedAsync(context, outcome).ConfigureAwait(false);
else Report(context, outcome, deep);
}
catch (Exception ex) when (ex is not (OperationCanceledException or ArchiveOfflineException))
@@ -63,6 +64,24 @@ internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser anal
if (failed.Count > 0) throw new InvalidOperationException(failed.Count == 1 ? failure : Loc.L("Errors.Analysis.Failed", failed.Count, targets.Count));
}
/// <summary>
/// A sequence whose frames changed while it was analysed: nothing was recorded from the frames the analysis read (the
/// deep report it saved counts only for the frames it describes). When this index holds the frames as they are, and no
/// light analysis is queued for it, one is queued; frames another process changed are analysed by that process, and
/// indexed here by the next scan (<see cref="FramesChange.NotIndexed"/>).
/// </summary>
private async Task NotRecordedAsync(JobContext context, AnalysisOutcome outcome)
{
var sequence = outcome.Sequence;
if (outcome.FramesChanged == FramesChange.NotIndexed)
{
context.Log(Loc.L("Advisor.Log.FramesChangedElsewhere", sequence.DisplayTitle));
return;
}
context.Log(Loc.L("Advisor.Log.FramesChanged", sequence.DisplayTitle));
await AnalysisFollowUp.QueueAsync(db, context, [sequence.Id], sequence.DisplayTitle).ConfigureAwait(false);
}
private async Task<string> TitleAsync(Guid sequenceId, CancellationToken cancellationToken) =>
(await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false))?.DisplayTitle ?? sequenceId.ToString();
+54 -3
View File
@@ -16,8 +16,29 @@ namespace Titano.Data.Processing;
/// <param name="SettingsChanged">The advisor changed Auto values of the project.</param>
/// <param name="SettingsUnreadable">The project could not be read, so its Auto values were left alone.</param>
/// <param name="Presets">Sequence presets that fit the content (deep analysis only).</param>
/// <param name="FramesChanged">How the frames it read were no longer the sequence's when it recorded: anything but
/// <see cref="FramesChange.None"/> means nothing was recorded from them.</param>
internal sealed record AnalysisOutcome(Sequence Sequence, int Frames, int Warnings, bool SettingsChanged, bool SettingsUnreadable,
IReadOnlyList<SequencePreset> Presets);
IReadOnlyList<SequencePreset> Presets, FramesChange FramesChanged = FramesChange.None);
/// <summary>How the frames an analysis read had changed by the time it recorded, under the sequence lock.</summary>
internal enum FramesChange
{
/// <summary>Still the sequence's frames, or changed in this index with a light analysis queued to replace what it records.</summary>
None,
/// <summary>
/// Added, removed or renumbered in this index (an upload, an import, a scan), with no light analysis queued: one must
/// run here for the frames as they are.
/// </summary>
Indexed,
/// <summary>
/// Changed in the sidecar by another process (a desktop sharing a server's archive, or that server), which analyses
/// them; this index holds them only after its next scan, which on a server queues their analysis here too.
/// </summary>
NotIndexed,
}
/// <summary>
/// Light (BRIEF §10.1) and deep (§10.2) analysis of archived sequences, followed by the advisor (§10.3–10.4) filling the
@@ -71,9 +92,15 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
// only while it describes the frames as they are under the lock (ReadReport), so a deep pass loads them again: a
// proxy that arrived while it ran (for hours) makes its verdict on that frame's original stale. The light analysis
// the proxy queued then either ran before this, and the advice, status and warnings stay without the report as it
// left them, or runs after.
// left them, or runs after. A pass whose frames were added to, removed or renumbered since it read them records
// nothing (FramesChangeAsync), and a light analysis of the frames as they are runs instead, here or where they
// were changed.
await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
var change = await FramesChangeAsync(sequence, manifest, cancellationToken).ConfigureAwait(false);
if (change != FramesChange.None)
return new AnalysisOutcome(sequence, frames.Count, 0, SettingsChanged: false, SettingsUnreadable: false, [], change);
if (deep)
{
var now = await SequenceFrames.LoadAsync(db, archive, sequence, useProxies: false, options.Archive.Decoder, cancellationToken).ConfigureAwait(false);
@@ -100,7 +127,6 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
| (warnings > 0 ? SequenceStatus.HasWarnings : SequenceStatus.None);
// Without a current report (none, or made before frames were added) the deep status no longer holds.
var clear = (report is null ? SequenceStatus.AnalyzedDeep : SequenceStatus.None) | (warnings > 0 ? SequenceStatus.None : SequenceStatus.HasWarnings);
var manifest = SequenceWriter.ReadLocked(folder, sequence.Id);
var inStep = await indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
var status = (manifest.Status | set) & ~clear;
if (status != manifest.Status) ManifestStore.WriteSequence(folder.ManifestPath, manifest with { Status = status, UpdatedAt = DateTimeOffset.UtcNow });
@@ -114,6 +140,31 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
return new AnalysisOutcome(sequence, frames.Count, warnings, changed, unreadable, presets);
}
/// <summary>
/// How the frames this pass read had changed by now, under the sequence lock. Every writer of this index's frames bumps
/// the row's frames version with them under the same lock (an upload or import, a scan reconciling photos copied in by
/// hand or indexing frames another process listed in the sidecar), and every writer of the sidecar's frames bumps its
/// version (<paramref name="manifest"/>, read under the lock). What the pass found then describes other frames:
/// recorded, it would mark the new ones analysed, with Auto values and warnings counted on the old ones, over what an
/// analysis of the frames as they are may have recorded already, in the shared sidecar and <c>project.json</c> too.
/// A sidecar at another version than the row lists frames another process changed and this index does not hold yet
/// (<see cref="FramesChange.NotIndexed"/>): nothing is queued here, since a light analysis would read this index as
/// it is and find it behind the sidecar again until the next scan indexes them. A row whose version moved since the
/// pass read it holds the frames as they are, and a light analysis here covers them (<see cref="FramesChange.Indexed"/>).
/// One already queued for the sequence runs after this on the frames as they are then, so the pass still records
/// meanwhile, as an image pass keeps its flag (<see cref="ArchiveImages"/>): during an upload burst every pass is
/// overtaken, and a sequence being shot would otherwise show no analysis until uploads paused.
/// </summary>
private async Task<FramesChange> FramesChangeAsync(Sequence sequence, SequenceManifest manifest, CancellationToken cancellationToken)
{
if (await db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false) is not { } row) return FramesChange.None;
if (manifest.Versions.Frames != row.FramesVersion) return FramesChange.NotIndexed;
return row.FramesVersion == sequence.FramesVersion
|| await db.Jobs.IsQueuedAsync(JobKind.LightAnalyse, sequence.Id, cancellationToken).ConfigureAwait(false)
? FramesChange.None
: FramesChange.Indexed;
}
/// <summary>
/// The saved deep report when it describes <paramref name="frames"/> as this host reads them now: also stale when a
/// frame it found unreadable has been read from its proxy since (one sent for an original this host cannot decode,
+28 -14
View File
@@ -51,7 +51,10 @@ public sealed class SyncAgent : IAsyncDisposable
private readonly Dictionary<Guid, (int Failures, DateTime NotBefore)> _proxyFailures = [];
/// <summary>The server's update time at which a cache holding thumbnails in place of proxies was last compared with its manifest.</summary>
/// <summary>
/// The server's update time at which a cache holding stand-ins (thumbnails or no file in place of proxies) was last
/// compared with its manifest, or had its download queued.
/// </summary>
private readonly Dictionary<Guid, DateTimeOffset> _standInsCompared = [];
private readonly SemaphoreSlim _refreshing = new(1, 1);
@@ -226,9 +229,11 @@ public sealed class SyncAgent : IAsyncDisposable
/// <summary>
/// Queues (background priority) the proxies of server sequences this PC keeps proxies of, without local originals,
/// whose cache is stale: frames changed on a server that has the sequence's proxies, or the server now offers the
/// proxy of a frame the cache holds a thumbnail for (<see cref="OffersProxiesAsync"/>). A sequence whose last
/// download failed waits for its backoff.
/// whose cache is stale: frames changed on a server that has the sequence's proxies; on such a server, a download
/// left stand-ins and the server's sequence changed since (the proxy pass that draws frames added after its last one
/// records the sequence's state, while its flag already offers their proxies); or the server, without the sequence's
/// proxies, now offers the proxy of a frame the cache holds a stand-in for (<see cref="OffersProxiesAsync"/>). A
/// sequence whose last download failed waits for its backoff.
/// </summary>
private async Task QueueProxiesAsync(SyncSnapshot snapshot, CancellationToken cancellationToken)
{
@@ -254,27 +259,36 @@ public sealed class SyncAgent : IAsyncDisposable
{
if (entry is not { Local: null, Transfer: null, Link: { ProxiesCached: > 0, ProxiesStale: true } link }) continue;
if (_proxyFailures.TryGetValue(link.RemoteId, out var failed) && DateTime.UtcNow < failed.NotBefore) continue;
if (!link.ServerHasProxies && !await OffersProxiesAsync(link, cancellationToken).ConfigureAwait(false)) continue;
// A download that left stand-ins on a server with the proxies brings nothing new until the sequence changes: a
// frame the server offers but cannot serve yet, or one that never gets a proxy, would otherwise be fetched at
// every refresh.
if (link.ServerHasProxies ? link.ProxiesFramesVersion is null && ComparedNow(link) : !await OffersProxiesAsync(link, cancellationToken).ConfigureAwait(false))
continue;
var job = await _sync.EnqueueDownloadAsync(_engine!, Server, link.RemoteId, link.Title, SyncDownloadMode.Proxies, null, JobPriority.Background,
cancellationToken).ConfigureAwait(false);
_proxyJobs[link.RemoteId] = job.Id;
// Compared at this update time once the download that brings what the server offers is queued.
if (!link.ServerHasProxies) _standInsCompared[link.RemoteId] = link.RemoteUpdatedAt;
_standInsCompared[link.RemoteId] = link.RemoteUpdatedAt;
}
}
/// <summary>Whether the cache was compared with the server's sequence, or its download queued, at the sequence's current update time.</summary>
private bool ComparedNow(SyncLink link) =>
_standInsCompared.TryGetValue(link.RemoteId, out var compared) && SyncService.SameMoment(compared, link.RemoteUpdatedAt);
/// <summary>
/// Whether the server now offers the proxy of a frame whose cached file only stands in for one (a thumbnail, a file
/// of a cache that did not record its kind) or that has no cached file. The sequence's proxy flag cannot say: it waits
/// for every frame, a missing or damaged one never gets a proxy, and clients and render nodes send the other frames'
/// proxies one by one. The manifest is read once per change of the server's sequence, since a proxy that arrives
/// leaves a new update time (the proxy pass it queues records the sequence's state). A comparison that offers nothing
/// is recorded here; one that offers proxies is recorded when their download is queued, and dropped when that
/// download does not finish (<see cref="QueueProxiesAsync"/>).
/// Whether the server, without the sequence's proxies, now offers the proxy of a frame whose cached file only stands in
/// for one (a thumbnail, a file of a cache that did not record its kind) or that has no cached file. The sequence's
/// proxy flag cannot say: a pass sets it only once every frame the server cannot decode has its proxy, a missing or
/// damaged one never gets a proxy, and clients and render nodes send the other frames' proxies one by one. The
/// manifest is read once per change of the server's sequence, since a proxy that arrives leaves a new update time
/// (the proxy pass it queues records the sequence's state). A comparison that offers nothing is recorded here; one
/// that offers proxies is recorded when their download is queued, and dropped when that download does not finish
/// (<see cref="QueueProxiesAsync"/>).
/// </summary>
private async Task<bool> OffersProxiesAsync(SyncLink link, CancellationToken cancellationToken)
{
if (_standInsCompared.TryGetValue(link.RemoteId, out var compared) && SyncService.SameMoment(compared, link.RemoteUpdatedAt)) return false;
if (ComparedNow(link)) return false;
SequenceManifest manifest;
try
{
+10 -5
View File
@@ -421,16 +421,18 @@ public sealed class SyncService
}
/// <summary>
/// Records what the proxy cache holds for a server sequence. Thumbnails standing in for proxies the server did not
/// have leave the cache stale: it is filled again once the server has its proxies.
/// Records what the proxy cache holds for a server sequence. Stand-ins (<paramref name="standIns"/>: thumbnails, or
/// no file, in place of proxies a frame may still get) leave the cache stale, whether the server has the sequence's
/// proxies or not: its flag also offers the proxies of frames added since its last proxy pass, which it cannot serve
/// until that pass draws them. The cache is filled again once the server has those proxies.
/// </summary>
internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, int thumbnails, int framesVersion, CancellationToken cancellationToken)
internal async Task SetProxiesAsync(string server, SequenceDto dto, int cached, int standIns, int framesVersion, CancellationToken cancellationToken)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
var link = Observe(await _links.GetAsync(server, dto.Id, cancellationToken).ConfigureAwait(false), server, dto);
int? filledAt = thumbnails > 0 && !link.ServerHasProxies ? null : framesVersion;
int? filledAt = standIns > 0 ? null : framesVersion;
await _links.UpsertAsync(link with { ProxiesCached = cached, ProxiesFramesVersion = filledAt }, cancellationToken).ConfigureAwait(false);
}
finally
@@ -765,6 +767,9 @@ public sealed class SyncService
if (metadata)
{
var manifest = SequenceWriter.ReadLocked(folder, row.Id);
// Asked before the sidecar is written: frames or flags another process wrote there since this index last
// synced the folder keep it changed for the next scan (ArchiveIndexer.InStepAsync).
var inStep = await Archives.Indexer.InStepAsync(archive, folder, manifest, cancellationToken).ConfigureAwait(false);
ManifestStore.WriteSequence(folder.ManifestPath, manifest with
{
Title = updated.Title,
@@ -774,7 +779,7 @@ public sealed class SyncService
Versions = manifest.Versions with { Settings = Math.Max(manifest.Versions.Settings, updated.SettingsVersion) },
UpdatedAt = DateTimeOffset.UtcNow,
});
await Archives.Indexer.RecordStampsAsync(archive, folder, row.Id, cancellationToken).ConfigureAwait(false);
if (inStep) await Archives.Indexer.RecordStampsAsync(archive, folder, row.Id, cancellationToken).ConfigureAwait(false);
}
return updated;
}
+8 -1
View File
@@ -447,7 +447,8 @@ internal sealed class SyncTransfers(SyncService sync)
sync.Proxies.Save(remote.Server, remoteId, new ProxyCacheIndex(dto, manifest.SettingsJson, manifest.FramesVersion, frames, files, kinds));
var cached = files.Count(f => f is not null);
await sync.SetProxiesAsync(remote.Server, dto, cached, kinds.Count(k => k == ProxyCache.Thumb), manifest.FramesVersion, ct).ConfigureAwait(false);
var standIns = Enumerable.Range(0, frames.Count).Count(i => kinds[i] != ProxyCache.Proxy && !NeverProxied(frames[i]));
await sync.SetProxiesAsync(remote.Server, dto, cached, standIns, manifest.FramesVersion, ct).ConfigureAwait(false);
if (cached < frames.Count) context.Log($"{frames.Count - cached} frame(s) have neither proxy nor thumbnail on the server");
}
@@ -628,6 +629,12 @@ internal sealed class SyncTransfers(SyncService sync)
return cached ? (name, ProxyCache.Thumb) : null;
}
/// <summary>
/// A frame missing or damaged on the server: its manifest never asks for its proxy and a pass makes none of a missing
/// one, so the thumbnail (or the lack of a file) that stands in for it does not keep the cache stale.
/// </summary>
private static bool NeverProxied(FrameDto frame) => ((FrameFlags)frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0;
private static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
{
(true, true) => [ProxyCache.Proxy, ProxyCache.Thumb],