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

+1
View File
@@ -53,6 +53,7 @@
<data name="Errors.Workspace.CopyKept" xml:space="preserve"><value>Its local copy could not be removed now: Remove local copy takes it later.</value><comment>long</comment></data>
<data name="Errors.Workspace.CopyMismatch" xml:space="preserve"><value>{0} did not match its source after it was copied.</value><comment>{0} file path</comment></data>
<data name="Errors.Workspace.Damaged" xml:space="preserve"><value>A file of this project in the workspace cannot be read; the log names it.</value></data>
<data name="Errors.Workspace.DeletedAtHome" xml:space="preserve"><value>This project was deleted in the library; nothing was removed. Discard changes removes its local copy.</value></data>
<data name="Errors.Workspace.DiskFull" xml:space="preserve"><value>The workspace drive needs {0} GB more for this copy.</value><comment>{0} gigabytes missing</comment></data>
<data name="Errors.Workspace.EditNotStored" xml:space="preserve"><value>The last edit could not be stored yet; it is tried again, try once more in a moment.</value></data>
<data name="Errors.Workspace.HomeCheck" xml:space="preserve"><value>The library's copy of this project does not match what was sent; nothing was removed.</value></data>
+1
View File
@@ -53,6 +53,7 @@
<data name="Errors.Workspace.CopyKept" xml:space="preserve"><value>La sua copia locale ora non è stata rimossa: Rimuovi copia locale la toglie più tardi.</value></data>
<data name="Errors.Workspace.CopyMismatch" xml:space="preserve"><value>{0} non corrispondeva all'originale dopo la copia.</value></data>
<data name="Errors.Workspace.Damaged" xml:space="preserve"><value>Un file di questo progetto nello spazio di lavoro non è leggibile; il log lo indica.</value></data>
<data name="Errors.Workspace.DeletedAtHome" xml:space="preserve"><value>Questo progetto è stato eliminato nella libreria; non è stato rimosso nulla. Scarta modifiche rimuove la sua copia locale.</value></data>
<data name="Errors.Workspace.DiskFull" xml:space="preserve"><value>Al disco dello spazio di lavoro servono altri {0} GB per questa copia.</value></data>
<data name="Errors.Workspace.EditNotStored" xml:space="preserve"><value>L'ultima modifica non è ancora stata memorizzata; viene ritentata, riprova tra un momento.</value></data>
<data name="Errors.Workspace.HomeCheck" xml:space="preserve"><value>La copia di questo progetto nella libreria non corrisponde a quanto inviato; non è stato rimosso nulla.</value></data>
@@ -600,6 +600,11 @@ public sealed class WorkspaceHost
held = basis is not null && await home.HoldsAsync(projectId, head, cancellationToken).ConfigureAwait(false)
&& (basis.Id == head.Id || await home.HoldsAsync(projectId, basis, cancellationToken).ConfigureAwait(false));
}
catch (ProjectException ex) when (ex.Reason is ProjectError.NotFound or ProjectError.SequenceNotFound)
{
// Deleted at the home (its trash keeps every version sent): this copy goes only when its user discards it.
throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"), ex);
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"), ex);
@@ -368,6 +368,11 @@ public sealed class ArchiveIndexer
{
Log.Warning("projects", $"The projects of {row.Folder} could not be read back; the next project operation tries again", ex);
}
catch (DatabaseException ex)
{
// The index refused a project of this sequence: the scan goes on with the others, and the next project operation tries again.
Log.Warning("projects", $"The projects of {row.Folder} could not be indexed; the next project operation tries again", ex);
}
}
/// <summary>Indexes one folder; returns its sequence and the sidecar bytes when they were read and not rewritten since (for the snapshot).</summary>
+4 -1
View File
@@ -27,7 +27,10 @@ public interface IProjectHome
/// <summary>A new project named <paramref name="name"/> from <paramref name="fromVersionId"/> (a version of any project of the sequence), or from Main's head.</summary>
Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken);
/// <summary>The project's newest version.</summary>
/// <summary>
/// The project's newest version; a project deleted at the home has none (<see cref="ProjectException"/>,
/// <see cref="ProjectError.NotFound"/>), so a workspace's copy of it reads as gone, never as in step.
/// </summary>
Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken);
/// <summary>A version of the project by id; null when the home has none.</summary>
+66 -4
View File
@@ -53,11 +53,21 @@ internal sealed class ProjectIndexer(ChronosDatabase db)
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("projects", $"The project in {directory} cannot be read; it stays as the index has it", ex);
// Its folder names it (<id>, or <id>-<time> in the trash): its row stays as it is, never taken for gone nor written
// again, and a live one is held back (it may be Main).
// Its folder names it (<id>, or <id>-<time> in the trash).
var name = Path.GetFileName(directory);
if (Guid.TryParseExact(trashed && name.Length > 32 ? name[..32] : name, "N", out var named) && seen.Add(named) && !trashed) heldBack.Add(named);
if (!Guid.TryParseExact(trashed && name.Length > 32 ? name[..32] : name, "N", out var named)) continue;
if (!trashed && !File.Exists(Path.Combine(directory, ArchiveLayout.ProjectFile))
&& await db.Projects.GetAsync(named, cancellationToken).ConfigureAwait(false) is null)
{
// Versions with no record, of a project no index row names: a creation a crash or a lost disk cut short before its
// record (versions are written first), or one a sync tool is still bringing. No project of the sequence is
// hidden in it, so it holds nothing back; it is left as it is, and indexed once its record is there.
Log.Info("projects", $"{directory} holds no project record; it is left as it is");
continue;
}
Log.Warning("projects", $"The project in {directory} cannot be read; it stays as the index has it", ex);
// Its row stays as it is, never taken for gone nor written again, and a live one is held back (it may be Main).
if (seen.Add(named) && !trashed) heldBack.Add(named);
continue;
}
// A sequence folder copied by hand carries the projects of its source, which stay that sequence's.
@@ -79,9 +89,61 @@ internal sealed class ProjectIndexer(ChronosDatabase db)
if (record.Deleted is null) heldBack.Add(record.Id);
}
}
try
{
await SettleMainAsync(sequenceId, live, heldBack, cancellationToken).ConfigureAwait(false);
}
catch (DatabaseException ex) when (ex.IsUniqueViolation || ex.IsForeignKeyViolation)
{
Log.Warning("projects", $"The Main of sequence {sequenceId} could not be taken from its records; tried again next time", ex);
}
return new ProjectReconcile(false, seen, heldBack, live);
}
/// <summary>
/// Stores <paramref name="demoted"/> and <paramref name="promoted"/>, Main passing from the first to the second, each
/// with its new name, in one transaction: the first goes through a name no project has, so no two live projects of the
/// sequence ever hold one name, nor both Main.
/// </summary>
internal static async Task SwapMainAsync(ChronosDatabase db, SequenceProject demoted, SequenceProject promoted, CancellationToken cancellationToken)
{
await using var tx = await db.BeginAsync(cancellationToken).ConfigureAwait(false);
await tx.Projects.UpdateAsync(demoted with { IsMain = false, Name = "~" + demoted.Id.ToString("N") }, cancellationToken).ConfigureAwait(false);
await tx.Projects.UpdateAsync(promoted with { IsMain = true }, cancellationToken).ConfigureAwait(false);
await tx.Projects.UpdateAsync(demoted with { IsMain = false }, cancellationToken).ConfigureAwait(false);
await tx.CommitAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The index's Main taken from the records, which say which project is Main (another index of the archive passed it on:
/// an index-only Main written back beside the one made into the archive meanwhile): when the index's Main is read and its
/// record no longer says it is Main, or the index has none, the oldest project whose record says it is becomes Main, and
/// both take their records' names where free. Only records in step with the index count (a record behind it, put back
/// from an older backup, says what was): never while the index's Main is held back or its record is not in step, and
/// never more than one Main.
/// </summary>
private async Task SettleMainAsync(Guid sequenceId, IReadOnlyDictionary<Guid, ProjectRecord> live, IReadOnlySet<Guid> heldBack, CancellationToken cancellationToken)
{
var rows = await db.Projects.ListBySequenceAsync(sequenceId, includeDeleted: false, cancellationToken).ConfigureAwait(false);
ProjectRecord? InStep(SequenceProject row) =>
!heldBack.Contains(row.Id) && live.TryGetValue(row.Id, out var record) && record.Head?.Id == row.HeadVersionId ? record : null;
var main = rows.FirstOrDefault(p => p.IsMain);
var own = main is null ? null : InStep(main);
if (main is not null && own is not { IsMain: false }) return;
var claimant = rows.Where(p => !p.IsMain && InStep(p) is { IsMain: true }).OrderBy(p => p.CreatedAt).ThenBy(p => p.Id).FirstOrDefault();
if (claimant is null) return;
var others = rows.Where(p => p.Id != claimant.Id && p.Id != main?.Id).ToList();
var promoted = claimant with { IsMain = true, Name = FreeName(others, live[claimant.Id].Name, claimant.Id), MirroredVersionId = null, MirroredSettingsVersion = null };
Log.Warning("projects", $"The records of sequence {sequenceId} name project {claimant.Id} as Main{(main is null ? string.Empty : $", not {main.Id}")}; the index takes it");
if (main is null)
{
await db.Projects.UpdateAsync(promoted, cancellationToken).ConfigureAwait(false);
return;
}
var demoted = main with { IsMain = false, Name = FreeName([.. others, promoted], own!.Name, main.Id), MirroredVersionId = null, MirroredSettingsVersion = null };
await SwapMainAsync(db, demoted, promoted, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// <paramref name="name"/>, or "<paramref name="name"/> (2)", "(3)"… (within <see cref="ProjectService.MaxNameLength"/>):
/// the first no project of <paramref name="live"/> but <paramref name="projectId"/> has.
+214 -65
View File
@@ -134,6 +134,11 @@ public sealed class ProjectService
/// <summary>Whether an archive takes writes now (<see cref="ArchiveVolume.Probe"/>; tests stand in a read-only one).</summary>
internal Func<ArchivePaths, ArchiveAvailability> Availability { get; set; } = ArchiveVolume.Probe;
/// <summary>Called at each named step between two writes, so a test can stop there as a crash would.</summary>
internal Action<string>? Cut { get; set; }
private void Step(string name) => Cut?.Invoke(name);
/// <summary>The live projects of a sequence, Main first; read from the index alone while the archive is offline.</summary>
/// <exception cref="ProjectException">The sequence is not in the index.</exception>
public async Task<IReadOnlyList<SequenceProject>> ListAsync(Guid sequenceId, CancellationToken cancellationToken = default)
@@ -224,7 +229,7 @@ public sealed class ProjectService
var current = await LiveAsync(projectId, ct).ConfigureAwait(false);
if (current.Name == trimmed) return current;
await EnsureNameFreeAsync(current.SequenceId, projectId, trimmed, ct).ConfigureAwait(false);
var record = OwnRecord(context, projectId);
var record = await OwnRecordAsync(context, current, ct).ConfigureAwait(false);
var renamed = current with { Name = trimmed, UpdatedAt = DateTimeOffset.UtcNow };
ProjectSidecars.WriteRecord(context.Folder.ProjectRecordPath(projectId), ProjectRecord.Of(renamed, record.Mirrored));
await _db.Projects.UpdateAsync(renamed, ct).ConfigureAwait(false);
@@ -245,7 +250,7 @@ public sealed class ProjectService
await UnderLeaseAsync(project.SequenceId, async (context, ct) =>
{
var current = await LiveAsync(projectId, ct).ConfigureAwait(false);
var record = OwnRecord(context, projectId);
var record = await OwnRecordAsync(context, current, ct).ConfigureAwait(false);
var now = DateTimeOffset.UtcNow;
var deleted = current with { DeletedAt = now, UpdatedAt = now };
Directory.CreateDirectory(context.Folder.ProjectsTrashDirectory);
@@ -288,13 +293,15 @@ public sealed class ProjectService
public Task<ProjectVersion?> GetVersionAsync(Guid versionId, CancellationToken cancellationToken = default) =>
_db.Projects.GetVersionAsync(versionId, cancellationToken);
/// <summary>The newest version of a project, after catching up.</summary>
/// <exception cref="ProjectException">Unknown project.</exception>
/// <summary>The newest version of a live project, after catching up.</summary>
/// <exception cref="ProjectException">
/// Unknown project, or one deleted (<see cref="ProjectError.NotFound"/>): a workspace's copy of it is gone from its home.
/// </exception>
public async Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var project = await KnownAsync(projectId, cancellationToken).ConfigureAwait(false);
await ReadAsync(project.SequenceId, cancellationToken).ConfigureAwait(false);
project = await KnownAsync(projectId, cancellationToken).ConfigureAwait(false);
project = await LiveAsync(projectId, cancellationToken).ConfigureAwait(false);
return await _db.Projects.GetVersionAsync(project.HeadVersionId ?? Guid.Empty, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.NotFound, $"Project {projectId} has no version.");
}
@@ -409,16 +416,25 @@ public sealed class ProjectService
{
try
{
await UnderLeaseAsync(sequenceId, (_, _) => Task.FromResult(true), cancellationToken, ReadWait).ConfigureAwait(false);
}
catch (ArchiveOfflineException ex) when (ex.Availability == ArchiveAvailability.ReadOnly)
{
await ReadOnlyCatchUpAsync(sequenceId, cancellationToken).ConfigureAwait(false);
try
{
await UnderLeaseAsync(sequenceId, (_, _) => Task.FromResult(true), cancellationToken, ReadWait).ConfigureAwait(false);
}
catch (ArchiveOfflineException ex) when (ex.Availability == ArchiveAvailability.ReadOnly)
{
await ReadOnlyCatchUpAsync(sequenceId, cancellationToken).ConfigureAwait(false);
}
}
catch (Exception ex) when (ex is ArchiveOfflineException or LeaseUnavailableException or SequenceFolderMovedException or ProjectsUnreadableException)
{
Log.Info("projects", $"The projects of sequence {sequenceId} are read from the index: {ex.Message}");
}
catch (DatabaseException ex)
{
// The index refused a step of the catch-up (a row, a lock held a moment too long): the read answers from it as it
// is, and the next operation tries again.
Log.Warning("projects", $"The projects of sequence {sequenceId} could not be caught up; they are read from the index", ex);
}
}
/// <summary>
@@ -536,41 +552,63 @@ public sealed class ProjectService
return;
}
// The head is newer than the mirror: a push whose mirror a crash (or a settings edit at the same moment) cut short.
var mirrored = await _db.Projects.GetVersionAsync(main.MirroredVersionId.Value, cancellationToken).ConfigureAwait(false);
if (sameAsHead)
{
// A head that is the external version of a merge a crash stopped before its merge version (its parent a push no
// mirror wrote): the merge is finished now, else that push would never be in force. Any other: in force already.
if (head.Kind == ProjectVersionKind.External && head.ParentId is { } pushedId && pushedId != main.MirroredVersionId
&& mirrored is { } basis && basis.ProjectId == main.Id
&& await _db.Projects.GetVersionAsync(pushedId, cancellationToken).ConfigureAwait(false) is { } pushed && pushed.ProjectId == main.Id)
{
Log.Warning("projects", $"The merge of version {pushed.Number} of Main of sequence {context.Row.Id} stopped after version {head.Number}; it is finished");
await MergeIntoMainAsync(context, main, basis, pushed, head.SettingsJson, head, frames.Photos, cancellationToken).ConfigureAwait(false);
return;
}
await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
return;
}
var mirrored = await _db.Projects.GetVersionAsync(main.MirroredVersionId.Value, cancellationToken).ConfigureAwait(false);
if (main.MirroredSettingsVersion == context.Row.SettingsVersion || mirrored is null || ProjectContent.SameChoices(mirrored.SettingsJson, current, frames.Photos))
{
// Nobody changed the settings since the last mirror: the mirror completes.
await MirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
return;
}
// Both moved: the settings written meanwhile merge with the head (the version made in a workspace wins where both changed),
// each photo named as the frames hold it now so the same photo merges as one. Where both changed, the settings written
// meanwhile become an external version first, so the values the merge leaves out stay in the history to restore.
await MergeIntoMainAsync(context, main, mirrored, head, current, null, frames.Photos, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Both moved: the settings written meanwhile (<paramref name="theirs"/>) merge with <paramref name="pushed"/>, the head no
/// mirror wrote, over <paramref name="basis"/>, the version mirrored last (the version made in a workspace wins where both
/// changed), each photo named as the frames hold it now so the same photo merges as one. Where both changed, the settings
/// written meanwhile become an external version first, so the values the merge leaves out stay in the history to restore;
/// the merge version follows it and is mirrored. <paramref name="external"/> is that external version when a crash
/// stopped the pair between its two versions: the merge version is made on it, so a cut anywhere is finished next time.
/// </summary>
private async Task MergeIntoMainAsync(LeaseContext context, SequenceProject main, ProjectVersion basis, ProjectVersion pushed, string theirs,
ProjectVersion? external, FramePhotos photos, CancellationToken cancellationToken)
{
ProjectMergeResult merged;
try
{
merged = ProjectMerge.MergeWithConflicts(ProjectMerge.Read(ProjectContent.Rebind(mirrored.SettingsJson, frames.Photos)),
ProjectMerge.Read(ProjectContent.Rebind(head.SettingsJson, frames.Photos)), ProjectMerge.Read(ProjectContent.Rebind(current, frames.Photos)));
merged = ProjectMerge.MergeWithConflicts(ProjectMerge.Read(ProjectContent.Rebind(basis.SettingsJson, photos)),
ProjectMerge.Read(ProjectContent.Rebind(pushed.SettingsJson, photos)), ProjectMerge.Read(ProjectContent.Rebind(theirs, photos)));
}
catch (NewerSettingsException ex)
{
// A newer Chronos's version is never merged with this one's settings: both are left as they are, recorded as seen.
Log.Warning("projects", $"Version {head.Number} of Main of sequence {context.Row.Id} and its settings written meanwhile are left as they are", ex);
await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
Log.Warning("projects", $"Version {pushed.Number} of Main of sequence {context.Row.Id} and its settings written meanwhile are left as they are", ex);
await _db.Projects.SetMirroredAsync(main.Id, main.HeadVersionId, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
return;
}
var parent = head;
if (merged.HasConflicts)
var parent = external ?? pushed;
if (merged.HasConflicts && external is null)
{
parent = await AppendDerivedAsync(context, main, head, current, ProjectVersionKind.External, cancellationToken).ConfigureAwait(false);
parent = await AppendDerivedAsync(context, main, pushed, theirs, ProjectVersionKind.External, cancellationToken).ConfigureAwait(false);
main = (await _db.Projects.GetAsync(main.Id, cancellationToken).ConfigureAwait(false))!;
Log.Info("projects", $"Version {head.Number} of Main of sequence {context.Row.Id} and its settings written meanwhile both changed "
+ $"{string.Join(", ", merged.Conflicts.Select(c => c.Path))}: version {head.Number}'s values are kept, the others are version {parent.Number}");
Log.Info("projects", $"Version {pushed.Number} of Main of sequence {context.Row.Id} and its settings written meanwhile both changed "
+ $"{string.Join(", ", merged.Conflicts.Select(c => c.Path))}: version {pushed.Number}'s values are kept, the others are version {parent.Number}");
Step("catchup.external");
}
var version = await AppendDerivedAsync(context, main, parent, ProjectContent.Canonical(merged.Merged.ToJson()), ProjectVersionKind.Merge, cancellationToken)
.ConfigureAwait(false);
@@ -582,9 +620,11 @@ public sealed class ProjectService
/// Main as this index meets it with no mirror known (an index rebuilt from the sidecars, another PC's index of the archive,
/// an index taken back from a backup): the sequence's settings are what its <c>project.json</c> holds, the file every
/// mirror writes, never this index's copy, which may have been read long ago. The head's choices: in step, this index's
/// copy brought up to them. Those of the version Main's record says was mirrored last (an older record names none: of a
/// version the head descends from): a mirror a crash cut short, completed. Neither: settings another path wrote since,
/// an external version.
/// copy brought up to them. Those of a version the head descends from, down to the one Main's record says was mirrored
/// last (a record whose write failed after <c>project.json</c>'s lags it, so it only bounds the search; an older record
/// names none: the last versions): a mirror a crash cut short, completed. Neither: settings another path wrote since,
/// merged with the versions no mirror wrote when the record names the one mirrored last (as an index that knows its
/// mirror merges them), else an external version.
/// </summary>
private async Task MeetMainAsync(LeaseContext context, SequenceProject main, ProjectVersion head, FramePhotos photos, CancellationToken cancellationToken)
{
@@ -594,40 +634,69 @@ public sealed class ProjectService
await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
return;
}
var recorded = await RecordedMirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
if (ProjectContent.SameChoices(head.SettingsJson, shared, photos))
{
// The external version of a merge a crash stopped before its merge version (see CatchUpAsync): finished now.
if (recorded is not null && head.Kind == ProjectVersionKind.External && head.ParentId is { } pushedId && pushedId != recorded.Id
&& await _db.Projects.GetVersionAsync(pushedId, cancellationToken).ConfigureAwait(false) is { } pushed && pushed.ProjectId == main.Id)
{
await MergeIntoMainAsync(context, main, recorded, pushed, head.SettingsJson, head, photos, cancellationToken).ConfigureAwait(false);
return;
}
if (CurrentPortable(context, photos) is { } copy && ProjectContent.SameChoices(head.SettingsJson, copy, photos))
await _db.Projects.SetMirroredAsync(main.Id, head.Id, context.Row.SettingsVersion, cancellationToken).ConfigureAwait(false);
else
await MirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
return;
}
if (await MirroredBeforeAsync(context, main, head, shared, photos, cancellationToken).ConfigureAwait(false))
// A record that names the head as mirrored says project.json held it: whatever it holds now was written since.
var headMirrored = context.Reconcile.Live.TryGetValue(main.Id, out var record) && record.Mirrored?.Id == head.Id;
if (!headMirrored && await MirroredBeforeAsync(main, head, recorded, shared, photos, cancellationToken).ConfigureAwait(false))
{
await MirrorAsync(context, main, head, cancellationToken).ConfigureAwait(false);
return;
}
if (recorded is not null)
{
await MergeIntoMainAsync(context, main, recorded, head, shared, null, photos, cancellationToken).ConfigureAwait(false);
return;
}
var external = await AppendDerivedAsync(context, main, head, shared, ProjectVersionKind.External, cancellationToken).ConfigureAwait(false);
main = (await _db.Projects.GetAsync(main.Id, cancellationToken).ConfigureAwait(false))!;
await MirrorAsync(context, main, external, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Whether <paramref name="shared"/> holds the choices of an earlier version of Main a mirror wrote: the one Main's record
/// names as mirrored last, else (an older record) one of the versions the head descends from.
/// The version Main's record names as mirrored last, when it is one the head descends from (not the head itself) and of
/// a format this Chronos reads; null otherwise (an older record names none).
/// </summary>
private async Task<bool> MirroredBeforeAsync(LeaseContext context, SequenceProject main, ProjectVersion head, string shared, FramePhotos photos,
private async Task<ProjectVersion?> RecordedMirrorAsync(LeaseContext context, SequenceProject main, ProjectVersion head, CancellationToken cancellationToken)
{
if (!context.Reconcile.Live.TryGetValue(main.Id, out var record) || record.Mirrored is not { } recorded || recorded.Number >= head.Number) return null;
for (var parent = head.ParentId; parent is { } id;)
{
if (await _db.Projects.GetVersionAsync(id, cancellationToken).ConfigureAwait(false) is not { } version || version.ProjectId != main.Id
|| version.Number < recorded.Number) return null;
if (version.Id == recorded.Id) return IsNewer(version) ? null : version;
parent = version.ParentId;
}
return null;
}
/// <summary>
/// Whether <paramref name="shared"/> holds the choices of an earlier version of Main a mirror wrote: one the head descends
/// from, down to <paramref name="recorded"/> (the version Main's record names as mirrored last), else among the last
/// <see cref="MirrorSearch"/>.
/// </summary>
private async Task<bool> MirroredBeforeAsync(SequenceProject main, ProjectVersion head, ProjectVersion? recorded, string shared, FramePhotos photos,
CancellationToken cancellationToken)
{
if (context.Reconcile.Live.TryGetValue(main.Id, out var record) && record.Mirrored is { } recorded)
var floor = recorded?.Number ?? head.Number - MirrorSearch;
for (var parent = head.ParentId; parent is { } id;)
{
return recorded.Id != head.Id && await _db.Projects.GetVersionAsync(recorded.Id, cancellationToken).ConfigureAwait(false) is { } mirrored
&& mirrored.ProjectId == main.Id && !IsNewer(mirrored) && ProjectContent.SameChoices(mirrored.SettingsJson, shared, photos);
}
var parent = head.ParentId;
for (var step = 0; parent is { } id && step < MirrorSearch; step++)
{
if (await _db.Projects.GetVersionAsync(id, cancellationToken).ConfigureAwait(false) is not { } version || version.ProjectId != main.Id) break;
if (await _db.Projects.GetVersionAsync(id, cancellationToken).ConfigureAwait(false) is not { } version || version.ProjectId != main.Id
|| version.Number < floor) break;
if (!IsNewer(version) && ProjectContent.SameChoices(version.SettingsJson, shared, photos)) return true;
parent = version.ParentId;
}
@@ -678,18 +747,9 @@ public sealed class ProjectService
}
try
{
for (var after = 0; ;)
{
var page = await _db.Projects.ListVersionsAfterAsync(row.Id, after, WriteBackPage, cancellationToken).ConfigureAwait(false);
foreach (var version in page) ProjectSidecars.WriteVersion(context.Folder.VersionPath(row.Id, version.Number, version.Id), version);
if (page.Count < WriteBackPage) break;
after = page[^1].Number;
}
var mirrored = project.IsMain && project.MirroredVersionId is { } mirroredId
&& await _db.Projects.GetVersionAsync(mirroredId, cancellationToken).ConfigureAwait(false) is { } known
? new ProjectHead(known.Id, known.Number)
: null;
ProjectSidecars.WriteRecord(context.Folder.ProjectRecordPath(row.Id), ProjectRecord.Of(project, mirrored));
await WriteVersionsAsync(context.Folder, row.Id, 0, cancellationToken).ConfigureAwait(false);
ProjectSidecars.WriteRecord(context.Folder.ProjectRecordPath(row.Id), ProjectRecord.Of(project, await MirroredHeadAsync(project, null, cancellationToken)
.ConfigureAwait(false)));
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
@@ -697,12 +757,86 @@ public sealed class ProjectService
continue;
}
Log.Warning("projects", $"Project {row.Id} of sequence {context.Row.Id} had no folder in the archive; its sidecars are written again from the index");
if (project == row) continue;
await _db.Projects.UpdateAsync(project, cancellationToken).ConfigureAwait(false);
if (promoted is not null) await _db.Projects.UpdateAsync(promoted, cancellationToken).ConfigureAwait(false);
try
{
// Main passes to theirs in one step, this one through a name no project has: never two Mains, nor one name twice.
if (promoted is not null) await ProjectIndexer.SwapMainAsync(_db, project, promoted, cancellationToken).ConfigureAwait(false);
else if (project != row) await _db.Projects.UpdateAsync(project, cancellationToken).ConfigureAwait(false);
}
catch (DatabaseException ex) when (ex.IsUniqueViolation || ex.IsForeignKeyViolation)
{
// The sidecars written are the truth: the next reconcile takes the names and Main from them (ProjectIndexer).
Log.Warning("projects", $"The index could not take project {row.Id} as its sidecars now name it; it does next time", ex);
}
}
await HealBehindAsync(context, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// The records the archive has whose head is behind the index's (a projects folder put back from an older backup, a sync
/// tool that brought an older record back): the versions they lack and the record written again from the index, which
/// holds the newer chain, so the sidecars hold every version again. A record ahead of the index, or naming a head the
/// index does not have at its number, is never written over (<see cref="WritableRecordAsync"/>).
/// </summary>
private async Task HealBehindAsync(LeaseContext context, CancellationToken cancellationToken)
{
foreach (var (id, record) in context.Reconcile.Live)
{
if (context.Reconcile.HeldBack.Contains(id) || await _db.Projects.GetAsync(id, cancellationToken).ConfigureAwait(false) is not { DeletedAt: null } row
|| !await BehindAsync(row, record, cancellationToken).ConfigureAwait(false)) continue;
try
{
await HealAsync(context.Folder, row, record, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("projects", $"The record of project {id} is behind the index and could not be written again; tried again next time", ex);
}
}
}
/// <summary>Whether <paramref name="record"/>'s head is one of the versions the index holds below its head: the record is behind.</summary>
private async Task<bool> BehindAsync(SequenceProject project, ProjectRecord record, CancellationToken cancellationToken)
{
if (project.HeadVersionId is null) return false;
if (record.Head is not { } head) return true;
return head.Number < project.HeadNumber && await _db.Projects.GetVersionAsync(head.Id, cancellationToken).ConfigureAwait(false) is { } version
&& version.ProjectId == project.Id && version.Number == head.Number;
}
/// <summary>
/// A record behind the index made whole: the version files past its head written from the index (those there are left
/// as they are), then the record naming the index's head.
/// </summary>
private async Task<ProjectRecord> HealAsync(SequencePaths folder, SequenceProject project, ProjectRecord record, CancellationToken cancellationToken)
{
await WriteVersionsAsync(folder, project.Id, record.Head?.Number ?? 0, cancellationToken).ConfigureAwait(false);
var healed = ProjectRecord.Of(project with { UpdatedAt = DateTimeOffset.UtcNow }, await MirroredHeadAsync(project, record.Mirrored, cancellationToken)
.ConfigureAwait(false));
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(project.Id), healed);
Log.Warning("projects", $"The record of project {project.Id} named version {record.Head?.Number} as its head, behind the index's {project.HeadNumber}; "
+ "its versions and record are written again from the index");
return healed;
}
/// <summary>The version files of a project numbered above <paramref name="after"/> written from the index (immutable: one there already is left).</summary>
private async Task WriteVersionsAsync(SequencePaths folder, Guid projectId, int after, CancellationToken cancellationToken)
{
while (true)
{
var page = await _db.Projects.ListVersionsAfterAsync(projectId, after, WriteBackPage, cancellationToken).ConfigureAwait(false);
foreach (var version in page) ProjectSidecars.WriteVersion(folder.VersionPath(projectId, version.Number, version.Id), version);
if (page.Count < WriteBackPage) return;
after = page[^1].Number;
}
}
/// <summary>The version a Main record names as mirrored: the one this index mirrored when it knows it, else <paramref name="fallback"/>.</summary>
private async Task<ProjectHead?> MirroredHeadAsync(SequenceProject project, ProjectHead? fallback, CancellationToken cancellationToken) =>
project.IsMain && project.MirroredVersionId is { } mirroredId && await _db.Projects.GetVersionAsync(mirroredId, cancellationToken).ConfigureAwait(false) is { } known
? new ProjectHead(known.Id, known.Number)
: fallback;
/// <summary>
/// The Main project of a sequence that has none: version 1 from the sequence's settings as its <c>project.json</c> holds
/// them (this index's copy when there is none, else defaults), this index's copy brought up to them. With the archive
@@ -828,15 +962,12 @@ public sealed class ProjectService
/// <summary>
/// A version appended to a project: its sidecar, the record's head, then the version row and the head in one
/// transaction. Only onto the head the record names, read again now: a record that cannot be read, or that names another
/// head than the index has (a version this Chronos cannot read), is never written over and the version is not made.
/// transaction. Only onto the head the record names, read again now (<see cref="WritableRecordAsync"/>).
/// </summary>
/// <exception cref="ProjectsUnreadableException">The record cannot be read, or its head is not the index's.</exception>
/// <exception cref="ProjectsUnreadableException">The record cannot be read, or its head is ahead of the index's or not one the index holds.</exception>
private async Task<SequenceProject> AppendAsync(SequencePaths folder, SequenceProject project, ProjectVersion version, CancellationToken cancellationToken)
{
var record = ReadOwnRecord(folder, project.Id);
if (record.Head != (project.HeadVersionId is { } headId ? new ProjectHead(headId, project.HeadNumber) : null))
throw new ProjectsUnreadableException($"The record of project {project.Id} names version {record.Head?.Number} as its head, which the index does not hold.");
var record = await WritableRecordAsync(folder, project, cancellationToken).ConfigureAwait(false);
var now = DateTimeOffset.UtcNow;
var advanced = project with { HeadVersionId = version.Id, HeadNumber = version.Number, UpdatedAt = now };
ProjectSidecars.WriteVersion(folder.VersionPath(project.Id, version.Number, version.Id), version);
@@ -849,12 +980,30 @@ public sealed class ProjectService
return advanced;
}
/// <summary>The record of a live project as its folder holds it now, before it is written again: one held back or unreadable is never written over.</summary>
/// <exception cref="ProjectsUnreadableException">The project is held back, or its record cannot be read.</exception>
private static ProjectRecord OwnRecord(LeaseContext context, Guid projectId) =>
context.Reconcile.HeldBack.Contains(projectId)
? throw new ProjectsUnreadableException($"Project {projectId} cannot be read now.")
: ReadOwnRecord(context.Folder, projectId);
/// <summary>
/// The record of a live project as its folder holds it now, before it is written again, naming the index's head. One
/// behind the index (a projects folder put back from an older backup) is made whole first (<see cref="HealAsync"/>).
/// One that cannot be read, or that is ahead of the index or names a head the index does not hold at its number (a
/// version this Chronos cannot read), is never written over: nothing is written.
/// </summary>
/// <exception cref="ProjectsUnreadableException">The record cannot be read, or is ahead of the index or apart from it.</exception>
private async Task<ProjectRecord> WritableRecordAsync(SequencePaths folder, SequenceProject project, CancellationToken cancellationToken)
{
var record = ReadOwnRecord(folder, project.Id);
var head = project.HeadVersionId is { } headId ? new ProjectHead(headId, project.HeadNumber) : null;
if (record.Head == head) return record;
if (await BehindAsync(project, record, cancellationToken).ConfigureAwait(false)) return await HealAsync(folder, project, record, cancellationToken).ConfigureAwait(false);
throw new ProjectsUnreadableException(record.Head is { } named && named.Number > project.HeadNumber
? $"The record of project {project.Id} names version {named.Number} as its head, past the {project.HeadNumber} the index holds."
: $"The record of project {project.Id} names version {record.Head?.Number} as its head, which is not the version the index holds at that number.");
}
/// <summary>The record of a live project, before it is written again: one held back is never written over (<see cref="WritableRecordAsync"/>).</summary>
/// <exception cref="ProjectsUnreadableException">The project is held back, or its record cannot be read or is not the index's.</exception>
private async Task<ProjectRecord> OwnRecordAsync(LeaseContext context, SequenceProject project, CancellationToken cancellationToken) =>
context.Reconcile.HeldBack.Contains(project.Id)
? throw new ProjectsUnreadableException($"Project {project.Id} cannot be read now.")
: await WritableRecordAsync(context.Folder, project, cancellationToken).ConfigureAwait(false);
private static ProjectRecord ReadOwnRecord(SequencePaths folder, Guid projectId)
{
@@ -308,6 +308,25 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Empty(host.Store.List());
}
[Test]
public async Task ACopyOfAProjectDeletedInTheLibraryReadsGoneAndGoesOnlyWhenDiscarded()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
Assert.Equal(WorkspaceState.InSync, (await host.StatusAsync(vertical)).State);
// Another PC deletes it in the library: never in step, and the copy goes only when its user discards it.
await bed.Archives.Projects.DeleteAsync(vertical, bed.Ct);
Assert.Equal(WorkspaceState.Gone, (await host.StatusAsync(vertical)).State);
Assert.True((await host.PlanRemovalAsync(vertical)).Gone);
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(vertical, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.DeletedAtHome"), refused.Message);
Assert.NotNull(host.Store.Find(vertical), "nothing was removed");
await host.RemoveLocalCopyAsync(vertical, discard: true);
Assert.Null(host.Store.Find(vertical));
}
[Test]
public async Task OlderVersionsArePrunedPastKeptVersionsOnlyOnceTheLibraryHoldsThem()
{
@@ -2,9 +2,11 @@ using System.Globalization;
using System.Text.Json.Nodes;
using Chronos.Core.Model;
using Chronos.Core.Project;
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.Testing;
namespace Chronos.Data.Tests.Projects;
@@ -162,6 +164,60 @@ public abstract class MainMergeTests(TestContext context) : DatabaseTest(context
Assert.SequenceEqual([3], settings.ExcludedFrames);
}
[Test]
public async Task AMergeACrashStopsBetweenItsTwoVersionsIsFinishedNextTime()
{
foreach (var rebuild in new[] { false, true })
{
var fx = await FixtureAsync();
var (sequence, frames) = await ProjectServiceTests.UploadedAsync(fx, 4);
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, ProjectServiceTests.Draft(first, new ProjectSettings
{
Stack = new StackSettings { Mode = StackSetting.Median },
Exposure = new ExposureSettings { ExposureOffsetEv = 0.5 },
}, frames), fx.Ct)).Version!;
var folder = fx.Paths.Sequence(sequence.Folder);
var record = ProjectSidecars.ReadRecord(folder.ProjectRecordPath(main.Id));
ProjectSidecars.WriteRecord(folder.ProjectRecordPath(main.Id), record with { Mirrored = new ProjectHead(first.Id, 1) });
// The push's mirror cut short, another path's settings meanwhile, and the catch-up's merge cut after its external version.
var reverted = await ProjectServiceTests.WriteSettingsAsync(fx, sequence.Id, new ProjectSettings());
await fx.Db.Projects.SetMirroredAsync(main.Id, first.Id, reverted.SettingsVersion, fx.Ct);
var theirs = new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 1.25 }, ExcludedFrames = [3] };
await ProjectServiceTests.WriteSettingsAsync(fx, sequence.Id, theirs);
File.WriteAllText(folder.ProjectPath, theirs.ToJson());
projects.Cut = step =>
{
if (step == "catchup.external") throw new CutException(step);
};
await Assert.ThrowsAsync<CutException>(() => projects.ListAsync(sequence.Id, fx.Ct));
projects.Cut = null;
Assert.SequenceEqual([ProjectVersionKind.External, ProjectVersionKind.Commit, ProjectVersionKind.Imported],
(await fx.Db.Projects.ListVersionsAsync(main.Id, null, 10, fx.Ct)).Select(v => v.Kind));
// The next catch-up (by this index, or by one rebuilt from the sidecars) makes the merge version: the push is in force.
if (rebuild)
{
await fx.ReopenWithEmptyIndexAsync();
await fx.ScanAsync(ScanMode.Rebuild);
}
var history = await fx.Service.Projects.HistoryAsync(main.Id, cancellationToken: fx.Ct);
Assert.SequenceEqual([ProjectVersionKind.Merge, ProjectVersionKind.External, ProjectVersionKind.Commit, ProjectVersionKind.Imported],
history.Select(v => v.Kind));
Assert.Equal((history[1].Id, pushed.Id), (history[0].ParentId, history[1].ParentId));
foreach (var settings in new[] { ProjectSettings.FromJson((await fx.Db.Sequences.GetAsync(sequence.Id))!.SettingsJson!),
ProjectSettings.FromJson(File.ReadAllText(folder.ProjectPath)) })
{
Assert.Equal((0.5, StackSetting.Median), (settings.Exposure.ExposureOffsetEv, settings.Stack.Mode));
Assert.SequenceEqual([3], settings.ExcludedFrames);
}
Assert.Count(4, await fx.Service.Projects.HistoryAsync(main.Id, cancellationToken: fx.Ct));
}
}
[Test]
public async Task ANewerChronosHeadOfMainIsNotMergedWithSettingsWrittenMeanwhile()
{
@@ -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)