fix(workspace): a cancelled copy clears only media no other copy writes; a deletion keeps late versions

Owner review 2, phase 5a, fix round 5.

- A cancelled workspace copy clears its partial media only under the project's
  lease, after checking again that the job is still cancelled, that no other
  copy of the same root and project is queued, running or paused, and that no
  copy in this process is writing. The engine now waits for a paused job's run
  to end before calling the cancel handler, so the clean-up is never skipped.
- The clean-up never recreates a project folder that was removed meanwhile
  (the lease no longer creates the folder). The next list removes a project
  folder that holds only lease files nobody holds, older than the lease.
- A Main this Chronos cannot read (newer or damaged) refuses the open at once
  only when nothing else can be offered. Otherwise Open in workspace lists it
  disabled, with the reason as its tooltip. The refusal's action tooltip is
  now Remove copy.
- The removal plan counts a conflict the same way the sync status does: a
  conflict that a settling replay took past its commit point is not work
  left.
- A healed record is stamped after both the record's time and the index's, so
  the next rename made elsewhere is taken.
- A trash folder holds back the rebuild of a lost record only when it is this
  sequence's deletion: its record names this sequence or cannot be read, or it
  has no record, is within a one-day grace and holds no version of another
  project. What was seen of folders that are gone or have a record again is
  forgotten.
- When a deletion wins, version files pushed into the live folder before the
  deletion arrived are moved beside the deleted record in the trash, never
  deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-03 15:10:44 +01:00
1 parent 93afe71639
commit 7692ab402e
16 files changed
+750 -61

No files matched your search

@@ -66,8 +66,9 @@ public static class WorkspaceJobs
/// job stops saying how much is missing (the workspace shares this PC's drive with the index and the logs).
/// Checkpoint: <c>copy:&lt;frame&gt;:&lt;frames version&gt;:&lt;folder&gt;</c>; a run resumed on other frames or in another folder
/// checks every file again, and a pass started again stores that before it reads anything. A first copy the user cancels
/// removes the media it wrote itself, once it has stopped writing and under the project's lease (<see cref="RemovePartialMediaAsync"/>);
/// one cancelled while paused or failed, which no handler runs, has them removed the same way (<see cref="CancelledAsync"/>).
/// removes the media it wrote itself, once it has stopped writing and under the project's lease, unless another copy of the
/// project goes on with them (<see cref="RemovePartialMediaAsync"/>); one cancelled while paused or failed, which no handler
/// runs, has them removed the same way (<see cref="CancelledAsync"/>).
/// Originals come in phase 5c: asked for, the job fails saying so.
/// </summary>
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives) : ICancelledJobHandler
@@ -110,7 +111,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
try
{
await CopyAsync(context, project, sequenceId, archive, parameters, ct).ConfigureAwait(false);
using (WritingMedia(project)) await CopyAsync(context, project, sequenceId, archive, parameters, ct).ConfigureAwait(false);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
@@ -158,27 +159,106 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
/// A first copy of the project's media the user cancelled (the job reads <see cref="JobState.Cancelled"/>), once it has
/// stopped writing: the photos it wrote (copies the home can make again) are removed under the project's lease, so the
/// workspace holds no half media. Media that a copy ever finished (<c>media.json</c>) stay, as do those of a copy paused,
/// yielded or stopped with the program, which goes on from its checkpoint. A failure is logged: the next copy checks
/// every file it finds.
/// yielded or stopped with the program, which goes on from its checkpoint, and those another copy of the project into
/// this workspace still writes or goes on with (queued, running or paused: <see cref="OtherCopyAsync"/>). The last
/// look is taken under the lease, and no copy of this program starts writing while the media go
/// (<see cref="WritingMedia"/>). A folder that is no project any more (its removal under way) is left as it is, and the
/// lease never makes it again. A failure is logged: the next copy checks every file it finds.
/// </summary>
private async Task RemovePartialMediaAsync(Job job, WorkspaceProject project)
{
try
{
if (await db.Jobs.GetAsync(job.Id, CancellationToken.None).ConfigureAwait(false) is not { State: JobState.Cancelled }) return;
// Nothing half written (or the copy removed meanwhile): the lease, which makes the folder, is not taken.
if (File.Exists(project.MediaIndexPath) || !Directory.Exists(project.MediaDirectory)) return;
using (await project.LockAsync(LockWait, CancellationToken.None).ConfigureAwait(false))
// Nothing half written (or the copy removed meanwhile): the lease is not taken.
if (!Clearable(project) || !await StillToClearAsync(job, project).ConfigureAwait(false)) return;
using (await project.LockExistingAsync(LockWait, CancellationToken.None).ConfigureAwait(false))
{
if (File.Exists(project.MediaIndexPath) || !Directory.Exists(project.MediaDirectory)) return;
Directory.Delete(project.MediaDirectory, recursive: true);
if (!Clearable(project) || !await StillToClearAsync(job, project).ConfigureAwait(false)) return;
lock (WritersGate)
{
// A copy of this program that started since the jobs were read: its files stay.
if (Writers.ContainsKey(project.Folder) || !Clearable(project)) return;
Directory.Delete(project.MediaDirectory, recursive: true);
}
}
Log.Info("workspace", $"The media a cancelled first copy of project {project.ProjectId} wrote were removed");
}
catch (DirectoryNotFoundException)
{
// The project's folder went meanwhile (its removal): nothing is left to clear.
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("workspace", $"The media of a cancelled copy of project {project.ProjectId} could not be removed", ex);
}
// A project (its working state there) with media no copy ever finished.
static bool Clearable(WorkspaceProject project) => project.Exists && !File.Exists(project.MediaIndexPath) && Directory.Exists(project.MediaDirectory);
}
/// <summary>The cancelled copy still reads so, and no other copy of the project into this workspace waits, runs or is paused.</summary>
private async Task<bool> StillToClearAsync(Job job, WorkspaceProject project)
{
if (await db.Jobs.GetAsync(job.Id, CancellationToken.None).ConfigureAwait(false) is not { State: JobState.Cancelled }) return false;
if (await OtherCopyAsync(job, project).ConfigureAwait(false) is not { } other) return true;
Log.Info("workspace", $"The media of cancelled copy {job.Id} stay: copy {other.Id} of project {project.ProjectId} is {other.State}");
return false;
}
/// <summary>
/// Another copy of the project into the same workspace that is queued, running or paused: it writes the media folder, or
/// goes on with what is there. A job whose parameters cannot be read counts, so nothing is removed on a guess.
/// </summary>
private async Task<Job?> OtherCopyAsync(Job job, WorkspaceProject project)
{
var sequenceId = job.TargetIds.FirstOrDefault();
foreach (var other in await db.Jobs.ListPendingAsync(JobKind.WorkspaceCopy, sequenceId, CancellationToken.None).ConfigureAwait(false))
{
if (other.Id == job.Id) continue;
try
{
var parameters = Parameters(other);
if (parameters.ProjectId != project.ProjectId) continue;
// Case aside: a match on a case-sensitive drive only keeps media that could have gone.
if (!string.Equals(WorkspaceStore.FullRoot(parameters.WorkspaceRoot), project.Store.Root, StringComparison.OrdinalIgnoreCase)) continue;
}
catch (Exception ex) when (ex is InvalidDataException or ArgumentException or IOException or NotSupportedException or System.Security.SecurityException)
{
Log.Debug("workspace", $"Copy {other.Id} cannot be read: it counts as one of project {project.ProjectId}: {ex.Message}");
}
return other;
}
return null;
}
/// <summary>The project folders copies of this program write media into now, with how many copies write each.</summary>
private static readonly Dictionary<string, int> Writers = new(StringComparer.OrdinalIgnoreCase);
private static readonly Lock WritersGate = new();
/// <summary>
/// Marks the copy into <paramref name="project"/> as writing its media until disposed: a clean-up after a cancelled copy
/// leaves them (<see cref="RemovePartialMediaAsync"/>), and one under way finishes before the copy writes anything.
/// </summary>
private static IDisposable WritingMedia(WorkspaceProject project)
{
lock (WritersGate) Writers[project.Folder] = Writers.GetValueOrDefault(project.Folder) + 1;
return new Writing(project.Folder);
}
private sealed class Writing(string folder) : IDisposable
{
private int _done;
public void Dispose()
{
if (Interlocked.Exchange(ref _done, 1) != 0) return;
lock (WritersGate)
{
if (Writers.GetValueOrDefault(folder) <= 1) Writers.Remove(folder);
else Writers[folder]--;
}
}
}
private async Task CopyAsync(JobContext context, WorkspaceProject project, Guid sequenceId, Archive archive, WorkspaceCopyParameters parameters,