fix(render-node): a restarted node frees its job; downloads resume; batches split on arrival

A node registering again gives back the job its previous run abandoned, so
a restart within the heartbeat timeout no longer leaves it running forever.
Frame downloads retry dropped connections from the partial file; a 404 at
registration waits for the next poll; render remarks reach the job log; a
render the server engine started stays with it. POST /jobs splits a batch
into one job per preset, and a node fails a batch it cannot send back
instead of reporting it done. Renders honour Settings > Rendering: hardware
encoders only where the preference allows them, also for what a node offers.

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 04a40ea22a
commit 23c40ece6f
14 files changed
+512 -82

No files matched your search

+29 -5
View File
@@ -36,14 +36,31 @@ public static class ProcessingJobs
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentNullException.ThrowIfNull(export);
var resolved = ExportResolver.Resolve(export);
var name = PresetName(resolved);
var parameters = new RenderJobParameters(name, JsonSerializer.Serialize(export, ProcessingJson.Default.ExportSettings), CodecName(resolved.Codec),
resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight, useProxies, project?.ToJson());
return new ArchiveJobRequest(JobKind.Render, [sequence.Id], $"{sequence.DisplayTitle} → {name}",
var parameters = Parameters(export, sourceWidth, sourceHeight, project?.ToJson(), useProxies);
return new ArchiveJobRequest(JobKind.Render, [sequence.Id], $"{sequence.DisplayTitle} → {parameters.PresetName}",
JsonSerializer.Serialize(parameters, ProtocolJson.Default.RenderJobParameters), JobPriority.User);
}
/// <summary>
/// A posted render job as one job per preset, as <see cref="RenderEach"/> makes them (a render node uploads one file
/// per job): the job itself when it has no batch; otherwise its own preset, then each batch preset with its own values,
/// all with the job's project and proxy choice. <paramref name="sourceWidth"/>×<paramref name="sourceHeight"/> stands in
/// for a batch preset without a fixed size.
/// </summary>
/// <exception cref="InvalidDataException">The preset JSON is not an export section.</exception>
public static IReadOnlyList<RenderJobParameters> Split(RenderJobParameters parameters, int sourceWidth, int sourceHeight)
{
ArgumentNullException.ThrowIfNull(parameters);
var export = ReadExport(parameters.PresetJson);
var batch = BatchPresets(export).ToList();
if (batch.Count == 0) return [parameters];
return
[
parameters with { PresetJson = JsonSerializer.Serialize(export with { Batch = [] }, ProcessingJson.Default.ExportSettings) },
.. batch.Select(id => Parameters(BatchExport(export, id), sourceWidth, sourceHeight, parameters.SettingsJson, parameters.UseProxies)),
];
}
/// <summary>
/// One <see cref="Render"/> job per preset of <paramref name="export"/>: its preset, then each batch preset with its
/// own values. For a server: a render node uploads one file per job, so a batch must not travel as one job.
@@ -70,6 +87,13 @@ public static class ProcessingJobs
internal static ExportSettings BatchExport(ExportSettings export, string presetId) =>
new() { Preset = new Auto<string>().WithManual(presetId), NameTemplate = export.NameTemplate, Folder = export.Folder };
private static RenderJobParameters Parameters(ExportSettings export, int sourceWidth, int sourceHeight, string? settingsJson, bool useProxies)
{
var resolved = ExportResolver.Resolve(export);
return new RenderJobParameters(PresetName(resolved), JsonSerializer.Serialize(export, ProcessingJson.Default.ExportSettings), CodecName(resolved.Codec),
resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight, useProxies, settingsJson);
}
/// <summary>Codec name in job parameters and render-node capabilities ("h264", "hevc", "mjpeg", "pngsequence"…).</summary>
public static string CodecName(VideoCodec codec) => codec.ToString().ToLowerInvariant();
@@ -15,12 +15,31 @@ namespace Titano.Data.Processing;
/// </summary>
public sealed record ProcessingOptions
{
/// <summary><see cref="SequenceChanged"/> after a render was recorded.</summary>
public const string RenderedChange = "renders";
/// <summary><see cref="SequenceChanged"/> after the advisor changed the project.</summary>
public const string SettingsChange = "settings";
/// <summary>Decoders, lease owner and lease timing for the sidecar and project writes.</summary>
public ArchiveServiceOptions Archive { get; init; } = new();
/// <summary>Encoder providers in priority order.</summary>
public IReadOnlyList<IVideoEncoderProvider> Encoders { get; init; } = [new ManagedEncoderProvider()];
/// <summary>
/// Whether a render of the given preset (its base preset id) may use hardware encoders (Settings › Rendering); when
/// not, it gets only the software ones. Asked at every render, so a changed preference applies to the next one.
/// </summary>
public Func<string, bool> AllowsHardware { get; init; } = _ => true;
/// <summary>
/// Told after a job changed a sequence: <see cref="RenderedChange"/> (a render was recorded) or
/// <see cref="SettingsChange"/> (the advisor changed Auto values). A server tells its connected clients (BRIEF §14.3).
/// A failure is logged and never fails the job.
/// </summary>
public Func<Guid, string, CancellationToken, Task>? SequenceChanged { get; init; }
/// <summary>The server delegates platform codecs to render nodes and never runs them itself.</summary>
public EncoderHost Host { get; init; } = EncoderHost.Client;
@@ -34,6 +53,24 @@ public sealed record ProcessingOptions
public RenderOptions Render { get; init; } = RenderOptions.Default;
/// <summary>Tells <see cref="SequenceChanged"/>; a failure is logged, never passed on to the job.</summary>
internal async Task NotifyAsync(Guid sequenceId, string change, CancellationToken cancellationToken)
{
if (SequenceChanged is null) return;
try
{
await SequenceChanged(sequenceId, change, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
Core.Diagnostics.Log.Warning("processing", $"The {change} change of sequence {sequenceId} could not be announced", ex);
}
}
/// <summary><see cref="Encoders"/> without their hardware encoders, for renders <see cref="AllowsHardware"/> keeps off them.</summary>
internal IReadOnlyList<IVideoEncoderProvider> SoftwareEncoders =>
[.. Encoders.Select(e => e.Capabilities.Any(c => c.Hardware) ? new SoftwareEncoderProvider(e) : e)];
/// <summary>
/// Encoders the advisor may count on: this machine's on a client; none listed on the server (render nodes can
/// produce any codec, so the advisor rules none out).
+90 -31
View File
@@ -8,7 +8,6 @@ using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Render;
using Titano.Core.Video;
using Titano.Data.Processing.Jobs;
using Titano.Protocol;
using Titano.Protocol.Client;
@@ -37,16 +36,23 @@ public sealed record RenderNodeOptions
/// <summary>Concurrent frame downloads.</summary>
public int Downloads { get; init; } = 4;
/// <summary>Retries of a frame download cut by the network or a busy server, each resuming the partial file.</summary>
public int DownloadRetries { get; init; } = 5;
/// <summary>Wait before the first retry; it doubles with each further one.</summary>
public TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(1);
}
/// <summary>
/// "Offer this PC as render node" (BRIEF §14.7): registers this machine's single-file encoders with the server,
/// heart-beats, claims one render job at a time that it can encode, downloads the frames it needs (originals
/// hash-verified into a content-addressed cache, or proxies when the job asks), renders the job's preset with the
/// host's encoders and uploads the output, which the server files as a render of the sequence. Progress goes to the
/// server; a job cancelled or reassigned there stops here; a failure is reported with its reason. Stopping abandons
/// the job in flight without reporting it, so the server requeues it once the heartbeats stop. Image sequences are
/// not offered: the protocol uploads one file per job.
/// hash-verified into a content-addressed cache, or proxies when the job asks; a dropped download resumes), renders the
/// job's preset with the host's encoders and uploads the output, which the server files as a render of the sequence.
/// Progress and render remarks go to the server; a job cancelled or reassigned there stops here; a failure is reported
/// with its reason. Stopping abandons the job in flight without reporting it: the server requeues it when the node
/// registers again or its heartbeats stop. Image sequences are not offered and batches are refused: the protocol uploads
/// one file per job.
/// </summary>
public sealed class RenderNodeClient : IAsyncDisposable
{
@@ -66,14 +72,22 @@ public sealed class RenderNodeClient : IAsyncDisposable
_options = options;
}
/// <summary>The encoders this node offers: every single-file capability of the host's providers.</summary>
/// <summary>
/// The encoders this node offers: every single-file capability of the host's providers, hardware ones only when the
/// user lets renders use them (<see cref="ProcessingOptions.AllowsHardware"/>).
/// </summary>
public IReadOnlyList<NodeEncoder> Encoders =>
[
.. _processing.Encoders.SelectMany(p => p.Capabilities)
.Where(c => VideoCodecInfo.DefaultContainer(c.Codec) != ContainerFormat.ImageSequence)
.Where(c => VideoCodecInfo.DefaultContainer(c.Codec) != ContainerFormat.ImageSequence
&& (!c.Hardware || _processing.AllowsHardware(ExportResolver.CustomId)))
.Select(c => new NodeEncoder(ProcessingJobs.CodecName(c.Codec), c.Name, c.Hardware, c.SupportsTenBit)),
];
/// <summary>Completes when the node has stopped: asked to, or refused by the server (signed out, no render-node right,
/// changed certificate), which only the user can change.</summary>
public Task Completion => _running;
/// <summary>Starts registering, heart-beating and claiming in the background.</summary>
public void Start() => _running = Task.Run(() => RunAsync(_stopping.Token));
@@ -155,14 +169,14 @@ public sealed class RenderNodeClient : IAsyncDisposable
Log.Warning(LogCategory, "The server refused this render node", ex);
break;
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound && _nodeId is not null)
{
_nodeId = null; // removed on the server: register again
_nodeId = null; // removed on the server: register again at once
continue;
}
catch (Exception ex)
{
// Server unreachable or busy: the node keeps trying until it is stopped.
// Server unreachable, busy or without the render-node routes: the node keeps trying until it is stopped.
Log.Warning(LogCategory, "Render node cycle failed; retrying", ex);
}
try
@@ -212,10 +226,9 @@ public sealed class RenderNodeClient : IAsyncDisposable
var resolved = ExportResolver.Resolve(export);
var target = new ExportTarget(resolved, ProcessingJobs.PresetName(resolved));
if (target.Export.Container == ContainerFormat.ImageSequence) throw new InvalidOperationException(Loc.L("Errors.Render.NodeSequence"));
// One output per job: a server splits batches into one job per preset when they are posted.
if (ProcessingJobs.BatchPresets(export).Any()) throw new InvalidOperationException(Loc.L("Errors.Render.NodeBatch"));
var project = ProjectStore.Parse(claimed.SettingsJson) with { Export = export };
// One output per job: batch presets were meant for separate jobs (ProcessingJobs.RenderEach).
if (RenderJobHandler.Targets(export, target.PresetName).Skip(1).Select(t => t.PresetName).ToList() is { Count: > 0 } skipped)
await reporter.ReportAsync(0, claimed.Frames.Count, Loc.L("Export.Log.NodeBatch", string.Join(", ", skipped))).ConfigureAwait(false);
var sequence = ToSequence(await _client.GetSequenceAsync(claimed.SequenceId, cancellationToken).ConfigureAwait(false));
var frames = await ListFramesAsync(claimed.SequenceId, cancellationToken).ConfigureAwait(false);
@@ -229,7 +242,12 @@ public sealed class RenderNodeClient : IAsyncDisposable
[(0, target)],
(t, setup) => ExportNaming.OutputPath(work, project.Export.NameTemplate, SequenceRender.NameContext(sequence, t, setup)),
(_, _) => ValueTask.CompletedTask,
(_, t, result) => new ValueTask(UploadAsync(reporter.NodeId, claimed.Job.Id, t, result, cancellationToken)),
async (_, t, result) =>
{
// Remarks first: completing the upload ends the job on the server.
foreach (var remark in SequenceRender.Remarks(result)) await reporter.LogAsync(remark).ConfigureAwait(false);
await UploadAsync(reporter.NodeId, claimed.Job.Id, t, result, cancellationToken).ConfigureAwait(false);
},
reporter.ReportAsync,
cancellationToken).ConfigureAwait(false);
}
@@ -288,15 +306,17 @@ public sealed class RenderNodeClient : IAsyncDisposable
return files;
}
/// <summary>A proxy into the job folder (regenerable, so not cached); the original when the server has none for the frame.</summary>
/// <summary>
/// A proxy into the job folder (regenerable, so neither cached nor hashed: the server keeps no hash of it); the original
/// when the server has none for the frame.
/// </summary>
private async Task<string> DownloadProxyAsync(ManifestFrame frame, string work, CancellationToken cancellationToken)
{
var path = Path.Combine(work, "proxies", frame.Id.ToString("N") + ".jpg");
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
try
{
await using (var file = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
await _client.DownloadFrameAsync(frame.Id, "proxy", file, null, cancellationToken).ConfigureAwait(false);
await FetchAsync(frame, "proxy", path, cancellationToken).ConfigureAwait(false);
return path;
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
@@ -322,11 +342,7 @@ public sealed class RenderNodeClient : IAsyncDisposable
for (var attempt = 1; ; attempt++)
{
// A part as long as the file was complete when the last attempt stopped: only its hash is left to check.
if (!File.Exists(part) || new FileInfo(part).Length < frame.Size)
{
await using var file = new FileStream(part, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
await _client.DownloadFrameAsync(frame.Id, "original", file, null, cancellationToken).ConfigureAwait(false);
}
if (!File.Exists(part) || new FileInfo(part).Length < frame.Size) await FetchAsync(frame, "original", part, cancellationToken).ConfigureAwait(false);
if (await TitanoClient.HashFileAsync(part, cancellationToken).ConfigureAwait(false) == sha)
{
File.Move(part, path, overwrite: true);
@@ -337,6 +353,33 @@ public sealed class RenderNodeClient : IAsyncDisposable
}
}
/// <summary>
/// Fetches a frame resource into <paramref name="path"/>, appending to what an earlier attempt left there. A dropped
/// connection or a busy server is retried, resuming where the file ends (up to <see cref="RenderNodeOptions.DownloadRetries"/> times,
/// the wait doubling from <see cref="RenderNodeOptions.RetryDelay"/>).
/// </summary>
private async Task FetchAsync(ManifestFrame frame, string kind, string path, CancellationToken cancellationToken)
{
for (var attempt = 0; ; attempt++)
{
try
{
await using var file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
await _client.DownloadFrameAsync(frame.Id, kind, file, null, cancellationToken).ConfigureAwait(false);
return;
}
catch (Exception ex) when (attempt < _options.DownloadRetries && !cancellationToken.IsCancellationRequested && IsTransient(ex))
{
Log.Info(LogCategory, $"Download of {frame.FileName} ({kind}) interrupted, resuming: {ex.Message}");
await Task.Delay(_options.RetryDelay * (1 << attempt), cancellationToken).ConfigureAwait(false);
}
}
}
/// <summary>Failures a later attempt can get past: the network, a busy server, a timeout (not a cancellation of ours).</summary>
private static bool IsTransient(Exception ex) =>
ex is HttpRequestException or IOException or OperationCanceledException or TitanoApiException { IsTransient: true };
private async Task ReportFailureAsync(Guid nodeId, Guid jobId, string error, CancellationToken cancellationToken)
{
try
@@ -430,22 +473,38 @@ public sealed class RenderNodeClient : IAsyncDisposable
private readonly SemaphoreSlim _gate = new(1, 1);
private TimeSpan _last = TimeSpan.MinValue;
private long _lastDone;
private long _lastTotal;
private string? _lastMessage;
public Guid NodeId => nodeId;
public async ValueTask ReportAsync(long done, long total, string? message)
/// <summary>Progress, sent at most every interval; a stage message is sent when it changes.</summary>
public ValueTask ReportAsync(long done, long total, string? message) => SendAsync(done, total, message, remark: false);
/// <summary>A line for the job's log on the server, sent with the progress last reported.</summary>
public ValueTask LogAsync(string line) => SendAsync(0, 0, line, remark: true);
private async ValueTask SendAsync(long done, long total, string? message, bool remark)
{
await _gate.WaitAsync(CancellationToken.None).ConfigureAwait(false);
try
{
var now = _clock.Elapsed;
var line = message is not null && message != _lastMessage ? message : null;
if (line is null && done < total && now - _last < interval) return;
double? rate = _last == TimeSpan.MinValue || done < _lastDone ? null : (done - _lastDone) / double.Max((now - _last).TotalSeconds, 1e-3);
(_last, _lastDone) = (now, done);
if (line is not null) _lastMessage = line;
await client.ReportNodeProgressAsync(nodeId, jobId, new NodeProgress(done, total, rate, line), job.Token).ConfigureAwait(false);
NodeProgress progress;
if (remark)
{
progress = new NodeProgress(_lastDone, _lastTotal, null, message);
}
else
{
var now = _clock.Elapsed;
var line = message is not null && message != _lastMessage ? message : null;
if (line is null && done < total && now - _last < interval) return;
double? rate = _last == TimeSpan.MinValue || done < _lastDone ? null : (done - _lastDone) / double.Max((now - _last).TotalSeconds, 1e-3);
(_last, _lastDone, _lastTotal) = (now, done, total);
if (line is not null) _lastMessage = line;
progress = new NodeProgress(done, total, rate, line);
}
await client.ReportNodeProgressAsync(nodeId, jobId, progress, job.Token).ConfigureAwait(false);
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
+16 -5
View File
@@ -19,12 +19,14 @@ internal sealed record TargetOutcome(ExportTarget Target, RenderResult? Result,
/// frames that cannot be rendered excluded, and the pipeline with the host's encoders. Targets share one preparation
/// pass; each is named once its encoder (and so its codec and size) is known, and failures of one target do not stop
/// the others. Outputs are written by the encoder sessions to temporary names and renamed on completion, so a
/// cancelled or failed target leaves nothing behind.
/// cancelled or failed target leaves nothing behind. A target gets the hardware encoders only when the user allows them
/// for its preset (<see cref="ProcessingOptions.AllowsHardware"/>).
/// </summary>
internal sealed class SequenceRender : IAsyncDisposable
{
private readonly SequenceFrameSource _source;
private readonly RenderPipeline _pipeline;
private readonly ProcessingOptions _processing;
private readonly Dictionary<bool, RenderPipeline> _pipelines = [];
private readonly RenderOptions _options;
/// <param name="analysis">The sequence's deep report, when current: its luminance spares the preparation a decode pass.</param>
@@ -32,7 +34,7 @@ internal sealed class SequenceRender : IAsyncDisposable
{
var metadata = frames.LightFrames();
_source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder, options.FrameWindow);
_pipeline = new RenderPipeline(options.Encoders, options.Host);
_processing = options;
_options = options.Render;
Input = new RenderInput
{
@@ -46,7 +48,7 @@ internal sealed class SequenceRender : IAsyncDisposable
public RenderInput Input { get; }
/// <summary>Encoder, geometry and plan of an export before its output is named.</summary>
public RenderSetup Setup(ResolvedExport export) => _pipeline.Setup(Input, new RenderTarget(export, ExportNaming.FallbackName), _options);
public RenderSetup Setup(ResolvedExport export) => Pipeline(export).Setup(Input, new RenderTarget(export, ExportNaming.FallbackName), _options);
/// <summary>
/// Prepares the sequence once and renders every target. <paramref name="name"/> gives the output path of a target
@@ -97,7 +99,7 @@ internal sealed class SequenceRender : IAsyncDisposable
await starting(index, output).ConfigureAwait(false);
try
{
var result = await _pipeline.RenderAsync(Input, corrections, new RenderTarget(target.Export, output), _options,
var result = await Pipeline(target.Export).RenderAsync(Input, corrections, new RenderTarget(target.Export, output), _options,
Stage(chain, done, setup.Plan.Frames.Count, total, target.PresetName), cancellationToken).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
await finished(index, target, result).ConfigureAwait(false);
@@ -134,6 +136,15 @@ internal sealed class SequenceRender : IAsyncDisposable
public ValueTask DisposeAsync() => _source.DisposeAsync();
/// <summary>The pipeline with the encoders <paramref name="export"/> may use.</summary>
private RenderPipeline Pipeline(ResolvedExport export)
{
var hardware = _processing.AllowsHardware(export.BasePresetId);
if (!_pipelines.TryGetValue(hardware, out var pipeline))
_pipelines[hardware] = pipeline = new RenderPipeline(hardware ? _processing.Encoders : _processing.SoftwareEncoders, _processing.Host);
return pipeline;
}
private static string Reason(RenderSetup setup)
{
if (setup.Plan.Frames.Count == 0) return Loc.L("Export.Render.NoFrames");
@@ -0,0 +1,30 @@
using Titano.Core.Video;
namespace Titano.Data.Processing;
/// <summary>
/// The software encoders of a provider, for renders the user keeps off the GPU (Settings › Rendering): hardware
/// capabilities are hidden, so the encoder selector falls back as on a PC without them (HEVC → software H.264), and an
/// encode opens the software encoder by name, ignoring a hardware one named in the export.
/// </summary>
internal sealed class SoftwareEncoderProvider(IVideoEncoderProvider inner) : IVideoEncoderProvider
{
public string Name => inner.Name;
public IReadOnlyList<EncoderCapability> Capabilities { get; } = [.. inner.Capabilities.Where(c => !c.Hardware)];
public bool CanEncode(EncodeSettings settings) => Software(settings) is not null;
public IVideoEncoderSession Open(EncodeSettings settings) =>
inner.Open(Software(settings) ?? throw new NotSupportedException($"No software encoder of {inner.Name} accepts {settings.Codec} {settings.Width}×{settings.Height}"));
/// <summary>The settings naming the first software encoder that accepts them; null when none does.</summary>
private EncodeSettings? Software(EncodeSettings settings)
{
var named = settings.EncoderName is { } name && Capabilities.Any(c => c.Name == name);
return Capabilities
.Where(c => c.Codec == settings.Codec && (!named || c.Name == settings.EncoderName))
.Select(c => settings with { EncoderName = c.Name, PreferHardware = false })
.FirstOrDefault(inner.CanEncode);
}
}