Merge branch 'review2-p5a-fix4-sync' into review2-p5a-int4

This commit is contained in:
Alby96 committed 2026-11-03 14:23:47 +01:00
commit 93afe71639
14 files changed
+729 -57

No files matched your search

@@ -2,6 +2,7 @@ using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Repositories;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Tests.Projects;
@@ -268,10 +269,17 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
var both = await three.ResolveAsync(id, fx.Home, ConflictChoice.SaveBoth, cancellationToken: fx.Ct);
Assert.Equal(WorkspaceState.Gone, both.Status.State);
// Gone holds no conflict to answer: the editor says the project is gone, never asks the conflict again.
Assert.Null(both.Status.Conflict, "a project the home no longer has asks nothing");
var copy = Assert.NotNull(both.SavedAs, "the copy holds this side's work at the home");
Assert.NotNull(project.ReadSync().Conflict, "the conflict stays recorded");
Assert.Null((await three.StatusAsync(id, fx.Home, fx.Ct)).Conflict);
var listed = (await fx.Home.ListAsync(fx.Ct)).Count;
var again = await three.ResolveAsync(id, fx.Home, ConflictChoice.SaveBoth, cancellationToken: fx.Ct);
Assert.Equal(WorkspaceState.Gone, again.Status.State);
Assert.Null(again.Status.Conflict);
Assert.Equal(listed, (await fx.Home.ListAsync(fx.Ct)).Count);
Assert.Contains(await fx.Home.ListAsync(fx.Ct), p => p.Id == copy.Id);
Assert.Equal(WorkspaceState.Gone, (await three.PushAsync(id, fx.Home, fx.Ct)).Status.State);
// Nothing of this side's is lost: its versions wait here, the working state as it was.
@@ -280,6 +288,116 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
Assert.Contains(project.Versions(), v => v.Note == "bright");
}
[Test]
public async Task KeepMineOrTakeTheLibrarysOnAProjectDeletedAtTheHomeIsGoneAndChangesNothing()
{
var fx = await FixtureAsync();
var side = await ProjectAsync(fx, "Side");
var (_, three, project, id) = await SavedConflictAsync(fx, side);
await EditAsync(three, id, s => s with { Stack = new StackSettings { Mode = StackSetting.Mean } }, fx.Ct);
var shown = Assert.NotNull(project.ReadSync().Conflict);
var versions = project.Versions().Select(v => (v.Id, v.ContentHash)).ToList();
await fx.Archive.Service.Projects.DeleteAsync(id, fx.Ct);
// Neither choice is merged onto the last version the home had: Gone, the working state and the unsent version as they were.
foreach (var choice in new[] { ConflictChoice.KeepMine, ConflictChoice.TakeServer })
{
var result = await three.ResolveAsync(id, fx.Home, choice, shown: shown, cancellationToken: fx.Ct);
Assert.Equal(WorkspaceState.Gone, result.Status.State, $"{choice}");
Assert.Null(result.Status.Conflict);
Assert.Null(result.Kept, "nothing was taken over");
Assert.Empty(result.Pulled);
var working = (await three.OpenAsync(id, fx.Ct)).Working;
Assert.Equal((2.0, StackSetting.Mean), (working.Exposure.ExposureOffsetEv, working.Stack.Mode));
Assert.Equal("bright", three.Unpushed(id).Single().Note);
Assert.SequenceEqual(versions, project.Versions().Select(v => (v.Id, v.ContentHash)));
Assert.Empty(Replaced(project));
Assert.Equal(shown.TheirsVersionId, Assert.NotNull(project.ReadSync().Conflict).TheirsVersionId, "the conflict stays recorded");
}
Assert.Equal(WorkspaceState.Gone, (await three.PullAsync(id, fx.Home, fx.Ct)).Status.State);
Assert.Equal("bright", three.Unpushed(id).Single().Note);
}
[Test]
public async Task APushStoppedAtAConflictLeavesTheReplacedVersionsAndOneThatEndsWellPrunesThem()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, three) = fx.Workspace("three");
var id = (await fx.CheckoutAsync(one)).ProjectId;
var project = await fx.CheckoutAsync(three, id);
await EditAsync(one, id, s => Offset(s, 0.5), fx.Ct);
await one.CommitAsync(id, cancellationToken: fx.Ct);
await one.PushAsync(id, fx.Home, fx.Ct);
await EditAsync(three, id, s => Offset(s, 2), fx.Ct);
await three.CommitAsync(id, "bright", cancellationToken: fx.Ct);
var old = OldReplaced(project, 40);
var stopped = await three.PushAsync(id, fx.Home, fx.Ct);
Assert.Equal(WorkspaceState.Conflict, stopped.Status.State);
Assert.FileExists(old);
await three.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: stopped.Status.Conflict, cancellationToken: fx.Ct);
Assert.Count(1, (await three.PushAsync(id, fx.Home, fx.Ct)).Pushed);
Assert.False(File.Exists(old), "a push that ended well prunes");
}
/// <summary>A file in <c>versions/.replaced</c> set aside <paramref name="days"/> days ago, by this Chronos (the folder known since then).</summary>
private static string OldReplaced(WorkspaceProject project, int days)
{
var aside = Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedFolder);
Directory.CreateDirectory(aside);
var then = DateTime.UtcNow - TimeSpan.FromDays(days);
File.WriteAllText(Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedSinceFile), then.ToString("O", System.Globalization.CultureInfo.InvariantCulture));
var old = Path.Combine(aside, $"1-{Guid.CreateVersion7():N}.json");
File.WriteAllText(old, "{}");
File.SetLastWriteTimeUtc(old, then);
return old;
}
[Test]
public async Task AMergeIsMarkedOnTheVersionThatCarriesItNeverOnOneTheWorkingStateAloneConflicted()
{
var fx = await FixtureAsync();
var (_, one) = fx.Workspace("one");
var (_, two) = fx.Workspace("two");
var id = (await fx.CheckoutAsync(one)).ProjectId;
await fx.CheckoutAsync(two, id);
await EditAsync(one, id, s => Offset(s, 0.5), fx.Ct);
await one.CommitAsync(id, cancellationToken: fx.Ct);
await one.PushAsync(id, fx.Home, fx.Ct);
// Saved here: a stack the library never touched; then, not saved, the offset the library changed too.
await EditAsync(two, id, s => s with { Stack = new StackSettings { Mode = StackSetting.Mean } }, fx.Ct);
await two.CommitAsync(id, "stacked", cancellationToken: fx.Ct);
await EditAsync(two, id, s => Offset(s, 1.0), fx.Ct);
var shown = Assert.NotNull((await two.PullAsync(id, fx.Home, fx.Ct)).Status.Conflict);
Assert.Equal("exposure.exposureOffsetEv", shown.Differences.Single().Path);
// Keep mine: the choice lives in the working state; "stacked" replayed merges nothing and stays a commit.
var kept = await two.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: shown, cancellationToken: fx.Ct);
Assert.Null(kept.Status.Conflict);
var stacked = two.Unpushed(id).Single();
Assert.Equal(("stacked", ProjectVersionKind.Commit), (stacked.Note, stacked.Kind));
Assert.Equal(1.0, await WorkingOffsetAsync(two, id, fx.Ct));
// A version whose own change met the library's: marked as the merge.
var (_, three) = fx.Workspace("three");
await fx.CheckoutAsync(three, id);
await two.PushAsync(id, fx.Home, fx.Ct);
await EditAsync(three, id, s => Offset(s, 2.0), fx.Ct);
await three.CommitAsync(id, "bright", cancellationToken: fx.Ct);
await EditAsync(three, id, s => s with { Stack = new StackSettings { Mode = StackSetting.Median } }, fx.Ct);
await three.CommitAsync(id, "median", cancellationToken: fx.Ct);
await two.CommitAsync(id, "sent", cancellationToken: fx.Ct);
await two.PushAsync(id, fx.Home, fx.Ct);
var asked = Assert.NotNull((await three.PushAsync(id, fx.Home, fx.Ct)).Status.Conflict);
await three.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: asked, cancellationToken: fx.Ct);
var replayed = three.Unpushed(id);
Assert.SequenceEqual(["bright", "median"], replayed.Select(v => v.Note));
Assert.Equal(ProjectVersionKind.Merge, replayed[^1].Kind, "the last version carrying the choice");
Assert.Equal(ProjectVersionKind.Commit, replayed[0].Kind);
}
[Test]
public async Task ACopyWritesAConvertedPhotoUnderANameOfItsOwnAndSwitchesAtItsCommit()
{
@@ -375,6 +493,70 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
Assert.Equal(fx.Frames.Count, Directory.GetFiles(project.ProxiesDirectory, "*.jpg").Length);
}
[Test]
public async Task AFirstCopyCancelledWhilePausedRemovesTheMediaItWroteUnderTheLease()
{
var fx = await FixtureAsync();
var (store, sync) = fx.Workspace();
var id = (await fx.Archive.Service.Projects.MainAsync(fx.Sequence.Id, fx.Ct)).Id;
var project = await sync.CheckoutAsync(fx.Home, id, cancellationToken: fx.Ct);
Job job;
using (await project.LockAsync(Wait, fx.Ct))
{
job = await fx.StartCopyAsync(store, id);
await UntilAsync(() => Directory.Exists(project.ProxiesDirectory) && Directory.GetFiles(project.ProxiesDirectory, "*.jpg").Length == fx.Frames.Count,
"the copy's files", fx.Ct);
await fx.PauseAsync(job.Id);
await fx.Archive.WaitForAsync(job.Id, JobState.Paused, (int)TestTiming.Budget(30));
}
// Cancelled while paused (no handler runs it) and while another holds the project: removed once that one let go.
var lease = await project.LockAsync(Wait, fx.Ct);
try
{
await fx.CancelAsync(job.Id);
await fx.Archive.WaitForAsync(job.Id, JobState.Cancelled, (int)TestTiming.Budget(30));
await Task.Delay(200, fx.Ct);
Assert.True(Directory.Exists(project.MediaDirectory), "nothing is removed while another holds the project");
}
finally
{
lease.Dispose();
}
await UntilAsync(() => !Directory.Exists(project.MediaDirectory), "the cancelled copy's media removed", fx.Ct);
Assert.Equal(id, project.ReadBundle().Workspace!.ProjectId);
// Copied again, then a copy paused and cancelled: media a copy finished stay.
await fx.CopyAsync(store, id);
var media = project.ReadMedia()!;
using (await project.LockAsync(Wait, fx.Ct))
{
job = await fx.StartCopyAsync(store, id);
await fx.Archive.WaitForAsync(job.Id, JobState.Running, (int)TestTiming.Budget(30));
await fx.PauseAsync(job.Id);
await fx.Archive.WaitForAsync(job.Id, JobState.Paused, (int)TestTiming.Budget(30));
await fx.CancelAsync(job.Id);
}
await Task.Delay(200, fx.Ct);
using (await project.LockAsync(Wait, fx.Ct))
Assert.Equal(media.Frames.Count, project.ReadMedia()!.Frames.Count);
foreach (var frame in media.Frames) Assert.FileExists(project.MediaFile(frame.File!));
}
[Test]
public void TheSpaceACopyNeedsCountsAPhotoHeldUnderEitherName()
{
var a = Guid.CreateVersion7();
var b = Guid.CreateVersion7();
var held = WorkspaceCopyJobHandler.HeldFrames([
Path.Combine("p", $"{a:N}.jpg"),
Path.Combine("p", $"{b:N}-0123456789abcdef.jpg"),
Path.Combine("p", $"{Guid.CreateVersion7():N}x.jpg"),
Path.Combine("p", "notes.jpg"),
]);
Assert.SequenceEqual(new[] { a, b }.Order(), held.Order());
}
[Test]
public async Task AVersionReadAsDamagedWhileAnotherHoldsTheProjectIsReportedOnlyOnceConfirmed()
{
@@ -404,6 +586,9 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
var aside = Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedFolder);
Directory.CreateDirectory(aside);
var now = DateTime.UtcNow;
// This Chronos has known the folder for longer than any of its files.
File.WriteAllText(Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedSinceFile),
(now - TimeSpan.FromDays(400)).ToString("O", System.Globalization.CultureInfo.InvariantCulture));
var files = new List<(string Path, Guid Id)>();
for (var i = 0; i < 25; i++)
{
@@ -426,6 +611,37 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
Assert.DoesNotContain(files[23].Path, left);
}
[Test]
public void AFileAnEarlierBuildSetAsideIsKeptAMonthFromWhenThisOneFirstKnewTheFolder()
{
var store = new WorkspaceStore(Path.Combine(Context.CreateTempDirectory("prune-old"), "workspace"));
var project = store.Project(Guid.CreateVersion7());
var aside = Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedFolder);
Directory.CreateDirectory(aside);
var now = DateTime.UtcNow;
// Set aside by an earlier build, which kept the time its version was written: a year ago.
var old = Path.Combine(aside, $"1-{Guid.CreateVersion7():N}.json");
File.WriteAllText(old, "{}");
File.SetLastWriteTimeUtc(old, now - TimeSpan.FromDays(365));
Assert.Equal(0, project.PruneReplaced(new HashSet<Guid>(), now));
Assert.FileExists(old);
var since = Path.Combine(project.VersionsDirectory, WorkspaceProject.ReplacedSinceFile);
Assert.FileExists(since);
Assert.Equal(0, project.PruneReplaced(new HashSet<Guid>(), now + TimeSpan.FromDays(29)));
Assert.FileExists(old);
Assert.Equal(1, project.PruneReplaced(new HashSet<Guid>(), now + TimeSpan.FromDays(31)));
Assert.False(File.Exists(old), "a month after this Chronos first knew it");
// A marker that cannot be read is written again as now: nothing goes by an age it cannot tell.
var older = Path.Combine(aside, $"2-{Guid.CreateVersion7():N}.json");
File.WriteAllText(older, "{}");
File.SetLastWriteTimeUtc(older, now - TimeSpan.FromDays(365));
File.WriteAllText(since, "not a time");
Assert.Equal(0, project.PruneReplaced(new HashSet<Guid>(), now));
Assert.FileExists(older);
}
[Test]
public async Task ASyncThatEndsWellPrunesTheReplacedVersions()
{
@@ -438,9 +654,7 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
Assert.Count(1, files);
var taken = files[0];
Assert.True(DateTime.UtcNow - File.GetLastWriteTimeUtc(taken) < TimeSpan.FromHours(1), "a file set aside is dated then");
var old = Path.Combine(aside, $"1-{Guid.CreateVersion7():N}.json");
File.WriteAllText(old, "{}");
File.SetLastWriteTimeUtc(old, DateTime.UtcNow - TimeSpan.FromDays(40));
var old = OldReplaced(project, 40);
await two.PushAsync(id, fx.Home, fx.Ct);
Assert.False(File.Exists(old));
@@ -465,6 +679,28 @@ public abstract class WorkspaceSafetyTests(TestContext context) : DatabaseTest(c
Assert.Equal(read + 1, home.FramesReads);
Assert.True((await sync.StatusAsync(id, home, fx.Ct)).MediaOutdated);
Assert.Equal(read + 1, home.FramesReads);
// A hash replaced in place (a Verify that found other bytes) moves the stamp, with no other frames version.
var frame = (await fx.Db.Frames.ListBySequenceAsync(fx.Sequence.Id, cancellationToken: fx.Ct))[2];
var before = await fx.Home.FramesStampAsync(fx.Ct);
var sha = frame.Sha256 ?? new string('0', 64);
var other = (sha[0] == 'f' ? "e" : "f") + sha[1..];
Assert.Equal(1, await fx.Db.Frames.UpdateIntegrityAsync([new FrameIntegrity(frame.Id, frame.Flags, other)], fx.Ct));
Assert.NotEqual(before, await fx.Home.FramesStampAsync(fx.Ct));
await sync.StatusAsync(id, home, fx.Ct);
Assert.Equal(read + 2, home.FramesReads, "the frames read again");
}
[Test]
public async Task TheFramesStampMovesWhenTwoPhotosSwapTheirHashes()
{
var fx = await FixtureAsync(4);
var frames = await fx.Db.Frames.ListBySequenceAsync(fx.Sequence.Id, cancellationToken: fx.Ct);
var (a, b) = (new string('a', 64), new string('b', 64));
await fx.Db.Frames.UpdateIntegrityAsync([new FrameIntegrity(frames[0].Id, frames[0].Flags, a), new FrameIntegrity(frames[1].Id, frames[1].Flags, b)], fx.Ct);
var before = await fx.Home.FramesStampAsync(fx.Ct);
await fx.Db.Frames.UpdateIntegrityAsync([new FrameIntegrity(frames[0].Id, frames[0].Flags, b), new FrameIntegrity(frames[1].Id, frames[1].Flags, a)], fx.Ct);
Assert.NotEqual(before, await fx.Home.FramesStampAsync(fx.Ct));
}
}