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

@@ -17,6 +17,7 @@ using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Archiving;
using Titano.Data.Archiving.Jobs;
using Titano.Data.Jobs;
using Titano.Data.Processing;
using Titano.Data.Processing.Jobs;
using Titano.Data.Repositories;
@@ -254,6 +255,172 @@ public sealed class AnalysisJobTests(TestContext context)
Assert.Equal(advice, await AutoValuesAsync());
}
[Test]
public async Task FramesAddedDuringADeepAnalysisKeepTheLightAnalysisOfTheFramesAsTheyAre()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
var folder = fx.Folder(sequence);
await fx.StartEngineAsync(workers: 2);
// A deep analysis starts on twelve frames; while it runs, a thirteenth photo this host cannot decode is indexed,
// and a light analysis on the other worker analyses all thirteen.
fx.Decoder.HoldFrame(0);
var deep = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
fx.Decoder.Tiers[ProcessingFixture.FileName(12)] = new FileTier(ImageFileFormat.Jpeg, DecodeTier.Unavailable, null, "test", 0, 0);
await fx.AddAsync(Flickering(13), first: 12);
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.WaitForAsync(light.Id, JobState.Done);
var analysed = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
var advice = await ProjectJsonAsync(fx, folder);
Assert.Equal(13, analysed.FrameCount);
Assert.Contains("13", ProjectSettings.FromJson(advice).Timing.FrameRate.ReasonArgs!);
Assert.True(analysed.Status.HasFlag(SequenceStatus.HasWarnings), "the photo this host cannot decode is a warning");
fx.Decoder.Release();
var done = await fx.WaitForAsync(deep.Id, JobState.Done);
// The deep pass measured twelve of them: it saved its report but applied none of it (neither the Auto values nor
// the status and warnings of twelve frames), and queued a light analysis of the frames as they are.
Assert.Contains(Loc.L("Advisor.Log.FramesChanged", sequence.DisplayTitle), done.LogTail);
Assert.Equal(12, SequenceAnalyser.ReadReport(folder, 12)!.FrameCount);
var again = Assert.Contains(await LightJobsAsync(fx), j => j.Id != light.Id);
await fx.WaitForAsync(again.Id, JobState.Done);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal((analysed.WarningCount, analysed.Status), (row.WarningCount, row.Status));
Assert.Null(row.AnalysisJson);
Assert.Equal(advice, await ProjectJsonAsync(fx, folder));
}
[Test]
public async Task AnAnalysisOvertakenWhileALightAnalysisWaitsRecordsAndThatOneReplacesIt()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
var folder = fx.Folder(sequence);
await fx.StartEngineAsync();
// A deep analysis starts on twelve frames on the only worker; while it runs a thirteenth photo is indexed, and its
// light analysis waits in the queue, as during an upload burst.
fx.Decoder.HoldFrame(0);
var deep = await fx.EnqueueAsync(ProcessingJobs.DeepAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
await fx.AddAsync(Flickering(13), first: 12);
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
fx.Decoder.Hold = null;
fx.Decoder.Release();
// The light analysis waits on the new photo's probe, so what the deep pass left can be seen.
fx.Decoder.HoldProbeOf(12);
var done = await fx.WaitForAsync(deep.Id, JobState.Done);
// The deep pass records the analysis of the frames it read meanwhile, and queues nothing more.
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Contains(Loc.L("Advisor.Log.DeepDone", sequence.DisplayTitle, 12, row.WarningCount), done.LogTail);
Assert.False(done.LogTail!.Contains(Loc.L("Advisor.Log.FramesChanged", sequence.DisplayTitle), StringComparison.Ordinal), done.LogTail);
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
Assert.SequenceEqual([light.Id], (await LightJobsAsync(fx)).Select(j => j.Id));
// The light analysis that waited replaces it with the analysis of all thirteen.
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
fx.Decoder.Release();
await fx.WaitForAsync(light.Id, JobState.Done);
Assert.Contains("13", ProjectSettings.FromJson(await ProjectJsonAsync(fx, folder)).Timing.FrameRate.ReasonArgs!);
}
[Test]
public async Task ALightAnalysisOvertakenByAScanMarksNothingAnalysedAndRunsAgain()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
var folder = fx.Folder(sequence);
await fx.StartEngineAsync();
// A light analysis reads twelve frames; before it records, a scan indexes a thirteenth photo copied into the folder.
fx.Decoder.HoldProbeOf(0);
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
await fx.AddAsync(Flickering(13), first: 12);
fx.Decoder.Release();
// The light analysis that follows waits on the new photo's probe, so what the first one left can be seen.
fx.Decoder.HoldProbeOf(12);
var done = await fx.WaitForAsync(light.Id, JobState.Done);
Assert.Contains(Loc.L("Advisor.Log.FramesChanged", sequence.DisplayTitle), done.LogTail);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(13, row.FrameCount);
Assert.False(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.False(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
Assert.False(ProjectSettings.FromJson(await ProjectJsonAsync(fx, folder)).Timing.FrameRate.HasAdvice, "no advice for twelve frames");
var again = Assert.Contains(await LightJobsAsync(fx), j => j.Id != light.Id);
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
fx.Decoder.Release();
await fx.WaitForAsync(again.Id, JobState.Done);
row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.True(ManifestStore.ReadSequence(folder.ManifestPath).Status.HasFlag(SequenceStatus.AnalyzedLight), "sidecar status");
Assert.Contains("13", ProjectSettings.FromJson(await ProjectJsonAsync(fx, folder)).Timing.FrameRate.ReasonArgs!);
}
[Test]
public async Task AnAnalysisOfPhotosAnotherTitanoChangedLeavesWhatThatTitanoRecorded()
{
await using var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Flickering(12));
var folder = fx.Folder(sequence);
await fx.StartEngineAsync();
// A server sharing this desktop's archive, with its own index and analysis.
await using var serverDb = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("server"), "titano.db")), fx.Ct);
var serverOptions = fx.Processing.Options with
{
Archive = new ArchiveServiceOptions { Decoder = new ImageDecoder([new ManagedDecoderProvider()]), Owner = "server", LeaseWait = TimeSpan.FromSeconds(20) },
};
var server = new ArchiveService(serverDb, serverOptions.Archive);
var archive = await server.OpenAsync(fx.Archive.Archive.RootPath, fx.Ct);
await server.Indexer.ScanAsync(archive, ScanMode.Incremental, null, _ => ValueTask.CompletedTask, fx.Ct);
await using var serverEngine = new JobEngine(serverDb, new ProcessingService(serverDb, serverOptions).CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "server", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await serverEngine.StartAsync(fx.Ct);
// A light analysis here reads twelve frames; before it records, the server takes a thirteenth photo and analyses
// the sequence as it is now, in the shared sidecar and project.
fx.Decoder.HoldProbeOf(0);
var light = await fx.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]));
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
var staged = fx.Archive.Stage(new DateTime(2024, 6, 21, 19, 2, 0), seed: 90);
await server.Ingest.CommitAsync(new IngestRequest(archive.Id, sequence.Id, null, null, staged.Path, "IMG_0013.JPG", staged.Size, staged.Sha256, null, null),
fx.Ct);
var analysed = await serverEngine.EnqueueAsync(ProcessingJobs.LightAnalysis([sequence.Id]), cancellationToken: fx.Ct);
for (var until = DateTime.UtcNow.AddSeconds(60); (await serverDb.Jobs.GetAsync(analysed.Id, fx.Ct))!.State != JobState.Done;)
{
Assert.True(DateTime.UtcNow < until, "the server's light analysis ends");
await Task.Delay(20, fx.Ct);
}
var advice = await ProjectJsonAsync(fx, folder);
Assert.Contains("13", ProjectSettings.FromJson(advice).Timing.FrameRate.ReasonArgs!);
var status = ManifestStore.ReadSequence(folder.ManifestPath).Status;
Assert.True(status.HasFlag(SequenceStatus.AnalyzedLight), "the server's status");
fx.Decoder.Release();
var done = await fx.WaitForAsync(light.Id, JobState.Done);
// This index still holds twelve frames: the analysis here records nothing over the server's, and queues nothing.
Assert.Contains(Loc.L("Advisor.Log.FramesChangedElsewhere", sequence.DisplayTitle), done.LogTail);
Assert.Equal(advice, await ProjectJsonAsync(fx, folder));
Assert.Equal(status, ManifestStore.ReadSequence(folder.ManifestPath).Status);
var row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(12, row.FrameCount);
Assert.False(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.SequenceEqual([light.Id], (await LightJobsAsync(fx)).Select(j => j.Id));
// The next scan here indexes the photo with the server's analysis, which a desktop keeps.
Assert.Contains(sequence.Id, (await fx.Archive.ScanAsync()).Sequences);
row = (await fx.Db.Sequences.GetAsync(sequence.Id, fx.Ct))!;
Assert.Equal(13, row.FrameCount);
Assert.True(row.Status.HasFlag(SequenceStatus.AnalyzedLight), "index status");
Assert.Equal(advice, await ProjectJsonAsync(fx, folder));
}
[Test]
public async Task AFrameTheDeepAnalysisCouldNotReadIsReadAgainOnceItsProxyArrives()
{
@@ -612,6 +779,13 @@ public sealed class AnalysisJobTests(TestContext context)
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
}
private static async Task<IReadOnlyList<Job>> LightJobsAsync(ProcessingFixture fx) =>
(await fx.Db.Jobs.ListAsync(null, JobKind.LightAnalyse, 100, null, fx.Ct)).Items;
/// <summary>The project as <c>project.json</c> holds it (the defaults before any analysis wrote it).</summary>
private static async Task<string> ProjectJsonAsync(ProcessingFixture fx, SequencePaths folder) =>
(File.Exists(folder.ProjectPath) ? ProjectSettings.FromJson(await File.ReadAllTextAsync(folder.ProjectPath, fx.Ct)) : new ProjectSettings()).ToJson();
private static async Task<List<bool>> AnalysedAsync(ProcessingFixture fx, params Sequence[] sequences)
{
var analysed = new List<bool>();
@@ -126,6 +126,18 @@ internal sealed class GateDecoder : IImageDecoderProvider
Hold = ProcessingFixture.FileName(index);
}
/// <summary>File name whose tier probe waits until <see cref="Release"/> (a light analysis probes frames whose tier is
/// not known yet, and decodes nothing); null probes everything.</summary>
public string? HoldProbe { get; private set; }
/// <summary>Holds the next tier probe of frame <paramref name="index"/>'s file, as <see cref="HoldFrame"/> holds a decode.</summary>
public void HoldProbeOf(int index)
{
Holding = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_released = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
HoldProbe = ProcessingFixture.FileName(index);
}
/// <summary>Lets the held decode go on, as a slow read would.</summary>
public void Release() => _released.TrySetResult();
@@ -147,8 +159,16 @@ internal sealed class GateDecoder : IImageDecoderProvider
public FileTier Probe(string path, ImageFileFormat format) => Probe(path, format, null);
public FileTier Probe(string path, ImageFileFormat format, string? companion) =>
Tiers.TryGetValue(Path.GetFileName(path), out var tier) ? tier : _managed.Probe(path, format, companion);
public FileTier Probe(string path, ImageFileFormat format, string? companion)
{
var name = Path.GetFileName(path);
if (HoldProbe is { } hold && name == hold)
{
Holding.TrySetResult();
_released.Task.Wait(TimeSpan.FromSeconds(30));
}
return Tiers.TryGetValue(name, out var tier) ? tier : _managed.Probe(path, format, companion);
}
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
{
@@ -39,6 +39,12 @@ internal sealed class FakeSyncRemote : ISyncRemote
/// <summary>Proxy and thumbnail downloads fail with a server error.</summary>
public bool FailAssets { get; set; }
/// <summary>
/// Assets (frame id, kind) the sequence's flags offer that the server has not drawn yet: frames added since its last
/// thumbnail or proxy pass answer 404 until that pass ends, as the real endpoints do.
/// </summary>
public HashSet<(Guid Frame, string Kind)> Undrawn { get; } = [];
/// <summary>Proxies clients sent, by frame id (for sequences the server cannot decode).</summary>
public Dictionary<Guid, byte[]> SentProxies { get; } = [];
@@ -174,6 +180,7 @@ internal sealed class FakeSyncRemote : ISyncRemote
"original" when CorruptOnce == frameId => [.. frame.Bytes.Select(b => (byte)~b)],
"original" => frame.Bytes,
"proxy" or "thumb" when FailAssets => throw new TitanoApiException(HttpStatusCode.InternalServerError, new ApiError("internal", "failed")),
"proxy" or "thumb" when Undrawn.Contains((frameId, kind)) => throw NotFound(),
// A proxy a client or render node sent is served as soon as it is filed, like the manifest says.
"proxy" when SentProxies.TryGetValue(frameId, out var sent) => sent,
"proxy" when (sequence.Status & SequenceStatus.ProxiesBuilt) != 0 => frame.Proxy,
@@ -192,6 +192,45 @@ public sealed class SyncAgentTests(TestContext context)
Assert.Count(2, await DownloadsAsync(f));
}
[Test]
public async Task FramesTheServerHadNotDrawnAreFetchedAgainOnceItDid()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Construction cam", f.NewPhotos(2));
var engine = await f.StartEngineAsync();
await f.RefreshAsync();
var first = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Construction cam", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(first.Id, JobState.Done);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: true), engine, EventsOnly);
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
// A photo reaches the server, whose proxy flag stays set until its next proxy pass draws the photo: the refresh
// that follows the upload caches nothing for it.
var added = remote.AddFrame(f.NewPhotos(1)[0]);
f.Remote.Undrawn.UnionWith([(added.Id, "proxy"), (added.Id, "thumb")]);
await agent.RefreshAsync(f.Ct);
var refresh = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id);
await f.Archive.WaitForAsync(refresh.Id, JobState.Done);
Assert.Null(Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id)).Files[2]);
Assert.True((await f.EntryAsync("Construction cam")).Link!.ProxiesStale);
// Nothing is fetched again while the server's sequence stands still.
await agent.RefreshAsync(f.Ct);
Assert.Count(2, await DownloadsAsync(f));
// The pass draws the photo and records the sequence's state.
f.Remote.Undrawn.Clear();
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
await agent.RefreshAsync(f.Ct);
var drawn = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id && j.Id != refresh.Id);
await f.Archive.WaitForAsync(drawn.Id, JobState.Done);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual(remote.Frames.Select(r => (long)r.Proxy.Length), opened.Files.Select(file => new FileInfo(file!).Length));
Assert.False((await f.EntryAsync("Construction cam")).Link!.ProxiesStale);
await agent.RefreshAsync(f.Ct);
Assert.Count(3, await DownloadsAsync(f));
}
[Test]
public async Task AStandInDownloadThatFailedIsQueuedAgainAfterItsBackoff()
{
@@ -1,6 +1,8 @@
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Archiving;
using Titano.Data.Sync;
using Titano.Data.Tests.Archiving;
using Titano.Protocol;
using Titano.Protocol.Client;
using Titano.Testing;
@@ -289,6 +291,34 @@ public sealed class SyncServiceTests(TestContext context)
Assert.SequenceEqual(["sunset"], (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!.Tags);
}
[Test]
public async Task InfoTakenFromTheServerLeavesPhotosAnotherWriterAddedHereToTheNextScan()
{
await using var f = await SyncFixture.CreateAsync(context);
var photos = f.NewPhotos(2);
var local = await f.LocalAsync("Harbour", photos);
var remote = f.Remote.Add("Harbour", photos);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
await f.RefreshAsync();
// A desktop sharing this PC's archive imports a photo into the sequence: its own index follows the sidecar, this one not yet.
var (desktop, archive) = await f.Archive.OtherWriterAsync();
var staged = f.Archive.Stage(ArchiveFixture.Start.AddMinutes(10), seed: 90);
await desktop.Ingest.CommitAsync(new IngestRequest(archive.Id, local.Id, null, null, staged.Path, "IMG_0009.JPG", staged.Size, staged.Sha256, null, null),
f.Ct);
// The server's new title reaches this PC meanwhile, in its index and the sidecar.
await f.Remote.UpdateSequenceAsync(remote.Id, new UpdateSequenceRequest("Harbour at dusk", null, null, null, null, null), f.Ct);
await f.RefreshAsync();
var taken = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.Equal(("Harbour at dusk", 2), (taken.Title, taken.FrameCount));
// The next scan still finds the folder changed, and indexes the photo.
Assert.Contains(local.Id, (await f.Archive.ScanAsync()).Sequences);
var row = (await f.Db.Sequences.GetAsync(local.Id, f.Ct))!;
Assert.Equal(("Harbour at dusk", 3), (row.Title, row.FrameCount));
}
[Test]
public async Task TheSameEditOnBothSidesIsAgreedWithoutAConflict()
{
@@ -420,6 +420,41 @@ public sealed class SyncTransferTests(TestContext context)
Assert.False((await f.EntryAsync("Fog")).Link!.ProxiesStale);
}
[Test]
public async Task ACacheMadeBeforeTheServerDrewItsNewFramesStaysStaleUntilItHasTheirProxies()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Harbour", f.NewPhotos(2));
await f.RefreshAsync();
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
Assert.False((await f.EntryAsync("Harbour")).Link!.ProxiesStale);
// Two photos reach the server. Its proxy flag stays set until its next proxy pass, which has not drawn them yet:
// the first has its thumbnail only, the second nothing at all.
var added = f.NewPhotos(2).Select(photo => remote.AddFrame(photo)).ToList();
f.Remote.Undrawn.UnionWith([(added[0].Id, "proxy"), (added[1].Id, "proxy"), (added[1].Id, "thumb")]);
await f.RefreshAsync();
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual([remote.Frames[0].Proxy.Length, remote.Frames[1].Proxy.Length, 64], opened.Files.Take(3).Select(file => (int)new FileInfo(file!).Length));
Assert.Null(opened.Files[3]);
Assert.True((await f.EntryAsync("Harbour")).Link!.ProxiesStale, "a thumbnail or a missing file stands in for a proxy the server offers");
// The pass draws them: the frames stay as they were, the server's sequence records the pass.
f.Remote.Undrawn.Clear();
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
await f.RefreshAsync();
Assert.True((await f.EntryAsync("Harbour")).Link!.ProxiesStale);
job = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Harbour", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual(remote.Frames.Select(r => (long)r.Proxy.Length), opened.Files.Select(file => new FileInfo(file!).Length));
Assert.False((await f.EntryAsync("Harbour")).Link!.ProxiesStale);
}
[Test]
public async Task TheServersRendersAreFetchedIntoTheLocalExports()
{