fix(archive): scans leave sequences waiting for a folder alone and build server images

A sequence created through POST /api/v1/sequences keeps an empty folder until its
first frame. Scans no longer adopt loose photos at the archive root under its id,
and a rebuild, the orphans report and fix, verify and the scan follow-ups no longer
treat it as the root sequence, as missing or as a sequence to analyse. All of them
use ArchiveIngest.AwaitsFolder.

On the server (ArchiveServiceOptions.ImagesAfterScan), a scan that indexes sequences
without thumbnails or proxies queues background Thumbs and Proxies passes for them,
as an upload does. A scan that finds photos added or removed clears ThumbsBuilt and
ProxiesBuilt together with AnalyzedLight.

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 15:58:37 +00:00
1 parent 32a0e9bbc1
commit fba05c2840
10 files changed
+290 -29

No files matched your search

+42 -14
View File
@@ -20,7 +20,9 @@ public enum ScanMode
public sealed record ScanProgress(int FoldersDone, int FoldersTotal, string Folder, bool Changed);
/// <param name="Failed">Folders that could not be indexed, with the reason; they are retried by the next scan.</param>
public sealed record ScanSummary(int Folders, int Indexed, int Adopted, int Removed, IReadOnlyList<(string Folder, string Error)> Failed);
/// <param name="Sequences">The sequences this run indexed (<paramref name="Indexed"/> of them), in folder order.</param>
public sealed record ScanSummary(int Folders, int Indexed, int Adopted, int Removed, IReadOnlyList<(string Folder, string Error)> Failed,
IReadOnlyList<Guid> Sequences);
/// <summary>
/// Keeps the database index in line with the archive on disk (BRIEF §7, §12.5): scans by size/time stamps, adopts
@@ -49,11 +51,15 @@ public sealed class ArchiveIndexer
if (mode == ScanMode.Rebuild && resumeAfter is null) await _db.Archives.ClearFolderStatesAsync(archive.Id, cancellationToken).ConfigureAwait(false);
var folders = ArchiveScanner.FindSequenceFolders(paths, cancellationToken);
var states = await _db.Archives.GetFolderStatesAsync(archive.Id, cancellationToken).ConfigureAwait(false);
var locations = new Locations(await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false));
var rows = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
// A sequence waiting for its first frame has no folder yet: the archive root, adopted or re-adopted, never takes its id.
var awaiting = await AwaitingFolderAsync(paths, rows, cancellationToken).ConfigureAwait(false);
var locations = new Locations(rows.Where(r => !awaiting.Contains(r.Id)));
var snapshot = mode == ScanMode.Rebuild ? IndexSnapshot.TryLoad(paths.SnapshotPath) : null;
using var snapshotWriter = mode != ScanMode.Incremental && resumeAfter is null ? new IndexSnapshot.Writer(paths.SnapshotPath) : null;
int indexed = 0, adopted = 0;
int adopted = 0;
var indexed = new List<Guid>();
var failed = new List<(string, string)>();
for (var i = 0; i < folders.Count; i++)
{
@@ -67,14 +73,14 @@ public sealed class ArchiveIndexer
try
{
var reconcile = mode == ScanMode.Full || (state is not null && state.Photos != folder.Photos);
var bytes = await IndexFolderAsync(archive, paths, folder, reconcile, snapshot, locations, cancellationToken).ConfigureAwait(false);
var (id, bytes) = await IndexFolderAsync(archive, paths, folder, reconcile, snapshot, locations, cancellationToken).ConfigureAwait(false);
if (snapshotWriter is not null)
{
var sidecar = paths.Sequence(folder.RelativeFolder).ManifestPath;
snapshotWriter.Add(folder.RelativeFolder, FileStamp.Of(sidecar)!.Value,
bytes ?? await File.ReadAllBytesAsync(sidecar, cancellationToken).ConfigureAwait(false));
}
indexed++;
indexed.Add(id);
if (folder.Sidecar is null) adopted++;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
@@ -88,7 +94,7 @@ public sealed class ArchiveIndexer
var removed = mode == ScanMode.Rebuild ? await RemoveUnbackedAsync(archive, paths, folders, locations, cancellationToken).ConfigureAwait(false) : 0;
if (failed.Count == 0) snapshotWriter?.Commit();
return new ScanSummary(folders.Count, indexed, adopted, removed, failed);
return new ScanSummary(folders.Count, indexed.Count, adopted, removed, failed, indexed);
}
/// <summary>
@@ -156,8 +162,8 @@ public sealed class ArchiveIndexer
}
}
/// <summary>Indexes one folder; returns the sidecar bytes when they were read and not rewritten since (for the snapshot).</summary>
private async Task<byte[]?> IndexFolderAsync(Archive archive, ArchivePaths paths, SequenceFolder folder, bool reconcile, IndexSnapshot? snapshot,
/// <summary>Indexes one folder; returns its sequence and the sidecar bytes when they were read and not rewritten since (for the snapshot).</summary>
private async Task<(Guid Id, byte[]? Bytes)> IndexFolderAsync(Archive archive, ArchivePaths paths, SequenceFolder folder, bool reconcile, IndexSnapshot? snapshot,
Locations locations, CancellationToken cancellationToken)
{
var sequence = paths.Sequence(folder.RelativeFolder);
@@ -189,10 +195,11 @@ public sealed class ArchiveIndexer
}
if (reconcile || File.Exists(sequence.IngestJournalPath))
{
// Photos added, gone or back: the light analysis no longer describes the frames, so the scan's follow-up runs it again.
// Photos added, gone or back: the light analysis, thumbnails and proxies no longer cover the frames, so the scan's
// follow-ups make them again (the images on a server, ArchiveServiceOptions.ImagesAfterScan).
manifest = await UpdateAndSyncAsync(archive, paths, sequence, manifest.Id,
m => SequenceAdopter.Reconcile(sequence, m, cancellationToken) is { } reconciled
? reconciled with { Status = reconciled.Status & ~SequenceStatus.AnalyzedLight }
? reconciled with { Status = reconciled.Status & ~(SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt | SequenceStatus.ProxiesBuilt) }
: null,
cancellationToken).ConfigureAwait(false);
bytes = null;
@@ -208,7 +215,23 @@ public sealed class ArchiveIndexer
await SyncAsync(archive, sequence, manifest, cancellationToken).ConfigureAwait(false);
}
locations.Set(manifest.Id, folder.RelativeFolder);
return bytes;
return (manifest.Id, bytes);
}
/// <summary>
/// The sequences among <paramref name="locations"/> created without photos that still wait for their first frame
/// (<see cref="ArchiveIngest.AwaitsFolder"/>). Their empty folder is not the archive root: scans do not adopt the root
/// under their id, a rebuild keeps them although they have no sidecar yet, and orphan checks do not count them missing.
/// </summary>
internal async Task<HashSet<Guid>> AwaitingFolderAsync(ArchivePaths paths, IEnumerable<SequenceLocation> locations, CancellationToken cancellationToken)
{
var awaiting = new HashSet<Guid>();
foreach (var location in locations.Where(l => l.Folder.Length == 0))
{
if (await _db.Sequences.GetAsync(location.Id, cancellationToken).ConfigureAwait(false) is { } sequence && ArchiveIngest.AwaitsFolder(sequence, paths))
awaiting.Add(sequence.Id);
}
return awaiting;
}
/// <summary>The index holds a project for this sequence and other frames than the sidecar: its positions may move.</summary>
@@ -261,16 +284,21 @@ public sealed class ArchiveIndexer
UpdatedAt = DateTimeOffset.UtcNow,
};
/// <summary>Rebuild only: rows whose folder no longer holds a sidecar leave the index (their files are untouched).</summary>
/// <summary>
/// Rebuild only: rows whose folder no longer holds a sidecar leave the index (their files are untouched). A sequence
/// waiting for its first frame has no sidecar yet and stays.
/// </summary>
private async Task<int> RemoveUnbackedAsync(Archive archive, ArchivePaths paths, IReadOnlyList<SequenceFolder> folders, Locations locations,
CancellationToken cancellationToken)
{
ArchiveVolume.EnsureWritable(paths);
var present = folders.Where(f => File.Exists(paths.Sequence(f.RelativeFolder).ManifestPath)).Select(f => f.RelativeFolder).ToHashSet(StringComparer.Ordinal);
var rows = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
var awaiting = await AwaitingFolderAsync(paths, rows, cancellationToken).ConfigureAwait(false);
var removed = 0;
foreach (var location in await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false))
foreach (var location in rows)
{
if (present.Contains(location.Folder) && locations.AtFolder(location.Folder) == location.Id) continue;
if (awaiting.Contains(location.Id) || (present.Contains(location.Folder) && locations.AtFolder(location.Folder) == location.Id)) continue;
if (await _db.Sequences.DeleteAsync(location.Id, cancellationToken).ConfigureAwait(false)) removed++;
await _db.Archives.DeleteFolderStateAsync(archive.Id, location.Folder, cancellationToken).ConfigureAwait(false);
}
@@ -71,7 +71,10 @@ public sealed class ArchiveMaintenance
{
var paths = new ArchivePaths(archive.RootPath);
if (ArchiveVolume.Probe(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(paths.Root, ArchiveAvailability.Offline);
var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
var all = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
// A sequence waiting for its first frame has no folder yet: none of it is missing, and the archive root is not its folder.
var awaiting = await _indexer.AwaitingFolderAsync(paths, all, cancellationToken).ConfigureAwait(false);
var locations = all.Where(l => !awaiting.Contains(l.Id)).ToList();
var sequences = new List<SequenceOrphans>();
var missing = new List<SequenceLocation>();
foreach (var location in locations)
@@ -91,7 +94,10 @@ public sealed class ArchiveMaintenance
return new OrphanReport(sequences, missing, unindexed);
}
/// <summary>Drops index rows of sequences whose sidecar is gone (an orphans fix action); rows whose sidecar is back are kept.</summary>
/// <summary>
/// Drops index rows of sequences whose sidecar is gone (an orphans fix action); rows whose sidecar is back are kept, and
/// so are sequences waiting for their first frame (<see cref="ArchiveIngest.AwaitsFolder"/>), which have none yet.
/// </summary>
public async Task<int> RemoveMissingSequencesAsync(Archive archive, IReadOnlyList<Guid> sequenceIds, CancellationToken cancellationToken = default)
{
var paths = new ArchivePaths(archive.RootPath);
@@ -100,7 +106,7 @@ public sealed class ArchiveMaintenance
foreach (var id in sequenceIds)
{
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { } sequence || sequence.ArchiveId != archive.Id) continue;
if (File.Exists(paths.Sequence(sequence.Folder).ManifestPath)) continue;
if (File.Exists(paths.Sequence(sequence.Folder).ManifestPath) || ArchiveIngest.AwaitsFolder(sequence, paths)) continue;
if (await _db.Sequences.DeleteAsync(id, cancellationToken).ConfigureAwait(false)) removed++;
await _db.Archives.DeleteFolderStateAsync(archive.Id, sequence.Folder, cancellationToken).ConfigureAwait(false);
}
+2 -2
View File
@@ -54,8 +54,8 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <summary>Handlers for scan, rebuild, verify, import, thumbs, proxies and maintenance jobs; register them on the <see cref="JobEngine"/>.</summary>
public IReadOnlyList<IJobHandler> CreateJobHandlers() =>
[
new ScanJobHandler(_db, Indexer, JobKind.Scan),
new ScanJobHandler(_db, Indexer, JobKind.Rebuild),
new ScanJobHandler(_db, Indexer, JobKind.Scan, _writer.Options.ImagesAfterScan),
new ScanJobHandler(_db, Indexer, JobKind.Rebuild, _writer.Options.ImagesAfterScan),
new VerifyJobHandler(_db, Verifier),
new ImportJobHandler(_db, Imports),
new ImageJobHandler(_db, Images, JobKind.Thumbs),
+5 -3
View File
@@ -44,7 +44,7 @@ public sealed class ArchiveVerifier
{
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var targets = await TargetsAsync(archive, sequenceIds, cancellationToken).ConfigureAwait(false);
var targets = await TargetsAsync(archive, paths, sequenceIds, cancellationToken).ConfigureAwait(false);
var bytesTotal = targets.Sum(t => t.TotalBytes);
var bytesDone = targets.Take(resume.Sequence).Sum(t => t.TotalBytes);
long checkedFrames = 0, ok = 0, hashed = 0;
@@ -82,13 +82,15 @@ public sealed class ArchiveVerifier
return new VerifyReport(targets.Count, checkedFrames, ok, hashed, problems);
}
private async Task<List<Sequence>> TargetsAsync(Archive archive, IReadOnlyList<Guid>? sequenceIds, CancellationToken cancellationToken)
/// <summary>The sequences to check; one waiting for its first frame (<see cref="ArchiveIngest.AwaitsFolder"/>) has no sidecar to check yet.</summary>
private async Task<List<Sequence>> TargetsAsync(Archive archive, ArchivePaths paths, IReadOnlyList<Guid>? sequenceIds, CancellationToken cancellationToken)
{
var ids = sequenceIds ?? (await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false)).Select(l => l.Id).ToList();
var targets = new List<Sequence>(ids.Count);
foreach (var id in ids)
{
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } s && s.ArchiveId == archive.Id) targets.Add(s);
if (await _db.Sequences.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } s && s.ArchiveId == archive.Id && !ArchiveIngest.AwaitsFolder(s, paths))
targets.Add(s);
}
return targets;
}
@@ -1,7 +1,9 @@
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Jobs;
using Titano.Data.Processing;
using Titano.Data.Repositories;
namespace Titano.Data.Archiving.Jobs;
@@ -18,9 +20,12 @@ internal static class JobArchive
/// <see cref="JobKind.Scan"/> (incremental, or full with <see cref="ScanParameters.Full"/>) and
/// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:&lt;folder&gt;</c>, the last folder indexed. When anything was
/// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are
/// queued for it, and for a background deep analysis too when <see cref="ScanParameters.DeepAnalysis"/> asks.
/// queued for it, and for a background deep analysis too when <see cref="ScanParameters.DeepAnalysis"/> asks. On the
/// server (<paramref name="imagesAfterScan"/>, <see cref="ArchiveServiceOptions.ImagesAfterScan"/>) the sequences it indexed
/// without thumbnails or proxies are queued for them too, as after an upload. Sequences waiting for their first frame
/// (<see cref="ArchiveIngest.AwaitsFolder"/>) have nothing to analyse or draw yet and are left out.
/// </summary>
internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer, JobKind kind) : IJobHandler
internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer, JobKind kind, bool imagesAfterScan = false) : IJobHandler
{
private const string Prefix = "after:";
@@ -42,9 +47,47 @@ internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer,
// A resumed scan may have indexed its folders before the interruption.
if (summary.Indexed > 0 || resume is not null)
{
var unanalysed = await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false);
var awaiting = await indexer.AwaitingFolderAsync(new ArchivePaths(archive.RootPath),
await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation).ConfigureAwait(false), context.Cancellation).ConfigureAwait(false);
var unanalysed = (await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false))
.Where(id => !awaiting.Contains(id)).ToList();
await AnalysisFollowUp.QueueAsync(db, context, unanalysed).ConfigureAwait(false);
if (kind == JobKind.Scan && parameters.DeepAnalysis) await AnalysisFollowUp.QueueDeepAsync(db, context, unanalysed).ConfigureAwait(false);
if (imagesAfterScan)
{
var resumed = resume is not null;
await QueueImagesAsync(context, archive, JobKind.Thumbs, SequenceStatus.ThumbsBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false);
// An archive whose policy makes no proxies would get a pass that does nothing.
if (archive.ProxyLongEdge != ProxyPolicy.Disabled)
await QueueImagesAsync(context, archive, JobKind.Proxies, SequenceStatus.ProxiesBuilt, summary.Sequences, resumed, awaiting).ConfigureAwait(false);
}
}
}
/// <summary>
/// Queues one background <paramref name="pass"/> (thumbnails or proxies) of the sequences this run indexed whose
/// <paramref name="built"/> flag is clear: new and adopted sequences, and those whose photos changed (the scan clears the
/// flag then). After a resumed run, which may have indexed sequences before the interruption, every sequence of the
/// archive without the flag but those in <paramref name="awaiting"/>. Sequences already waiting in a queued pass of that
/// kind are left out.
/// </summary>
private async Task QueueImagesAsync(JobContext context, Archive archive, JobKind pass, SequenceStatus built, IReadOnlyList<Guid> indexed,
bool resumed, IReadOnlySet<Guid> awaiting)
{
var missing = new HashSet<Guid>();
var query = new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = built, Sort = SequenceSort.Oldest, Limit = 1000 };
do
{
var page = await db.Sequences.ListAsync(query, context.Cancellation).ConfigureAwait(false);
missing.UnionWith(page.Items.Select(s => s.Id));
query = query with { Cursor = page.NextCursor };
}
while (query.Cursor is not null);
missing.ExceptWith(awaiting);
var waiting = (await db.Jobs.ListQueuedAsync([pass], 1000, context.Cancellation).ConfigureAwait(false)).SelectMany(j => j.TargetIds).ToHashSet();
var targets = (resumed ? missing : indexed.Where(missing.Contains)).Where(id => !waiting.Contains(id)).Distinct().ToList();
if (targets.Count == 0) return;
var request = pass == JobKind.Thumbs ? ArchiveJobs.Thumbnails(targets, context.Job.TargetLabel) : ArchiveJobs.Proxies(targets, context.Job.TargetLabel);
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
}
}
@@ -17,6 +17,13 @@ public sealed record ArchiveServiceOptions
public TimeSpan LeaseWait { get; init; } = TimeSpan.FromMinutes(2);
public TimeSpan LeaseDuration { get; init; } = LeaseFile.DefaultDuration;
/// <summary>
/// Scans queue thumbnails and proxies of the sequences they index without them, as an upload does (the server, whose
/// clients load both from it: BRIEF §4.3, §14.4). The desktop decodes its thumbnails on demand and makes proxies when
/// asked.
/// </summary>
public bool ImagesAfterScan { get; init; }
}
/// <summary>