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

@@ -0,0 +1,132 @@
using Titano.Data.Archiving;
using Titano.Testing;
namespace Titano.Data.Tests.Archiving;
/// <summary>Several photos of a pass at once (owner review 1, R2), their results taken in order.</summary>
public sealed class OrderedWorkTests
{
[Test]
public async Task ResultsAreTakenInOrderWhateverFinishesFirst()
{
var taken = new List<int>();
await using (var work = new OrderedWork<int>(4, n =>
{
taken.Add(n);
return ValueTask.CompletedTask;
}, CancellationToken.None))
{
for (var i = 0; i < 24; i++)
{
var n = i;
// The later items are the quicker ones.
await work.AddAsync(_ =>
{
Thread.Sleep((24 - n) * 2);
return n;
});
if (n % 5 == 0) await work.AddAsync(1000 + n);
}
await work.CompleteAsync();
}
int[] expected = [.. Enumerable.Range(0, 24).SelectMany(n => n % 5 == 0 ? new[] { n, 1000 + n } : [n])];
Assert.SequenceEqual(expected, taken);
}
[Test]
public async Task ExactlyTheParallelismRunsAtOnceAndOneRunsInline()
{
var running = 0;
var peak = 0;
await using (var work = new OrderedWork<int>(3, _ => ValueTask.CompletedTask, CancellationToken.None))
{
for (var i = 0; i < 12; i++)
{
await work.AddAsync(_ =>
{
var now = Interlocked.Increment(ref running);
int seen;
while ((seen = Volatile.Read(ref peak)) < now && Interlocked.CompareExchange(ref peak, now, seen) != seen)
{
}
// Each waits for two others, which proves three run together whatever the load (the pool adds threads).
SpinWait.SpinUntil(() => Volatile.Read(ref peak) >= 3, TimeSpan.FromSeconds(10));
Thread.Sleep(2);
Interlocked.Decrement(ref running);
return 0;
});
}
await work.CompleteAsync();
}
Assert.Equal(3, peak);
var caller = Environment.CurrentManagedThreadId;
var threads = new List<int>();
await using (var single = new OrderedWork<int>(1, _ => ValueTask.CompletedTask, CancellationToken.None))
{
for (var i = 0; i < 3; i++)
{
await single.AddAsync(_ =>
{
threads.Add(Environment.CurrentManagedThreadId);
return 0;
});
}
await single.CompleteAsync();
}
Assert.SequenceEqual([caller, caller, caller], threads);
}
[Test]
public async Task AFailureStopsTheWorkStillRunningBeforeThePassEnds()
{
var started = 0;
var finished = 0;
var stopped = 0;
var taken = new List<int>();
var work = new OrderedWork<int>(4, n =>
{
taken.Add(n);
return ValueTask.CompletedTask;
}, CancellationToken.None);
var failure = await Assert.ThrowsAsync<InvalidDataException>(async () =>
{
try
{
for (var i = 0; i < 8; i++)
{
var n = i;
await work.AddAsync(ct =>
{
Interlocked.Increment(ref started);
try
{
if (n == 2) throw new InvalidDataException("damaged photo");
if (n > 2)
{
// The photos after the damaged one take long, until the pass stops them.
if (ct.WaitHandle.WaitOne(TimeSpan.FromSeconds(10))) Interlocked.Increment(ref stopped);
ct.ThrowIfCancellationRequested();
}
return n;
}
finally
{
Interlocked.Increment(ref finished);
}
});
}
await work.CompleteAsync();
}
finally
{
await work.DisposeAsync();
}
});
Assert.Equal("damaged photo", failure.Message);
Assert.SequenceEqual([0, 1], taken);
// Nothing the pass started outlives it.
Assert.Equal(Volatile.Read(ref started), Volatile.Read(ref finished));
Assert.Equal(Volatile.Read(ref started) - 3, Volatile.Read(ref stopped));
}
}
@@ -0,0 +1,97 @@
using Titano.Core.Archiving;
using Titano.Data.Archiving;
using Titano.Testing;
using static Titano.Data.Tests.Archiving.ArchiveFixture;
namespace Titano.Data.Tests.Archiving;
/// <summary>
/// Thumbnail and proxy passes working on several photos at once (owner review 1, R2: the parallelism decides how many
/// photos the running job processes at once): the same images as one at a time, written in frame order, and checkpoints
/// that still mean every frame before them is done.
/// </summary>
[Category("archive")]
public sealed class ParallelPassTests(TestContext context)
{
[Test]
public async Task SeveralPhotosAtOnceDrawTheSameThumbnailsInFrameOrder()
{
await using var fx = await CreateAsync(context);
// The pass commits its pack and checkpoints every 200 frames.
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "a"), Start, 430);
await fx.ScanAsync();
var location = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single();
var sequence = (await fx.Db.Sequences.GetAsync(location.Id))!;
var folder = fx.Paths.Sequence("a");
var parallel = new ArchiveService(fx.Db, new ArchiveServiceOptions { Owner = "test", Parallelism = () => 4 });
var checkpoints = new List<(int Next, int Total)>();
var result = await parallel.Images.BuildThumbnailsAsync(fx.Archive, sequence, false, 0, (next, total) =>
{
checkpoints.Add((next, total));
return ValueTask.CompletedTask;
}, fx.Ct);
Assert.Equal((430, 0, 0), (result.Built, result.Reused, result.Undecodable));
Assert.SequenceEqual([(200, 430), (400, 430)], checkpoints);
Dictionary<int, byte[]> drawn;
using (var pack = ThumbPackReader.Open(folder.ThumbsPackPath))
{
var entries = pack.Entries.Values.OrderBy(e => e.FrameIndex).ToList();
Assert.Count(430, entries);
// Appended in frame order, as one at a time.
Assert.SequenceEqual(entries.Select(e => e.Offset).Order(), entries.Select(e => e.Offset));
drawn = entries.ToDictionary(e => e.FrameIndex, e => pack.Read(e.FrameIndex)!);
}
var single = new ArchiveService(fx.Db, new ArchiveServiceOptions { Owner = "test", Parallelism = () => 1 });
await single.Images.BuildThumbnailsAsync(fx.Archive, sequence, force: true, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
using (var pack = ThumbPackReader.Open(folder.ThumbsPackPath))
{
foreach (var (index, jpeg) in drawn) Assert.SequenceEqual(jpeg, pack.Read(index)!);
}
}
[Test]
public async Task SeveralPhotosAtOnceWriteEveryProxyAndAResumedPassChecksWhatTheEarlierRunDid()
{
await using var fx = await CreateAsync(context);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "a"), Start, 24);
await fx.ScanAsync();
var location = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single();
var sequence = (await fx.Db.Sequences.GetAsync(location.Id))!;
var folder = fx.Paths.Sequence("a");
var parallel = new ArchiveService(fx.Db, new ArchiveServiceOptions { Owner = "test", Parallelism = () => 6 });
// Resumed at frame 10: it makes the proxies from there on, and those before it, which the earlier run should have
// made, are missing, so the sequence is not built.
var resumed = await parallel.Images.BuildProxiesAsync(fx.Archive, sequence, false, 10, (_, _) => ValueTask.CompletedTask, fx.Ct);
Assert.Equal((14, 0, 0), (resumed.Built, resumed.Reused, resumed.Undecodable));
Assert.FileMissing(folder.Proxy(0));
Assert.FileExists(folder.Proxy(10));
Assert.False((await fx.Db.Sequences.GetAsync(location.Id))!.Status.HasFlag(Titano.Core.Model.SequenceStatus.ProxiesBuilt), "not built");
var full = await parallel.Images.BuildProxiesAsync(fx.Archive, sequence, false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
Assert.Equal((10, 14), (full.Built, full.Reused));
foreach (var frame in ManifestStore.ReadSequence(folder.ManifestPath).Frames)
Assert.True(ArchiveImages.IsProxyOf(folder.Proxy(frame.I), frame.CapturedAt, frame.W, frame.H, null), $"proxy of {frame.File}");
Assert.True((await fx.Db.Sequences.GetAsync(location.Id))!.Status.HasFlag(Titano.Core.Model.SequenceStatus.ProxiesBuilt), "built");
}
[Test]
public void LargeOriginalsDecodeFewerAtOnceWithinTheMemoryBudget()
{
// 24 MP takes some 768 MB while it is decoded.
const long sensor24 = 6000 * 4000;
Assert.Equal(2, DecodeBudget.PhotosAtOnce(8, 2L << 30, sensor24));
Assert.Equal(1, DecodeBudget.PhotosAtOnce(8, 512L << 20, sensor24));
Assert.Equal(8, DecodeBudget.PhotosAtOnce(8, 64L << 30, sensor24));
Assert.Equal(1, DecodeBudget.PhotosAtOnce(1, 64L << 30, sensor24));
// Small photos all fit; an unknown size counts as 24 MP.
Assert.Equal(8, DecodeBudget.PhotosAtOnce(8, 2L << 30, 48 * 32));
Assert.Equal(2, DecodeBudget.PhotosAtOnce(8, 2L << 30, 0));
// The size a damaged file claims never overflows: one decode at a time.
Assert.Equal(1, DecodeBudget.PhotosAtOnce(8, 64L << 30, 1L << 59));
Assert.Equal(1, DecodeBudget.PhotosAtOnce(8, 64L << 30, long.MaxValue));
}
}
+164 -41
View File
@@ -252,63 +252,186 @@ public sealed class JobEngineTests(TestContext context)
Assert.Empty((await db.Jobs.ListAsync(null, JobKind.LightAnalyse)).Items);
}
[Test]
public async Task TheNumberOfWorkersChangesWhileTheEngineRuns()
/// <summary>Waits until <paramref name="condition"/> holds, failing with <paramref name="what"/> after ten seconds.</summary>
private static async Task UntilAsync(Func<bool> condition, string what)
{
await using var db = await OpenAsync();
var running = 0;
var started = 0;
var release = new SemaphoreSlim(0);
var handler = new CallbackHandler(JobKind.Thumbs, async c =>
var until = DateTime.UtcNow.AddSeconds(10);
while (!condition())
{
Interlocked.Increment(ref running);
Interlocked.Increment(ref started);
Assert.True(DateTime.UtcNow < until, what);
await Task.Delay(20);
}
}
/// <summary>A handler whose jobs run until released, counting those running and started, by kind.</summary>
private sealed class GatedHandler(JobKind kind, SemaphoreSlim release) : IJobHandler
{
public int Running;
public int Started;
public JobKind Kind => kind;
public async Task RunAsync(JobContext c)
{
Interlocked.Increment(ref Running);
Interlocked.Increment(ref Started);
try
{
await release.WaitAsync(c.Cancellation);
}
finally
{
Interlocked.Decrement(ref running);
}
});
await using var engine = new JobEngine(db, [handler], new JobEngineOptions { Workers = 1, WorkerId = "pc", PollInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync();
var jobs = new List<Job>();
for (var i = 0; i < 6; i++) jobs.Add(await engine.EnqueueAsync(JobKind.Thumbs, []));
async Task UntilAsync(Func<bool> condition, string what)
{
var until = DateTime.UtcNow.AddSeconds(10);
while (!condition())
{
Assert.True(DateTime.UtcNow < until, what);
await Task.Delay(20);
Interlocked.Decrement(ref Running);
}
}
}
// One worker: one job at a time.
await UntilAsync(() => Volatile.Read(ref running) == 1, "the first job runs");
[Test]
public async Task JobsRunOneAtATimeAndPausingStartsTheNext()
{
// Owner review 1 (R2): one job at a time by default; pausing the running job lets the next one start.
await using var db = await OpenAsync();
var release = new SemaphoreSlim(0);
var handler = new GatedHandler(JobKind.Thumbs, release);
await using var engine = new JobEngine(db, [handler], new JobEngineOptions { WorkerId = "pc", PollInterval = TimeSpan.FromMilliseconds(50) });
Assert.Equal(1, engine.Options.Workers);
await engine.StartAsync();
var jobs = new List<Job>();
for (var i = 0; i < 3; i++) jobs.Add(await engine.EnqueueAsync(JobKind.Thumbs, []));
await UntilAsync(() => Volatile.Read(ref handler.Running) == 1, "the first job runs");
await Task.Delay(300);
Assert.Equal(1, Volatile.Read(ref running));
Assert.Equal((1, 1), (Volatile.Read(ref handler.Running), Volatile.Read(ref handler.Started)));
Assert.Count(1, engine.RunningJobIds);
var first = engine.RunningJobIds.First();
Assert.Equal("pc", (await db.Jobs.GetAsync(first))!.NodeId);
// Three workers: two more jobs start at once, and no fourth.
engine.SetWorkers(3);
Assert.Equal(3, engine.Workers);
await UntilAsync(() => Volatile.Read(ref running) == 3, "three jobs run together");
await engine.PauseAsync(first);
await UntilAsync(() => Volatile.Read(ref handler.Started) == 2 && Volatile.Read(ref handler.Running) == 1, "the next job starts");
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(first))!.State);
release.Release(10);
foreach (var job in jobs.Where(j => j.Id != first)) await WaitForStateAsync(db, job.Id, JobState.Done, TimeSpan.FromSeconds(10));
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(first))!.State);
}
[Test]
public async Task WithoutThePriorityQueueARunningJobIsNeverInterrupted()
{
await using var db = await OpenAsync();
var release = new SemaphoreSlim(0);
var scan = new GatedHandler(JobKind.Scan, release);
var render = new GatedHandler(JobKind.Render, release);
await using var engine = new JobEngine(db, [scan, render], new JobEngineOptions { WorkerId = "pc", PollInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync();
var scanning = await engine.EnqueueAsync(JobKind.Scan, []);
await UntilAsync(() => Volatile.Read(ref scan.Running) == 1, "the scan runs");
var rendering = await engine.EnqueueAsync(JobKind.Render, [], priority: JobPriority.User);
await Task.Delay(400);
Assert.Equal((1, 0), (Volatile.Read(ref scan.Running), Volatile.Read(ref render.Started)));
Assert.Equal(JobState.Queued, (await db.Jobs.GetAsync(rendering.Id))!.State);
release.Release(10);
await WaitForStateAsync(db, scanning.Id, JobState.Done, TimeSpan.FromSeconds(10));
await WaitForStateAsync(db, rendering.Id, JobState.Done, TimeSpan.FromSeconds(10));
Assert.Equal(1, Volatile.Read(ref scan.Started));
}
[Test]
public async Task AHigherJobPausesTheRunningOneWhichResumesFromItsCheckpoint()
{
// Owner review 1 (R2): with render at the highest level, starting a render while a scan runs pauses the scan
// without asking, renders, and resumes the scan by itself where it was.
await using var db = await OpenAsync();
var checkpointed = new TaskCompletionSource();
var go = new SemaphoreSlim(0);
var scan = new CountingHandler(JobKind.Scan, 4, async (i, ct) =>
{
if (i < 2) return;
checkpointed.TrySetResult();
await go.WaitAsync(ct);
});
var renderRelease = new SemaphoreSlim(0);
var render = new GatedHandler(JobKind.Render, renderRelease);
var queue = new JobPriorityQueue { Enabled = true };
Assert.Equal((JobKindPriority.High, JobKindPriority.Normal), (queue.LevelOf(JobKind.Render), queue.LevelOf(JobKind.Scan)));
await using var engine = new JobEngine(db, [scan, render],
new JobEngineOptions { WorkerId = "pc", PollInterval = TimeSpan.FromMilliseconds(50), PriorityQueue = () => queue });
await engine.StartAsync();
var scanning = await engine.EnqueueAsync(JobKind.Scan, []);
await checkpointed.Task.WaitAsync(TimeSpan.FromSeconds(10));
var rendering = await engine.EnqueueAsync(JobKind.Render, [], priority: JobPriority.User);
await UntilAsync(() => Volatile.Read(ref render.Running) == 1, "the render starts at once");
var paused = await db.Jobs.GetAsync(scanning.Id);
Assert.Equal((JobState.Queued, "2", (string?)null), (paused!.State, paused.Checkpoint, paused.NodeId));
Assert.Contains(Titano.Core.Localization.Loc.L("Jobs.Kind.Render"), paused.LogTail);
// The scan waits while the render runs, then resumes from its checkpoint without being asked.
go.Release(10);
await Task.Delay(300);
Assert.Equal(3, Volatile.Read(ref running));
Assert.Equal(JobState.Queued, (await db.Jobs.GetAsync(scanning.Id))!.State);
renderRelease.Release();
await WaitForStateAsync(db, rendering.Id, JobState.Done, TimeSpan.FromSeconds(10));
await WaitForStateAsync(db, scanning.Id, JobState.Done, TimeSpan.FromSeconds(10));
lock (scan.SeenCheckpoints) Assert.SequenceEqual([null, "2"], scan.SeenCheckpoints);
Assert.Equal(1, scan.Completed);
}
// Back to one: the running jobs finish undisturbed, then a single worker carries on.
engine.SetWorkers(1);
release.Release(3);
await UntilAsync(() => Volatile.Read(ref started) == 4 && Volatile.Read(ref running) == 1, "one job after the three");
await Task.Delay(300);
Assert.Equal((4, 1), (Volatile.Read(ref started), Volatile.Read(ref running)));
[Test]
public async Task OnlyAHigherLevelInterruptsAndNeverTheJobsOwnFollowUps()
{
await using var db = await OpenAsync();
var release = new SemaphoreSlim(0);
var queued = new TaskCompletionSource<Job?>();
// The light analysis queues a deep analysis of the same sequence, which the user put higher.
var light = new CallbackHandler(JobKind.LightAnalyse, async c =>
{
queued.TrySetResult(await c.EnqueueFollowUpAsync(JobKind.DeepAnalyse, [Guid.NewGuid()], "Roof", null, JobPriority.Background));
await release.WaitAsync(c.Cancellation);
});
var deep = new GatedHandler(JobKind.DeepAnalyse, release);
var thumbs = new GatedHandler(JobKind.Thumbs, release);
var queue = new JobPriorityQueue
{
Enabled = true,
Levels = new Dictionary<JobKind, JobKindPriority> { [JobKind.DeepAnalyse] = JobKindPriority.High, [JobKind.Thumbs] = JobKindPriority.Normal },
};
await using var engine = new JobEngine(db, [light, deep, thumbs],
new JobEngineOptions { WorkerId = "pc", PollInterval = TimeSpan.FromMilliseconds(50), PriorityQueue = () => queue });
await engine.StartAsync();
var analysing = await engine.EnqueueAsync(JobKind.LightAnalyse, []);
var followUp = Assert.NotNull(await queued.Task.WaitAsync(TimeSpan.FromSeconds(10)));
// A job of the same level waits too.
var drawing = await engine.EnqueueAsync(JobKind.Thumbs, [], priority: JobPriority.User);
await Task.Delay(400);
Assert.Equal(JobState.Running, (await db.Jobs.GetAsync(analysing.Id))!.State);
Assert.Equal((0, 0), (Volatile.Read(ref deep.Started), Volatile.Read(ref thumbs.Started)));
Assert.False(await engine.ReviewAsync(context.Cancellation));
release.Release(3);
foreach (var job in jobs) await WaitForStateAsync(db, job.Id, JobState.Done, TimeSpan.FromSeconds(10));
Assert.Throws<ArgumentOutOfRangeException>(() => engine.SetWorkers(0));
// Another deep analysis, not its own, interrupts it.
var other = await engine.EnqueueAsync(JobKind.DeepAnalyse, [Guid.NewGuid()], priority: JobPriority.User);
await UntilAsync(() => Volatile.Read(ref deep.Running) == 1, "a higher job runs");
Assert.Equal(JobState.Queued, (await db.Jobs.GetAsync(analysing.Id))!.State);
release.Release(20);
foreach (var id in new[] { analysing.Id, followUp.Id, drawing.Id, other.Id }) await WaitForStateAsync(db, id, JobState.Done, TimeSpan.FromSeconds(10));
}
[Test]
public async Task RequeueingAYieldedJobLeavesPausesAndOtherNodesAlone()
{
await using var db = await OpenAsync();
var job = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.Verify, State = JobState.Queued, Created = DateTimeOffset.UtcNow };
await db.Jobs.EnqueueAsync(job);
Assert.NotNull(await db.Jobs.ClaimNextAsync("pc"));
Assert.False(await db.Jobs.RequeueAsync(job.Id, "other"));
await db.Jobs.SetStateAsync(job.Id, JobState.Paused);
Assert.False(await db.Jobs.RequeueAsync(job.Id, "pc"));
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(job.Id))!.State);
await db.Jobs.SetStateAsync(job.Id, JobState.Queued);
Assert.NotNull(await db.Jobs.ClaimNextAsync("pc"));
Assert.True(await db.Jobs.RequeueAsync(job.Id, "pc"));
Assert.Equal((JobState.Queued, (string?)null), ((await db.Jobs.GetAsync(job.Id))!.State, (await db.Jobs.GetAsync(job.Id))!.NodeId));
}
[Test]
@@ -0,0 +1,106 @@
using Titano.Core.Model;
using Titano.Data.Jobs;
using Titano.Testing;
namespace Titano.Data.Tests.Jobs;
/// <summary>The priority queue of the settings (owner review 1, R2): levels per kind of job, the claim order and what interrupts.</summary>
[Category("jobs")]
public sealed class JobPriorityQueueTests
{
private static readonly DateTimeOffset T0 = new(2026, 10, 16, 9, 0, 0, TimeSpan.Zero);
[Test]
public void RendersImportsAndDownloadsComeFirstAndTheLongResumablePassesLast()
{
var queue = new JobPriorityQueue();
Assert.Equal(JobKindPriority.High, queue.LevelOf(JobKind.Render));
Assert.Equal(JobKindPriority.High, queue.LevelOf(JobKind.Import));
Assert.Equal(JobKindPriority.High, queue.LevelOf(JobKind.Download));
Assert.Equal(JobKindPriority.Low, queue.LevelOf(JobKind.Verify));
Assert.Equal(JobKindPriority.Low, queue.LevelOf(JobKind.Proxies));
foreach (var kind in new[] { JobKind.Scan, JobKind.Thumbs, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Maintenance })
Assert.Equal(JobKindPriority.Normal, queue.LevelOf(kind));
// A level the user set wins over the default.
Assert.Equal(JobKindPriority.Low, (queue with { Levels = new Dictionary<JobKind, JobKindPriority> { [JobKind.Render] = JobKindPriority.Low } }).LevelOf(JobKind.Render));
}
[Test]
public void OnlyAHigherLevelInterruptsAndOnlyWhileTheQueueIsOn()
{
var on = new JobPriorityQueue { Enabled = true };
Assert.True(on.Interrupts(JobKind.Render, JobKind.Scan));
Assert.True(on.Interrupts(JobKind.Scan, JobKind.Verify));
Assert.False(on.Interrupts(JobKind.Scan, JobKind.Render));
Assert.False(on.Interrupts(JobKind.Thumbs, JobKind.Scan));
Assert.False(on.Interrupts(JobKind.Import, JobKind.Render));
Assert.False(JobPriorityQueue.Off.Interrupts(JobKind.Render, JobKind.Verify));
}
[Test]
public void TheQueueOrdersByLevelThenPriorityThenAge()
{
var on = new JobPriorityQueue { Enabled = true };
var oldVerify = Job(JobKind.Verify, JobPriority.User, -30);
var backgroundScan = Job(JobKind.Scan, JobPriority.Background, -20);
var userThumbs = Job(JobKind.Thumbs, JobPriority.User, -10);
var render = Job(JobKind.Render, JobPriority.Normal, 0);
Job[] jobs = [oldVerify, backgroundScan, userThumbs, render];
Assert.SequenceEqual([render, userThumbs, backgroundScan, oldVerify], Sorted(jobs, on));
// Off, the strict queue of before: priority, then age.
Assert.SequenceEqual([oldVerify, userThumbs, render, backgroundScan], Sorted(jobs, JobPriorityQueue.Off));
// Two jobs alike fall back to the id.
var twin = render with { Id = Guid.CreateVersion7() };
Assert.True(on.ClaimsBefore(render, twin) != on.ClaimsBefore(twin, render));
}
[Test]
public void SettingsKeepOnlyTheLevelsThatDifferAndSkipWhatTheyCannotRead()
{
var queue = JobPriorityQueue.From(true, new Dictionary<string, string>
{
["deep-analyse"] = "high",
["Scan"] = "LOW",
["render"] = "high",
["teleport"] = "high",
["verify"] = "urgent",
["99"] = "low",
});
Assert.True(queue.Enabled);
Assert.Equal((JobKindPriority.High, JobKindPriority.Low, JobKindPriority.Low), (queue.LevelOf(JobKind.DeepAnalyse), queue.LevelOf(JobKind.Scan), queue.LevelOf(JobKind.Verify)));
var stored = JobPriorityQueue.Changed(Enum.GetValues<JobKind>().ToDictionary(k => k, queue.LevelOf));
Assert.SequenceEqual(["deep-analyse", "scan"], stored.Keys.Order(StringComparer.Ordinal));
Assert.Equal(("high", "low"), (stored["deep-analyse"], stored["scan"]));
var reread = JobPriorityQueue.From(true, stored);
foreach (var kind in Enum.GetValues<JobKind>()) Assert.Equal(queue.LevelOf(kind), reread.LevelOf(kind));
Assert.Equal(JobKindPriority.High, JobPriorityQueue.From(false, stored).LevelOf(JobKind.DeepAnalyse));
Assert.False(JobPriorityQueue.From(false, null).Enabled);
}
[Test]
public void TheClaimOrderOfTheDatabaseListsOnlyTheLevelsOtherThanNormal()
{
var on = new JobPriorityQueue { Enabled = true };
Assert.Equal(string.Empty, JobPriorityQueue.Off.OrderSql([JobKind.Render, JobKind.Verify]));
Assert.Equal(string.Empty, on.OrderSql([JobKind.Scan, JobKind.Thumbs]));
Assert.Equal("CASE WHEN kind IN (7) THEN 2 WHEN kind IN (2) THEN 0 ELSE 1 END DESC, ", on.OrderSql([JobKind.Render, JobKind.Verify, JobKind.Scan, JobKind.Render]));
}
private static Job[] Sorted(Job[] jobs, JobPriorityQueue queue)
{
var list = jobs.ToList();
list.Sort((a, b) => a.Id == b.Id ? 0 : queue.ClaimsBefore(a, b) ? -1 : 1);
return [.. list];
}
private static Job Job(JobKind kind, JobPriority priority, int minutes) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
Priority = priority,
State = JobState.Queued,
Created = T0.AddMinutes(minutes),
};
}
@@ -0,0 +1,176 @@
using Titano.Core.Analysis.Deep;
using Titano.Core.Archiving;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Processing;
using Titano.Testing;
using SequenceFrames = Titano.Data.Processing.SequenceFrames;
namespace Titano.Data.Tests.Processing;
/// <summary>
/// Photos decoded at once (owner review 1, R2): the whole parallelism, unless developing large originals whole would
/// exceed the memory budget. Only the decodes that develop an original count: a JPEG at least twice the size asked for
/// decodes scaled down, and a frame read through its proxy or an embedded preview of that size needs no development.
/// </summary>
public sealed class DecodeParallelismTests
{
/// <summary>2 GiB: two 24 MP developments (some 768 MB each), one of 45 MP.</summary>
private const long Budget = 2L << 30;
private static readonly ImageDecoder Server = DecoderFactory.CreateServer();
[Test]
public void WhatADecodeDevelopsWholeDependsOnTheFormatTheSizeAskedForAndThePreview()
{
const int w = 6000, h = 4000;
Assert.Equal(0, DecodeBudget.Developed(ImageFileFormat.Jpeg, w, h, 0, 320, preferPreview: false));
Assert.Equal(0, DecodeBudget.Developed(ImageFileFormat.Jpeg, w, h, 0, 3000, preferPreview: false));
// A 4K render of a 24 MP JPEG decodes it nearly whole; full size (0) always does.
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Jpeg, w, h, 0, 3840, preferPreview: false));
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Jpeg, w, h, 0, 0, preferPreview: true));
// A preview reaching the size serves only decodes that prefer previews; a render develops the RAW.
Assert.Equal(0, DecodeBudget.Developed(ImageFileFormat.Cr2, w, h, 1620, 512, preferPreview: true));
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Cr2, w, h, 1620, 512, preferPreview: false));
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Cr2, w, h, 1620, 2048, preferPreview: true));
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Tiff, w, h, 0, 320, preferPreview: true));
// Only RAW decoders take a preview by choice: a TIFF's or a HEIF's is never a shortcut.
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Tiff, w, h, w, 512, preferPreview: true));
Assert.Equal(24_000_000, DecodeBudget.Developed(ImageFileFormat.Heif, w, h, 512, 512, preferPreview: true));
Assert.Equal(0, DecodeBudget.Developed(ImageFileFormat.Dng, w, h, 1024, 512, preferPreview: true));
Assert.Equal(DecodeBudget.UnknownPixels, DecodeBudget.Developed(ImageFileFormat.Png, 0, 0, 0, 320, preferPreview: true));
}
[Test]
public void ThumbnailAndProxyPassesHoldBackOnlyForTheOriginalsTheyDevelop()
{
static SidecarFrame Frame(ImageFileFormat format, int width, int height, int? preview = null) =>
new() { Id = Guid.NewGuid(), File = "f", Format = format, W = width, H = height, PreviewW = preview, PreviewH = preview * 2 / 3 };
static int Thumbnails(params SidecarFrame[] frames) => ArchiveImages.PassParallelism(8, Budget, frames, 320, preferPreview: true, Server);
static int Proxies(int edge, params SidecarFrame[] frames) => ArchiveImages.PassParallelism(8, Budget, frames, edge, preferPreview: false, Server);
Assert.Equal(8, Thumbnails(Frame(ImageFileFormat.Jpeg, 8192, 5464), Frame(ImageFileFormat.Cr2, 8192, 5464, preview: 1620)));
// A HEIF the server reads through its proxy or preview develops nothing either.
Assert.Equal(8, Thumbnails(Frame(ImageFileFormat.Heif, 8192, 5464)));
// A 45 MP TIFF is decoded whole: one at a time within 2 GiB, whatever the JPEGs beside it.
Assert.Equal(1, Thumbnails(Frame(ImageFileFormat.Jpeg, 8192, 5464), Frame(ImageFileFormat.Tiff, 8192, 5464)));
// A RAW whose preview is smaller than the thumbnail is developed; a size nobody knows counts as 24 MP.
Assert.Equal(2, Thumbnails(Frame(ImageFileFormat.Cr2, 6000, 4000, preview: 160)));
Assert.Equal(2, Thumbnails(Frame(ImageFileFormat.Png, 0, 0)));
Assert.Equal(1, ArchiveImages.PassParallelism(0, Budget, [Frame(ImageFileFormat.Jpeg, 48, 32)], 320, preferPreview: true, Server));
// Proxies of 2048 px scale JPEGs down but develop every RAW, preview or not; full-size proxies decode JPEGs whole.
Assert.Equal(8, Proxies(2048, Frame(ImageFileFormat.Jpeg, 8192, 5464)));
Assert.Equal(2, Proxies(2048, Frame(ImageFileFormat.Cr2, 6000, 4000, preview: 6000)));
Assert.Equal(2, Proxies(0, Frame(ImageFileFormat.Jpeg, 6000, 4000)));
}
[Test]
public void ADeepAnalysisHoldsBackOnlyForTheOriginalsItDevelops()
{
var analysis = DeepAnalysisOptions.Default with { MaxDegreeOfParallelism = 8 };
Assert.Equal(8, SequenceAnalyser.AnalysisParallelism(analysis, Frames((ImageFileFormat.Jpeg, 8192, 5464, 0)), Budget));
// A DNG whose embedded preview reaches the analysis size (half the long edge, at most 2048 px) develops nothing.
Assert.Equal(8, SequenceAnalyser.AnalysisParallelism(analysis, Frames((ImageFileFormat.Dng, 5568, 4872, 2784)), Budget));
Assert.Equal(1, SequenceAnalyser.AnalysisParallelism(analysis, Frames((ImageFileFormat.Dng, 5568, 4872, 1024), (ImageFileFormat.Tiff, 8192, 5464, 0)), Budget));
// Frames read through their proxies decode as JPEGs.
Assert.Equal(8, SequenceAnalyser.AnalysisParallelism(analysis, Frames((ImageFileFormat.Tiff, 8192, 5464, 0)) with { Proxied = [true] }, Budget));
}
[Test]
public async Task AWindowHoldsBackWheneverItsDecodesDevelopOriginals()
{
var window = new FrameWindowOptions { MemoryBudget = Budget, MaxConcurrentLoads = 8, Ahead = 8 };
var tiffs = Frames((ImageFileFormat.Tiff, 8192, 5464, 0), (ImageFileFormat.Tiff, 8192, 5464, 0));
// A render node renders downloaded originals without counting what they decode (Originals unset): still held back.
await using (var node = new SequenceFrameSource(tiffs, tiffs.LightFrames(), Server, window))
{
Assert.Equal(1, node.WindowOptions(1920, DecodePurpose.Render).MaxConcurrentLoads);
// A preparation pass decodes TIFFs whole too.
Assert.Equal(1, node.WindowOptions(512, DecodePurpose.Analysis).MaxConcurrentLoads);
Assert.Equal((Budget, 8), (node.WindowOptions(1920, DecodePurpose.Render).MemoryBudget, node.WindowOptions(1920, DecodePurpose.Render).Ahead));
}
// RAWs whose previews reach the preparation's size: the preparation runs them all, the render develops them.
var raws = Frames((ImageFileFormat.Cr2, 6000, 4000, 1620), (ImageFileFormat.Cr2, 6000, 4000, 1620));
await using (var raw = new SequenceFrameSource(raws, raws.LightFrames(), Server, window) { Originals = true })
{
Assert.Equal(8, raw.WindowOptions(512, DecodePurpose.Analysis).MaxConcurrentLoads);
Assert.Equal(2, raw.WindowOptions(1920, DecodePurpose.Render).MaxConcurrentLoads);
}
// Proxies decode as JPEGs, flagged or found in a proxy cache's .jpg files.
await using (var proxied = new SequenceFrameSource(tiffs with { Proxied = [true, true] }, tiffs.LightFrames(), Server, window))
Assert.Equal(8, proxied.WindowOptions(1920, DecodePurpose.Render).MaxConcurrentLoads);
var cached = raws with { Files = ["cache/0001.jpg", "cache/0002.JPG"] };
await using var cache = new SequenceFrameSource(cached, cached.LightFrames(), Server, window);
Assert.Equal(8, cache.WindowOptions(1920, DecodePurpose.Render).MaxConcurrentLoads);
}
[Test]
public async Task ADemandLoadWaitsForTheReadAheadOfADevelopingWindow()
{
// The window caps its read-ahead only: a render that skips frames (a speed-up) asks for a frame the read-ahead is
// not decoding while it develops another, and both would run. One development at a time fits this budget.
var decoder = new CountingDecoder();
var tiffs = Frames([.. Enumerable.Repeat((ImageFileFormat.Tiff, 8192, 5464, 0), 8)]);
var frames = tiffs with { Files = [.. tiffs.Files.Select(f => f + ".tif")] };
var window = new FrameWindowOptions { MemoryBudget = Budget, MaxConcurrentLoads = 8, Ahead = 8 };
await using (var source = new SequenceFrameSource(frames, frames.LightFrames(), new ImageDecoder([decoder]), window))
{
Assert.Equal(1, source.DevelopingLimit(1920, DecodePurpose.Render));
foreach (var index in new[] { 0, 2, 4, 6 })
using (await source.GetFrameAsync(index, 1920, DecodePurpose.Render, CancellationToken.None)) { }
}
Assert.Equal(1, decoder.Peak);
Assert.Greater(decoder.Decodes, 4);
}
/// <summary>Decodes anything as a tiny frame, slowly, and counts how many decodes run at once.</summary>
private sealed class CountingDecoder : IImageDecoderProvider
{
private int _running;
private int _peak;
private int _decodes;
public int Peak => Volatile.Read(ref _peak);
public int Decodes => Volatile.Read(ref _decodes);
public string Name => "counting";
public DecodeTier? TierFor(ImageFileFormat format) => DecodeTier.Native;
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
{
var now = Interlocked.Increment(ref _running);
int seen;
while ((seen = Volatile.Read(ref _peak)) < now && Interlocked.CompareExchange(ref _peak, now, seen) != seen)
{
}
Interlocked.Increment(ref _decodes);
Thread.Sleep(40);
Interlocked.Decrement(ref _running);
return new DecodedImage(new ImageBuffer(8, 6), DecodeTier.Native, Name, 8192, 5464);
}
}
private static SequenceFrames Frames(params (ImageFileFormat Format, int Width, int Height, int Preview)[] specs)
{
var sequence = new Sequence { Id = Guid.NewGuid(), ArchiveId = Guid.NewGuid(), Folder = "a" };
var frames = specs.Select((s, i) => new Frame
{
Id = Guid.NewGuid(),
SequenceId = sequence.Id,
Index = i,
RelativePath = $"a/IMG_{i:0000}",
FileName = $"IMG_{i:0000}",
CapturedAt = new DateTime(2026, 10, 16, 6, 0, 0).AddSeconds(10 * i),
Width = s.Width,
Height = s.Height,
Format = s.Format,
PreviewWidth = s.Preview,
PreviewHeight = s.Preview * 2 / 3,
}).ToList();
return new SequenceFrames(sequence, frames, [.. frames.Select(f => (string?)f.RelativePath)]);
}
}
@@ -36,6 +36,27 @@ public abstract class JobRepositoryTests(TestContext context) : RepositoryTest(c
Assert.Equal(job with { TargetIds = read.TargetIds }, read);
}
[Test]
public async Task ThePriorityQueueClaimsTheHigherKindsFirst()
{
// Owner review 1 (R2): on, the level of the kind comes before priority and age; off, the strict queue stays.
var db = await OpenTitanoAsync();
var oldVerify = TestData.Job(JobKind.Verify, JobPriority.User, TestData.Now.AddMinutes(-30));
var backgroundScan = TestData.Job(JobKind.Scan, JobPriority.Background, TestData.Now.AddMinutes(-20));
var userThumbs = TestData.Job(JobKind.Thumbs, JobPriority.User, TestData.Now.AddMinutes(-10));
var render = TestData.Job(JobKind.Render, JobPriority.Normal, TestData.Now);
foreach (var job in new[] { oldVerify, backgroundScan, userThumbs, render }) await db.Jobs.EnqueueAsync(job, Ct);
var queue = new Titano.Data.Jobs.JobPriorityQueue { Enabled = true };
JobKind[] kinds = [JobKind.Verify, JobKind.Scan, JobKind.Thumbs, JobKind.Render];
Assert.SequenceEqual([render.Id, userThumbs.Id, backgroundScan.Id, oldVerify.Id], (await db.Jobs.ListQueuedAsync(kinds, 10, queue, Ct)).Select(j => j.Id));
Assert.SequenceEqual([oldVerify.Id, userThumbs.Id, render.Id, backgroundScan.Id], (await db.Jobs.ListQueuedAsync(kinds, 10, Ct)).Select(j => j.Id));
Assert.Equal(userThumbs.Id, (await db.Jobs.ClaimNextAsync("server", [JobKind.Scan, JobKind.Thumbs, JobKind.Verify], queue, Ct))?.Id);
var order = new List<Guid>();
while (await db.Jobs.ClaimNextAsync("server", null, queue, Ct) is { } claimed) order.Add(claimed.Id);
Assert.SequenceEqual([render.Id, backgroundScan.Id, oldVerify.Id], order);
}
[Test]
public async Task ClaimsByPriorityThenAgeAndKind()
{