merge: review2-p5a-fix-merge into phase 5a fix round 1 integration

This commit is contained in:
Alby96 committed 2026-11-03 10:38:09 +01:00
commit 6542562428
12 files changed
+905 -38

No files matched your search

+39 -18
View File
@@ -22,6 +22,12 @@ public sealed record ProjectReplay(IReadOnlyList<ProjectSettings> Commits, IRead
public bool HasConflicts => Conflicts.Count > 0;
}
/// <summary>
/// A merge both sides of which changed met settings of a newer Chronos (<see cref="ProjectSettings.IsNewerFormat"/>): this
/// Chronos never merges them, as their known members may mean something else there (owner review 2, R8). Nothing was merged.
/// </summary>
public sealed class NewerSettingsException(string message) : InvalidOperationException(message);
/// <summary>
/// Three-way merge of projects: the editor's edit (<c>ours</c>) and a change stored meanwhile by someone else
/// (<c>theirs</c>: an analysis filling Auto values, another client through the server, another workspace through a
@@ -31,15 +37,24 @@ public sealed record ProjectReplay(IReadOnlyList<ProjectSettings> Commits, IRead
/// user instead (a server sequence, BRIEF §14.5; a workspace project, owner review 2, R8). Pending frames (frame
/// positions parked by photo, the portable form of <see cref="ProjectContent"/>) merge photo by photo and flag by flag, so
/// two people excluding different photos never conflict; two heroes chosen on both sides do (path <see cref="HeroPath"/>).
/// Members this Chronos does not know merge like the others and are kept.
/// Entries of one photo in one project (saved under two names, alike since) merge as one, keeping the positions of both.
/// Members this Chronos does not know merge like the others and are kept. Settings of a newer Chronos are never merged:
/// a side that did not change takes the other's as they are, anything else is refused (<see cref="NewerSettingsException"/>).
/// </summary>
public static class ProjectMerge
{
/// <summary>The path of the conflict of two heroes chosen among pending frames on both sides.</summary>
public const string HeroPath = "hero";
/// <summary>
/// The path of the settings format (<see cref="ProjectSettings.Version"/>): a difference there is settings of a newer
/// Chronos that this one cannot merge with its own (a workspace's conflict of format).
/// </summary>
public const string FormatPath = "version";
private const string PendingPath = "pendingFrames";
/// <exception cref="NewerSettingsException">Both sides changed, and one of the three is of a newer format.</exception>
public static ProjectSettings Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) =>
MergeWithConflicts(basis, ours, theirs).Merged;
@@ -48,6 +63,7 @@ public static class ProjectMerge
/// conflicts. A conflict whose path is in <paramref name="takeTheirs"/> takes theirs (the user chose "take server"
/// there), every other one ours.
/// </summary>
/// <exception cref="NewerSettingsException">Both sides changed, and one of the three is of a newer format.</exception>
public static ProjectMergeResult MergeWithConflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs, IReadOnlySet<string>? takeTheirs = null)
{
ArgumentNullException.ThrowIfNull(basis);
@@ -56,6 +72,14 @@ public static class ProjectMerge
var conflicts = new List<SettingsDifference>();
var choice = takeTheirs ?? EmptySet;
var (b, o, t) = (Keyed(basis), Keyed(ours), Keyed(theirs));
if (basis.IsNewerFormat || ours.IsNewerFormat || theirs.IsNewerFormat)
{
// Their known members may mean something else there: only a side that did not change gives way.
if (JsonNode.DeepEquals(o, b) || JsonNode.DeepEquals(t, o)) return new ProjectMergeResult(Read(theirs.ToJson()), []);
if (JsonNode.DeepEquals(t, b)) return new ProjectMergeResult(Read(ours.ToJson()), []);
throw new NewerSettingsException(string.Create(CultureInfo.InvariantCulture,
$"Settings of format {Math.Max(basis.Version, Math.Max(ours.Version, theirs.Version))} are not merged by this Chronos (format {ProjectSettings.CurrentVersion})."));
}
var merged = MergeNode(b, o, t, string.Empty, conflicts, choice) as JsonObject ?? new JsonObject();
OneHero(merged, o, t, conflicts, choice);
return new ProjectMergeResult(FromKeyed(merged), conflicts);
@@ -75,6 +99,7 @@ public static class ProjectMerge
/// history stays linear and the last one holds the net change. Conflicts are those of the last commit; their paths in
/// <paramref name="takeTheirs"/> take theirs in every commit.
/// </summary>
/// <exception cref="NewerSettingsException">A commit and theirs both changed, and one of them (or the basis) is of a newer format.</exception>
public static ProjectReplay Replay(ProjectSettings basis, IReadOnlyList<ProjectSettings> mine, ProjectSettings theirs, IReadOnlySet<string>? takeTheirs = null)
{
ArgumentNullException.ThrowIfNull(mine);
@@ -157,14 +182,22 @@ public static class ProjectMerge
private static string? HeroOf(JsonObject project) =>
project[PendingPath] is JsonObject pending ? pending.FirstOrDefault(p => p.Value is JsonObject entry && Flag(entry, "hero")).Key : null;
/// <summary>The project as JSON with its pending frames as an object keyed by photo (<see cref="KeyOf"/>).</summary>
/// <summary>
/// The project as JSON with its pending frames as an object keyed by photo (<see cref="KeyOf"/>); entries of one photo
/// (saved under two names, alike since) are one, with the positions of both (<see cref="ProjectContent.Fold"/>).
/// </summary>
private static JsonObject Keyed(ProjectSettings settings)
{
var project = JsonNode.Parse(settings.ToJson())!.AsObject();
if (project[PendingPath] is JsonArray pending)
{
var keyed = new JsonObject();
foreach (var entry in pending) keyed[KeyOf(entry)] = entry?.DeepClone();
foreach (var entry in pending)
{
var key = KeyOf(entry);
if (keyed[key] is JsonObject known && entry is JsonObject other) ProjectContent.Fold(known, other);
else keyed[key] = entry?.DeepClone();
}
project[PendingPath] = keyed;
}
return project;
@@ -188,22 +221,10 @@ public static class ProjectMerge
}
/// <summary>
/// The key of a pending entry: its photo and which copy of it ("sha:…#0", or "photo:size@ticks#0" for a photo not hashed),
/// or its JSON for an entry naming no photo.
/// The key of a pending entry: its photo and which copy of it (<see cref="ProjectContent.PhotoKey"/>: "sha:…#0", or
/// "photo:size@ticks#0" for a photo not hashed), or its JSON for an entry naming no photo.
/// </summary>
private static string KeyOf(JsonNode? entry)
{
if (entry is JsonObject e)
{
var occurrence = e["occurrence"] is JsonValue o && o.TryGetValue<int>(out var n) ? n : 0;
if (e["sha256"] is JsonValue s && s.TryGetValue<string>(out var sha) && sha.Length > 0)
return string.Create(CultureInfo.InvariantCulture, $"sha:{sha.ToLowerInvariant()}#{occurrence}");
var size = e["size"] is JsonValue z && z.TryGetValue<long>(out var bytes) ? bytes : 0;
if (e["capturedAt"] is JsonValue c && c.TryGetValue<DateTime>(out var at))
return string.Create(CultureInfo.InvariantCulture, $"photo:{size}@{at.Ticks}#{occurrence}");
}
return "raw:" + (entry?.ToJsonString() ?? "null");
}
private static string KeyOf(JsonNode? entry) => ProjectContent.PhotoKey(entry) ?? "raw:" + (entry?.ToJsonString() ?? "null");
/// <summary>The entry of the photo of <paramref name="template"/> holding no position; null for an entry naming no photo.</summary>
private static JsonNode? Unplaced(JsonNode? template)
+24 -4
View File
@@ -549,10 +549,30 @@ public sealed class ProjectService
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.
var merged = ProjectMerge.Merge(ProjectMerge.Read(ProjectContent.Rebind(mirrored.SettingsJson, frames.Photos)),
ProjectMerge.Read(ProjectContent.Rebind(head.SettingsJson, frames.Photos)), ProjectMerge.Read(ProjectContent.Rebind(current, frames.Photos)));
var version = await AppendDerivedAsync(context, main, head, ProjectContent.Canonical(merged.ToJson()), ProjectVersionKind.Merge, cancellationToken)
// 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.
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)));
}
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);
return;
}
var parent = head;
if (merged.HasConflicts)
{
parent = await AppendDerivedAsync(context, main, head, current, 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}");
}
var version = await AppendDerivedAsync(context, main, parent, ProjectContent.Canonical(merged.Merged.ToJson()), ProjectVersionKind.Merge, cancellationToken)
.ConfigureAwait(false);
main = (await _db.Projects.GetAsync(main.Id, cancellationToken).ConfigureAwait(false))!;
await MirrorAsync(context, main, version, cancellationToken).ConfigureAwait(false);
@@ -4,6 +4,7 @@ using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Processing;
using Chronos.Data.Projects;
namespace Chronos.Data.Workspaces;
@@ -104,6 +105,45 @@ public sealed record WorkspaceMedia(string Format, int FormatVersion, string Kin
/// <summary>The frames held, as the processing engine reads them.</summary>
public IReadOnlyList<Frame> ToFrames() => [.. Frames.Select(f => f.ToFrame(SequenceId))];
/// <summary>
/// These media with their photos named as <paramref name="home"/> names them now (owner review 2, R8): a frame copied
/// before the home hashed its photo (a folder adopted, verified since) takes the SHA-256 the home's frame of that id has
/// for the same photo (the same size and capture time; a conversion that gave the frame another file is not the same
/// photo), and the encodings the home's conversions joined since the copy are added to <see cref="Aliases"/>. Versions
/// the home made since name those photos so; named alike here, one photo merges as one. The frames, their files and the
/// frames version stay as they are. This instance when there is nothing to learn.
/// </summary>
public WorkspaceMedia NamedAsAt(HomeFrames home)
{
ArgumentNullException.ThrowIfNull(home);
var there = new Dictionary<Guid, Frame>(home.Frames.Count);
foreach (var frame in home.Frames) there[frame.Id] = frame;
var learned = false;
var frames = new List<WorkspaceFrame>(Frames.Count);
foreach (var frame in Frames)
{
if (string.IsNullOrEmpty(frame.Sha256) && there.TryGetValue(frame.Id, out var held) && !string.IsNullOrEmpty(held.Sha256)
&& held.Size == frame.Size && Millisecond(held.CapturedAt) == Millisecond(frame.CapturedAt))
{
frames.Add(frame with { Sha256 = held.Sha256.ToLowerInvariant() });
learned = true;
}
else
{
frames.Add(frame);
}
}
var known = Aliases ?? [];
var links = known.Select(Link).ToHashSet();
var added = home.Photos.Aliases.Where(a => links.Add(Link(a))).ToList();
if (!learned && added.Count == 0) return this;
return this with { Frames = learned ? frames : Frames, Aliases = added.Count > 0 ? [.. known, .. added] : Aliases };
static long? Millisecond(DateTime? time) => time is { } at ? at.Ticks / TimeSpan.TicksPerMillisecond : null;
// A media index read back may hold a damaged link: compared as it is, and left out of the classes like any other.
static (string?, string?) Link(PhotoAlias alias) => (alias.Sha256?.ToLowerInvariant(), alias.Replacement?.ToLowerInvariant());
}
}
/// <summary>
+10 -1
View File
@@ -27,7 +27,16 @@ public sealed record WorkspaceSyncState(Guid? RestoredFrom, WorkspaceConflict? C
/// taking the server's (each member or all), or saving both (<see cref="WorkspaceSync.ResolveAsync"/>).
/// </summary>
public sealed record WorkspaceConflict(Guid TheirsVersionId, int TheirsNumber, Guid BaseVersionId, IReadOnlyList<Guid> Mine,
IReadOnlyList<SettingsDifference> Differences, DateTimeOffset Found);
IReadOnlyList<SettingsDifference> Differences, DateTimeOffset Found)
{
/// <summary>
/// The home's head holds settings of a newer Chronos (a difference at <see cref="ProjectMerge.FormatPath"/>): nothing of
/// this workspace's is merged into them. Only Save both settles it (this workspace's versions go to a new project in this
/// Chronos's format), or a Chronos that reads them; keeping mine or taking the server's is refused.
/// </summary>
[JsonIgnore]
public bool NewerFormat => Differences.Any(d => d.Path == ProjectMerge.FormatPath);
}
/// <summary>
/// Parameters of a <see cref="JobKind.WorkspaceCopy"/> job: target = the home's sequence; the workspace folder, the
+59 -4
View File
@@ -1,3 +1,4 @@
using System.Globalization;
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Core.Project;
@@ -81,9 +82,12 @@ public sealed class WorkspaceSyncException(PushOutcome outcome, string message)
/// (<see cref="ProjectMerge.Replay"/>, new ids, the old files kept in <c>versions/.replaced</c>), and the working state is
/// merged too (<see cref="ProjectMerge.MergeWithConflicts"/>); settings both sides changed to different values stop
/// there as a conflict (<see cref="WorkspaceConflict"/>) for the user to settle (<see cref="ResolveAsync"/>). Versions
/// 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.
/// travel in the portable form (<see cref="ProjectContent"/>), so frames inserted at the home never move a position; before
/// a merge the media learn how the home names its photos now (hashed or converted there since the copy), so every side
/// names one photo alike. Settings of a newer Chronos are never merged with this one's: a project with nothing of its own
/// moves onto them read-only, any other waits on a conflict of format that only Save both settles
/// (<see cref="WorkspaceConflict.NewerFormat"/>). Every operation holds the project's lease; nothing is ever deleted: a
/// restore or save-both first saves uncommitted changes as a version.
/// </summary>
public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
{
@@ -357,8 +361,10 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
var tipVersion = locals.Count > 0 ? locals[^1] : basis;
if (ours.Count > 0) basis = theirs.First(v => v.Id == ours[^1].Id);
locals = [.. locals.Skip(ours.Count)];
var media = project.ReadMedia();
// The media first learn how the home names its photos now (hashed or converted there since the copy).
var media = await MediaNamedAsAtHomeAsync(project, home, cancellationToken).ConfigureAwait(false);
var photos = media?.Photos ?? NoFrames;
if (IsNewer(head) || IsNewer(basis)) return NewerAtHome(project, bundle, media, tipVersion, locals, basis, head, theirs, takeTheirs);
// Each side names a photo as the frames held it when it was saved: named as the media hold it now (a conversion or a
// hash since), the same photo merges as one.
var basisSettings = basis is null ? new ProjectSettings() : ProjectMerge.Read(ProjectContent.Rebind(basis.SettingsJson, photos));
@@ -406,6 +412,55 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName)
return (moved, null, theirs);
}
/// <summary>
/// The workspace's media with their photos named as the home names them now (<see cref="WorkspaceMedia.NamedAsAt"/>),
/// written back when the home taught them anything, so the versions, the working state and every comparison after this
/// one name each photo alike. Null while the workspace holds no media.
/// </summary>
private static async Task<WorkspaceMedia?> MediaNamedAsAtHomeAsync(WorkspaceProject project, IProjectHome home, CancellationToken cancellationToken)
{
if (project.ReadMedia() is not { } media) return null;
var named = media.NamedAsAt(await home.FramesAsync(cancellationToken).ConfigureAwait(false));
if (!ReferenceEquals(named, media)) project.WriteMedia(named);
return named;
}
private static bool IsNewer(ProjectVersion? version) => version is not null && ProjectContent.FormatOf(version.SettingsJson) > ProjectSettings.CurrentVersion;
/// <summary>
/// The home's head, or the base, holds settings of a newer Chronos: nothing is merged into or out of them, as their known
/// members may mean something else there. With nothing of this workspace's own (no version to send, the working state the
/// last version's), the project moves onto the head as it is, read-only when that is the newer one. Otherwise the local
/// versions and the working state stay as they are and a conflict of format waits (<see cref="WorkspaceConflict.NewerFormat"/>):
/// Save both sends them to a new project made from the base, in this Chronos's format. A choice to merge them
/// (<paramref name="takeTheirs"/> set: keep mine, take the server's) is refused, the conflict left recorded.
/// </summary>
/// <exception cref="WorkspaceSyncException">A choice to merge was made.</exception>
private static (ProjectBundle Bundle, WorkspaceConflict? Conflict, IReadOnlyList<ProjectVersion> Pulled) NewerAtHome(WorkspaceProject project,
ProjectBundle bundle, WorkspaceMedia? media, ProjectVersion? tipVersion, IReadOnlyList<ProjectVersion> locals, ProjectVersion? basis, ProjectVersion head,
IReadOnlyList<ProjectVersion> theirs, IReadOnlySet<string>? takeTheirs)
{
var photos = media?.Photos ?? NoFrames;
var tip = tipVersion?.SettingsJson ?? ProjectContent.ToPortable(new ProjectSettings(), photos);
if (locals.Count == 0 && (bundle.IsReadOnly
|| ProjectContent.SameChoices(tip, Portable(bundle.Project, media) ?? throw MediaMissing(project.ProjectId), photos)))
{
var placed = ProjectSettings.FromJson(ProjectContent.Place(head.SettingsJson, photos), allowNewer: true);
var moved = WithBase(bundle, head) with { Project = placed, Saved = DateTimeOffset.UtcNow };
project.WriteBundle(moved);
return (moved, null, theirs);
}
var newer = Math.Max(ProjectContent.FormatOf(head.SettingsJson), basis is null ? 0 : ProjectContent.FormatOf(basis.SettingsJson));
var format = new SettingsDifference(ProjectMerge.FormatPath, ProjectContent.FormatOf(tip).ToString(CultureInfo.InvariantCulture),
newer.ToString(CultureInfo.InvariantCulture));
var conflict = new WorkspaceConflict(head.Id, head.Number, basis?.Id ?? Guid.Empty, [.. locals.Select(v => v.Id)], [format], DateTimeOffset.UtcNow);
project.WriteSync(project.ReadSync() with { Conflict = conflict });
if (takeTheirs is not null)
throw new WorkspaceSyncException(PushOutcome.NewerFormat,
$"Version {head.Number} of project {project.ProjectId} holds settings of a newer Chronos: nothing of this workspace's is merged into it (save both, or update Chronos).");
return (bundle, conflict, theirs);
}
/// <summary>Both sides kept: this workspace's versions to a new project at the home, this project onto the home's head.</summary>
private async Task<WorkspaceSyncResult> SaveBothAsync(WorkspaceProject project, ProjectBundle bundle, IProjectHome home, string? name, CancellationToken cancellationToken)
{