fix(processing): concurrent renders keep their own names; analysis status under the lock; server announces changes

A render reserves the output name it picks, so the same preset queued twice
no longer overwrites one output with the other; render rows take ids from
their job and entry, so a resumed job recognises only its own outputs and
never deletes another render's file. A light pass records its status under
the sequence lock and cannot clear a deep pass's. Renders and Auto value
changes made by the server engine publish sequenceChanged events.

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-02 23:16:23 +00:00
1 parent 23c40ece6f
commit c7ca1ef463
9 files changed
+316 -56

No files matched your search

@@ -1,3 +1,5 @@
using System.Buffers.Binary;
using System.Security.Cryptography;
using Titano.Core.Archiving;
using Titano.Core.Export;
using Titano.Core.Localization;
@@ -13,9 +15,11 @@ namespace Titano.Data.Processing.Jobs;
/// <c>RenderJobParameters</c> whose preset JSON is the export section of a project (preset, overrides, name template,
/// folder, batch). The project is the embedded one or the sequence's own; frames flagged missing, corrupt, excluded or
/// undecodable are left out. The preset and every batch preset render after one preparation pass into the sequence's
/// <c>exports/</c> (or the export folder, never on a server), named by the template, and each finished output is recorded at once.
/// Checkpoint: the batch entries recorded and the output being written, so a crashed attempt's leftovers are removed and
/// only unfinished entries render again. A failed entry fails the job after the others ran; retrying renders it alone.
/// <c>exports/</c> (or the export folder, never on a server), named by the template without taking a name another render
/// of this process is writing, and each finished output is recorded at once (its row id derives from the job and the
/// entry, so every attempt knows what is recorded). Checkpoint: the entries recorded and the output being written, so a
/// crashed attempt's leftovers are removed and only unfinished entries render again. A failed entry fails the job after
/// the others ran; retrying renders it alone.
/// </summary>
internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions options) : IJobHandler
{
@@ -36,16 +40,23 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
var project = (parameters.SettingsJson is { } embedded ? ProjectStore.Parse(embedded) : ProjectStore.Read(sequence, folder)) with { Export = export };
var settingsJson = project.ToJson();
using var names = new OutputNames();
var all = Targets(export, parameters.PresetName);
var resume = RenderCheckpoint.Parse(context.Checkpoint);
var done = resume.Done.ToList();
if (resume is { Pending: { } pending, PendingOutput: { } output })
// A crash after a render row was written but before the checkpoint: that entry is finished.
for (var i = 0; i < all.Count; i++)
{
// A crash after the render row was written but before the checkpoint: that entry is finished.
var recorded = await db.Renders.ListBySequenceAsync(sequence.Id, cancellation).ConfigureAwait(false);
if (recorded.Any(r => r.OutputPath == Stored(paths, output))) done.Add(pending);
else Discard(output);
if (!done.Contains(i) && await db.Renders.GetAsync(RenderId(context.Job.Id, i), cancellation).ConfigureAwait(false) is not null) done.Add(i);
}
var targets = Targets(export, parameters.PresetName).Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).ToList();
if (resume is { Pending: { } pending, PendingOutput: { } output } && !done.Contains(pending) && names.TryReserve(output))
{
// Unless another render recorded that name since (the output did not exist yet when it chose it).
var recorded = await db.Renders.ListBySequenceAsync(sequence.Id, cancellation).ConfigureAwait(false);
Discard(output, keepOutput: recorded.Any(r => r.OutputPath == Stored(paths, output)));
names.Release(output); // free again for the entry's new attempt
}
var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).ToList();
if (targets.Count == 0) return;
var frames = await SequenceFrames.LoadAsync(db, archive, sequence, parameters.UseProxies, cancellation).ConfigureAwait(false);
@@ -54,17 +65,22 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
{
outcomes = await render.RenderAllAsync(
targets,
(target, setup) => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup)),
(target, setup) => names.Reserve(taken => ExportNaming.OutputPath(project.Export, folder.Exports, SequenceRender.NameContext(sequence, target, setup), taken)),
(index, path) => context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total),
async (index, target, result) =>
{
// The output is complete: record it even if the job is being cancelled, so it is never orphaned.
var entity = result.ToEntity(sequence.Id, target.PresetName, settingsJson, options.ProducedBy) with { OutputPath = Stored(paths, result.OutputPath) };
var entity = result.ToEntity(sequence.Id, target.PresetName, settingsJson, options.ProducedBy) with
{
Id = RenderId(context.Job.Id, index),
OutputPath = Stored(paths, result.OutputPath),
};
await db.Renders.InsertAsync(entity, CancellationToken.None).ConfigureAwait(false);
done.Add(index);
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
context.Log(Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
await options.NotifyAsync(sequence.Id, ProcessingOptions.RenderedChange, CancellationToken.None).ConfigureAwait(false);
},
context.ReportAsync,
cancellation).ConfigureAwait(false);
@@ -90,15 +106,32 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
return relative.StartsWith("..", StringComparison.Ordinal) || Path.IsPathRooted(relative) ? output : relative;
}
/// <summary>
/// The id of the render row of entry <paramref name="index"/> of a job: the same in every attempt, so a resumed job
/// finds what it recorded (a name-based UUID, version 8).
/// </summary>
internal static Guid RenderId(Guid jobId, int index)
{
Span<byte> name = stackalloc byte[20];
jobId.TryWriteBytes(name, bigEndian: true, out _);
BinaryPrimitives.WriteInt32BigEndian(name[16..], index);
Span<byte> hash = stackalloc byte[SHA256.HashSizeInBytes];
SHA256.HashData(name, hash);
hash[6] = (byte)((hash[6] & 0x0F) | 0x80);
hash[8] = (byte)((hash[8] & 0x3F) | 0x80);
return new Guid(hash[..16], bigEndian: true);
}
/// <summary>
/// Removes what an interrupted attempt left of <paramref name="output"/>: the encoder's hidden temporary file or
/// folder, and an output that was completed but never recorded (it renders again under the same name).
/// </summary>
private static void Discard(string output)
private static void Discard(string output, bool keepOutput)
{
var parent = Path.GetDirectoryName(output);
if (parent is null || !Directory.Exists(parent)) return;
foreach (var leftover in Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp").Append(output))
var leftovers = Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp");
foreach (var leftover in keepOutput ? leftovers : leftovers.Append(output))
{
if (Directory.Exists(leftover)) Directory.Delete(leftover, recursive: true);
else if (File.Exists(leftover)) File.Delete(leftover);
+55
View File
@@ -0,0 +1,55 @@
using System.Collections.Concurrent;
namespace Titano.Data.Processing;
/// <summary>
/// The output paths the renders of this process are writing. Encoders write to a hidden temporary file and rename it over
/// the output when they finish, so two renders that picked the same free name (the same preset queued twice) would
/// overwrite each other: a render reserves each name it picks until it ends.
/// </summary>
internal sealed class OutputNames : IDisposable
{
private static readonly ConcurrentDictionary<string, byte> Writing = new(StringComparer.OrdinalIgnoreCase);
private readonly List<string> _mine = [];
/// <summary>A path from <paramref name="pick"/>, given the test for paths other renders are writing, reserved for this render.</summary>
public string Reserve(Func<Func<string, bool>, string> pick)
{
while (true)
{
var path = pick(p => Writing.ContainsKey(Key(p)));
// Another render may have taken the same name since: pick again.
if (TryReserve(path)) return path;
}
}
/// <summary>Reserves <paramref name="path"/> for this render; false when another render is writing it.</summary>
public bool TryReserve(string path)
{
var key = Key(path);
if (!Writing.TryAdd(key, 0)) return false;
lock (_mine) _mine.Add(key);
return true;
}
/// <summary>Gives back a path this render reserved, so it can be picked again.</summary>
public void Release(string path)
{
var key = Key(path);
lock (_mine)
{
if (_mine.Remove(key)) Writing.TryRemove(key, out _);
}
}
public void Dispose()
{
lock (_mine)
{
foreach (var key in _mine) Writing.TryRemove(key, out _);
_mine.Clear();
}
}
private static string Key(string path) => Path.GetFullPath(path);
}
+19 -14
View File
@@ -59,21 +59,26 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
(changed, unreadable) = (false, true);
}
// A deep analysis of the same sequence may have finished meanwhile: count its findings and keep its status.
report ??= ReadReport(folder, frames.Count);
var warnings = Advisor.Recommend(light, report, context).Findings.Count(f => f.Severity >= FindingSeverity.Warning);
var set = SequenceStatus.AnalyzedLight | (report is null ? SequenceStatus.None : SequenceStatus.AnalyzedDeep)
| (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 summary = deep && report is not null ? AnalysisSummary.From(report).ToJson() : null;
await writer.UpdateAsync(paths, sequence.Id, sequence.Folder, m =>
if (changed) await options.NotifyAsync(sequence.Id, ProcessingOptions.SettingsChange, cancellationToken).ConfigureAwait(false);
int warnings;
// Under the sequence lock, which a deep pass of the same sequence also takes to record its report: a light pass
// then either sees that report or runs before it is recorded, and never clears what it recorded.
await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var status = (m.Status | set) & ~clear;
return status == m.Status ? null : m with { Status = status, UpdatedAt = DateTimeOffset.UtcNow };
}, cancellationToken).ConfigureAwait(false);
await db.Sequences.RecordAnalysisAsync(sequence.Id, set, clear, warnings, summary, cancellationToken).ConfigureAwait(false);
await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
report ??= ReadReport(folder, frames.Count);
warnings = Advisor.Recommend(light, report, context).Findings.Count(f => f.Severity >= FindingSeverity.Warning);
var set = SequenceStatus.AnalyzedLight | (report is null ? SequenceStatus.None : SequenceStatus.AnalyzedDeep)
| (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 status = (manifest.Status | set) & ~clear;
if (status != manifest.Status) ManifestStore.WriteSequence(folder.ManifestPath, manifest with { Status = status, UpdatedAt = DateTimeOffset.UtcNow });
var summary = deep && report is not null ? AnalysisSummary.From(report).ToJson() : null;
await db.Sequences.RecordAnalysisAsync(sequence.Id, set, clear, warnings, summary, cancellationToken).ConfigureAwait(false);
await indexer.RecordStampsAsync(archive, folder, sequence.Id, cancellationToken).ConfigureAwait(false);
}
var presets = deep ? SequencePresets.Generate(light, report, context) : [];
return new AnalysisOutcome(sequence, frames.Count, warnings, changed, unreadable, presets);