feat(processing): selective render claims, analysis follow-ups, per-sequence failures

- JobEngine: ISelectiveJobHandler lets a host decline jobs of a kind it runs;
  declined jobs stay queued for other claimers without holding up the rest.
  JobContext.EnqueueFollowUpAsync queues follow-up work on the same engine.
- Server renders the jobs whose every output a managed encoder produces
  (ManagedRenderJobHandler); MP4 jobs stay for render nodes. Program.cs
  registers ProcessingModule next to ArchiveModule. Server renders ignore a
  client's export folder.
- Light analysis is queued after imports and after scans that indexed new
  sequences, so the advisor's Auto values exist without user action.
- Analysis jobs log a failing sequence and go on; the job then fails and a
  retry analyses only the failed ones. The advised frame rate follows the
  user's fit-to duration.
- ProcessingJobs.RenderEach splits a batch into one job per preset for
  servers; render nodes say which batch presets they did not render, fetch
  each content once and stop on a changed certificate.

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 17:01:50 +00:00
1 parent d729d2d09c
commit 14cdbf1f7d
30 files changed
+572 -85

No files matched your search

@@ -1,5 +1,6 @@
using System.Globalization;
using Titano.Core.Analysis.Deep;
using Titano.Core.Archiving;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Jobs;
@@ -8,8 +9,10 @@ namespace Titano.Data.Processing.Jobs;
/// <summary>
/// <see cref="JobKind.LightAnalyse"/> and <see cref="JobKind.DeepAnalyse"/> over the target sequences, one after the
/// other. Progress counts sequences (light) or frames (deep); checkpoint: the number of sequences done. A deep pass
/// interrupted inside a sequence resumes from that sequence's <c>analysis.partial</c>.
/// other. Progress counts sequences (light) or frames (deep). A sequence that cannot be analysed is logged and the
/// others still run; the job then fails, and a retry analyses only the failed ones. An offline archive stops the job at
/// once. Checkpoint: the next target and the failed ones (<c>next[;i,j…]</c>). A deep pass interrupted inside a
/// sequence resumes from that sequence's <c>analysis.partial</c>.
/// </summary>
internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser analyser, JobKind kind) : IJobHandler
{
@@ -19,29 +22,47 @@ internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser anal
{
var deep = kind == JobKind.DeepAnalyse;
var targets = context.Job.TargetIds;
var first = int.TryParse(context.Checkpoint, NumberStyles.None, CultureInfo.InvariantCulture, out var next) ? next : 0;
var (next, retry) = Parse(context.Checkpoint, targets.Count);
// Deep progress is in frames across all targets, so the bar and the ETA cover the whole job.
var frames = new long[targets.Count];
if (deep)
{
for (var i = 0; i < targets.Count; i++)
frames[i] = (await db.Sequences.GetAsync(targets[i], context.Cancellation).ConfigureAwait(false))?.FrameCount ?? 0;
}
var total = deep ? frames.Sum() : targets.Count;
for (var i = first; i < targets.Count; i++)
var units = new long[targets.Count];
for (var i = 0; i < targets.Count; i++)
units[i] = deep ? (await db.Sequences.GetAsync(targets[i], context.Cancellation).ConfigureAwait(false))?.FrameCount ?? 0 : 1;
var total = units.Sum();
var done = Enumerable.Range(0, next).Where(i => !retry.Contains(i)).Sum(i => units[i]);
var failed = new List<int>();
int[] order = [.. retry, .. Enumerable.Range(next, targets.Count - next)];
for (var k = 0; k < order.Length; k++)
{
context.Cancellation.ThrowIfCancellationRequested();
var before = deep ? frames[..i].Sum() : i;
var i = order[k];
var before = done;
var chain = new ProgressChain(context.ReportAsync);
var progress = deep ? chain.For<AnalysisProgress>(p => (before + p.Done, total, null)) : null;
var outcome = await analyser.AnalyseAsync(targets[i], deep, progress, context.Cancellation).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
if (outcome is null) context.Log(Loc.L("Archive.Log.SequenceMissing", targets[i]));
else Report(context, outcome, deep);
await context.CheckpointAsync((i + 1).ToString(CultureInfo.InvariantCulture), deep ? before + frames[i] : i + 1, total).ConfigureAwait(false);
try
{
var outcome = await analyser.AnalyseAsync(targets[i], deep, progress, context.Cancellation).ConfigureAwait(false);
await chain.FlushAsync().ConfigureAwait(false);
if (outcome is null) context.Log(Loc.L("Archive.Log.SequenceMissing", targets[i]));
else Report(context, outcome, deep);
}
catch (Exception ex) when (ex is not (OperationCanceledException or ArchiveOfflineException))
{
await chain.FlushAsync().ConfigureAwait(false);
Core.Diagnostics.Log.Warning("processing", $"Analysis of sequence {targets[i]} failed", ex);
context.Log(Loc.L("Advisor.Log.Failed", await TitleAsync(targets[i], context.Cancellation).ConfigureAwait(false), ex.Message));
failed.Add(i);
}
done += units[i];
next = int.Max(next, i + 1);
// Failed targets of an earlier attempt not retried yet stay listed.
await context.CheckpointAsync(Format(next, [.. failed, .. retry.Skip(k + 1)]), done, total).ConfigureAwait(false);
}
if (failed.Count > 0) throw new InvalidOperationException(Loc.L("Errors.Analysis.Failed", failed.Count, targets.Count));
}
private async Task<string> TitleAsync(Guid sequenceId, CancellationToken cancellationToken) =>
(await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false))?.DisplayTitle ?? sequenceId.ToString();
private static void Report(JobContext context, AnalysisOutcome outcome, bool deep)
{
var title = outcome.Sequence.DisplayTitle;
@@ -50,4 +71,23 @@ internal sealed class AnalyseJobHandler(TitanoDatabase db, SequenceAnalyser anal
if (outcome.SettingsUnreadable) context.Log(Loc.L("Advisor.Log.ProjectUnreadable", title));
if (outcome.Presets.Count > 0) context.Log(Loc.L("Advisor.Log.Presets", string.Join(" · ", outcome.Presets.Select(p => p.DisplayName()))));
}
/// <summary>Next target and the failed targets to retry first; a missing or unreadable checkpoint starts over.</summary>
internal static (int Next, IReadOnlyList<int> Retry) Parse(string? checkpoint, int count)
{
var parts = checkpoint?.Split(';');
if (parts is not ([_] or [_, _]) || !int.TryParse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture, out var next) || next > count) return (0, []);
var retry = new List<int>();
foreach (var item in parts.Length == 2 ? parts[1].Split(',') : [])
{
if (!int.TryParse(item, NumberStyles.None, CultureInfo.InvariantCulture, out var index) || index >= next) return (0, []);
if (!retry.Contains(index)) retry.Add(index);
}
return (next, retry);
}
internal static string Format(int next, IReadOnlyCollection<int> failed) =>
failed.Count == 0
? next.ToString(CultureInfo.InvariantCulture)
: string.Create(CultureInfo.InvariantCulture, $"{next};{string.Join(',', failed.Order())}");
}
@@ -0,0 +1,40 @@
using Titano.Core.Export;
using Titano.Core.Model;
using Titano.Core.Video;
using Titano.Data.Jobs;
namespace Titano.Data.Processing.Jobs;
/// <summary>
/// <see cref="JobKind.Render"/> on the server (BRIEF §4.4, §14.5): it takes only jobs whose every output (the preset and
/// each batch preset) its managed encoders produce, and runs them like a client does. Jobs that need a platform encoder
/// (MP4) stay queued for render nodes (§14.7). Jobs whose parameters cannot be read are taken, so they fail with their
/// reason instead of waiting for a claimer that never comes.
/// </summary>
internal sealed class ManagedRenderJobHandler(RenderJobHandler render, IReadOnlyList<IVideoEncoderProvider> encoders) : ISelectiveJobHandler
{
private readonly EncoderCapability[] _capabilities = [.. encoders.SelectMany(e => e.Capabilities)];
public JobKind Kind => JobKind.Render;
public bool Accepts(Job job)
{
ArgumentNullException.ThrowIfNull(job);
try
{
var parameters = ProcessingJobs.ReadParameters(job.ParametersJson);
// Most declined jobs are decided by the main codec, before the export is read.
return _capabilities.Any(c => string.Equals(ProcessingJobs.CodecName(c.Codec), parameters.Codec, StringComparison.OrdinalIgnoreCase))
&& RenderJobHandler.Targets(ProcessingJobs.ReadExport(parameters.PresetJson), parameters.PresetName).All(t => Produces(t.Export));
}
catch (InvalidDataException)
{
return true;
}
}
public Task RunAsync(JobContext context) => render.RunAsync(context);
private bool Produces(ResolvedExport export) =>
_capabilities.Any(c => c.Codec == export.Codec && export.Width <= c.MaxWidth && export.Height <= c.MaxHeight);
}
@@ -13,7 +13,7 @@ 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), named by the template, and each finished output is recorded at once.
/// <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.
/// </summary>
@@ -31,6 +31,8 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var folder = paths.Sequence(sequence.Folder);
// A server writes only inside its archive (BRIEF §14.2): an export folder chosen on a client means nothing there.
if (options.Host == EncoderHost.Server) export = export with { Folder = null };
var project = (parameters.SettingsJson is { } embedded ? ProjectStore.Parse(embedded) : ProjectStore.Read(sequence, folder)) with { Export = export };
var settingsJson = project.ToJson();
@@ -74,18 +76,12 @@ internal sealed class RenderJobHandler(TitanoDatabase db, ProcessingOptions opti
}
/// <summary>The job's preset, then every other preset of the batch with its own values.</summary>
internal static List<ExportTarget> Targets(ExportSettings export, string presetName)
{
var main = ExportResolver.Resolve(export);
var targets = new List<ExportTarget> { new(main, presetName) };
foreach (var id in export.Batch.Distinct(StringComparer.OrdinalIgnoreCase))
{
if (id.Equals(main.BasePresetId, StringComparison.OrdinalIgnoreCase)) continue;
var resolved = ExportResolver.Resolve(new ExportSettings { Preset = new Auto<string>().WithManual(id) });
targets.Add(new ExportTarget(resolved, ProcessingJobs.PresetName(resolved)));
}
return targets;
}
internal static List<ExportTarget> Targets(ExportSettings export, string presetName) =>
[
new(ExportResolver.Resolve(export), presetName),
.. ProcessingJobs.BatchPresets(export).Select(id => ExportResolver.Resolve(ProcessingJobs.BatchExport(export, id)))
.Select(resolved => new ExportTarget(resolved, ProcessingJobs.PresetName(resolved))),
];
/// <summary>Archive-relative for outputs inside the archive (like the server's renders), absolute otherwise.</summary>
private static string Stored(ArchivePaths paths, string output)