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

+49 -10
View File
@@ -32,7 +32,10 @@ public sealed class EditorSession : IAsyncDisposable
private readonly ProjectSaver _saver;
private ProjectSettings _basis;
/// <summary>The sequence being read again (<see cref="ReloadAsync"/>) until its content is taken: saves wait for it.</summary>
/// <summary>
/// The sequence being read again (<see cref="BeginReadAsync"/>) until its content is taken: saves and other reads wait
/// for it.
/// </summary>
private Task _reading = Task.CompletedTask;
public EditorSession(ISequenceSource source, SequenceContent content, IReadOnlyList<EncoderCapability> codecs, TimeSpan? saveDelay = null)
@@ -209,15 +212,30 @@ public sealed class EditorSession : IAsyncDisposable
public Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken = default) => Source.SubmitAsync(request, cancellationToken);
/// <summary>
/// Makes the project's frame positions name the sequence's frames as they are now, before the project is taken along
/// (a render embeds it): frames inserted since the last read (a sync download, an import of earlier photos, a scan)
/// are read again and the positions follow them (<see cref="ReloadAsync"/>). A server sequence whose frames changed
/// becomes outdated instead (<see cref="ISequenceSource.IsOutdated"/>: read-only, its renders refused).
/// </summary>
public async Task EnsureFramesAsync(CancellationToken cancellationToken = default)
{
while (!_reading.IsCompleted) await _reading;
var current = await Source.FramesCurrentAsync(cancellationToken);
// A read that began meanwhile (a save that met the new frames) may have taken them already: it ends first.
while (!_reading.IsCompleted) await _reading;
if (!current && !IsRemote) await ReloadAsync(cancellationToken);
}
/// <summary>
/// Reads the sequence again (an analysis finished): new reports and advice, the frames with the project's positions
/// following them (<see cref="Follow"/>), the stored project merged into the open one. Saves wait until it is taken.
/// following them (<see cref="Follow"/>), the stored project merged into the open one. Saves wait until it is taken,
/// and a read waits for the one under way, so each follows the frames the one before it took.
/// </summary>
public async Task ReloadAsync(CancellationToken cancellationToken = default)
{
await _saver.FlushAsync();
var taken = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_reading = taken.Task;
var taken = await BeginReadAsync();
try
{
var content = await Source.LoadAsync(cancellationToken);
@@ -257,23 +275,34 @@ public sealed class EditorSession : IAsyncDisposable
/// Takes <paramref name="content"/> as the sequence. Frames inserted or removed since the last read (a sync download,
/// an import of earlier photos, a scan) moved the stored project's frame positions with their frames: the editor's
/// project, its undo and redo steps and its basis move the same way (<see cref="ProjectSettings.FollowFrames"/>), so
/// they keep naming the frames the user chose. Returns that move (none when the frames are the same).
/// they keep naming the frames the user chose. Call while the read is under way (<see cref="BeginReadAsync"/>).
/// </summary>
private Func<ProjectSettings, ProjectSettings> Follow(SequenceContent content)
private void Follow(SequenceContent content)
{
var before = Content.Frames.Select(f => f.Id).ToList();
(Content, Context, Advice, Presets) = Analyse(content, _codecs);
if (before.SequenceEqual(content.Frames.Select(f => f.Id))) return static project => project;
if (before.SequenceEqual(content.Frames.Select(f => f.Id))) return;
var after = content.Frames;
Log.Info("editor", $"The frames of {content.Sequence.DisplayTitle} changed while it was open; its frame positions follow them");
_basis = Move(_basis);
History.Remap(Move);
return Move;
ProjectSettings Move(ProjectSettings project) =>
NamesFrames(project) && ProjectSettings.FollowFrames(project.ToJson(), before, after) is { } moved ? ProjectSettings.FromJson(moved) : project;
}
/// <summary>
/// Waits for the read under way (two jobs that end together read the sequence one after the other), then marks a new
/// one under way until the returned source is completed.
/// </summary>
private async Task<TaskCompletionSource> BeginReadAsync()
{
while (!_reading.IsCompleted) await _reading;
var taken = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_reading = taken.Task;
return taken;
}
/// <summary>Exclusions, a hero, keyframes or frames waiting for their photos: positions that follow frames.</summary>
private static bool NamesFrames(ProjectSettings project) =>
project.ExcludedFrames.Count > 0 || project.HeroFrame is not null || project.Camera.Keyframes.Count > 0 || project.PendingFrames is { Count: > 0 };
@@ -334,8 +363,18 @@ public sealed class EditorSession : IAsyncDisposable
catch (FramesChangedException) when (attempt < FollowAttempts)
{
// Frames were inserted under the editor and the stored positions moved with them: the frames are read
// again, this edit's positions follow them too, and it is saved in the new order.
project = Follow(await Source.LoadAsync(CancellationToken.None))(project);
// again (after a read under way, whose move this edit's snapshot missed), the project's positions follow
// them, and the project as it is then, which contains this edit, is saved in the new order.
var taken = await BeginReadAsync();
try
{
Follow(await Source.LoadAsync(CancellationToken.None));
}
finally
{
taken.SetResult();
}
project = Project;
ContentChanged?.Invoke();
}
catch (ProjectConflictException ex)
+27 -1
View File
@@ -48,6 +48,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private readonly AsyncRelayCommand _cancelServerJob;
private PreviewRenderer _renderer;
private int _currentIndex;
/// <summary>The frame on screen: it stays on screen when frames are inserted or removed before it.</summary>
private Guid _currentFrameId;
private EditorTab _selectedTab;
private ImageSource? _previewImage;
private ImageSource? _originalImage;
@@ -111,6 +114,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Tabs = [Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), new ExportTab(this)];
_selectedTab = Exposure;
_currentIndex = session.Project.HeroFrame is { } hero && (uint)hero < (uint)FrameCount ? hero : 0;
_currentFrameId = FrameId(_currentIndex);
// Until the link is read (AttachJobsAsync), a sequence of this PC cannot send its renders.
_syncGate = session.IsRemote ? ExportSyncGate.Remote : ExportSyncGate.SignedOut;
RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))];
@@ -233,6 +237,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
set
{
var clamped = FrameCount == 0 ? 0 : int.Clamp(value, 0, FrameCount - 1);
_currentFrameId = FrameId(clamped);
if (!Set(ref _currentIndex, clamped)) return;
foreach (var tab in Tabs) tab.OnCurrentFrameChanged();
UpdateInfo();
@@ -515,6 +520,10 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// </summary>
public async Task RenderAsync(JobPriority priority, bool batch)
{
// The job embeds the project: its frame positions follow frames inserted since the editor read them first. A server
// sequence whose frames changed is outdated instead, and its toast says so and offers fresh proxies.
await Session.EnsureFramesAsync();
if (IsOutdated) return;
var export = batch ? RenderExport : RenderExport with { Batch = [] };
var requests = Session.RenderRequests(export);
foreach (var request in requests) await Session.SubmitAsync(request with { Priority = priority });
@@ -801,6 +810,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private void OnContentChanged()
{
// The frame on screen stays on screen, wherever frames inserted or removed before it put it (the tabs that reload
// below may seek meanwhile).
var shown = IndexOfFrame(_currentFrameId) ?? int.Min(CurrentIndex, int.Max(0, FrameCount - 1));
_renderer = new PreviewRenderer(Session.Content, Session.Source);
Planner = new ExportPlanner(Session.Content, _encoders, _host);
if (Thumbnails.Count != FrameCount) Thumbnails = new EditorThumbnails(Session.Source, FrameCount);
@@ -808,13 +820,27 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
foreach (var tab in Tabs) tab.OnContentChanged();
OnPropertyChanged(nameof(Summary));
OnPropertyChanged(nameof(FrameCount));
CurrentIndex = int.Min(CurrentIndex, int.Max(0, FrameCount - 1));
CurrentIndex = shown;
UpdateMarkers();
RequestCorrections();
RequestPlan();
RequestPreview(immediate: true);
}
/// <summary>The id of frame <paramref name="index"/>; empty when there is none.</summary>
private Guid FrameId(int index) => (uint)index < (uint)FrameCount ? Session.Content.Frames[index].Id : Guid.Empty;
/// <summary>Where frame <paramref name="id"/> is now; null when the sequence no longer has it.</summary>
private int? IndexOfFrame(Guid id)
{
var frames = Session.Content.Frames;
for (var i = 0; i < frames.Count; i++)
{
if (frames[i].Id == id) return i;
}
return null;
}
/// <summary>
/// The UI language changed: what the tabs keep in objects (chart legends and summaries, the Auto chips of the
/// settings), the timeline markers and the preview's info line are made again in the new language.
+8
View File
@@ -44,6 +44,14 @@ public interface ISequenceSource : IAsyncDisposable
/// <exception cref="EditorException">The sequence is gone, or its project cannot be read (corrupt, or written by a newer Titano).</exception>
Task<SequenceContent> LoadAsync(CancellationToken cancellationToken);
/// <summary>
/// Whether the frames <see cref="LoadAsync"/> read last are still the sequence's, in the same order: frames inserted
/// or removed since (a sync download, an import of earlier photos, a scan) moved the stored project's positions. A
/// server sequence whose frames changed becomes <see cref="IsOutdated"/>.
/// </summary>
/// <exception cref="EditorException">The sequence is gone.</exception>
Task<bool> FramesCurrentAsync(CancellationToken cancellationToken);
/// <summary>
/// Frame <paramref name="index"/> in linear light, oriented, long edge at most <paramref name="maxLongEdge"/>; null
/// when the frame cannot be read. The caller owns the buffer.
@@ -105,6 +105,14 @@ public sealed class LocalSequenceSource : ISequenceSource
}, cancellationToken);
}
/// <remarks>An insertion bumps the row's frames version in the transaction that renumbers the frames.</remarks>
public async Task<bool> FramesCurrentAsync(CancellationToken cancellationToken)
{
var framesVersion = _framesVersion;
var row = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
return row.FramesVersion == framesVersion;
}
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
if ((uint)index >= (uint)_files.Length || _files[index] is not { } file) return null;
+23 -3
View File
@@ -130,6 +130,13 @@ public sealed class RemoteSequenceSource : ISequenceSource
}, cancellationToken);
}
/// <remarks>Read from the server's manifest: a sequence whose frames are not this PC's becomes outdated.</remarks>
public async Task<bool> FramesCurrentAsync(CancellationToken cancellationToken)
{
if (IsOutdated) return false;
return Compare(await Call(() => _api.GetManifestAsync(Id, cancellationToken)));
}
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
if ((uint)index >= (uint)_remote.Frames.Count) return null;
@@ -305,9 +312,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
{
try
{
var manifest = await _api.GetManifestAsync(Id, cancellationToken).ConfigureAwait(false);
if (SameFrames(manifest)) Volatile.Write(ref _framesVersion, manifest.FramesVersion);
else MarkOutdated();
Compare(await _api.GetManifestAsync(Id, cancellationToken).ConfigureAwait(false));
}
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or JsonException
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
@@ -344,6 +349,21 @@ public sealed class RemoteSequenceSource : ISequenceSource
JobChanged?.Invoke(job);
}
/// <summary>
/// Takes the server's frames as <paramref name="manifest"/> lists them: their frames version when they are this PC's
/// (saves name it), outdated otherwise. Returns whether they are.
/// </summary>
private bool Compare(SequenceManifest manifest)
{
if (!SameFrames(manifest))
{
MarkOutdated();
return false;
}
Volatile.Write(ref _framesVersion, manifest.FramesVersion);
return true;
}
/// <summary>The server's frames are the cached ones, in the same order (frame positions in the project mean the same frames).</summary>
private bool SameFrames(SequenceManifest manifest) =>
manifest.Frames.OrderBy(f => f.Index).Select(f => f.Id).SequenceEqual(_remote.Frames.Select(f => f.Id));