fix: logging never fails a job, one backup retention, first copy after the upgrade

Owner review 2, phase 2 review findings (scheduler core).

- Log.Write caught only IOException. Microsoft.Extensions.Logging wraps
  provider failures in an AggregateException, so a log line that could not
  be written (in tests: the process-wide sink of a stopped server whose log
  folder was gone) escaped JobEngine.RunAsync's catch before the failure was
  stored: the job stayed running and the worker faulted. This was the cause
  of the intermittent JobApiTests/ArchiveModuleTests failures. Log.Write now
  drops any non-fatal sink failure, TeeLogSink keeps a line from the other
  sinks, FileLogSink drops a line it cannot write and reopens the file at the
  next one, and LoggerSink drops what the providers throw. The scheduler's
  loop relies on the same guarantee.
- The daily backup loop (RunDailyAsync, IsDue, Interval, CheckInterval) had
  no caller since the index-backup schedule replaced it; it is removed and
  the DatabaseBackups summary describes the schedule.
- The first copy after the upgrade no longer waits a day (or for 03:00):
  SystemSchedule.LastDone seeds a new row due at once when its work was last
  done a period or more before, and both hosts pass the newest copy in the
  backups folder for index-backup.
- Back up now (Settings and Archive), the copy kept before a restore and a
  backup job that keeps fewer prune to the largest Copies kept of the backup
  schedules (DatabaseBackups.KeptAsync), not a fixed three. The four
  tooltips that promised three daily copies are reworded (en, it) and their
  stale translations deleted.
- New tests for the scheduler loop itself: a tick, Wake, a pass that threw,
  and dispose during a pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c5ad0c4c3f636129afe5dd1ce039185516da5621)
This commit is contained in:
Alby96 committed 2026-10-27 09:56:47 +01:00
1 parent 422f33d5f3
commit e384564784
59 files changed
+668 -264

No files matched your search

@@ -1,25 +1,20 @@
using Chronos.Core.Model;
using Chronos.Data.Repositories;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.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, 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.
/// BRIEF §6.2: VACUUM INTO copies of the SQLite index (the index backup schedule's, Back up now's, the one kept before a
/// restore), as many kept as the backup schedules keep, and a restore from Settings › 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)
{
/// <summary>A clock the test moves; timers created on it never fire by themselves.</summary>
private sealed class ManualClock(DateTimeOffset now) : TimeProvider
{
public DateTimeOffset Now { get; set; } = now;
public override DateTimeOffset GetUtcNow() => Now;
}
private async Task<(ChronosDatabase Db, string Path)> OpenAsync(string name = "chronos.db")
{
var path = System.IO.Path.Combine(context.CreateTempDirectory("db"), name);
@@ -49,42 +44,55 @@ public sealed class DatabaseBackupsTests(TestContext context)
}
[Test]
public void ACopyIsDueWhenTheNewestIsADayOld()
public async Task TheNewestCopyIsWhatTheIndexBackupIsSeededWith()
{
var now = new DateTimeOffset(2026, 10, 12, 9, 0, 0, TimeSpan.Zero);
Assert.True(DatabaseBackups.IsDue([], now));
Assert.False(DatabaseBackups.IsDue([new DatabaseBackup("b", now.AddHours(-23), 1)], now));
Assert.True(DatabaseBackups.IsDue([new DatabaseBackup("b", now.AddHours(-24), 1)], now));
}
[Test]
public async Task TheDailyCopyIsMadeAtStartOnlyWhenDue()
{
var (db, _) = await OpenAsync();
var (db, path) = await OpenAsync();
await using var _ = db;
var directory = context.CreateTempDirectory("backups");
var clock = new ManualClock(DateTimeOffset.UtcNow);
Assert.Null(DatabaseBackups.Newest(db, directory));
File.WriteAllText(Path.Combine(directory, "chronos-20261010-030000-000.db"), "a");
File.WriteAllText(Path.Combine(directory, "chronos-20261012-030000-000.db"), "b");
File.WriteAllText(Path.Combine(directory, "other-20261013-030000-000.db"), "x");
Assert.Equal(new DateTimeOffset(2026, 10, 12, 3, 0, 0, TimeSpan.Zero), DatabaseBackups.Newest(db, directory));
// Without a folder of its own, the one next to the index.
Assert.Null(DatabaseBackups.Newest(db, null));
await db.BackupAsync(DatabaseBackups.DefaultDirectory(path), DatabaseBackups.Keep, context.Cancellation);
Assert.NotNull(DatabaseBackups.Newest(db, null));
await using var memory = await ChronosDatabase.OpenAsync(DatabaseOptions.SqliteInMemory(), context.Cancellation);
Assert.Null(DatabaseBackups.Newest(memory, directory));
}
// No copy yet: one is made at once, then the loop waits for its hourly check until stopped.
using (var stop = new CancellationTokenSource())
{
var loop = DatabaseBackups.RunDailyAsync(db, directory, clock, stop.Token);
var until = DateTime.UtcNow.AddSeconds(20);
while (Directory.GetFiles(directory, "*.db").Length == 0 && DateTime.UtcNow < until) await Task.Delay(20);
await stop.CancelAsync();
await loop.WaitAsync(TimeSpan.FromSeconds(20));
}
Assert.Count(1, Directory.GetFiles(directory, "*.db"));
/// <summary>
/// One folder, one retention (owner review 2, R10): Back up now and the copy kept before a restore keep as many copies
/// as the backup schedules keep (the largest Copies kept, enabled or not), not a fixed three.
/// </summary>
[Test]
public async Task EveryCopyKeepsAsManyAsTheBackupSchedulesKeep()
{
var (db, path) = await OpenAsync();
var directory = context.CreateTempDirectory("backups");
Assert.Equal(DatabaseBackups.Keep, await DatabaseBackups.KeptAsync(db, context.Cancellation));
await db.Schedules.EnsureSystemAsync(
[
new SystemSchedule(DatabaseBackups.ScheduleKey, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.Parse("every:1d"), new ScheduleParametersDto(Keep: 5)),
new SystemSchedule("other-backup", "Other backup", ScheduleActions.Backup, ScheduleRecurrence.Parse("every:1d"), new ScheduleParametersDto(Keep: 1), Enabled: false),
new SystemSchedule("cleanup", "Clean-up", ScheduleActions.Cleanup, ScheduleRecurrence.Parse("daily:04:00"), new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 30)),
], DateTimeOffset.UtcNow, context.Cancellation);
Assert.Equal(5, await DatabaseBackups.KeptAsync(db, context.Cancellation));
// A fresh copy exists: starting again makes none.
using (var stop = new CancellationTokenSource())
{
var loop = DatabaseBackups.RunDailyAsync(db, directory, clock, stop.Token);
await Task.Delay(300);
await stop.CancelAsync();
await loop.WaitAsync(TimeSpan.FromSeconds(20));
}
Assert.Count(1, Directory.GetFiles(directory, "*.db"));
// Five copies of the schedule, then Back up now: the four newest stay with the new one.
for (var i = 0; i < 5; i++) await db.BackupAsync(directory, 5, context.Cancellation);
var scheduled = DatabaseBackups.List(directory, path).Select(b => b.Path).ToList();
var manual = await db.BackupAsync(directory, await DatabaseBackups.KeptAsync(db, context.Cancellation), context.Cancellation);
Assert.SequenceEqual([manual, .. scheduled.Take(4)], DatabaseBackups.List(directory, path).Select(b => b.Path));
// The copy of the index a restore replaces prunes the same way.
await DatabaseBackups.StageRestoreAsync(scheduled[0], path, context.Cancellation);
await db.DisposeAsync();
Assert.True(await DatabaseBackups.RestoreStagedAsync(path, directory, context.Cancellation));
var after = DatabaseBackups.List(directory, path).Select(b => b.Path).ToList();
Assert.Count(5, after);
Assert.SequenceEqual([manual, .. scheduled.Take(3)], after.Skip(1));
}
[Test]