fix(workspace): every cut of a sync is recoverable, renders name only versions the home holds

A push now moves the base before its local file reads as sent; a replay
journals itself in sync.json, writes the replayed versions, then the base
(the commit point), and only then sets the old ones aside and adopts the
local commits the home already held; a conflict met past such commits moves
the base onto them first. A save-both journals its copy and the ids it sends
under, so a retry completes the same copy instead of making another. The
next push, pull or resolve finishes or undoes whatever a cut left, so no
version is orphaned and no false conflict appears.

The editor reads the working state and the media index under the project
lease; workspace.json is written whole and moved into place (an empty one is
made again); project files may hold 64 MiB and one that would be larger is
refused before it is written, so large projects check out. The workspace copy
checks the drive's free space before and during the copy, keeps the folder in
its checkpoint and stores a reset when a pass starts again, and runs at High
level in the priority queue. Renders record a version only when the index
holds it with the settings rendered; an unsent version renders as the project.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-03 10:19:56 +01:00
1 parent 50e28fd63d
commit 833d7cf8e9
18 files changed
+950 -92

No files matched your search

+188 -28
View File
@@ -1,4 +1,5 @@
using System.Text.Json;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
@@ -84,6 +85,11 @@ public sealed class WorkspaceSyncException(PushOutcome outcome, string message)
/// travel in the portable form (<see cref="ProjectContent"/>), so frames inserted at the home never move a position. Every
/// operation holds the project's lease; nothing is ever deleted: a restore or save-both first saves uncommitted changes
/// as a version.
/// Every write sequence survives a cut at any step: the working state's base is the commit point. A push moves the base
/// before its local file reads as sent; a replay journals itself in <c>sync.json</c> (<see cref="WorkspaceReplay"/>), writes
/// the replayed versions, then the base, and only then sets the old ones aside; a save-both journals its copy and the ids
/// it sends under (<see cref="WorkspaceSaveBoth"/>). The next push, pull or resolve finishes or undoes what a cut left
/// (<see cref="SettleAsync"/>).
/// </summary>
public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
{
@@ -100,6 +106,11 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
/// <summary>How long an operation waits for the project's lease (another program working on it).</summary>
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
/// <summary>For tests: called with a step's name between the writes of a sync, where it may throw as a crash would.</summary>
internal Action<string>? Cut { get; init; }
private void Step(string name) => Cut?.Invoke(name);
/// <summary>
/// The project <paramref name="projectId"/> of <paramref name="home"/> brought into the workspace: its folder, the home's
/// head as the base and the working state (positions waiting for the media, which a
@@ -126,30 +137,41 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {projectId}.");
var head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
Verify(head);
project.WriteVersion(head, replace: true);
Directory.CreateDirectory(project.ExportsDirectory);
var bundle = new ProjectBundle(sequence.Archive, sequence.Sequence, ProjectSettings.FromJson(head.SettingsJson, allowNewer: true), DateTimeOffset.UtcNow)
{
Workspace = new BundleWorkspace(projectId, listed.Name, listed.IsMain, sequence.Home, Base(head), new BundleMedia(media, 0)),
};
// The working state first: one larger than a project file holds is refused before anything is written
// (ProjectTooLargeException), never left as a file no later open could read. Its base is fetched again if a cut
// comes before the version's own file.
project.WriteBundle(bundle);
project.WriteVersion(head, replace: true);
Directory.CreateDirectory(project.ExportsDirectory);
return project;
}
}
/// <summary>The working state for the editor: its settings placed on the media's frames, and the media's sequence.</summary>
/// <summary>
/// The working state for the editor: its settings placed on the media's frames, and the media's sequence. Both files are
/// read under the project's lease, as one state: a copy committing new media rewrites them in turn.
/// </summary>
/// <exception cref="InvalidOperationException">The project is not in the workspace.</exception>
public Task<WorkspaceSession> OpenAsync(Guid projectId, CancellationToken cancellationToken = default) =>
Task.Run(() =>
/// <exception cref="Core.Archiving.LeaseUnavailableException">Another writer kept the project for longer than <see cref="LockWait"/>.</exception>
public async Task<WorkspaceSession> OpenAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var project = Existing(projectId);
ProjectBundle bundle;
WorkspaceMedia? media;
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
(bundle, media) = await Task.Run(() => (project.ReadBundle(), project.ReadMedia()), cancellationToken).ConfigureAwait(false);
return await Task.Run(() =>
{
var project = Existing(projectId);
var bundle = project.ReadBundle();
var media = project.ReadMedia();
var working = bundle.Project;
if (media is not null && !working.IsNewerFormat)
working = ProjectSettings.FromJson(ProjectContent.Place(working.ToJson(), media.Photos), allowNewer: true);
return new WorkspaceSession(project, bundle, working, media, media is null ? null : SequenceOf(project, bundle, media));
}, cancellationToken);
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>Stores the working state (the editor's settings, positions on the media's frames); no version is made.</summary>
/// <exception cref="InvalidOperationException">The project is read-only (a newer Chronos's settings) or not in the workspace.</exception>
@@ -192,6 +214,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var project = Existing(projectId);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
var pushed = new List<ProjectVersion>();
var pulled = new List<ProjectVersion>();
for (var attempt = 0; attempt < PushAttempts; attempt++)
@@ -206,10 +229,13 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
{
case PushOutcome.Stored or PushOutcome.AlreadyStored when result.Version is { } stored:
Verify(stored);
if (stored.Number != local.Number) project.SetAside(local);
project.WriteVersion(stored, replace: true);
// The base moves first: cut after it, the local file still reads as unsent and the next sync
// adopts it; cut before it, the home answers "already stored" next time. Marked sent first, it
// would leave the chain from the old base and take the versions after it along.
bundle = WithBase(bundle, stored);
project.WriteBundle(bundle);
Step("push.base");
Adopt(project, local, stored);
pushed.Add(stored);
continue;
case PushOutcome.Diverged:
@@ -240,6 +266,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var project = Existing(projectId);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
IReadOnlyList<ProjectVersion> pulled = [];
if (project.ReadSync().Conflict is null)
{
@@ -267,6 +294,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var project = Existing(projectId);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
await SettleAsync(project, home, cancellationToken).ConfigureAwait(false);
var bundle = project.ReadBundle();
var sync = project.ReadSync();
if (sync.Conflict is null) return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), [], []);
@@ -328,15 +356,19 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
/// <summary>
/// Pulls the home's versions after the base and replays the local ones and the working state on its head. With
/// <paramref name="takeTheirs"/> null a conflict is recorded and nothing else moves (the versions pulled are kept as
/// files); with a choice the conflicts are settled by it.
/// files; the base only moves onto local commits the home already holds); with a choice the conflicts are settled by it.
/// Written in steps a cut can stop at any point (<see cref="WorkspaceReplay"/>): the journal, the replayed versions, the
/// base with the merged working state (the commit point), then the old versions set aside and the held ones adopted.
/// </summary>
private async Task<(ProjectBundle Bundle, WorkspaceConflict? Conflict, IReadOnlyList<ProjectVersion> Pulled)> ReplayAsync(WorkspaceProject project,
ProjectBundle bundle, IProjectHome home, IReadOnlySet<string>? takeTheirs, CancellationToken cancellationToken)
{
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
// Read before the home's versions are written over them: a local commit the home stored although its answer was lost
// comes back among them, and the commits after it were made on it.
// A local commit the home stored although its answer was lost comes back among the home's versions, and the commits
// after it were made on it. Its file keeps reading as unsent until the base has moved onto it or past it: written
// over now, it would leave the chain from the base, and the commits after it with it.
var locals = Unpushed(project, bundle);
var unsent = project.Versions().Where(v => v.StoredAt is null).Select(v => v.Id).ToHashSet();
var theirs = new List<ProjectVersion>();
for (var after = basis?.Number ?? 0; ;)
{
@@ -344,13 +376,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
foreach (var version in page)
{
Verify(version);
project.WriteVersion(version, replace: true);
if (!unsent.Contains(version.Id)) project.WriteVersion(version, replace: true);
}
theirs.AddRange(page);
if (page.Count < PullPage) break;
after = page[^1].Number;
}
if (theirs.Count == 0) return (bundle, null, theirs);
var held = theirs.Where(v => unsent.Contains(v.Id)).ToList();
var head = theirs[^1];
var atHome = theirs.Select(v => v.Id).ToHashSet();
var ours = locals.TakeWhile(v => atHome.Contains(v.Id)).ToList();
@@ -377,15 +410,28 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
if (differences.Count > 0 && takeTheirs is null)
{
var conflict = new WorkspaceConflict(head.Id, head.Number, basis?.Id ?? Guid.Empty, [.. locals.Select(v => v.Id)], differences, DateTimeOffset.UtcNow);
project.WriteSync(project.ReadSync() with { Conflict = conflict });
if (ours.Count > 0)
{
// The conflict is met past local commits the home holds: the base moves onto the last of them (their files
// adopted once it has), so the commits after them stay in the chain and the conflict is settled against it.
var onto = new WorkspaceReplay(basis!.Id, [], [], [.. held.Select(v => v.Id)]);
project.WriteSync(project.ReadSync() with { Replay = onto });
Step("replay.journal");
bundle = WithBase(bundle, basis);
project.WriteBundle(bundle);
Step("replay.base");
await FinishReplayAsync(project, onto, held, home, cancellationToken).ConfigureAwait(false);
}
project.WriteSync(project.ReadSync() with { Conflict = conflict, Replay = null });
return (bundle, conflict, theirs);
}
var parent = head;
var rebased = new List<ProjectVersion>(locals.Count);
ProjectVersion parent = head;
for (var i = 0; i < locals.Count; i++)
{
var local = locals[i];
var portable = ProjectContent.Canonical(replay.Commits[i].ToJson());
var rebased = local with
parent = local with
{
Id = Guid.CreateVersion7(),
ParentId = parent.Id,
@@ -396,48 +442,162 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
SettingsFormat = ProjectContent.FormatOf(portable),
StoredAt = null,
};
project.SetAside(local);
project.WriteVersion(rebased);
parent = rebased;
rebased.Add(parent);
}
var placed = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Canonical(merge.Merged.ToJson()), photos), allowNewer: true);
var moved = WithBase(bundle, head) with { Project = placed, Saved = DateTimeOffset.UtcNow };
var journal = new WorkspaceReplay(head.Id, [.. locals.Select(v => v.Id)], [.. rebased.Select(v => v.Id)], [.. held.Select(v => v.Id)]);
project.WriteSync(project.ReadSync() with { Replay = journal });
Step("replay.journal");
foreach (var version in rebased)
{
project.WriteVersion(version);
Step("replay.version");
}
// The commit point: before it the old chain hangs from the old base, after it the replayed one from the head.
project.WriteBundle(moved);
Step("replay.base");
await FinishReplayAsync(project, journal, held, home, cancellationToken).ConfigureAwait(false);
project.WriteSync(project.ReadSync() with { Replay = null });
return (moved, null, theirs);
}
/// <summary>Both sides kept: this workspace's versions to a new project at the home, this project onto the home's head.</summary>
/// <summary>
/// Finishes a replay whose base moved (<see cref="WorkspaceReplay.OntoBase"/>): each local version the home holds takes
/// its copy (from <paramref name="known"/>, a file of the workspace, else the home), the replaced ones are set aside.
/// </summary>
private static async Task FinishReplayAsync(WorkspaceProject project, WorkspaceReplay replay, IReadOnlyList<ProjectVersion> known, IProjectHome home,
CancellationToken cancellationToken)
{
foreach (var id in replay.Adopted)
{
var locals = project.Versions().Where(v => v.Id == id && v.StoredAt is null).ToList();
if (locals.Count == 0) continue;
if ((known.FirstOrDefault(v => v.Id == id) ?? await StoredCopyAsync(project, id, home, cancellationToken).ConfigureAwait(false)) is not { } stored) continue;
foreach (var local in locals) Adopt(project, local, stored);
}
foreach (var id in replay.Replaced) SetAsideUnsent(project, id);
}
/// <summary>
/// Finishes or undoes what a cut left (see the class remarks), before anything reads the chain: a replay's journal is
/// finished once the base is its target, else its replayed versions are set aside (the old chain still hangs from the
/// base); a save-both whose project moved onto the home's head sets its sent versions aside and clears its conflict; a
/// local file of the version the base names (a push cut after it moved the base) takes the home's copy.
/// </summary>
private static async Task SettleAsync(WorkspaceProject project, IProjectHome home, CancellationToken cancellationToken)
{
var sync = project.ReadSync();
var basis = project.ReadBundle().Workspace!.Base;
if (sync.Replay is { } replay)
{
if (basis?.VersionId == replay.OntoBase) await FinishReplayAsync(project, replay, [], home, cancellationToken).ConfigureAwait(false);
else foreach (var id in replay.Replayed) SetAsideUnsent(project, id);
sync = sync with { Replay = null };
project.WriteSync(sync);
Log.Info("workspace", $"A sync of project {project.ProjectId} cut short was {(basis?.VersionId == replay.OntoBase ? "finished" : "undone")}");
}
if (sync.SaveBoth is { } both && basis?.VersionId != both.FromBase)
{
foreach (var move in both.Moves) SetAsideUnsent(project, move.LocalId);
var settled = sync.Conflict is { } conflict && conflict.BaseVersionId == (both.FromBase ?? Guid.Empty);
sync = sync with { SaveBoth = null, Conflict = settled ? null : sync.Conflict };
project.WriteSync(sync);
Log.Info("workspace", $"A save-both of project {project.ProjectId} cut short was finished");
}
if (basis is not null && project.Versions().Where(v => v.Id == basis.VersionId && v.StoredAt is null).ToList() is { Count: > 0 } lingering
&& await StoredCopyAsync(project, basis.VersionId, home, cancellationToken).ConfigureAwait(false) is { } stored)
{
foreach (var local in lingering) Adopt(project, local, stored);
}
}
/// <summary>The home's copy of version <paramref name="id"/>: a file of the workspace marked sent, else asked from the home (kept as a file); null when the home has none.</summary>
private static async Task<ProjectVersion?> StoredCopyAsync(WorkspaceProject project, Guid id, IProjectHome home, CancellationToken cancellationToken)
{
if (project.Versions().FirstOrDefault(v => v.Id == id && v.StoredAt is not null) is { } file) return file;
if (await home.GetVersionAsync(project.ProjectId, id, cancellationToken).ConfigureAwait(false) is not { StoredAt: not null } fetched) return null;
Verify(fetched);
return fetched;
}
/// <summary>
/// The local file of a version the home holds takes the home's copy (sent, maybe under another number). Called only once
/// the base names the version or one after it: before, the copy would take it out of the chain of unsent versions.
/// </summary>
private static void Adopt(WorkspaceProject project, ProjectVersion local, ProjectVersion stored)
{
project.WriteVersion(stored, replace: true);
if (stored.Number != local.Number) project.SetAside(local);
}
/// <summary>Sets aside the unsent local files of version <paramref name="id"/>.</summary>
private static void SetAsideUnsent(WorkspaceProject project, Guid id)
{
foreach (var version in project.Versions().Where(v => v.Id == id && v.StoredAt is null)) project.SetAside(version);
}
/// <summary>
/// Both sides kept: this workspace's versions to a new project at the home, this project onto the home's head. The copy
/// and the ids its versions are sent under are journaled before the first is sent (<see cref="WorkspaceSaveBoth"/>): a
/// retry after a cut sends to the same copy what it lacks (the home answers "already stored" for the rest), whatever name
/// it is asked for, and the base moving onto the home's head is the commit point.
/// </summary>
private async Task<WorkspaceSyncResult> SaveBothAsync(WorkspaceProject project, ProjectBundle bundle, IProjectHome home, string? name, CancellationToken cancellationToken)
{
var workspace = bundle.Workspace!;
if (!bundle.IsReadOnly) CommitLocked(project, bundle, null, null);
bundle = project.ReadBundle();
var locals = Unpushed(project, bundle);
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
var sync = project.ReadSync();
var pending = sync.SaveBoth;
SequenceProject? copy = null;
if (pending is not null)
{
copy = (await home.ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(p => p.Id == pending.CopyId);
// A copy deleted at the home meanwhile: a new one is made.
if (copy is null) pending = null;
}
var pushed = new List<ProjectVersion>();
if (locals.Count > 0)
{
copy = await CreateNamedAsync(home, name, workspace.Name, basis?.Id, cancellationToken).ConfigureAwait(false);
var parent = await home.HeadAsync(copy.Id, cancellationToken).ConfigureAwait(false);
if (pending is null)
{
var basis = await BaseVersionAsync(project, bundle, home, cancellationToken).ConfigureAwait(false);
copy = await CreateNamedAsync(home, name, workspace.Name, basis?.Id, cancellationToken).ConfigureAwait(false);
var first = await home.HeadAsync(copy.Id, cancellationToken).ConfigureAwait(false);
pending = new WorkspaceSaveBoth(copy.Id, first.Id, first.Number, workspace.Base?.VersionId, []);
}
var known = pending.Moves.Select(m => m.LocalId).ToHashSet();
if (locals.Any(l => !known.Contains(l.Id)) || !ReferenceEquals(pending, sync.SaveBoth))
{
pending = pending with { Moves = [.. pending.Moves, .. locals.Where(l => !known.Contains(l.Id)).Select(l => new WorkspaceMove(l.Id, Guid.CreateVersion7()))] };
project.WriteSync(sync with { SaveBoth = pending });
}
Step("saveboth.journal");
var ids = pending.Moves.ToDictionary(m => m.LocalId, m => m.CopyVersionId);
var (parentId, parentNumber) = (pending.CopyBaseId, pending.CopyBaseNumber);
foreach (var local in locals)
{
var moved = local with { Id = Guid.CreateVersion7(), ProjectId = copy.Id, ParentId = parent.Id, Number = parent.Number + 1, StoredAt = null };
var moved = local with { Id = ids[local.Id], ProjectId = copy!.Id, ParentId = parentId, Number = parentNumber + 1, StoredAt = null };
var result = await home.PushAsync(copy.Id, moved, cancellationToken).ConfigureAwait(false);
if (result is not { Outcome: PushOutcome.Stored or PushOutcome.AlreadyStored, Version: { } stored })
throw new WorkspaceSyncException(result.Outcome, $"The home refused version {local.Number} saved as project '{copy.Name}': {result.Outcome}.");
pushed.Add(stored);
parent = stored;
(parentId, parentNumber) = (stored.Id, stored.Number);
Step("saveboth.pushed");
}
}
// This project takes the home's head: the local versions now live in the copy (and their files in versions/.replaced).
var head = await home.HeadAsync(project.ProjectId, cancellationToken).ConfigureAwait(false);
Verify(head);
project.WriteVersion(head, replace: true);
foreach (var local in locals) project.SetAside(local);
var media = project.ReadMedia();
var working = ProjectSettings.FromJson(ProjectContent.Place(head.SettingsJson, media?.Photos ?? NoFrames), allowNewer: true);
project.WriteBundle(WithBase(bundle, head) with { Project = working, Saved = DateTimeOffset.UtcNow });
Step("saveboth.base");
foreach (var local in locals) project.SetAside(local);
foreach (var move in pending?.Moves ?? []) SetAsideUnsent(project, move.LocalId);
project.WriteSync(WorkspaceSyncState.None);
return new WorkspaceSyncResult(await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false), pushed, [head], copy);
}