feat: jobs run one at a time, parallelism per photo and a priority queue

Owner review 1, phase 2 (docs/requests/2026-10-15-owner-review-1.md, R2).

Jobs now run one at a time on the desktop and on the server. Parallelism
(Settings > Rendering, TITANO_PARALLELISM) is how many photos the running
job processes at once: thumbnail and proxy passes draw that many photos
together and still write the pack and checkpoints in frame order, decode
tiers are probed that many at a time, the deep analysis measures that many
frames and a render decodes that many ahead. Wherever originals are
developed whole (TIFF, PNG, RAW without a usable preview), fewer run at
once within the memory budget, which the running job now has whole; the
server's frame window is sized to the host instead of 1 GiB.

A new job waits its turn and pausing the running job starts the next one.
An optional priority queue gives each job kind a level (renders, imports
and downloads high, verifies and proxies low by default): a queued job of
a higher level pauses the running one without asking, and that job goes
back to the queue with its checkpoint and resumes by itself afterwards.
Jobs of the same level, and a job's own follow-ups, never interrupt it.
The Jobs screen and the admin panel show the parallelism and the queue;
Settings > Rendering and the admin panel's Settings set them, at once.

TITANO_WORKERS and the Workers key of server.json still set the
parallelism (1 to 64, with a warning at start for the variable).
Titano.Tools gains i18n prune, which removed the renamed keys from the 36
machine-translated languages; the new strings are translated in all 38.

Found while testing: uploads and imports failed when a pass read the
sidecar while they wrote it (atomic writes now retry the rename while a
reader holds the file, and never for a read-only one), and taking a lease
just released while another process read it failed on Windows (the create
now waits for the reader). Five adversarial review rounds checked the
phase before this commit.

Also updates BRIEF (12.8, 14.6, 14.8, 14.9, 24), DECISIONS, CHANGELOG,
ARCHITECTURE, STATUS, the request file and the compose/Unraid templates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-16 14:56:24 +02:00
1 parent 34d03051f5
commit 43b6871cdc
228 files changed
+3535 -793

No files matched your search

+243 -142
View File
@@ -1,14 +1,18 @@
using System.Collections.Concurrent;
using System.Threading.Channels;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Model;
namespace Titano.Data.Jobs;
public sealed record JobEngineOptions
{
/// <summary>Concurrent workers (BRIEF §14.6: default cores / 2).</summary>
public int Workers { get; init; } = Math.Max(1, Environment.ProcessorCount / 2);
/// <summary>
/// Jobs run at once: one (owner review 1, R2). Jobs run one at a time and the host's parallelism decides how many
/// photos the running job processes at once; tests run more workers to exercise concurrent claims.
/// </summary>
public int Workers { get; init; } = 1;
/// <summary>Identity stamped on claimed jobs (node id); also used for crash recovery.</summary>
public string WorkerId { get; init; } = Environment.MachineName;
@@ -18,7 +22,7 @@ public sealed record JobEngineOptions
public TimeSpan CheckpointInterval { get; init; } = TimeSpan.FromSeconds(5);
/// <summary>Fallback poll for jobs enqueued by other processes.</summary>
/// <summary>Fallback poll for jobs enqueued by other processes; also how often the priority queue is reviewed.</summary>
public TimeSpan PollInterval { get; init; } = TimeSpan.FromSeconds(3);
/// <summary>Finished jobs older than this are purged (BRIEF §14.6: 90 days).</summary>
@@ -26,20 +30,28 @@ public sealed record JobEngineOptions
/// <summary>Clock of the throughput windows and the checkpoint interval (tests pass their own).</summary>
public TimeProvider Time { get; init; } = TimeProvider.System;
/// <summary>The priority queue as the settings have it now, asked at every claim and review; null: off (<see cref="JobPriorityQueue"/>).</summary>
public Func<JobPriorityQueue>? PriorityQueue { get; init; }
}
/// <summary>
/// Persistent job queue runner (BRIEF §14.6): N workers claim queued jobs from the database by priority, run the
/// registered handler, checkpoint progress, and survive crashes (running jobs are requeued at start with their
/// checkpoints). Used by the desktop client (local mode) and the server. Jobs an <see cref="ISelectiveJobHandler"/>
/// declines stay queued for other claimers. The number of workers can change while the engine runs
/// (<see cref="SetWorkers"/>, Settings › Rendering › Parallelism on the desktop).
/// Persistent job queue runner (BRIEF §14.6, amended by owner review 1): one worker claims queued jobs from the database
/// in claim order, runs the registered handler, checkpoints progress, and survives crashes (running jobs are requeued at
/// start with their checkpoints). Used by the desktop client (local mode) and the server. Jobs an
/// <see cref="ISelectiveJobHandler"/> declines stay queued for other claimers. With the priority queue on
/// (<see cref="JobEngineOptions.PriorityQueue"/>) a queued job of a higher level makes the running job of a lower level
/// yield: it goes back to the queue with its checkpoint and resumes by itself afterwards, never interrupted by the
/// follow-ups it queued itself.
/// </summary>
public sealed class JobEngine : IAsyncDisposable
{
/// <summary>Queued jobs of selective kinds examined per claim; jobs declined beyond it wait until those ahead leave the queue.</summary>
private const int SelectiveWindow = 100;
/// <summary>Queued jobs a review looks through for one that is not a follow-up of the running job.</summary>
private const int ReviewWindow = 50;
/// <summary>Claims lost to other workers before a worker waits for the next poll.</summary>
private const int MaxClaimRaces = 16;
@@ -48,34 +60,22 @@ public sealed class JobEngine : IAsyncDisposable
private IReadOnlyCollection<JobKind> _kinds = [];
private Dictionary<JobKind, ISelectiveJobHandler> _selective = [];
private IReadOnlyCollection<JobKind> _others = [];
private readonly ConcurrentDictionary<Guid, CancellationTokenSource> _running = new();
private readonly ConcurrentDictionary<Guid, RunningJob> _running = new();
private readonly Channel<bool> _wake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
private readonly Channel<bool> _review = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
private readonly CancellationTokenSource _shutdown = new();
private readonly List<Task> _workers = [];
private readonly Lock _workerGate = new();
private readonly HashSet<int> _activeWorkers = [];
private int _workerTarget;
private bool _workersStarted;
private readonly List<Task> _loops = [];
private readonly Lock _gate = new();
public JobEngine(TitanoDatabase db, IEnumerable<IJobHandler> handlers, JobEngineOptions? options = null)
{
_db = db;
Options = options ?? new JobEngineOptions();
_handlers = handlers.ToDictionary(h => h.Kind);
_workerTarget = Options.Workers;
}
public JobEngineOptions Options { get; }
/// <summary>Workers that claim jobs: <see cref="JobEngineOptions.Workers"/> until <see cref="SetWorkers"/> changes it.</summary>
public int Workers
{
get
{
lock (_workerGate) return _workerTarget;
}
}
/// <summary>A job changed state (queued, running, done, failed, cancelled, paused).</summary>
public event Action<Job>? JobChanged;
@@ -84,7 +84,10 @@ public sealed class JobEngine : IAsyncDisposable
public IReadOnlyCollection<Guid> RunningJobIds => [.. _running.Keys];
/// <summary>Requeues this worker's interrupted jobs, purges old history and starts the workers.</summary>
/// <summary>The priority queue as it is now (<see cref="JobEngineOptions.PriorityQueue"/>).</summary>
public JobPriorityQueue PriorityQueue => Options.PriorityQueue?.Invoke() ?? JobPriorityQueue.Off;
/// <summary>Requeues this worker's interrupted jobs, purges old history and starts the worker and the queue's review.</summary>
public async Task StartAsync(CancellationToken cancellationToken = default)
{
var requeued = await _db.Jobs.RequeueRunningAsync(Options.WorkerId, cancellationToken).ConfigureAwait(false);
@@ -99,59 +102,28 @@ public sealed class JobEngine : IAsyncDisposable
Log.Info("jobs", "No job handlers; this engine claims nothing");
return;
}
lock (_workerGate)
var shutdown = _shutdown.Token;
lock (_gate)
{
_workersStarted = true;
for (var i = 0; i < _workerTarget; i++) StartWorker(i);
}
}
/// <summary>
/// Changes the number of workers. More start claiming at once; the surplus ones finish the job they are running
/// (never interrupted) and then stop. Before <see cref="StartAsync"/> it only sets how many start.
/// </summary>
public void SetWorkers(int count)
{
ArgumentOutOfRangeException.ThrowIfLessThan(count, 1);
lock (_workerGate)
{
if (_workerTarget == count) return;
_workerTarget = count;
if (_workersStarted)
for (var i = 0; i < Options.Workers; i++)
{
for (var i = 0; i < count; i++) StartWorker(i);
// A single worker keeps the plain id; numbered ones get "#n" (crash recovery requeues both).
var id = Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{i}";
_loops.Add(Task.Run(() => WorkerLoopAsync(id, shutdown), CancellationToken.None));
}
_loops.Add(Task.Run(() => SuperviseAsync(shutdown), CancellationToken.None));
}
Log.Info("jobs", $"Job engine set to {count} worker(s)");
Wake();
}
/// <summary>Queues a job and wakes a worker.</summary>
public async Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel = null, string? parametersJson = null,
JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default)
{
var job = new Job
{
Id = Guid.CreateVersion7(),
Kind = kind,
TargetIds = targets,
TargetLabel = targetLabel,
ParametersJson = parametersJson,
Priority = priority,
State = JobState.Queued,
CreatedBy = createdBy,
Created = DateTimeOffset.UtcNow,
};
await _db.Jobs.EnqueueAsync(job, cancellationToken).ConfigureAwait(false);
JobChanged?.Invoke(job);
Wake();
return job;
}
public Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel = null, string? parametersJson = null,
JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default) =>
EnqueueAsync(Guid.CreateVersion7(), kind, targets, targetLabel, parametersJson, priority, createdBy, cancellationToken);
/// <summary>Cancels a queued or running job; a running handler observes its token.</summary>
public Task CancelAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Cancelled, cancellationToken);
/// <summary>Pauses a job: a running one stops at its next check and keeps its checkpoint.</summary>
/// <summary>Pauses a job: a running one stops at its next check and keeps its checkpoint, and the next queued job starts.</summary>
public Task PauseAsync(Guid id, CancellationToken cancellationToken = default) => TransitionAsync(id, JobState.Paused, cancellationToken);
/// <summary>Resumes a paused job or retries a failed/cancelled one from its last checkpoint.</summary>
@@ -162,22 +134,24 @@ public sealed class JobEngine : IAsyncDisposable
Wake();
}
/// <summary>Signals workers that new work may be available (also call on PostgreSQL NOTIFY).</summary>
public void Wake() => _wake.Writer.TryWrite(true);
/// <summary>
/// Signals that the queue may have changed (also call on PostgreSQL NOTIFY, and after the priority queue's settings
/// changed): an idle worker looks for work, and the priority queue is reviewed at once.
/// </summary>
public void Wake()
{
_wake.Writer.TryWrite(true);
_review.Writer.TryWrite(true);
}
public async ValueTask DisposeAsync()
{
Task[] workers;
lock (_workerGate)
{
// No worker starts any more: the shutdown token is about to be disposed.
_workersStarted = false;
workers = [.. _workers];
}
Task[] loops;
lock (_gate) loops = [.. _loops];
await _shutdown.CancelAsync().ConfigureAwait(false);
try
{
await Task.WhenAll(workers).ConfigureAwait(false);
await Task.WhenAll(loops).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -226,9 +200,66 @@ public sealed class JobEngine : IAsyncDisposable
/// <summary>True when this engine claims jobs of <paramref name="kind"/> (it has a handler and the kind is not filtered out).</summary>
internal bool Runs(JobKind kind) => _kinds.Contains(kind);
/// <summary>
/// Queues follow-up work of the running job <paramref name="parent"/> (<see cref="JobContext.EnqueueFollowUpAsync"/>):
/// it works on what the parent produces, so it never interrupts it, whatever its level. Null when this engine has no
/// handler for <paramref name="kind"/>.
/// </summary>
internal async Task<Job?> EnqueueFollowUpAsync(Guid parent, JobKind kind, IReadOnlyList<Guid> targets, string? label, string? parametersJson,
JobPriority priority, Guid? createdBy, CancellationToken cancellationToken)
{
if (!Runs(kind)) return null;
var id = Guid.CreateVersion7();
// Known before the job is queued, so the review its queueing starts already leaves the parent running.
if (_running.TryGetValue(parent, out var run)) run.FollowUps.TryAdd(id, 0);
return await EnqueueAsync(id, kind, targets, label, parametersJson, priority, createdBy, cancellationToken).ConfigureAwait(false);
}
internal void StopJob(Guid id)
{
if (_running.TryGetValue(id, out var cts)) cts.Cancel();
if (_running.TryGetValue(id, out var run)) run.Stop();
}
/// <summary>
/// Makes the running job yield when the priority queue is on and a queued job of a higher level waits that this engine
/// would claim (not a follow-up of that running job): the running job of the lowest level stops, goes back to the
/// queue with its checkpoint and resumes after the higher ones. A free worker would claim the waiting job anyway, so
/// only a full engine interrupts one. True when a job was asked to yield.
/// </summary>
internal async Task<bool> ReviewAsync(CancellationToken cancellationToken)
{
var queue = PriorityQueue;
if (!queue.Enabled) return false;
var running = _running.Values.Where(r => !r.Yielding).ToList();
if (running.Count == 0 || running.Count < Options.Workers) return false;
var lowest = running.MinBy(r => queue.LevelOf(r.Job.Kind))!;
if (queue.LevelOf(lowest.Job.Kind) == JobKindPriority.High) return false;
var next = await PeekAsync(queue, lowest, cancellationToken).ConfigureAwait(false);
if (next is null || !queue.Interrupts(next.Kind, lowest.Job.Kind)) return false;
if (!lowest.Yield(next)) return false;
Log.Info("jobs", $"{lowest.Job.Kind} job {lowest.Job.Id} yields to {next.Kind} job {next.Id} (priority queue)");
return true;
}
private async Task<Job> EnqueueAsync(Guid id, JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel, string? parametersJson,
JobPriority priority, Guid? createdBy, CancellationToken cancellationToken)
{
var job = new Job
{
Id = id,
Kind = kind,
TargetIds = targets,
TargetLabel = targetLabel,
ParametersJson = parametersJson,
Priority = priority,
State = JobState.Queued,
CreatedBy = createdBy,
Created = DateTimeOffset.UtcNow,
};
await _db.Jobs.EnqueueAsync(job, cancellationToken).ConfigureAwait(false);
JobChanged?.Invoke(job);
Wake();
return job;
}
private async Task TransitionAsync(Guid id, JobState state, CancellationToken cancellationToken)
@@ -243,34 +274,11 @@ public sealed class JobEngine : IAsyncDisposable
if (await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } job) JobChanged?.Invoke(job);
}
/// <summary>Starts worker <paramref name="index"/> unless it runs already; call under <see cref="_workerGate"/>.</summary>
private void StartWorker(int index)
{
if (!_activeWorkers.Add(index)) return;
// A single worker keeps the plain id (as before workers could be added); numbered ones get "#n".
var id = index == 0 && Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{index}";
var shutdown = _shutdown.Token;
_workers.Add(Task.Run(() => WorkerLoopAsync(index, id, shutdown), CancellationToken.None));
}
/// <summary>True when worker <paramref name="index"/> is beyond the wanted count; it is then no longer active.</summary>
private bool Retires(int index)
{
lock (_workerGate)
{
if (index < _workerTarget) return false;
_activeWorkers.Remove(index);
return true;
}
}
/// <summary>Claims and runs jobs until shutdown, or until <see cref="SetWorkers"/> no longer wants this worker.
/// Nothing a job or a handler throws ends the worker.</summary>
private async Task WorkerLoopAsync(int index, string workerId, CancellationToken shutdown)
/// <summary>Claims and runs jobs until shutdown. Nothing a job or a handler throws ends the worker.</summary>
private async Task WorkerLoopAsync(string workerId, CancellationToken shutdown)
{
while (!shutdown.IsCancellationRequested)
{
if (Retires(index)) return;
Job? job;
try
{
@@ -288,22 +296,13 @@ public sealed class JobEngine : IAsyncDisposable
if (job is null)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
timeout.CancelAfter(Options.PollInterval);
try
{
await _wake.Reader.ReadAsync(timeout.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Poll interval elapsed or shutdown.
}
await WaitAsync(_wake, shutdown).ConfigureAwait(false);
continue;
}
try
{
await RunAsync(job, shutdown).ConfigureAwait(false);
await RunAsync(job, workerId, shutdown).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -315,28 +314,64 @@ public sealed class JobEngine : IAsyncDisposable
}
/// <summary>
/// The next job in claim order (priority, then age). Without selective handlers the database picks it atomically.
/// With them, the first job a selective handler accepts among the first <see cref="SelectiveWindow"/> of its kinds
/// competes with the head of the other kinds: the other kinds are still claimed atomically, the selective job by id.
/// A lost race means another worker took a job, so looking again at once makes progress.
/// Reviews the priority queue (<see cref="ReviewAsync"/>) whenever the queue may have changed (<see cref="Wake"/>) and
/// at every poll, which also covers jobs queued by other processes. Nothing a review throws ends it.
/// </summary>
private async Task SuperviseAsync(CancellationToken shutdown)
{
while (!shutdown.IsCancellationRequested)
{
await WaitAsync(_review, shutdown).ConfigureAwait(false);
if (shutdown.IsCancellationRequested) return;
try
{
await ReviewAsync(shutdown).ConfigureAwait(false);
}
catch (OperationCanceledException) when (shutdown.IsCancellationRequested)
{
return;
}
catch (Exception ex)
{
Log.Warning("jobs", "The priority queue could not be reviewed", ex);
}
}
}
/// <summary>Waits for a signal on <paramref name="channel"/>, the poll interval or shutdown, whichever comes first.</summary>
private async Task WaitAsync(Channel<bool> channel, CancellationToken shutdown)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
timeout.CancelAfter(Options.PollInterval);
try
{
await channel.Reader.ReadAsync(timeout.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Poll interval elapsed or shutdown.
}
}
/// <summary>
/// The next job in claim order (<see cref="JobPriorityQueue.ClaimsBefore"/>). Without selective handlers the database
/// picks it atomically. With them, the first job a selective handler accepts among the first
/// <see cref="SelectiveWindow"/> of its kinds competes with the head of the other kinds: the other kinds are still
/// claimed atomically, the selective job by id. A lost race means another worker took a job, so looking again at once
/// makes progress.
/// </summary>
private async Task<Job?> ClaimAsync(string workerId, CancellationToken cancellationToken)
{
if (_selective.Count == 0) return await _db.Jobs.ClaimNextAsync(workerId, _kinds, cancellationToken).ConfigureAwait(false);
var queue = PriorityQueue;
if (_selective.Count == 0) return await _db.Jobs.ClaimNextAsync(workerId, _kinds, queue, cancellationToken).ConfigureAwait(false);
for (var attempt = 0; attempt < MaxClaimRaces; attempt++)
{
Job? candidate = null;
foreach (var queued in await _db.Jobs.ListQueuedAsync(_selective.Keys, SelectiveWindow, cancellationToken).ConfigureAwait(false))
var candidate = await AcceptedAsync(queue, null, cancellationToken).ConfigureAwait(false);
if (candidate is null) return _others.Count > 0 ? await _db.Jobs.ClaimNextAsync(workerId, _others, queue, cancellationToken).ConfigureAwait(false) : null;
if (_others.Count > 0 && (await _db.Jobs.ListQueuedAsync(_others, 1, queue, cancellationToken).ConfigureAwait(false)).FirstOrDefault() is { } head
&& queue.ClaimsBefore(head, candidate))
{
if (!await AcceptsAsync(queued, cancellationToken).ConfigureAwait(false)) continue;
candidate = queued;
break;
}
if (candidate is null) return _others.Count > 0 ? await _db.Jobs.ClaimNextAsync(workerId, _others, cancellationToken).ConfigureAwait(false) : null;
if (_others.Count > 0 && (await _db.Jobs.ListQueuedAsync(_others, 1, cancellationToken).ConfigureAwait(false)).FirstOrDefault() is { } head
&& ClaimsBefore(head, candidate))
{
if (await _db.Jobs.ClaimNextAsync(workerId, _others, cancellationToken).ConfigureAwait(false) is { } next) return next;
if (await _db.Jobs.ClaimNextAsync(workerId, _others, queue, cancellationToken).ConfigureAwait(false) is { } next) return next;
}
else if (await _db.Jobs.TryClaimAsync(candidate.Id, workerId, cancellationToken).ConfigureAwait(false) is { } claimed)
{
@@ -346,6 +381,34 @@ public sealed class JobEngine : IAsyncDisposable
return null;
}
/// <summary>The job a free worker would claim now (<see cref="ClaimAsync"/>) leaving out the follow-ups of <paramref name="running"/>, without claiming it.</summary>
private async Task<Job?> PeekAsync(JobPriorityQueue queue, RunningJob running, CancellationToken cancellationToken)
{
var candidate = _selective.Count > 0 ? await AcceptedAsync(queue, running, cancellationToken).ConfigureAwait(false) : null;
Job? head = null;
if (_others.Count > 0)
{
foreach (var queued in await _db.Jobs.ListQueuedAsync(_others, ReviewWindow, queue, cancellationToken).ConfigureAwait(false))
{
if (running.FollowUps.ContainsKey(queued.Id)) continue;
head = queued;
break;
}
}
return head is null ? candidate : candidate is null || queue.ClaimsBefore(head, candidate) ? head : candidate;
}
/// <summary>The first queued job of the selective kinds whose handler takes it now, leaving out the follow-ups of <paramref name="running"/>.</summary>
private async Task<Job?> AcceptedAsync(JobPriorityQueue queue, RunningJob? running, CancellationToken cancellationToken)
{
foreach (var queued in await _db.Jobs.ListQueuedAsync(_selective.Keys, SelectiveWindow, queue, cancellationToken).ConfigureAwait(false))
{
if (running?.FollowUps.ContainsKey(queued.Id) == true || !await AcceptsAsync(queued, cancellationToken).ConfigureAwait(false)) continue;
return queued;
}
return null;
}
/// <summary>A job its handler cannot judge is taken, so it fails here with its reason instead of blocking the queue.</summary>
private async ValueTask<bool> AcceptsAsync(Job job, CancellationToken cancellationToken)
{
@@ -360,14 +423,14 @@ public sealed class JobEngine : IAsyncDisposable
}
}
private static bool ClaimsBefore(Job a, Job b) =>
a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0;
private async Task RunAsync(Job job, CancellationToken shutdown)
private async Task RunAsync(Job job, string workerId, CancellationToken shutdown)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(shutdown);
_running[job.Id] = cts;
var run = new RunningJob(job, cts);
_running[job.Id] = run;
JobChanged?.Invoke(job);
// A job queued while this one was being claimed may outrank it.
_review.Writer.TryWrite(true);
var context = new JobContext(this, job, cts.Token);
JobState final;
string? error = null;
@@ -381,15 +444,17 @@ public sealed class JobEngine : IAsyncDisposable
}
catch (OperationCanceledException) when (cts.IsCancellationRequested)
{
// Read once: the job a yield names is set together with the yield itself.
var yieldsTo = shutdown.IsCancellationRequested ? null : run.YieldsTo;
var yielded = yieldsTo is not null;
if (yieldsTo is not null) context.Log(Loc.L("Jobs.Line.Yielded", Loc.L("Jobs.Kind." + yieldsTo.Kind)));
await PersistAsync(context).ConfigureAwait(false);
if (shutdown.IsCancellationRequested)
{
// Engine stopping: leave the job running so the next start requeues it from its checkpoint.
_running.TryRemove(job.Id, out _);
return;
}
// Cancel or pause already wrote the state; keep it.
_running.TryRemove(job.Id, out _);
// Engine stopping: leave the job running so the next start requeues it from its checkpoint.
if (shutdown.IsCancellationRequested) return;
// Yielded to a higher job: back to the queue with its checkpoint, unless the user paused or cancelled it
// meanwhile (their state stays). Otherwise cancel or pause already wrote the state; keep it.
if (yielded) await _db.Jobs.RequeueAsync(job.Id, workerId, CancellationToken.None).ConfigureAwait(false);
await NotifyAsync(job.Id, CancellationToken.None).ConfigureAwait(false);
return;
}
@@ -408,4 +473,40 @@ public sealed class JobEngine : IAsyncDisposable
await _db.Jobs.SetStateAsync(job.Id, final, error, CancellationToken.None).ConfigureAwait(false);
await NotifyAsync(job.Id, CancellationToken.None).ConfigureAwait(false);
}
/// <summary>A job a worker runs: how it is stopped, whether it was stopped to yield, and the follow-ups it queued.</summary>
private sealed class RunningJob(Job job, CancellationTokenSource cancellation)
{
private Job? _yieldsTo;
public Job Job { get; } = job;
/// <summary>Jobs this one queued as follow-ups (<see cref="EnqueueFollowUpAsync"/>): they never make it yield.</summary>
public ConcurrentDictionary<Guid, byte> FollowUps { get; } = new();
public bool Yielding => YieldsTo is not null;
/// <summary>The job of a higher level this one yields to; set, atomically, before it is stopped.</summary>
public Job? YieldsTo => Volatile.Read(ref _yieldsTo);
/// <summary>Signals the job's token; a job that ended meanwhile (its source disposed) needs nothing.</summary>
public void Stop()
{
try
{
cancellation.Cancel();
}
catch (ObjectDisposedException)
{
}
}
/// <summary>Stops the job to yield to <paramref name="to"/>; false when it is yielding already.</summary>
public bool Yield(Job to)
{
if (Interlocked.CompareExchange(ref _yieldsTo, to, null) is not null) return false;
Stop();
return true;
}
}
}