fix: one audit retention, scans at start, live deep analysis and a 6-hour upload sweep

Settle what the R10 scheduler and R11 log packages left open when they were
integrated (owner review 2, phase 2).

- Audit retention has one source of truth, the audit-cleanup schedule's age
  limit. AuditRetentionDays defaults to 0 (the audit log is kept forever, so
  an upgrade deletes nothing; the schedule is seeded off) and accepts 0-3650,
  what a schedule's age limit takes. Saving Settings › Logs › Keep audit sets
  the schedule's limit (on with a limit, off at 0) without a restart;
  CHRONOS_AUDIT_RETENTION_DAYS locks it and Reset goes back to it.
- Both hosts scan right after start again, as their polling did: the server
  after the scheduler starts, the desktop once the archive was reopened and
  again when an unplugged one is back. Scheduler.RunSystemNowAsync runs the
  archive-scan schedule when it is enabled and has not run since the start,
  and skips while its scan is pending.
- Desktop scans follow Settings › Analysis › After a scan at every run: a scan
  schedule without its own deep parameter asks the host
  (IScheduleHost.DeepAnalysisAfterScan), the archive-scan schedule no longer
  freezes the setting, and the editor offers deep only for analyses, so the
  setting's tooltip stays true.
- The server's upload clean-up runs every 6 hours instead of every 30
  minutes, to keep the job history readable; idle uploads still expire after
  UploadRetentionHours.
- The Unraid template and docker-compose leave CHRONOS_LOG_LEVEL empty or
  commented out, and say that setting it locks both log levels, so the admin
  panel can change them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-27 02:51:04 +01:00
1 parent bc786c12c4
commit 8d66be709c
21 files changed
+299 -53

No files matched your search

@@ -35,14 +35,14 @@ public sealed class AppServicesTests
await new ArchiveService(setup).CreateAsync(root, "Exit");
var services = new AppServices(environment, new AppSettings { Language = "en", LastArchivePath = root }, () => { }, new NoDialogs());
await services.OpenAsync(environment.DatabasePath);
// The archive was reopened, then the schedules started (owner review 2, R10): its scan schedule queues a scan of it.
// The archive was reopened, then the schedules started (owner review 2, R10) and its scan schedule ran at once,
// as the rescans did at start: a scan of it is queued without waiting for the interval.
Assert.True(await services.SchedulerReady, "the schedules started");
var scan = Assert.NotNull(await services.Database!.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal(ScheduleOutcome.Queued, (await services.Scheduler!.RunNowAsync(scan.Id, null))?.Outcome);
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
while ((await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count == 0)
while (!(await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Any(j => j.ScheduleId == scan.Id))
{
Assert.True(DateTime.UtcNow < until, "no rescan queued");
Assert.True(DateTime.UtcNow < until, "no scan at start");
await Task.Delay(50);
}
@@ -26,7 +26,8 @@ public sealed class DesktopScheduleHostTests(TestContext context)
var scan = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal(("every:30m", false, JobPriority.Background, true, ScheduleActions.Scan), (scan.Recurrence, scan.CatchUp, scan.Priority, scan.Enabled, scan.Action));
Assert.Equal(true, ScheduleMapping.Parameters(scan).Deep);
// The deep analysis is not frozen into the schedule: each run reads Settings › Analysis › After a scan.
Assert.Null(ScheduleMapping.Parameters(scan).Deep);
Assert.Equal(fx.Clock.Now.AddMinutes(30), scan.NextRun);
// The user edits the schedule in Jobs › Scheduled; the old setting changes (or never changes again): the next
@@ -43,6 +44,52 @@ public sealed class DesktopScheduleHostTests(TestContext context)
Assert.Equal("every:5m", (await fx.Db.Schedules.GetAsync(scan.Id))!.Recurrence);
}
/// <summary>
/// Owner review 2, R10: the scheduled scans follow Settings › Analysis › After a scan as it is at each run, like the
/// scans started by hand, so that checkbox's tooltip stays true; and the archive is scanned right after it was opened
/// (once per start, and again when an unplugged archive is back), as the rescans did.
/// </summary>
[Test]
public async Task TheScanRunsAtOnceAndFollowsTheDeepAnalysisSettingAtEachRun()
{
var settings = new AppSettings { Language = "en", DeepAnalysisAfterScan = false };
await using var fx = await ScheduleFixture.CreateAsync(context, settings);
var archive = await fx.Archives.CreateAsync(Path.Combine(fx.Folder, "archive"), "archive");
settings.LastArchivePath = archive.RootPath;
var started = fx.Clock.Now;
var scheduler = await fx.StartAsync();
// Right after the start, not one interval later.
var first = Assert.NotNull(await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan, started));
Assert.Equal(ScheduleOutcome.Queued, first.Outcome);
Assert.False(await DeepAsync(fx, first.JobId!.Value));
Assert.Null(await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan, started));
// The setting changes after the schedule was seeded: the next run follows it.
settings.DeepAnalysisAfterScan = true;
await fx.Db.Jobs.SetStateAsync(first.JobId!.Value, JobState.Done);
var second = Assert.NotNull(await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal(ScheduleOutcome.Queued, second.Outcome);
Assert.True(await DeepAsync(fx, second.JobId!.Value));
Assert.True(fx.Host.DeepAnalysisAfterScan);
// The editor offers no deep switch for a scan (only for an analysis), so a scan schedule never freezes it.
using var vm = await fx.ViewModelAsync();
vm.NewCommand.Execute(null);
var editor = Assert.NotNull(vm.Editor);
editor.SelectedAction = editor.ActionOptions.Single(a => a.Name == ScheduleActions.Scan);
Assert.True(editor.ShowsForce && !editor.ShowsDeep, "a scan's switches: a full scan only");
}
/// <summary>Whether the scan job <paramref name="id"/> gives what it finds a deep analysis.</summary>
private static async Task<bool> DeepAsync(ScheduleFixture fx, Guid id)
{
var job = Assert.NotNull(await fx.Db.Jobs.GetAsync(id));
Assert.Equal(JobKind.Scan, job.Kind);
using var parameters = System.Text.Json.JsonDocument.Parse(job.ParametersJson!);
return parameters.RootElement.GetProperty("deepAnalysis").GetBoolean();
}
[Test]
public void TheFormerIntervalIsClampedToWhatAnIntervalAccepts()
{
@@ -41,6 +41,8 @@ internal sealed class TestScheduleHost(Archive? archive) : IScheduleHost
public IReadOnlyList<string> CleanupSteps { get; set; } = ["job-history", "audit", "trash-report"];
public bool DeepAnalysisAfterScan { get; set; }
public ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken) => ValueTask.FromResult(Archive);
public string? Unavailable(string action) => Refused.GetValueOrDefault(action);
@@ -431,6 +433,70 @@ public sealed class SchedulerTests(TestContext context)
Assert.Equal(ScheduleOutcome.Unavailable, (await other.RunNowAsync((await CreateAsync(other, ScheduleActions.Analysis)).Id, null, Ct))!.Outcome);
}
/// <summary>
/// Owner review 2, R10: both hosts scan right after they start (the desktop also when its archive is back), as their
/// polling did, through the archive scan system schedule: once, only while it is enabled, never twice for one start.
/// </summary>
[Test]
public async Task ASystemScheduleRunsNowOnceWhenEnabledAndNotRunSince()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var clock = new ScheduleClock(T0);
var host = new TestScheduleHost(fx.Archive);
host.Systems.Add(new SystemSchedule("archive-scan", "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(10, RecurrenceUnit.Minutes), CatchUp: false));
await using var scheduler = await StartAsync(fx.Db, engine, host, clock);
Assert.Null(await scheduler.RunSystemNowAsync("no-such-key", null, Ct));
// Right after the start: the scan is queued, without waiting for its first interval.
var started = clock.Now;
var run = Assert.NotNull(await scheduler.RunSystemNowAsync("archive-scan", started, Ct));
Assert.Equal(ScheduleOutcome.Queued, run.Outcome);
var job = (await fx.Db.Jobs.GetAsync(run.JobId!.Value, Ct))!;
Assert.Equal((JobKind.Scan, JobPriority.Background, (Guid?)run.Schedule.Id), (job.Kind, job.Priority, job.ScheduleId));
Assert.Equal(T0.AddMinutes(10), run.Schedule.NextRun);
// It ran since that start: not again. Asked again later (the archive is back), its pending scan is not queued twice.
Assert.Null(await scheduler.RunSystemNowAsync("archive-scan", started, Ct));
Assert.Equal(ScheduleOutcome.SkippedPending, (await scheduler.RunSystemNowAsync("archive-scan", null, Ct))!.Outcome);
Assert.Count(1, await fx.Db.Jobs.ListByScheduleAsync(run.Schedule.Id, cancellationToken: Ct));
// Turned off, it does not run at start.
Assert.Null((await scheduler.UpdateAsync(run.Schedule.Id, new UpdateScheduleRequest(Enabled: false), Ct)).Problem);
await fx.Db.Jobs.SetStateAsync(job.Id, JobState.Done, cancellationToken: Ct);
Assert.Null(await scheduler.RunSystemNowAsync("archive-scan", null, Ct));
}
/// <summary>
/// Owner review 2, R10: a scan whose schedule leaves deep unset follows the host at every run (the desktop's Settings ›
/// Analysis › After a scan as it is then), one that sets it keeps its own choice.
/// </summary>
[Test]
public async Task AScanWithoutItsOwnDeepFollowsTheHostAtEveryRun()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
await using var engine = Engine(fx);
var host = new TestScheduleHost(fx.Archive);
await using var scheduler = await StartAsync(fx.Db, engine, host, new ScheduleClock(T0));
var follows = await CreateAsync(scheduler, ScheduleActions.Scan);
Assert.Null(follows.Parameters.Deep);
var own = await CreateAsync(scheduler, ScheduleActions.Scan, parameters: new ScheduleParametersDto(Deep: false));
Assert.Equal(false, own.Parameters.Deep);
async Task<bool> DeepAsync(ScheduleDto schedule)
{
var resolution = await ScheduleActions.ResolveAsync(new ScheduleActionContext(fx.Db, host, _ => true, T0), schedule.Action, schedule.Parameters, Ct);
var request = resolution.Requests.Single();
return System.Text.Json.JsonSerializer.Deserialize(request.ParametersJson!, ArchiveJobJson.Default.ScanParameters)!.DeepAnalysis;
}
Assert.False(await DeepAsync(follows));
host.DeepAnalysisAfterScan = true;
Assert.True(await DeepAsync(follows));
Assert.False(await DeepAsync(own));
// The queued job carries it too.
var job = (await fx.Db.Jobs.GetAsync((await scheduler.RunNowAsync(follows.Id, null, Ct))!.JobId!.Value, Ct))!;
Assert.True(ArchiveJobJson.Read(job, ArchiveJobJson.Default.ScanParameters, new ScanParameters(false)).DeepAnalysis);
}
private static async Task<Guid> IngestAsync(ArchiveFixture fx, string key, int seed)
{
var staged = fx.Stage(ArchiveFixture.Start.AddMinutes(seed), seed);
@@ -38,7 +38,8 @@ public sealed class ScheduleEndpointTests(TestContext context)
Assert.Equal(("scan", new RecurrenceDto("every", 10, "minutes"), false, "background", true), (scan.Action, scan.Recurrence, scan.CatchUp, scan.Priority, scan.Enabled));
Assert.NotNull(scan.NextRun);
var uploads = SystemRow(list, ServerScheduleHost.UploadCleanup);
Assert.Equal(("cleanup", new RecurrenceDto("every", 30, "minutes"), true, (int?)90), (uploads.Action, uploads.Recurrence, uploads.CatchUp, uploads.Parameters.OlderThanDays));
// Every 6 hours, not more often: four clean-up jobs a day keep the job history readable.
Assert.Equal(("cleanup", new RecurrenceDto("every", 6, "hours"), true, (int?)90), (uploads.Action, uploads.Recurrence, uploads.CatchUp, uploads.Parameters.OlderThanDays));
Assert.SequenceEqual([UploadCleanupStep.StepName], uploads.Parameters.Steps!);
var backup = SystemRow(list, ServerScheduleHost.IndexBackup);
Assert.Equal(("backup", new RecurrenceDto("daily", Time: "03:00"), true, (int?)3), (backup.Action, backup.Recurrence, backup.CatchUp, backup.Parameters.Keep));
@@ -46,7 +47,8 @@ public sealed class ScheduleEndpointTests(TestContext context)
Assert.Equal((new RecurrenceDto("daily", Time: "04:00"), (int?)90), (history.Recurrence, history.Parameters.OlderThanDays));
Assert.SequenceEqual(["job-history"], history.Parameters.Steps!);
var audit = SystemRow(list, ServerScheduleHost.AuditCleanup);
Assert.Equal((new RecurrenceDto("daily", Time: "04:30"), (int?)365, true), (audit.Recurrence, audit.Parameters.OlderThanDays, audit.Enabled));
// The audit log is kept forever by default: no deletion after an upgrade.
Assert.Equal((new RecurrenceDto("daily", Time: "04:30"), (int?)0, false), (audit.Recurrence, audit.Parameters.OlderThanDays, audit.Enabled));
Assert.SequenceEqual(["audit"], audit.Parameters.Steps!);
// Every action, with whether this server runs it: without the processing module there is no analysis.
@@ -213,6 +215,58 @@ public sealed class ScheduleEndpointTests(TestContext context)
Assert.Equal((int?)30, (await reset.ReadAsync(ProtocolJson.Default.ScheduleDto)).Parameters.OlderThanDays);
}
/// <summary>
/// Owner review 2, R10 and R11: the audit retention has one source of truth, the audit clean-up schedule's age limit. The
/// field of Settings › Logs sets it (and turns the schedule on, or off at 0), Reset goes back to it, and at 0 the audit
/// step deletes nothing.
/// </summary>
[Test]
public async Task TheAuditRetentionOfTheSettingsIsTheAgeLimitOfTheAuditCleanUp()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var admin = await server.AdminAsync();
var audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)0, false), (audit.Parameters.OlderThanDays, audit.Enabled));
// At 0 a run (also of the disabled schedule, on request) keeps the whole audit log.
var entries = (await server.Database.Audit.ListByActionsAsync(null, [], 1000, null, Ct)).Items.Select(e => e.Id).ToList();
Assert.True(entries.Count > 0, "the sign-in left audit entries");
var run = await RunAsync(admin, audit.Id);
var job = await JobApiTests.WaitForAsync(admin, run.JobId!.Value, "done");
Assert.Contains("Audit log kept in full", job.LogTail);
var kept = (await server.Database.Audit.ListByActionsAsync(null, [], 1000, null, Ct)).Items.Select(e => e.Id).ToHashSet();
Assert.True(entries.All(kept.Contains), "no audit entry was deleted");
// Saved in Settings › Logs, a retention becomes the schedule's age limit and turns it on, without a restart.
await SaveAuditRetentionAsync(admin, 30);
Assert.Equal(30, server.Options.AuditRetentionDays);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)30, true), (audit.Parameters.OlderThanDays, audit.Enabled));
// Without an environment variable the schedule stays editable; Reset goes back to the setting.
using (var edit = await admin.PutAsJsonAsync($"/api/v1/schedules/{audit.Id}", new UpdateScheduleRequest(Parameters: new ScheduleParametersDto(Steps: ["audit"], OlderThanDays: 60)),
ProtocolJson.Default.UpdateScheduleRequest))
Assert.Equal((int?)60, (await edit.ReadAsync(ProtocolJson.Default.ScheduleDto)).Parameters.OlderThanDays);
using (var reset = await admin.PostAsync($"/api/v1/schedules/{audit.Id}/reset", null))
Assert.Equal((int?)30, (await reset.ReadAsync(ProtocolJson.Default.ScheduleDto)).Parameters.OlderThanDays);
// Back to 0: kept forever, the schedule off.
await SaveAuditRetentionAsync(admin, 0);
audit = SystemRow(await ListAsync(admin), ServerScheduleHost.AuditCleanup);
Assert.Equal(((int?)0, false), (audit.Parameters.OlderThanDays, audit.Enabled));
}
/// <summary>Saves Settings › Logs › Keep audit (days) as the admin panel does.</summary>
private static async Task SaveAuditRetentionAsync(HttpClient admin, int days)
{
using var read = await admin.GetAsync("/api/v1/server/settings");
var settings = await read.ReadAsync(ProtocolJson.Default.ServerSettingsDto);
// The test server listens on ports the OS chose, which the settings refuse: real ones are sent with the edit.
using var saved = await admin.PutAsJsonAsync("/api/v1/server/settings",
settings with { HttpPort = 18080, HttpsPort = 18443, Logs = settings.Logs with { AuditRetentionDays = days } }, ProtocolJson.Default.ServerSettingsDto);
await saved.ExpectAsync(HttpStatusCode.OK);
}
[Test]
public async Task RunNowQueuesTheJobsOnceAndListsThemAsRuns()
{
@@ -342,7 +396,7 @@ public sealed class ScheduleEndpointTests(TestContext context)
Assert.True(store.Exists(id));
var scheduleId = Assert.NotNull(await server.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.UploadCleanup, Ct)).Id;
// Two days later its half-hourly run expires the upload and deletes its partial file.
// Two days later its run (every 6 hours, with catch-up) expires the upload and deletes its partial file.
clock.Advance(TimeSpan.FromHours(49));
await server.Services.GetRequiredService<SchedulerHost>().Scheduler.RunDueAsync(Ct);
var until = DateTime.UtcNow + TimeSpan.FromSeconds(30);
@@ -373,7 +427,7 @@ public sealed class ScheduleEndpointTests(TestContext context)
await using (var first = await TestServer.StartAsync(context, Paths, ArchiveModule.Register))
{
var seeded = Assert.NotNull(await first.Database.Schedules.GetBySystemKeyAsync(ServerScheduleHost.AuditCleanup, Ct));
Assert.Equal((int?)365, ScheduleMapping.Parameters(seeded).OlderThanDays);
Assert.Equal(((int?)0, false), (ScheduleMapping.Parameters(seeded).OlderThanDays, seeded.Enabled));
}
// CHRONOS_AUDIT_RETENTION_DAYS=30 at the next start.
@@ -417,7 +471,9 @@ public sealed class ScheduleEndpointTests(TestContext context)
var options = ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = data, ["CHRONOS_DB"] = "postgres", [ServerOptions.AuditRetentionVariable] = "0" });
Assert.Equal(0, options.AuditRetentionDays);
Assert.Contains(nameof(ServerOptions.AuditRetentionDays), options.Locked);
Assert.Equal(365, new ServerOptions().AuditRetentionDays);
Assert.Equal(0, new ServerOptions().AuditRetentionDays);
Assert.Equal(3650, ServerOptions.Load(new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = data, ["CHRONOS_DB"] = "postgres", [ServerOptions.AuditRetentionVariable] = "3650" })
.AuditRetentionDays);
foreach (var invalid in new[] { "-1", "3651", "a year" })
{
Assert.Throws<InvalidOperationException>(() =>