fix(projects): phase 5a fix round 2 of the projects engine

The sidecars stay the truth of a sequence's projects in the cases round 1's
checkers found still open, and no version or setting is lost on the way:

- An index-only Main meeting a Main another index made is written back as
  another project, and Main passes to theirs in one transaction through a
  free temporary name, so ux_projects_name and ux_projects_main never fail
  (the SqliteException used to escape ListAsync and leave the index and the
  sidecars disagreeing). A refusal is logged; the next reconcile settles it.
- The reconcile takes Main from the records, in step with the index, when
  another index passed it on: exactly one Main per sequence, names from the
  records where free.
- A project folder with versions and no record, of a project no index row
  names (a creation cut before its record), no longer holds the sequence
  back forever: it is left as it is and indexed once its record arrives.
- A record behind the index (a projects folder put back from an older
  backup) is made whole from the index: its missing versions and the record
  are written again, at every catch-up and before any append, rename or
  delete. Only a record ahead of the index or naming another version is
  refused, with a message that says so.
- An index meeting Main walks the chain down to the version the record names
  as mirrored (a bound, since that record write may lag project.json), so a
  lagging record never makes an External that reverts a newer push. When the
  record names a mirrored ancestor, settings written since merge with the
  unmirrored versions, as for an index that knows its mirror.
- The catch-up merge's External + Merge pair is resumable: an External head
  whose parent is a push no mirror wrote is finished into its Merge version
  next time, by this index or one rebuilt from the sidecars.
- A project deleted at the home has no head there, so a workspace copy of it
  reads Gone, never In sync; Remove local copy without discard says the
  project was deleted in the library.
- DatabaseExceptions are contained per sequence in the archive scan's project
  reconcile and in ProjectService reads.

Tests: SQLite (PostgreSQL-ready) for each scenario, including a cut between
the two catch-up versions, a 40,000-exclusion version through save, push and
rebuild, and the App's Remove local copy of a project deleted at home.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-03 11:24:15 +01:00
1 parent 8256b72913
commit a368dc8bf0
10 files changed
+635 -70

No files matched your search

@@ -6,6 +6,8 @@ using Chronos.Data.Archiving;
using Chronos.Data.Projects;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Tests.Workspaces;
using Chronos.Data.Workspaces;
using Chronos.Testing;
using static Chronos.Data.Tests.Archiving.ArchiveFixture;
using static Chronos.Data.Tests.Projects.ProjectServiceTests;
@@ -488,6 +490,268 @@ public abstract class ProjectRecoveryTests(TestContext context) : DatabaseTest(c
Assert.FileExists(folder.VersionPath(main.Id, 1, head.Id));
Assert.Equal(PushOutcome.Stored, (await freshHome.PushAsync(main.Id, Draft(head, new ProjectSettings { ExcludedFrames = [0] }, freshFrames), fx.Ct)).Outcome);
}
[Test]
public async Task AnIndexOnlyMainMeetingAMainAnotherIndexMadeIsWrittenBackAsAnotherProject()
{
var fx = await FixtureAsync();
var (fresh, frames) = await UploadedAsync(fx, 2);
var projects = fx.Service.Projects;
projects.Availability = _ => ArchiveAvailability.ReadOnly;
var ours = (await projects.ListAsync(fresh.Id, fx.Ct)).Single();
// Meanwhile another PC's index makes its own Main into the archive; then this archive takes writes again.
var (other, _) = await fx.OtherWriterAsync();
var theirs = await other.Projects.MainAsync(fresh.Id, fx.Ct);
projects.Availability = ArchiveVolume.Probe;
// Theirs is Main, ours another project: in the index and in the sidecars alike, and it stays so.
foreach (var _ in new[] { 1, 2 })
{
Assert.SequenceEqual([(theirs.Id, "Main", true), (ours.Id, "Main (2)", false)],
(await projects.ListAsync(fresh.Id, fx.Ct)).Select(p => (p.Id, p.Name, p.IsMain)));
}
var folder = fx.Paths.Sequence(fresh.Folder);
Assert.Equal(1, MainRecords(folder));
var ourRecord = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(ours.Id));
Assert.Equal(("Main (2)", false), (ourRecord.Name, ourRecord.IsMain));
Assert.Equal(theirs.Id, (await other.Projects.MainAsync(fresh.Id, fx.Ct)).Id);
Assert.SequenceEqual([theirs.Id, ours.Id], (await other.Projects.ListAsync(fresh.Id, fx.Ct)).Select(p => p.Id));
Assert.Equal(PushOutcome.Stored,
(await projects.PushAsync(theirs.Id, Draft(await projects.HeadAsync(theirs.Id, fx.Ct), new ProjectSettings { ExcludedFrames = [1] }, frames), fx.Ct)).Outcome);
Assert.SequenceEqual([1], Settings(fx, fresh).ExcludedFrames);
}
[Test]
public async Task AMainAnotherIndexPassedOnIsTakenFromTheRecords()
{
var fx = await FixtureAsync();
var (sequence, _) = await UploadedAsync(fx, 2);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var second = await projects.CreateAsync(sequence.Id, "Main (2)", cancellationToken: fx.Ct);
var folder = fx.Paths.Sequence(sequence.Folder);
// Another index passed Main on, names and all: the records say the opposite of this index.
var mainRecord = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(main.Id));
var secondRecord = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(second.Id));
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(main.Id), mainRecord with { IsMain = false, Name = "Main (2)", Mirrored = null });
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(second.Id), secondRecord with { IsMain = true, Name = "Main" });
Assert.SequenceEqual([(second.Id, "Main", true), (main.Id, "Main (2)", false)],
(await projects.ListAsync(sequence.Id, fx.Ct)).Select(p => (p.Id, p.Name, p.IsMain)));
Assert.Equal(second.Id, (await projects.MainAsync(sequence.Id, fx.Ct)).Id);
Assert.Count(1, (await fx.Db.Projects.ListBySequenceAsync(sequence.Id, includeDeleted: true, fx.Ct)).Where(p => p.IsMain));
Assert.Equal(1, MainRecords(folder));
}
[Test]
public async Task AProjectCreationCutBeforeItsRecordHoldsNothingBack()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 2);
var folder = fx.Paths.Sequence(sequence.Folder);
// As making Main leaves it when its record cannot be written after its version (a lost disk, a crash): a folder with
// version 1 and no record, of a project no index row names.
var id = Guid.CreateVersion7();
var settings = ProjectContent.ToPortable(new ProjectSettings(), Photos(frames));
var now = DateTimeOffset.UtcNow;
var cut = new ProjectVersion
{
Id = Guid.CreateVersion7(),
ProjectId = id,
Number = 1,
Kind = ProjectVersionKind.Imported,
ClientName = "cut",
SettingsJson = settings,
ContentHash = ProjectContent.Hash(settings),
SettingsFormat = ProjectContent.FormatOf(settings),
FramesVersion = sequence.FramesVersion,
CreatedAt = now,
StoredAt = now,
};
ProjectSidecars.WriteVersion(folder.VersionPath(id, 1, cut.Id), cut);
var main = await fx.Service.Projects.MainAsync(sequence.Id, fx.Ct);
Assert.NotEqual(id, main.Id);
Assert.SequenceEqual([main.Id], (await new ArchiveProjectHome(fx.Db, fx.Service.Projects, sequence.Id).ListAsync(fx.Ct)).Select(p => p.Id));
Assert.FileExists(folder.VersionPath(id, 1, cut.Id));
Assert.Null(await fx.Db.Projects.GetAsync(id));
// Its record there at last (a sync tool bringing another PC's project): indexed as another project, Main stays.
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(id), new ProjectRecord(id, sequence.Id, ProjectService.MainName, true, new ProjectHead(cut.Id, 1), now, null, now));
Assert.SequenceEqual([(main.Id, true), (id, false)], (await fx.Service.Projects.ListAsync(sequence.Id, fx.Ct)).Select(p => (p.Id, p.IsMain)));
}
[Test]
public async Task AProjectsFolderPutBackFromAnOlderBackupIsMadeWholeFromTheIndex()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var vertical = await projects.CreateAsync(sequence.Id, "Vertical", cancellationToken: fx.Ct);
var folder = fx.Paths.Sequence(sequence.Folder);
var backup = folder.ProjectsDirectory + "-backup";
CopyDirectory(folder.ProjectsDirectory, backup);
var v2 = (await projects.PushAsync(vertical.Id, Draft(await projects.HeadAsync(vertical.Id, fx.Ct), new ProjectSettings { ExcludedFrames = [1] }, frames), fx.Ct))
.Version!;
var m2 = (await projects.PushAsync(main.Id, Draft(await projects.HeadAsync(main.Id, fx.Ct), new ProjectSettings { ExcludedFrames = [2] }, frames), fx.Ct)).Version!;
// The backup made before those pushes is put back: the records name version 1, the index holds version 2.
Directory.Delete(folder.ProjectsDirectory, recursive: true);
CopyDirectory(backup, folder.ProjectsDirectory);
Assert.Equal(PushOutcome.Stored, (await projects.PushAsync(vertical.Id, Draft(v2, new ProjectSettings { ExcludedFrames = [0] }, frames), fx.Ct)).Outcome);
Assert.Equal(PushOutcome.Stored, (await projects.PushAsync(main.Id, Draft(m2, new ProjectSettings { ExcludedFrames = [0] }, frames), fx.Ct)).Outcome);
Assert.Equal(3, ProjectSidecars.ReadRecord(folder.ProjectRecordPath(vertical.Id)).Head!.Number);
Assert.Equal(v2.ContentHash, ProjectSidecars.ReadVersion(folder.VersionPath(vertical.Id, 2, v2.Id)).ContentHash);
Assert.Equal(m2.ContentHash, ProjectSidecars.ReadVersion(folder.VersionPath(main.Id, 2, m2.Id)).ContentHash);
// The sidecars hold every version again: a rebuilt index has them all, and nothing was added.
await fx.ReopenWithEmptyIndexAsync();
await fx.ScanAsync(ScanMode.Rebuild);
Assert.SequenceEqual([3, 2, 1], (await fx.Service.Projects.HistoryAsync(vertical.Id, cancellationToken: fx.Ct)).Select(v => v.Number));
Assert.SequenceEqual([ProjectVersionKind.Commit, ProjectVersionKind.Commit, ProjectVersionKind.Imported],
(await fx.Service.Projects.HistoryAsync(main.Id, cancellationToken: fx.Ct)).Select(v => v.Kind));
Assert.SequenceEqual([0], Settings(fx, sequence).ExcludedFrames);
// A read alone makes the records whole too.
Directory.Delete(folder.ProjectsDirectory, recursive: true);
CopyDirectory(backup, folder.ProjectsDirectory);
await fx.Service.Projects.ListAsync(sequence.Id, fx.Ct);
Assert.Equal(3, ProjectSidecars.ReadRecord(folder.ProjectRecordPath(vertical.Id)).Head!.Number);
Assert.Count(3, ProjectSidecars.ListVersions(folder.ProjectVersionsDirectory(main.Id)));
}
[Test]
public async Task AMirrorRecordThatLagsProjectJsonNeverRevertsANewerPush()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var first = await projects.HeadAsync(main.Id, fx.Ct);
var second = (await projects.PushAsync(main.Id, Draft(first, new ProjectSettings { ExcludedFrames = [1] }, frames), fx.Ct)).Version!;
var folder = fx.Paths.Sequence(sequence.Folder);
var afterSecond = File.ReadAllText(folder.ProjectPath);
await projects.PushAsync(main.Id, Draft(second, new ProjectSettings { ExcludedFrames = [2] }, frames), fx.Ct);
// Version 2's mirror wrote project.json but not the record, and version 3's mirror was cut before project.json.
File.WriteAllText(folder.ProjectPath, afterSecond);
var record = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(main.Id));
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(main.Id), record with { Mirrored = new ProjectHead(first.Id, 1) });
await fx.ReopenWithEmptyIndexAsync();
await fx.ScanAsync(ScanMode.Rebuild);
// The mirror completes: no external version brings version 2 back over version 3.
Assert.SequenceEqual([3, 2, 1], (await fx.Service.Projects.HistoryAsync(main.Id, cancellationToken: fx.Ct)).Select(v => v.Number));
Assert.SequenceEqual([2], Settings(fx, sequence).ExcludedFrames);
}
[Test]
public async Task AnIndexMeetingMainMergesSettingsWrittenSinceWithAPushNoMirrorWrote()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var first = await projects.HeadAsync(main.Id, fx.Ct);
var pushed = (await projects.PushAsync(main.Id, Draft(first, new ProjectSettings { Stack = new StackSettings { Mode = StackSetting.Median } }, frames), fx.Ct))
.Version!;
// Version 2's mirror cut short (the record names version 1), and an older Chronos then writes an offset into project.json.
var folder = fx.Paths.Sequence(sequence.Folder);
File.WriteAllText(folder.ProjectPath, new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = -1 } }.ToJson());
var record = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(main.Id));
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(main.Id), record with { Mirrored = new ProjectHead(first.Id, 1) });
await fx.ReopenWithEmptyIndexAsync();
await fx.ScanAsync(ScanMode.Rebuild);
// Both are in force, as an index that knew its mirror would have merged them.
var history = await fx.Service.Projects.HistoryAsync(main.Id, cancellationToken: fx.Ct);
Assert.SequenceEqual([ProjectVersionKind.Merge, ProjectVersionKind.Commit, ProjectVersionKind.Imported], history.Select(v => v.Kind));
Assert.Equal(pushed.Id, history[0].ParentId);
Assert.Equal((StackSetting.Median, -1.0), (Settings(fx, sequence).Stack.Mode, Settings(fx, sequence).Exposure.ExposureOffsetEv));
}
[Test]
public async Task ANewerChronosHeadOverAMirrorCutShortIsLeftAsItIs()
{
var fx = await FixtureAsync();
var (sequence, frames) = await UploadedAsync(fx, 3);
var projects = fx.Service.Projects;
var main = await projects.MainAsync(sequence.Id, fx.Ct);
var first = await projects.HeadAsync(main.Id, fx.Ct);
var pushed = (await projects.PushAsync(main.Id, Draft(first, new ProjectSettings { ExcludedFrames = [1] }, frames), fx.Ct)).Version!;
// Version 2's mirror cut short, nobody writing the settings since; then a newer Chronos pushes version 3.
var reverted = await WriteSettingsAsync(fx, sequence.Id, new ProjectSettings());
await fx.Db.Projects.SetMirroredAsync(main.Id, first.Id, reverted.SettingsVersion, fx.Ct);
var newer = NewerChronos.Push(fx, sequence, pushed);
Assert.SequenceEqual([main.Id], (await projects.ListAsync(sequence.Id, fx.Ct)).Select(p => p.Id));
Assert.Equal(newer.Id, (await projects.HeadAsync(main.Id, fx.Ct)).Id);
Assert.Count(3, await projects.HistoryAsync(main.Id, cancellationToken: fx.Ct));
Assert.Empty(ProjectSettings.FromJson((await fx.Db.Sequences.GetAsync(sequence.Id))!.SettingsJson!).ExcludedFrames);
}
[Test]
public async Task AProjectDeletedAtItsHomeHasNoHeadThere()
{
var fx = await FixtureAsync();
var (sequence, _) = await UploadedAsync(fx, 2);
var projects = fx.Service.Projects;
var vertical = await projects.CreateAsync(sequence.Id, "Vertical", cancellationToken: fx.Ct);
var first = await projects.HeadAsync(vertical.Id, fx.Ct);
IProjectHome home = new ArchiveProjectHome(fx.Db, projects, sequence.Id);
// Deleted (by another PC, say): a workspace asking for its head learns it is gone, never that it is in step.
await projects.DeleteAsync(vertical.Id, fx.Ct);
Assert.Equal(ProjectError.NotFound, (await Assert.ThrowsAsync<ProjectException>(() => home.HeadAsync(vertical.Id, fx.Ct))).Reason);
Assert.False(await home.HoldsAsync(vertical.Id, first, fx.Ct));
Assert.Equal(first.Id, (await home.HistoryAsync(vertical.Id, null, 10, fx.Ct)).Single().Id);
}
[Test]
public async Task AVersionParkingFortyThousandPhotosGoesFromAWorkspaceToTheArchiveAndBack()
{
var fx = await FixtureAsync();
var bed = Own(await WorkspaceFixture.CreateAsync(Context, fx, 3));
var vertical = await fx.Service.Projects.CreateAsync(bed.Sequence.Id, "Vertical", cancellationToken: fx.Ct);
var (_, sync) = bed.Workspace();
var project = await bed.CheckoutAsync(sync, vertical.Id);
// A long sequence's nights excluded: 40,000 photos parked by a version, past the old 8 MB limit of both files.
var pending = Enumerable.Range(0, 40_000).Select(i => new PendingFrame
{
Sha256 = Convert.ToHexStringLower(SHA256.HashData(BitConverter.GetBytes(i))),
Size = 1_000_000 + i,
CapturedAt = Start.AddSeconds(i),
Excluded = true,
}).ToList();
var session = await sync.OpenAsync(vertical.Id, fx.Ct);
await sync.SaveAsync(vertical.Id, session.Working with { PendingFrames = pending }, fx.Ct);
var version = Assert.NotNull(await sync.CommitAsync(vertical.Id, "nights", cancellationToken: fx.Ct));
Assert.Greater(new FileInfo(project.VersionPath(version)).Length, 8L << 20);
Assert.Equal(1, (await sync.StatusAsync(vertical.Id, bed.Home, fx.Ct)).Ahead);
var pushed = await sync.PushAsync(vertical.Id, bed.Home, fx.Ct);
Assert.Equal(version.Id, pushed.Pushed.Single().Id);
Assert.Equal(WorkspaceState.InSync, pushed.Status.State);
await fx.ReopenWithEmptyIndexAsync();
await fx.ScanAsync(ScanMode.Rebuild);
var head = await fx.Service.Projects.HeadAsync(vertical.Id, fx.Ct);
Assert.Equal((version.Id, "nights"), (head.Id, head.Note));
Assert.Count(40_000, ProjectSettings.FromJson(head.SettingsJson).PendingFrames ?? []);
}
private static void CopyDirectory(string from, string to)
{
Directory.CreateDirectory(to);
foreach (var file in Directory.GetFiles(from)) File.Copy(file, Path.Combine(to, Path.GetFileName(file)));
foreach (var directory in Directory.GetDirectories(from)) CopyDirectory(directory, Path.Combine(to, Path.GetFileName(directory)));
}
}
public sealed class SqliteProjectRecoveryTests(TestContext context) : ProjectRecoveryTests(context)