fix(editor): read inserted frames before a render embeds the project

A render queued before the editor had seen frames inserted under it (a sync
download, an import of earlier photos, a scan without an event) embedded the
project's positions in the old frame order. Render now checks first that the
frames read are still the sequence's (ISequenceSource.FramesCurrentAsync: the
row's frames version on this PC, the manifest on a server). On this PC the
sequence is read again and the positions follow the frames; a server
sequence whose frames changed turns outdated and the render is not queued.

Reads of the sequence no longer overlap: a read waits for the one under way,
saves that meet new frames read them through the same slot, and they save
the project as it is once its positions followed. The frame on screen stays
on its photo when frames are inserted or removed before it.

Tests: the event-loss test waits for the listener's subscription before
dropping the stream, and the conflict tests flush once more after the
choice when a retry started before it was still failing.

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 19:59:45 +00:00
1 parent 99a0f37973
commit 827b224ee3
11 files changed
+351 -31

No files matched your search

+32 -4
View File
@@ -77,6 +77,9 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon
{
private readonly SyntheticFrameSource _pixels = new(sequence);
/// <summary>The frames the session read last (opened with, or loaded since).</summary>
private IReadOnlyList<Frame> _read = content.Frames;
public ProjectSettings Stored { get; set; } = content.Project;
public SequenceContent Content { get; set; } = content;
@@ -114,11 +117,36 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon
/// <summary>Thrown by the next load (the sequence read again after a job).</summary>
public Exception? FailNextLoad { get; set; }
public Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
/// <summary>Awaited by the next load once it has read the sequence (a read that is slow to complete).</summary>
public Task? NextLoadGate { get; set; }
/// <summary>Times the sequence was read (<see cref="LoadAsync"/>).</summary>
public int Loads { get; private set; }
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
{
if (FailNextLoad is not { } failure) return Task.FromResult(Content with { Project = Stored });
FailNextLoad = null;
return Task.FromException<SequenceContent>(failure);
if (FailNextLoad is { } failure)
{
FailNextLoad = null;
throw failure;
}
Loads++;
var content = Content with { Project = Stored };
if (NextLoadGate is { } gate)
{
NextLoadGate = null;
await gate;
}
_read = content.Frames;
return content;
}
/// <summary>Whether <see cref="Content"/> holds the frames read last; a server sequence becomes outdated when not.</summary>
public Task<bool> FramesCurrentAsync(CancellationToken cancellationToken)
{
var current = _read.Select(f => f.Id).SequenceEqual(Content.Frames.Select(f => f.Id));
if (!current && IsRemote) MarkOutdated();
return Task.FromResult(current);
}
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
@@ -151,6 +151,89 @@ public sealed class EditorSessionTests
}
}
[Test]
public async Task ARenderAfterFramesWereInsertedEmbedsThePositionsOfTheFramesTheUserChose()
{
var (session, source) = OpenShort();
await using (session)
{
Assert.True(session.SetExcluded([3], true));
Assert.True(session.SetHero(4));
Assert.True(await session.FlushAsync());
var frames = session.Content.Frames;
// Two earlier photos are inserted and the index moves the stored positions; the user renders without an edit.
InsertEarlier(source, 2);
source.Stored = source.Stored with { ExcludedFrames = [5], HeroFrame = 6 };
await session.EnsureFramesAsync();
var requests = session.RenderRequests(session.Project.Export);
Assert.Equal(frames.Count + 2, session.Content.Count, "the frames were read again");
var parameters = JsonSerializer.Deserialize(requests[0].ParametersJson!, ProtocolJson.Default.RenderJobParameters)!;
var embedded = ProjectSettings.FromJson(parameters.SettingsJson!);
Assert.SequenceEqual([5], embedded.ExcludedFrames);
Assert.Equal(6, embedded.HeroFrame);
Assert.Equal(frames[3].Id, session.Content.Frames[embedded.ExcludedFrames[0]].Id);
Assert.Equal(frames[4].Id, session.Content.Frames[embedded.HeroFrame!.Value].Id);
Assert.True(session.Undo());
Assert.Null(session.Project.HeroFrame);
Assert.SequenceEqual([5], session.Project.ExcludedFrames, "undo steps name the same frames");
// Frames that did not change are not read again.
var loads = source.Loads;
await session.EnsureFramesAsync();
Assert.Equal(loads, source.Loads);
}
}
[Test]
public async Task AServerSequenceWhoseFramesChangedIsOutdatedBeforeItsRender()
{
var sequence = EditorFixture.Sequence(12);
var content = EditorFixture.Content(sequence, deep: false);
var source = new FakeSequenceSource(sequence, content) { IsRemote = true };
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
InsertEarlier(source, 1);
await session.EnsureFramesAsync();
Assert.True(source.IsOutdated);
Assert.True(session.IsReadOnly);
Assert.Equal(0, source.Loads, "its proxies are not the server's frames: nothing is read");
Assert.Equal(12, session.Content.Count);
}
}
[Test]
public async Task ReadsThatOverlapFollowTheFramesInTheOrderTheyWereRead()
{
var (session, source) = OpenShort();
await using (session)
{
Assert.True(session.SetExcluded([3], true));
Assert.True(await session.FlushAsync());
var frames = session.Content.Frames;
// A job ends after an earlier photo was inserted, and its read of the sequence is slow to complete.
InsertEarlier(source, 1);
source.Stored = source.Stored with { ExcludedFrames = [4] };
var slow = new TaskCompletionSource();
source.NextLoadGate = slow.Task;
var first = session.ReloadAsync();
// Another job ends after two more were inserted: its read waits for the first one and follows its frames.
InsertEarlier(source, 2);
source.Stored = source.Stored with { ExcludedFrames = [6] };
var second = session.ReloadAsync();
slow.SetResult();
await Task.WhenAll(first, second);
Assert.Equal(frames.Count + 3, session.Content.Count);
Assert.SequenceEqual([6], session.Project.ExcludedFrames);
Assert.Equal(frames[3].Id, session.Content.Frames[6].Id);
}
}
/// <summary>A short sequence without its analysis, whose frame ids are all different (the synthetic ids repeat every 64 frames).</summary>
private static (EditorSession Session, FakeSequenceSource Source) OpenShort()
{
@@ -14,6 +14,7 @@ using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Advice;
using Titano.Core.Analysis;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Model;
@@ -299,6 +300,36 @@ public sealed class EditorSmokeTests
}
});
/// <summary>
/// Frames inserted under the editor (a sync download, an import of earlier photos) move the frame on screen with its
/// photo: what the frame actions (Exclude, Set hero, a keyframe) apply to stays the photo the user looks at.
/// </summary>
[Test]
public Task TheFrameOnScreenStaysWhenFramesAreInsertedBeforeIt() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var content = EditorFixture.Content(EditorFixture.Sunset, deep: false);
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
var editor = new EditorViewModel(app.Shell, new EditorSession(source, content, []), [], EncoderHost.Client);
await using (editor)
{
editor.CurrentIndex = 5;
var shown = content.Frames[5].Id;
// An earlier photo arrives and the last frame goes: as many frames as before, each one place later.
var first = content.Frames[0];
IReadOnlyList<Titano.Core.Model.Frame> frames =
[.. new[] { first with { Id = Guid.CreateVersion7(), CapturedAt = first.CapturedAt!.Value.AddMinutes(-1) } }.Concat(content.Frames.SkipLast(1))
.Select((f, i) => f with { Index = i })];
source.Content = content with { Frames = frames, Light = LightAnalyzer.Analyze(frames) };
await editor.Session.ReloadAsync();
Assert.Equal(6, editor.CurrentIndex);
Assert.Equal(shown, editor.Session.Content.Frames[editor.CurrentIndex].Id);
Assert.Equal(6, editor.Frames.Selected?.Index);
}
});
/// <summary>The measuring tool of each section has content.</summary>
private static void ExpectMeasure(SequenceView view, EditorTab tab)
{
@@ -18,6 +18,7 @@ namespace Titano.App.Tests.Editor;
internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Guid> frames) : IRemoteSequenceApi
{
private readonly Lock _gate = new();
private readonly TaskCompletionSource _subscribed = new(TaskCreationOptions.RunContinuationsAsynchronously);
private Channel<ServerEvent> _events = Channel.CreateUnbounded<ServerEvent>();
/// <summary>The server's frames in order (another list when frames are added or removed on the server).</summary>
@@ -55,6 +56,9 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Gui
public bool Disposed { get; private set; }
/// <summary>Completes once the editor's listener has opened an event stream (the stream open then is the one it reads).</summary>
public Task Subscribed => _subscribed.Task;
/// <summary>A job of the server, as <c>GET /jobs/{id}</c> returns it.</summary>
public JobDto Job(Guid id, string kind, string state, Guid? target = null, long done = 0, long total = 0) =>
new(id, kind, [target ?? sequence.Id], sequence.DisplayTitle, state, "user", done, total, null, null, null, null, 0, null, DateTimeOffset.UtcNow,
@@ -168,6 +172,7 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Gui
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
var events = Volatile.Read(ref _events).Reader;
_subscribed.TrySetResult();
while (await events.WaitToReadAsync(cancellationToken))
{
while (events.TryRead(out var e)) yield return e;
@@ -156,17 +156,7 @@ public sealed class ProjectStoreTests(TestContext context)
// Three photos taken before the others are found in the folder (a sync download, an import or a scan
// inserts them the same way): the index moves the stored positions with their frames.
var sequence = EditorFixture.Sequence(3);
var first = content.Frames[0].CapturedAt!.Value;
for (var i = 0; i < 3; i++)
{
using var image = sequence.Render(i);
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i] with { CapturedAt = first.AddMinutes(i - 3) });
File.WriteAllBytes(Path.Combine(root, "Synthetic", $"EARLY_{i + 1}.JPG"),
JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
}
var archive = (await db.Archives.GetAsync(content.Sequence.ArchiveId, context.Cancellation))!;
await new ArchiveService(db, options).Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
await InsertEarlierAsync(db, root, content, options, 3);
var moved = ProjectSettings.FromJson((await db.Sequences.GetAsync(sequenceId))!.SettingsJson!);
Assert.SequenceEqual([8], moved.ExcludedFrames);
Assert.Equal(9, moved.HeroFrame);
@@ -195,6 +185,36 @@ public sealed class ProjectStoreTests(TestContext context)
}
}
[Test]
public async Task ARenderAfterEarlierPhotosArriveEmbedsTheFramesTheUserChose()
{
var (db, sequenceId, root) = await ArchiveAsync(10);
await using (db)
{
var options = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) };
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null, options);
var content = await source.LoadAsync(context.Cancellation);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(session.SetExcluded([5], true));
Assert.True(await session.FlushAsync());
Assert.True(await source.FramesCurrentAsync(context.Cancellation));
// Earlier photos arrive while the editor is open; the user renders without another edit.
await InsertEarlierAsync(db, root, content, options, 3);
Assert.False(await source.FramesCurrentAsync(context.Cancellation));
await session.EnsureFramesAsync(context.Cancellation);
var request = session.RenderRequests(session.Project.Export)[0];
Assert.True(await source.FramesCurrentAsync(context.Cancellation));
Assert.Equal(13, session.Content.Count);
var embedded = ProjectSettings.FromJson(ProcessingJobs.ReadRender(request.ParametersJson).Parameters.SettingsJson!);
Assert.SequenceEqual([content.Frames[5].Id], embedded.ExcludedFrames.Select(i => session.Content.Frames[i].Id), "the photo the user excluded");
}
}
}
[Test]
public async Task ASaveThatDoesNotReachTheIndexThrows()
{
@@ -249,6 +269,25 @@ public sealed class ProjectStoreTests(TestContext context)
}
}
/// <summary>
/// Writes <paramref name="count"/> photos taken before the sequence's first frame into its folder and scans the
/// archive: they are inserted in front, and the index moves the stored positions with their frames.
/// </summary>
private async Task InsertEarlierAsync(TitanoDatabase db, string root, SequenceContent content, ArchiveServiceOptions options, int count)
{
var sequence = EditorFixture.Sequence(count);
var first = content.Frames[0].CapturedAt!.Value;
for (var i = 0; i < count; i++)
{
using var image = sequence.Render(i);
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i] with { CapturedAt = first.AddMinutes(i - count) });
File.WriteAllBytes(Path.Combine(root, "Synthetic", $"EARLY_{i + 1}.JPG"),
JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
}
var archive = (await db.Archives.GetAsync(content.Sequence.ArchiveId, context.Cancellation))!;
await new ArchiveService(db, options).Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
}
/// <summary>A temporary archive with one adopted folder of synthetic JPEGs, indexed.</summary>
private async Task<(TitanoDatabase Db, Guid SequenceId, string Root)> ArchiveAsync(int frames)
{
@@ -159,7 +159,7 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
Assert.Same(conflict, session.Conflict);
Assert.False(await session.FlushAsync(), "the change waits for the choice");
Assert.True(session.ResolveConflict(keepMine: true));
Assert.True(await session.FlushAsync());
Assert.True(await FlushAfterChoiceAsync(session));
Assert.Null(session.Conflict);
var stored = ProjectSettings.FromJson(api.SettingsJson!);
@@ -181,7 +181,7 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
await found.Task.WaitAsync(TimeSpan.FromSeconds(10));
Assert.True(session.ResolveConflict(keepMine: false));
Assert.True(await session.FlushAsync());
Assert.True(await FlushAfterChoiceAsync(session));
var stored = ProjectSettings.FromJson(api.SettingsJson!);
Assert.Equal((0.3, -0.2, (int?)2), (stored.Exposure.ExposureOffsetEv, stored.Camera.OffsetY, stored.HeroFrame),
"the server's values where both changed; the editor's other change is saved");
@@ -469,6 +469,8 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
await using (source)
{
await source.LoadAsync(context.Cancellation);
// The listener reads the stream open when it subscribes: it must have subscribed for the drop to reach it.
await api.Subscribed.WaitAsync(TimeSpan.FromSeconds(10), context.Cancellation);
api.DropEvents();
api.Frames = [.. remote.Frames.Skip(1).Select(f => f.Id)];
api.FramesVersion = 2;
@@ -478,6 +480,30 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
}
[Test]
public async Task ARenderIsRefusedOnceTheServersFramesChangedWithoutAnEvent()
{
var (source, api, remote) = Open();
await using (source)
{
await source.LoadAsync(context.Cancellation);
// A new frames version over the same frames: they are still this PC's.
api.FramesVersion = 2;
Assert.True(await source.FramesCurrentAsync(context.Cancellation));
Assert.False(source.IsOutdated);
// A server scan inserts an earlier photo and sends no event: the check before a render finds it.
api.Frames = [Guid.CreateVersion7(), .. remote.Frames.Select(f => f.Id)];
api.FramesVersion = 3;
Assert.False(await source.FramesCurrentAsync(context.Cancellation));
Assert.True(source.IsOutdated);
var refused = await Assert.ThrowsAsync<ProxiesOutdatedException>(() =>
source.SubmitAsync(ProcessingJobs.Render(remote.Sequence, new ExportSettings(), 1920, 1080), context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.FramesChanged"), refused.Message);
Assert.Empty(api.Posted);
}
}
[Test]
public async Task AConflictFoundOnOtherFramesIsNotMergedOntoThem()
{
@@ -591,6 +617,13 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
lock (seen) return seen[^1];
}
/// <summary>
/// Stores the change after the user settled a conflict. The test's thread is not the saver's: a retry that started
/// before the choice may still be failing on the old basis, and a flush that arrives meanwhile reports it, so one more
/// flush (on the UI thread the choice cannot land inside a retry) is answered by the attempt made after the choice.
/// </summary>
private static async Task<bool> FlushAfterChoiceAsync(EditorSession session) => await session.FlushAsync() || await session.FlushAsync();
private static async Task WaitAsync(Func<bool> condition)
{
for (var i = 0; i < 200; i++)