fix(settings): restore before the index opens; archive rows edit only their archive; parallelism follows the brief

Index restore (ENG-06, UI-09):
- A staged restore now runs on the files before the index is opened, so it also
  recovers an index that no longer opens; Settings > Advanced > Restore works
  without an open index (the current one is shown as unreadable).
- The staged copy passes PRAGMA quick_check (before migration, in a scratch copy)
  ahead of any backup: a damaged copy is set aside as .failed and never renews the
  daily copies. The index it replaces is kept as a VACUUM INTO copy, or, when it
  cannot be read, copied whole with its WAL as titano-replaced-<stamp>.db outside the
  rotation. The staged file is renamed over the index, so it is never applied twice.
- Archive > Maintenance gains Restore database..., which opens Settings > Advanced.

Archive settings (UI-03, ENG-03):
- An archive.json with an empty or overlong name (drive roots) can be edited again:
  the name read is made usable as at creation.
- Proxy and thumbnail sizes outside the presets (an admin's 3840) are listed and
  shown with their number.
- Changing the archive folder retargets the rows: an archive there is registered
  and rescanned; with none, the rows edit only the defaults of new archives. The
  rows never fall back to another archive of the index.
- Reset all and Import settings no longer rewrite the shared archive.json; Archive >
  Reset section asks first, naming the archive.
- PUT /api/v1/archive/settings: 409 archive_busy on a lease conflict, 409
  archive_manifest for a damaged, newer or foreign archive.json (was 500).

Parallelism (UI-02):
- Auto is the job engine's default, half the logical cores (BRIEF 14.6), with each
  job's own decode and analysis threads; a value the user sets is the number of
  workers and caps those threads. The memory budget is shared: each job's frame
  window gets budget / workers.

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-12 11:06:27 +00:00
1 parent 3e146c9f9f
commit 56aa4da674
63 files changed
+484 -179

No files matched your search

@@ -50,4 +50,47 @@ public sealed class AppServicesTests
environment.DeleteCaptureData();
}
}
/// <summary>BRIEF §6.2: a restore staged in Settings › Advanced recovers an index that no longer opens.</summary>
[Test]
[WindowsOnly]
public void AStagedRestoreRecoversAnIndexThatNoLongerOpens()
{
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
await using (var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)))
{
await db.Archives.UpsertAsync(new Archive { Id = Guid.CreateVersion7(), Name = "Kept", RootPath = @"C:\Kept", Created = DateTimeOffset.UtcNow });
var backup = await db.BackupAsync(environment.BackupDirectory, DatabaseBackups.Keep);
await DatabaseBackups.StageRestoreAsync(backup, environment.DatabasePath);
}
// The index is damaged beyond opening ("file is not a database").
File.Delete(environment.DatabasePath + "-wal");
File.Delete(environment.DatabasePath + "-shm");
await File.WriteAllBytesAsync(environment.DatabasePath, [.. Enumerable.Repeat((byte)0x5A, 8192)]);
var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs());
try
{
await services.OpenAsync(environment.DatabasePath);
Assert.Null(services.OpenError);
Assert.Equal(StagedRestoreResult.Restored, services.StagedRestore);
Assert.SequenceEqual(["Kept"], (await services.Database!.Archives.ListAsync()).Select(a => a.Name));
Assert.False(DatabaseBackups.HasStagedRestore(environment.DatabasePath));
}
finally
{
Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
}
});
}
finally
{
environment.DeleteCaptureData();
}
}
}
@@ -181,27 +181,35 @@ public sealed class SettingsLogicTests
var settings = new Titano.App.Infrastructure.AppSettings { Quality = Titano.App.Infrastructure.QualityProfile.Best, Parallelism = 3, MemoryBudgetGb = 6 };
var basis = new Titano.Data.Processing.ProcessingOptions();
// Three jobs at once share the 6 GB: 2 GB each; the user's 3 also caps the decodes and the analysis threads.
var best = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((6L << 30, @"C:\cache", 8, 2), (best.FrameWindow.MemoryBudget, best.FrameWindow.SpillDirectory, best.FrameWindow.Ahead, best.FrameWindow.MaxConcurrentLoads));
Assert.Equal((2L << 30, @"C:\cache", 8, 2), (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(int.Min(3, Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default.MaxDegreeOfParallelism), 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));
// Auto: a quarter of 32 GB shared by the engine's 8 workers on 16 cores; the jobs keep their own thread counts.
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, 4), (fast.FrameWindow.MemoryBudget, fast.FrameWindow.Ahead));
Assert.Equal((1L << 30, 4), (fast.FrameWindow.MemoryBudget, fast.FrameWindow.Ahead));
Assert.Equal((basis.FrameWindow.MaxConcurrentLoads, basis.DeepAnalysis.MaxDegreeOfParallelism), (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 ParallelismAutoLeavesFourCoresToTheInterface()
public void ParallelismAutoIsTheJobEnginesDefault()
{
Assert.Equal(12, ProcessingTuning.ParallelismAuto(16));
Assert.Equal(1, ProcessingTuning.ParallelismAuto(4));
Assert.Equal(1, ProcessingTuning.ParallelismAuto(2));
Assert.Equal(12, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings(), 16));
// BRIEF §14.6: workers default to half the cores; a 4-core laptop keeps two, so a long render never blocks a scan.
Assert.Equal(8, ProcessingTuning.ParallelismAuto(16));
Assert.Equal(2, ProcessingTuning.ParallelismAuto(4));
Assert.Equal(1, ProcessingTuning.ParallelismAuto(1));
Assert.Equal(new Titano.Data.Jobs.JobEngineOptions().Workers, ProcessingTuning.ParallelismAuto(Environment.ProcessorCount));
Assert.Equal(8, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings(), 16));
Assert.Equal(5, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings { Parallelism = 5 }, 16));
}
@@ -249,6 +257,18 @@ public sealed class SettingsLogicTests
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()
{
@@ -117,6 +117,22 @@ public sealed class SettingsScreenSmokeTests
await WaitAsync(() => Titano.Core.Archiving.ManifestStore.ReadArchive(manifestPath).ThumbnailPolicy.LongEdge == 480, "written into archive.json");
Assert.Equal(480, shell.Services.Settings.ThumbnailLongEdge);
// A proxy size the admin panel set (3840 is none of the presets) is shown as it is, not as 1920.
manifest = Titano.Core.Archiving.ManifestStore.ReadArchive(manifestPath);
Titano.Core.Archiving.ManifestStore.WriteArchive(manifestPath, manifest with { ProxyPolicy = manifest.ProxyPolicy with { LongEdge = 3840 } });
shell.Navigate(SectionKey.Library);
shell.Navigate(SectionKey.Settings);
await WaitAsync(() => settings.SelectedProxySize.Value == 3840, "the archive's own proxy size is shown");
Assert.Equal("3840", settings.SelectedProxySize.Label);
Assert.SequenceEqual([1280, 1920, 2560, 3840, Titano.Core.Archiving.ProxyPolicy.FullSize, Titano.Core.Archiving.ProxyPolicy.Disabled],
settings.ProxySizes.Select(s => s.Value));
// Reset section on Archive changes the archive everyone shares: it asks first, and a "no" leaves archive.json alone.
settings.ResetSectionCommand.Execute(null);
Assert.Equal((480, 3840), (Titano.Core.Archiving.ManifestStore.ReadArchive(manifestPath).ThumbnailPolicy.LongEdge,
Titano.Core.Archiving.ManifestStore.ReadArchive(manifestPath).ProxyPolicy.LongEdge));
Assert.Equal(480, settings.SelectedThumbnailSize.Value);
// Import: the defaults of new cards.
settings.Page = SettingsPage.Import;
await app.ExpectAsync<SettingsView>("settings-import");
@@ -62,6 +62,25 @@ public sealed class ArchiveSettingsTests(TestContext context)
Assert.Equal("{date}_{n:0000}", (string)written["layoutTemplates"]!["file"]!);
}
[Test]
public async Task AnArchiveWhoseFileHasNoUsableNameCanStillBeEdited()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var folder = Path.GetFileName(fx.Paths.Root);
// Archives made at a drive root before names were checked carry an empty name; others one over the limit.
foreach (var (stored, expected) in new[] { (string.Empty, folder), (new string('n', ArchiveSettings.MaxNameLength + 20), new string('n', ArchiveSettings.MaxNameLength)) })
{
var json = JsonNode.Parse(await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct))!.AsObject();
json["name"] = stored;
await File.WriteAllTextAsync(fx.Paths.ManifestPath, json.ToJsonString(), fx.Ct);
var updated = await fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Templates = s.Templates with { File = "{date}_{n:0000}" } }, fx.Ct);
Assert.Equal((expected, "{date}_{n:0000}"), (updated.Name, updated.FileTemplate));
Assert.Equal(expected, ManifestStore.ReadArchive(fx.Paths.ManifestPath).Name);
}
}
[Test]
public async Task InvalidSettingsAreRefusedAndNothingIsWritten()
{
@@ -6,7 +6,8 @@ namespace Titano.Data.Tests.Sqlite;
/// <summary>
/// BRIEF §6.2: a VACUUM INTO copy of the SQLite index once a day, the newest three kept, and a restore from Settings ›
/// Advanced that waits for the next start, checks the copy first and never replaces a working index with a broken one.
/// Advanced that waits for the next start, runs before the index opens (so it recovers one that no longer opens), checks
/// the copy first (quick_check included) and never replaces a working index with a broken one.
/// </summary>
[Category("sqlite")]
public sealed class DatabaseBackupsTests(TestContext context)
@@ -106,50 +107,127 @@ public sealed class DatabaseBackupsTests(TestContext context)
Assert.True(DatabaseBackups.HasStagedRestore(path));
await db.DisposeAsync();
// The next start: the index as it was is copied first, then it is the chosen copy and the staged file is gone.
// The next start, before the index opens: the index as it was is copied first, then it is the chosen copy and
// the staged file is gone (consumed by the swap, so it can never be applied twice).
Assert.True(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
Assert.True(await DatabaseBackups.RestoreStagedAsync(reopened, directory, context.Cancellation));
Assert.SequenceEqual(["kept"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
Assert.False(DatabaseBackups.HasStagedRestore(path));
var copies = DatabaseBackups.List(directory, path);
Assert.Count(2, copies);
var replaced = await DatabaseBackups.SummarizeBackupAsync(copies[0].Path, context.CreateTempDirectory("scratch"), context.Cancellation);
Assert.Equal(2, replaced.Archives);
Assert.False(await DatabaseBackups.RestoreStagedAsync(reopened, directory, context.Cancellation), "nothing staged any more");
Assert.False(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation), "nothing staged any more");
}
[Test]
public async Task AStagedRestoreRecoversAnIndexThatNoLongerOpens()
{
var (db, path) = await OpenAsync();
var directory = context.CreateTempDirectory("backups");
await AddArchiveAsync(db, "kept");
await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
var newest = await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
var daily = DatabaseBackups.List(directory, path).Select(b => b.Path).ToList();
await DatabaseBackups.StageRestoreAsync(newest, path, context.Cancellation);
await db.DisposeAsync();
// The index is damaged beyond opening ("file is not a database").
File.Delete(path + "-wal");
File.Delete(path + "-shm");
var garbage = new byte[16384];
new Random(7).NextBytes(garbage);
await File.WriteAllBytesAsync(path, garbage, context.Cancellation);
await Assert.ThrowsAsync<DatabaseException>(async () => await (await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation)).DisposeAsync());
Assert.True(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
Assert.SequenceEqual(["kept"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
Assert.False(DatabaseBackups.HasStagedRestore(path));
// The damaged index is kept whole beside the daily copies, outside their rotation: none of them was pushed out.
Assert.SequenceEqual(daily, DatabaseBackups.List(directory, path).Select(b => b.Path));
var aside = Assert.Contains(Directory.GetFiles(directory), f => Path.GetFileName(f).StartsWith("titano-replaced-", StringComparison.Ordinal));
Assert.SequenceEqual(garbage, await File.ReadAllBytesAsync(aside, context.Cancellation));
}
[Test]
public async Task ABrokenStagedCopyIsSetAsideAndTheIndexKept()
{
var (db, path) = await OpenAsync();
await using var _ = db;
await AddArchiveAsync(db, "current");
await db.DisposeAsync();
await File.WriteAllTextAsync(DatabaseBackups.StagedPath(path), "this is not a database", context.Cancellation);
var backups = context.CreateTempDirectory("backups");
await Assert.ThrowsAsync<InvalidDataException>(() => DatabaseBackups.RestoreStagedAsync(db, backups, context.Cancellation));
await Assert.ThrowsAsync<InvalidDataException>(() => DatabaseBackups.RestoreStagedAsync(path, backups, context.Cancellation));
Assert.False(DatabaseBackups.HasStagedRestore(path));
Assert.FileExists(DatabaseBackups.StagedPath(path) + ".failed");
Assert.Empty(DatabaseBackups.List(backups, path));
Assert.SequenceEqual(["current"], (await db.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
Assert.Empty(Directory.GetFiles(backups));
await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
Assert.SequenceEqual(["current"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
await Assert.ThrowsAsync<InvalidDataException>(() =>
DatabaseBackups.SummarizeBackupAsync(DatabaseBackups.StagedPath(path) + ".failed", context.CreateTempDirectory("scratch"), context.Cancellation));
}
[Test]
public async Task AStagedCopyThatFailsItsIntegrityCheckIsSetAsideBeforeAnyCopyIsMade()
{
var (db, path) = await OpenAsync();
var directory = context.CreateTempDirectory("backups");
await AddArchiveAsync(db, "current");
// A table the summary never reads, filled so its pages come last in a VACUUM INTO copy.
await using (var session = await db.Database.OpenAsync(context.Cancellation))
{
await session.ExecuteScriptAsync("""
CREATE TABLE filler (id INTEGER PRIMARY KEY, data BLOB);
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 200) INSERT INTO filler (data) SELECT randomblob(1000) FROM n;
""", context.Cancellation);
}
for (var i = 0; i < DatabaseBackups.Keep; i++) await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
var daily = DatabaseBackups.List(directory, path).Select(b => b.Path).ToList();
await db.DisposeAsync();
// One damaged page in the filler table of the copy: the header, the schema and every counted table are intact.
var damaged = Path.Combine(context.CreateTempDirectory("damaged"), "copy.db");
File.Copy(daily[0], damaged);
var bytes = await File.ReadAllBytesAsync(damaged, context.Cancellation);
var pageSize = (bytes[16] << 8) | bytes[17];
if (pageSize == 1) pageSize = 65536;
bytes[bytes.Length - pageSize] = 0xFF;
await File.WriteAllBytesAsync(damaged, bytes, context.Cancellation);
// Opening, migrating and counting do not notice it: only quick_check does.
var probe = Path.Combine(context.CreateTempDirectory("probe"), "titano.db");
File.Copy(damaged, probe);
await using (var opened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(probe), context.Cancellation))
Assert.Equal(1, (await DatabaseBackups.SummarizeAsync(opened, context.Cancellation)).Archives);
await Assert.ThrowsAsync<InvalidDataException>(() => DatabaseBackups.SummarizeBackupAsync(damaged, context.CreateTempDirectory("scratch"), context.Cancellation));
await DatabaseBackups.StageRestoreAsync(damaged, path, context.Cancellation);
await Assert.ThrowsAsync<InvalidDataException>(() => DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
Assert.False(DatabaseBackups.HasStagedRestore(path), "set aside: the next start neither retries it nor makes another copy");
Assert.FileExists(DatabaseBackups.StagedPath(path) + ".failed");
Assert.SequenceEqual(daily, DatabaseBackups.List(directory, path).Select(b => b.Path));
Assert.False(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
Assert.SequenceEqual(["current"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
}
[Test]
public async Task CancellingAStagedRestoreKeepsTheIndex()
{
var (db, path) = await OpenAsync();
await using var _ = db;
var directory = context.CreateTempDirectory("backups");
var backup = await db.BackupAsync(directory, DatabaseBackups.Keep, context.Cancellation);
await DatabaseBackups.StageRestoreAsync(backup, path, context.Cancellation);
await db.DisposeAsync();
DatabaseBackups.CancelStagedRestore(path);
Assert.False(DatabaseBackups.HasStagedRestore(path));
Assert.False(await DatabaseBackups.RestoreStagedAsync(db, directory, context.Cancellation));
Assert.False(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
Assert.FileExists(backup);
}
@@ -157,17 +235,18 @@ public sealed class DatabaseBackupsTests(TestContext context)
public async Task ARestoreWaitsWhenTheIndexCannotBeBackedUpFirst()
{
var (db, path) = await OpenAsync();
await using var _ = db;
var backup = await db.BackupAsync(context.CreateTempDirectory("backups"), DatabaseBackups.Keep, context.Cancellation);
await AddArchiveAsync(db, "since the backup");
await DatabaseBackups.StageRestoreAsync(backup, path, context.Cancellation);
await db.DisposeAsync();
// The backups folder cannot be created: a file is in its way.
var blocked = Path.Combine(context.CreateTempDirectory("blocked"), "backups");
await File.WriteAllTextAsync(blocked, "not a folder", context.Cancellation);
await Assert.ThrowsAsync<IOException>(() => DatabaseBackups.RestoreStagedAsync(db, blocked, context.Cancellation));
await Assert.ThrowsAsync<IOException>(() => DatabaseBackups.RestoreStagedAsync(path, blocked, context.Cancellation));
Assert.SequenceEqual(["since the backup"], (await db.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
Assert.True(DatabaseBackups.HasStagedRestore(path), "the restore stays staged for the next start");
await using var reopened = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(path), context.Cancellation);
Assert.SequenceEqual(["since the backup"], (await reopened.Archives.ListAsync(context.Cancellation)).Select(a => a.Name));
}
}
@@ -163,5 +163,19 @@ public sealed class AdminTests(TestContext context)
File.Move(path + ".away", path);
}
Assert.Equal(-1, Titano.Core.Archiving.ManifestStore.ReadArchive(path).ProxyPolicy.LongEdge);
// A damaged archive.json is reported as such (not as an internal error) and left as it is.
var saved = await File.ReadAllBytesAsync(path, context.Cancellation);
await File.WriteAllTextAsync(path, "{ not json", context.Cancellation);
try
{
using var damaged = await admin.PutAsJsonAsync("/api/v1/archive/settings", changed with { ProxyLongEdge = 1280 }, ProtocolJson.Default.ArchiveSettingsDto);
await damaged.ExpectErrorAsync(HttpStatusCode.Conflict, "archive_manifest");
Assert.Equal("{ not json", await File.ReadAllTextAsync(path, context.Cancellation));
}
finally
{
await File.WriteAllBytesAsync(path, saved, context.Cancellation);
}
}
}