Files
Chronos/tests/Titano.App.Tests/Settings/SettingsLogicTests.cs
T
Alby96andClaude Opus 5.5 43b6871cdc 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>
2026-10-16 14:56:24 +02:00

333 lines
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.ComponentModel;
using System.Globalization;
using System.IO;
using Titano.App.Settings;
using Titano.Core.Localization;
using Titano.Core.Naming;
using Titano.Core.Video;
using Titano.Testing;
namespace Titano.App.Tests.Settings;
public sealed class SettingsLogicTests
{
public SettingsLogicTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public void DefaultTemplatesPreviewThreeNames()
{
var names = NamingPreview.FirstNames(TemplateDefaults.Folder, TemplateDefaults.File);
Assert.SequenceEqual(
[
"2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2",
"2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-13_0002.CR2",
"2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-15_0003.CR2",
],
names);
Assert.Null(NamingPreview.Validate(TemplateDefaults.Folder, isFolder: true));
Assert.Null(NamingPreview.Validate(TemplateDefaults.File, isFolder: false));
}
[Theory]
[Case("{date}_{time}_{n:0000", "Errors.Template.UnclosedBrace", "", 15)]
[Case("{date}_{nope}", "Errors.Template.UnknownToken", "nope", 8)]
[Case("{}_{n}", "Errors.Template.EmptyToken", "", 1)]
[Case("{n}}x", "Errors.Template.UnopenedBrace", "", 4)]
[Case(" ", "Errors.Template.Empty", "", 1)]
[Case("{date}", "Errors.Template.NotUnique", "", 0)]
[Case("{year}/{n}", "Errors.Template.FileSeparator", "", 0)]
[Case("{date:%}_{n}", "Errors.Template.Format", "", 0)]
public void InvalidFileTemplatesExplainTheProblem(string template, string key, string token, int position)
{
var expected = position > 0 ? Loc.L(key, token, position) : Loc.L(key);
Assert.Equal(expected, NamingPreview.Validate(template, isFolder: false), template);
Assert.Empty(NamingPreview.FirstNames(TemplateDefaults.Folder, template));
}
[Test]
public void TemplateErrorsNameThePosition()
{
Assert.Equal("The brace opened at position 8 is never closed.", NamingPreview.Validate("{date}_{time", isFolder: false));
Assert.Equal("Unknown token “nope” at position 8.", NamingPreview.Validate("{date}_{nope}", isFolder: false));
}
[Test]
public void FolderTemplatesMayNestAndRepeat()
{
Assert.Null(NamingPreview.Validate("{year}/{month}/{camera}", isFolder: true));
Assert.Equal("2026/09/Canon EOS R5/IMG_4211.CR2", NamingPreview.FirstNames("{year}/{month}/{camera}", "{name}")[0]);
}
[Test]
public void EnterCommitsAndEscReverts()
{
string? stored = null;
var field = new EditableField("8", v => int.TryParse(v, out var n) && n is >= 1 and <= 32 ? null : "1 to 32", v => stored = v, () => "Worker threads");
var changes = new List<string?>();
field.PropertyChanged += (_, e) => changes.Add(e.PropertyName);
var errors = 0;
field.ErrorsChanged += (_, _) => errors++;
field.Text = "12";
Assert.True(field.IsDirty);
Assert.False(field.HasErrors);
Assert.Equal("Worker threads", field.ToolTip);
Assert.True(field.Commit());
Assert.Equal("12", stored);
Assert.Equal("12", field.Value);
Assert.False(field.IsDirty);
field.Text = "99";
Assert.True(field.HasErrors);
Assert.Equal("1 to 32", field.ToolTip);
Assert.Equal("1 to 32", ((IEnumerable<string>)field.GetErrors(nameof(EditableField.Text))).Single());
Assert.False(field.Commit());
Assert.Equal("12", stored);
field.Revert();
Assert.Equal("12", field.Text);
Assert.False(field.HasErrors);
Assert.False(field.IsDirty);
Assert.Equal(2, errors);
Assert.Contains(nameof(EditableField.ToolTip), changes);
}
[Test]
public void LoadReplacesTheValueWithoutCommitting()
{
var commits = 0;
var field = new EditableField("a", v => v.Length == 0 ? "empty" : null, _ => commits++, () => "tip");
field.Load("b");
Assert.Equal("b", field.Value);
Assert.Equal("b", field.Text);
Assert.False(field.IsDirty);
Assert.Equal(0, commits);
Assert.True(field.Commit());
Assert.Equal(0, commits); // nothing changed, nothing stored
field.Load(string.Empty);
Assert.True(field.HasErrors);
}
[Test]
public void TheLanguageListHasEveryShippedCatalog()
{
var available = LanguageCatalog.Available;
Assert.Equal("en", available[0].Code);
Assert.Equal(available.Count, available.Select(l => l.Code).Distinct(StringComparer.OrdinalIgnoreCase).Count());
foreach (var option in available)
{
Assert.Contains(option.Code, Languages.Shipped);
Assert.True(LanguageCatalog.HasResources(option.Code), option.Code);
Assert.False(string.IsNullOrWhiteSpace(option.Name));
}
// Every culture folder of the catalog is offered, and nothing else.
var folders = Directory.EnumerateDirectories(Path.Combine(TestContext.RepositoryRoot, "i18n"))
.Select(Path.GetFileName)
.Where(n => n is not null && Directory.EnumerateFiles(Path.Combine(TestContext.RepositoryRoot, "i18n", n), "*.resx").Any())
.ToHashSet(StringComparer.OrdinalIgnoreCase);
Assert.Contains("it", folders);
Assert.SequenceEqual(folders.Order(StringComparer.OrdinalIgnoreCase), available.Select(o => o.Code).Order(StringComparer.OrdinalIgnoreCase));
Assert.Equal("Italiano", available.Single(o => o.Code == "it").Name);
Assert.Equal("it", LanguageCatalog.Match(CultureInfo.GetCultureInfo("it-CH")).Code);
Assert.Equal("en", LanguageCatalog.Match(CultureInfo.GetCultureInfo("sw")).Code);
}
[Test]
public void EachEncoderNamesThePresetsItServes()
{
var hevc = new EncoderRow("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc);
var av1 = hevc with { Codec = "AV1", Name = "NVIDIA AV1 Encoder MFT", VideoCodec = VideoCodec.Av1 };
var h264 = new EncoderRow("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264);
var animation = new EncoderRow("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null);
Assert.SequenceEqual(["8K archive", "4K archive", "4K HEVC", "DCI 4K", "Cinema 21:9", "4K 60 fps"], EncoderUse.Presets(hevc));
Assert.Equal("Animated GIF · Animated PNG", EncoderUse.Text(animation));
Assert.Contains("Share 1080p", EncoderUse.Presets(h264));
Assert.Equal("4K AV1", EncoderUse.Text(av1));
}
[Test]
public void ARenderNodeOffersHardwareEncodersOnlyWhenRendersMayUseThem()
{
EncoderRow[] rows =
[
new("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc),
new("H.264", "NVIDIA H.264 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, false, 4096, 4096, VideoCodec.H264),
new("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264),
new("MJPEG · AVI", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg),
];
Assert.Equal("HEVC · H.264", EncoderUse.Codecs(EncoderUse.Node(rows, allowsHardware: true)));
Assert.Equal(3, EncoderUse.Node(rows, allowsHardware: true).Count);
Assert.Equal("H.264", EncoderUse.Codecs(EncoderUse.Node(rows, allowsHardware: false)));
Assert.Null(EncoderUse.Codecs([]));
}
[Test]
public void ThePreviewTitleSpeaksTheInterfaceLanguage()
{
// The sample's title is a catalog string read on every preview (so a language switch shows at once), not English text.
Assert.Equal("Harbour sunset", NamingPreview.FirstNames("{title}", "{n:0000}")[0].Split('/')[0]);
Assert.Equal("Harbour sunset", NamingPreview.SampleFrames[0].Title);
Assert.False(ReferenceEquals(NamingPreview.SampleFrames, NamingPreview.SampleFrames), "built on each call");
var italian = Loc.Get("Settings.Naming.SampleTitle", CultureInfo.GetCultureInfo("it"));
Assert.True(italian is { Length: > 0 } && italian != "Harbour sunset", italian);
}
[Test]
public void TheQualityProfileTunesTheJobs()
{
var settings = new Titano.App.Infrastructure.AppSettings { Quality = Titano.App.Infrastructure.QualityProfile.Best, Parallelism = 3, MemoryBudgetGb = 6 };
var basis = new Titano.Data.Processing.ProcessingOptions();
// One job runs at a time (owner review 1): it has the whole 6 GB, and decodes and measures 3 photos at once.
var best = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((6L << 30, @"C:\cache", 8, 3), (best.FrameWindow.MemoryBudget, best.FrameWindow.SpillDirectory, best.FrameWindow.Ahead, best.FrameWindow.MaxConcurrentLoads));
Assert.Equal((1024, Titano.Core.Project.FlowQualitySetting.Best), (best.Render.AnalysisLongEdge, best.Render.DefaultFlowQuality));
Assert.Equal(3, best.DeepAnalysis.MaxDegreeOfParallelism);
settings.Parallelism = 1;
var single = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((6L << 30, 1, 1), (single.FrameWindow.MemoryBudget, single.FrameWindow.MaxConcurrentLoads, single.DeepAnalysis.MaxDegreeOfParallelism));
// A parallelism beyond the read-ahead widens the window, so the decodes have frames to work on.
settings.Parallelism = 12;
var wide = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((12, 12, 12), (wide.FrameWindow.Ahead, wide.FrameWindow.MaxConcurrentLoads, wide.DeepAnalysis.MaxDegreeOfParallelism));
// Auto: a quarter of 32 GB, and half the 16 cores at once, with no cap of the analysis threads.
settings.Quality = Titano.App.Infrastructure.QualityProfile.Fast;
settings.MemoryBudgetGb = null;
settings.Parallelism = null;
var fast = ProcessingTuning.Apply(basis, settings, 32L << 30, 16, @"C:\cache");
Assert.Equal((8L << 30, 8), (fast.FrameWindow.MemoryBudget, fast.FrameWindow.Ahead));
Assert.Equal((8, 8), (fast.FrameWindow.MaxConcurrentLoads, fast.DeepAnalysis.MaxDegreeOfParallelism));
Assert.Equal((256, Titano.Core.Project.FlowQualitySetting.Draft), (fast.Render.AnalysisLongEdge, fast.Render.DefaultFlowQuality));
Assert.Equal(512, ProcessingTuning.PreparationLongEdge(Titano.App.Infrastructure.QualityProfile.Balanced));
}
[Test]
public void ParallelismAutoIsHalfTheCores()
{
// Photos the running job processes at once (owner review 1): half the cores, the archive engine's own default.
Assert.Equal(8, ProcessingTuning.ParallelismAuto(16));
Assert.Equal(2, ProcessingTuning.ParallelismAuto(4));
Assert.Equal(1, ProcessingTuning.ParallelismAuto(1));
Assert.Equal(Titano.Data.Archiving.ArchiveServiceOptions.DefaultParallelism, ProcessingTuning.ParallelismAuto(Environment.ProcessorCount));
Assert.Equal(1, new Titano.Data.Jobs.JobEngineOptions().Workers);
Assert.Equal(8, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings(), 16));
Assert.Equal(5, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings { Parallelism = 5 }, 16));
}
[Test]
public void TheAnalysisSettingsBecomeTheDeepAnalysisParameters()
{
var defaults = new Titano.App.Infrastructure.AppSettings().DeepAnalysis(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default);
// The defaults of Settings › Analysis are the engine's own: nothing changes until the user does.
Assert.Equal(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default.Fingerprint(), defaults.Fingerprint());
Assert.Equal(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default.StarFieldDensity, defaults.StarFieldDensity);
var tuned = new Titano.App.Infrastructure.AppSettings { AnalysisLongEdge = 1024, NightBrightnessPercent = 12.5, StarFieldDensity = 60 }
.DeepAnalysis(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default);
Assert.Equal((1024, -3.0, 60.0), (tuned.MaxAnalysisLongEdge, tuned.DarkLogLuminance, tuned.StarFieldDensity));
}
[Test]
public void NewCardsStartFromSettingsImport()
{
var settings = new Titano.App.Infrastructure.AppSettings
{
ImportSessionGapMinutes = 90,
ImportMinimumFrames = 20,
ImportSubfolders = false,
ImportVerify = false,
ImportDuplicates = Titano.Core.Import.DuplicatePolicy.ImportAgain,
ImportAfter = Titano.Data.Archiving.AfterImport.DeleteImported,
ImportEject = false,
DeepAnalysisAfterImport = false,
};
var profile = settings.ImportProfile("{year}", "{name}");
Assert.Equal(("{year}", "{name}", 90, 20), (profile.FolderTemplate, profile.FileTemplate, profile.SessionGapMinutes, profile.MinimumSessionFrames));
Assert.Equal((false, false, false, false), (profile.IncludeSubfolders, profile.VerifyCopies, profile.Eject, profile.DeepAnalysis));
Assert.Equal((Titano.Core.Import.DuplicatePolicy.ImportAgain, Titano.Data.Archiving.AfterImport.DeleteImported), (profile.Duplicates, profile.AfterImport));
// Untouched settings give the brief's card defaults.
Assert.Equal(new Titano.Data.Archiving.CardProfile(), new Titano.App.Infrastructure.AppSettings().ImportProfile(TemplateDefaults.Folder, TemplateDefaults.File));
}
[Test]
public void NewArchivesTakeSettingsArchive()
{
var settings = new Titano.App.Infrastructure.AppSettings { FolderTemplate = "{year}", FileTemplate = "{name}", ProxyLongEdge = 2560, ThumbnailLongEdge = 480 };
var archive = settings.ArchiveDefaults();
Assert.Equal(("{year}", "{name}", 2560, 480), (archive.Templates.Folder, archive.Templates.File, archive.Proxies.LongEdge, archive.Thumbnails.LongEdge));
Assert.Null((new Titano.App.Infrastructure.AppSettings().ArchiveDefaults() with { Name = "Archive" }).Problem());
}
[Test]
public void TheArchiveRowsEditOnlyTheArchiveAtTheArchiveFolder()
{
var main = new Titano.Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Main", RootPath = "/archive", Created = DateTimeOffset.UtcNow };
var travel = new Titano.Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Travel", RootPath = "/media/travel", Created = DateTimeOffset.UtcNow };
Assert.Equal(travel.Id, Titano.App.Archiving.CurrentArchive.At([main, travel], "/media/travel/")!.Id);
// A folder no archive of the index is at: no archive at all, never the first one (its archive.json is someone else's).
Assert.Null(Titano.App.Archiving.CurrentArchive.At([main, travel], "/media/new"));
Assert.Equal(main.Id, Titano.App.Archiving.CurrentArchive.Pick([main, travel], "/media/new")!.Id);
}
[Test]
public void SettingsSurviveARoundTripWithTheNewSections()
{
var settings = new Titano.App.Infrastructure.AppSettings { ThumbnailLongEdge = 640, ScanIntervalMinutes = 30, NightBrightnessPercent = 3.5, DeepAnalysisAfterScan = true };
var copy = Titano.App.Infrastructure.AppSettings.Parse(settings.ToJson())!;
Assert.Equal((640, 30, 3.5, true), (copy.ThumbnailLongEdge, copy.ScanIntervalMinutes, copy.NightBrightnessPercent, copy.DeepAnalysisAfterScan));
}
[Test]
public void BackgroundPriorityRaisesTheInterfaceOnlyInFront()
{
Assert.Equal(ThreadPriority.AboveNormal, InterfacePriority.For(enabled: true, active: true));
Assert.Equal(ThreadPriority.Normal, InterfacePriority.For(enabled: true, active: false));
Assert.Equal(ThreadPriority.Normal, InterfacePriority.For(enabled: false, active: true));
}
[Test]
public void FormatsShowTheirTierAndWhatToInstall()
{
Assert.Equal(("JPEG XL", "CR3", "3FR"), (FormatNames.Of(Titano.Core.Imaging.ImageFileFormat.JpegXl), FormatNames.Of(Titano.Core.Imaging.ImageFileFormat.Cr3),
FormatNames.Of(Titano.Core.Imaging.ImageFileFormat.ThreeFr)));
var heif = Titano.Core.Windows.Codecs.StoreExtension.Get(Titano.Core.Windows.Codecs.StoreExtensionKind.HeifImage);
var format = Titano.Core.Imaging.Decoders.DecoderFactory.DescribeFormats(Titano.Core.Imaging.Decoders.DecoderFactory.CreateClient(null))
.First(f => f.Format.Format == Titano.Core.Imaging.ImageFileFormat.Heif).Format;
var row = new FormatRowViewModel(new FormatRow(format, Titano.Core.Imaging.DecodeTier.EmbeddedPreview, "managed", [heif]));
Assert.Equal(("Preview only", "Titano", heif.ProductName), (row.TierText, row.DecoderText, row.NeedsText));
Assert.Equal(Titano.Ui.Controls.StatusKind.Warning, row.TierKind);
Assert.Equal("HEIF: Preview only", row.Announcement);
var missing = new MissingExtensionViewModel(heif, new Titano.Ui.Mvvm.RelayCommand(() => { }));
Assert.Equal(heif.ProductName + " missing", missing.Text);
var none = new FormatRowViewModel(new FormatRow(format, Titano.Core.Imaging.DecodeTier.Unavailable, null, []));
Assert.Equal(("Not supported", "—", "—", false), (none.TierText, none.DecoderText, none.NeedsText, none.HasNeeds));
}
[Test]
public void EnumDrivenKeysExistInEveryRequiredLanguage()
{
var keys = new List<string>();
keys.AddRange(Enum.GetNames<Titano.Core.Model.JobKind>().Select(k => "Jobs.Kind." + k));
keys.AddRange(Enum.GetNames<Titano.Core.Model.JobState>().Select(k => "Jobs.State." + k));
keys.AddRange(Enum.GetNames<Titano.Core.Model.JobState>().Select(k => "Tooltips.Jobs.State." + k));
keys.AddRange(Enum.GetNames<Titano.App.Jobs.JobFilter>().SelectMany(k => new[] { "Jobs.Filter." + k, "Tooltips.Jobs.Filter." + k }));
keys.AddRange(Enum.GetNames<Titano.App.Library.StatusFilter>().Where(k => k != "Any").Select(k => "Library.Filter.Status." + k));
keys.AddRange(Enum.GetNames<Titano.Data.Repositories.SequenceSort>().Select(k => "Library.Sort." + k));
keys.AddRange(Enum.GetNames<Titano.App.Server.ConnectError>().Where(k => k != "None").Select(k => "Server.Error." + k));
keys.AddRange(Enum.GetNames<Titano.Core.Model.UserRole>().SelectMany(k => new[] { "Server.Role." + k, "Tooltips.Server.Role." + k }));
keys.AddRange(Enum.GetNames<SettingsPage>().SelectMany(k => new[] { "Settings.Page." + k, "Tooltips.Settings.Page." + k }));
keys.AddRange(Enum.GetNames<Titano.App.Infrastructure.QualityProfile>().Select(k => "Settings.Rendering.Quality." + k));
keys.AddRange(new[] { "UnclosedBrace", "EmptyToken", "UnknownToken", "UnopenedBrace", "Empty" }.Select(k => "Errors.Template." + k));
// Italian completeness is checked by `Titano.Tools i18n check`; here every enum value must have its key.
var english = Loc.GetArea("Jobs", CultureInfo.InvariantCulture).Keys
.Concat(new[] { "Library", "Server", "Settings", "Tooltips", "Errors" }.SelectMany(a => Loc.GetArea(a, CultureInfo.InvariantCulture).Keys))
.ToHashSet(StringComparer.Ordinal);
foreach (var key in keys) Assert.True(english.Contains(key), key);
}
}