fix(copies): close the owner review 6 gaps with tests

Photos not sent: automatic photos of an integrated pair that failed three
times in a row are now told with an error toast that shows the row, and the
row reads "not sent" with the last reason. The matches-found and linked toasts
of background detections run from their Windows notification too.

Maintenance now clears a merge's or an integration's journal whose job is done,
cancelled, or deleted without a cancel and untouched for the history's days.

Tests pin the matches jobs in the priority queue, the owner's defaults (ask
always, union, copy across), the dialog starting from the settings, Choose
each preselecting nothing, no automatic photos for a pair whose server copy
is gone, the repair of a corrupt local frame by an Integrate, and the owner's
whole scenario end to end against a real in-process server.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-17 14:03:23 +01:00
1 parent fe752a0a21
commit d10577b175
18 files changed
+804 -11

No files matched your search

@@ -0,0 +1,76 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Tests.Archiving;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>
/// What a merge or an integration leaves in the archive's journal folder (owner review 6, #73): the maintenance pass keeps
/// the journal a retry can use and clears the one no job will read again, as it does for conversions.
/// </summary>
[Category("archive")]
public sealed class CopyJournalMaintenanceTests(TestContext context)
{
[Test]
public async Task MaintenanceClearsTheJournalOfAMergeOrIntegrateNoJobWillReadAgain()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var failed = Guid.CreateVersion7();
var done = Guid.CreateVersion7();
var cancelled = Guid.CreateVersion7();
var paused = Guid.CreateVersion7();
foreach (var (id, kind, state) in new[]
{
(failed, JobKind.MergeSequences, JobState.Failed), (done, JobKind.Integrate, JobState.Done),
(cancelled, JobKind.MergeSequences, JobState.Cancelled), (paused, JobKind.Integrate, JobState.Paused),
})
await fx.Db.Jobs.EnqueueAsync(new Job { Id = id, Kind = kind, State = state, Created = DateTimeOffset.UtcNow }, fx.Ct);
// Deleted without a cancel: the index no longer knows the job.
var deleted = Guid.CreateVersion7();
var recent = Guid.CreateVersion7();
const int Old = Housekeeping.CleanupSteps.DefaultHistoryDays + 1;
string Write(string path, int daysOld)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, "{}");
File.SetLastWriteTimeUtc(path, DateTime.UtcNow.AddDays(-daysOld));
return path;
}
var failedJournal = Write(MergeJournal.PathFor(fx.Paths, failed), Old);
var doneJournal = Write(IntegrateJournal.PathFor(fx.Paths, done), 0);
var cancelledJournal = Write(MergeJournal.PathFor(fx.Paths, cancelled), 0);
var pausedJournal = Write(IntegrateJournal.PathFor(fx.Paths, paused), Old);
var deletedJournal = Write(MergeJournal.PathFor(fx.Paths, deleted), Old);
var recentJournal = Write(IntegrateJournal.PathFor(fx.Paths, recent), 1);
var other = Write(Path.Combine(fx.Paths.JournalDirectory, "merge-notes.json"), Old);
var dry = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: true, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.SequenceEqual(new[] { doneJournal, cancelledJournal, deletedJournal }.Select(fx.Paths.ToRelative).Order(), dry.TemporaryFiles.Order());
Assert.FileExists(deletedJournal);
await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.FileMissing(doneJournal);
Assert.FileMissing(cancelledJournal);
Assert.FileMissing(deletedJournal);
// A retry still reads these: the failed and the paused job's, and one another host may still be writing.
Assert.FileExists(failedJournal);
Assert.FileExists(pausedJournal);
Assert.FileExists(recentJournal);
Assert.FileExists(other);
}
[Test]
public void OnlyTheJournalsOfMergesAndIntegrationsAreRecognised()
{
var job = Guid.CreateVersion7();
Assert.Equal(job, ArchiveMaintenance.CopyJournalJob($"merge-{job:N}.json"));
Assert.Equal(job, ArchiveMaintenance.CopyJournalJob($"integrate-{job:N}.json"));
Assert.Null(ArchiveMaintenance.CopyJournalJob($"convert-{job:N}.json"));
Assert.Null(ArchiveMaintenance.CopyJournalJob($"merge-{job:N}.json.tmp"));
Assert.Null(ArchiveMaintenance.CopyJournalJob($"merge-{job:D}.json"));
}
}
@@ -280,6 +280,46 @@ public sealed class IntegrateTests(TestContext context)
Assert.False(File.Exists(IntegrateJournal.PathFor(f.Archive.Paths, job.Id)));
}
[Test]
public async Task ACorruptPhotoOnThisPcIsRepairedFromTheServersCopy()
{
await using var f = await FixtureAsync(context);
var local = await LocalAsync(f, "Comet", [(1, 0, "IMG_0001.JPG"), (2, 10_000, "IMG_0002.JPG")]);
var names = await NamesAsync(f, local.Id);
var remote = Remote(f, "Comet", [(1, 0, names[0]), (2, 10_000, names[1])]);
var pair = await PairAsync(f, local.Id, remote.Id);
// A verify finds the second photo damaged on this PC (design §5c: an unusable photo the other side holds is a repair).
var damaged = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Single(fr => fr.Sha256 == Sha(2, 10_000));
var file = f.Archive.Paths.FromRelative(damaged.RelativePath);
var bytes = await File.ReadAllBytesAsync(file, f.Ct);
bytes[^10] ^= 0xFF;
await File.WriteAllBytesAsync(file, bytes, f.Ct);
await f.Archive.Service.Verifier.VerifyAsync(f.Archive.Archive, [local.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: f.Ct);
Assert.Equal(FrameFlags.Corrupt, (await f.Db.Frames.GetAsync(damaged.Id, f.Ct))!.Flags);
var (engine, _) = Engine(f);
await using var _ = engine;
await engine.StartAsync(f.Ct);
var plan = await Planner(f).PlanAsync(f.Remote, pair, await ChoicesAsync(f, local.Id, remote.Id, CopyPhotoPolicy.Union), PlanContext(), f.Ct);
Assert.SequenceEqual([(PhotoAction.Fetch, Sha(2, 10_000))], plan.Photos.Select(p => (p.Action, p.Sha256!)));
Assert.Equal(0, plan.LeftOut);
var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.Count(2, frames);
var repaired = frames.Single(fr => fr.Sha256 == Sha(2, 10_000));
Assert.Equal(FrameFlags.None, repaired.Flags & (FrameFlags.Corrupt | FrameFlags.Missing));
var repairedFile = f.Archive.Paths.FromRelative(repaired.RelativePath);
Assert.Equal(Sha(2, 10_000), Sha(await File.ReadAllBytesAsync(repairedFile, f.Ct)));
// The damaged file is kept beside it, never deleted.
var aside = Directory.EnumerateFiles(Path.GetDirectoryName(repairedFile)!, Path.GetFileName(repairedFile) + ".damaged-*").ToList();
Assert.Count(1, aside);
Assert.True((await File.ReadAllBytesAsync(aside[0], f.Ct)).AsSpan().SequenceEqual(bytes), "the damaged file moved aside");
Assert.Equal(0, f.Remote.IntoUploads);
Assert.Equal(CopyState.Integrated, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
}
[Test]
public async Task AJobWhosePlanMovedRefusesAndSetsThePairBack()
{
@@ -197,6 +197,12 @@ internal sealed class FakeSyncRemote : ISyncRemote
return sequence;
}
/// <summary>Someone deletes the sequence on the server: every later call for it answers 404.</summary>
public void Drop(Guid id)
{
lock (_gate) Sequences.Remove(id);
}
/// <summary>Someone else edits the settings on the server.</summary>
public void EditSettings(Guid id, string settingsJson)
{
@@ -1,3 +1,4 @@
using Chronos.Core.IO;
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
@@ -76,6 +77,37 @@ public sealed class SyncAgentCopyTests(TestContext context)
Assert.Count(0, await QueuedAsync(f, JobKind.Download));
}
[Test]
public async Task APairWhoseServerCopyIsGoneQueuesNoAutomaticPhotos()
{
await using var f = await SyncFixture.CreateAsync(context);
// A server keyed by its id, so a 404 counts against the pair (design §7.5).
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("Comet NAS", photos.Take(2));
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
var row = await f.Sync.Copies.EnsureLinkedAsync(nas.Server, remote.Id, local.Id, f.Ct);
Assert.True(await f.Sync.Copies.SetStateAsync(row.Id, null, CopyState.Integrated,
new CopyAnswer(null, null, null, true, DateTimeOffset.UtcNow), f.Ct));
nas.Drop(remote.Id);
await using var engine = new JobEngine(f.Db, [.. f.Sync.CreateJobHandlers(new SyncFixture.Connector(nas))],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50) });
await using var agent = new SyncAgent(f.Sync, nas, () => new SyncPolicy(), engine, Quick);
await agent.RefreshAsync(f.Ct);
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), row.Id], f.Ct);
await agent.RefreshAsync(f.Ct);
var pair = (await f.Sync.Copies.GetAsync(row.Id, f.Ct))!;
Assert.True(pair.RemoteGoneHits > 0);
Assert.Equal((CopyState.Integrated, true), (pair.State, pair.AutoPhotos));
Assert.Count(0, await QueuedAsync(f, JobKind.UploadCommit));
Assert.Count(0, await QueuedAsync(f, JobKind.Download));
Assert.Count(0, agent.PhotoFailures);
}
[Test]
public async Task FailedTransfersCountWaitForTheirBackoffAndThreeInARowAreTold()
{