Files
Chronos/tests/Titano.Data.Tests/Archiving/SequenceTrashTests.cs
T
Claude 2b2d341497 fix(data): trash moves finish whatever is cancelled, archive-wide jobs hold their sequences
Once a folder has moved into the trash (or back), its index step runs to the
end with no cancellation and a failed step moves the folder back, so trash and
index never disagree. Running or paused archive-wide jobs (scan, rebuild,
import, maintenance, a verify of everything) block a delete of every sequence
of their archive; a verify of named sequences blocks those. A row whose folder
is gone is refused (FolderMissing) instead of losing its settings. Delete
revalidates the plan cheaply (index row, jobs, sidecar id from its head)
instead of measuring every folder again; the dry run reports progress. A
restored folder without a sidecar gets the record's title, tags, rating and
notes and drops a hero frame it no longer has. EditSequenceInfoAsync changes
one field from the current sidecar values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-05 22:06:31 +00:00

412 lines
20 KiB
C#

using Titano.Core.Archiving;
using Titano.Core.Model;
using Titano.Data.Archiving;
using Titano.Data.Tests.Infrastructure;
using Titano.Testing;
using static Titano.Data.Tests.Archiving.ArchiveFixture;
namespace Titano.Data.Tests.Archiving;
/// <summary>Deleting sequences into the archive's trash and restoring them (BRIEF §0.2 rule 8, §12.2, §12.5).</summary>
[Category("archive")]
public abstract class SequenceTrashTests(TestContext context) : DatabaseTest(context)
{
private async Task<ArchiveFixture> FixtureAsync() => Own(await CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true)));
/// <summary>Three scanned sequences in <c>inbox/a</c>, <c>inbox/b</c> and <c>inbox/c</c>, by folder.</summary>
private static async Task<List<Sequence>> PopulateAsync(ArchiveFixture fx)
{
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "a"), Start, 3);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "b"), Start.AddDays(1), 3, firstSeed: 10);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "c"), Start.AddDays(2), 3, firstSeed: 20);
await fx.ScanAsync();
var sequences = new List<Sequence>();
foreach (var location in (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).OrderBy(l => l.Folder))
sequences.Add((await fx.Db.Sequences.GetAsync(location.Id))!);
return sequences;
}
private static (int Files, long Bytes) OnDisk(string folder)
{
var files = new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories).ToList();
return (files.Count, files.Sum(f => f.Length));
}
/// <summary>One render of the sequence, stored in its exports folder.</summary>
private static async Task<Render> RenderAsync(ArchiveFixture fx, Sequence sequence)
{
var relative = sequence.Folder + "/exports/preview.mp4";
var path = fx.Paths.FromRelative(relative);
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
await File.WriteAllBytesAsync(path, new byte[1234]);
var render = new Render
{
Id = Guid.CreateVersion7(),
SequenceId = sequence.Id,
PresetName = "720p preview",
OutputPath = relative,
Codec = "h264",
Width = 1280,
Height = 720,
Fps = 30,
DurationSeconds = 2,
Bytes = 1234,
Created = new DateTimeOffset(2026, 10, 1, 9, 0, 0, TimeSpan.Zero),
};
await fx.Db.Renders.InsertAsync(render);
return render;
}
private static Job Running(JobKind kind, IReadOnlyList<Guid> targets, string? parameters = null) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
TargetIds = targets,
ParametersJson = parameters,
State = JobState.Running,
NodeId = "test#0",
Created = DateTimeOffset.UtcNow,
Started = DateTimeOffset.UtcNow,
};
/// <summary>Makes the next write of <paramref name="operation"/> on the sequences table fail, as a lost database connection would.</summary>
private async Task FailSequencesAsync(ArchiveFixture fx, string operation)
{
await using var session = await fx.Db.Database.OpenAsync(fx.Ct);
await session.ExecuteScriptAsync(ForDialect(
$"CREATE TRIGGER fail_{operation} BEFORE {operation} ON sequences BEGIN SELECT RAISE(ABORT, 'injected'); END;",
$"CREATE FUNCTION fail_{operation}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected'; END $$; " +
$"CREATE TRIGGER fail_{operation} BEFORE {operation} ON sequences FOR EACH ROW EXECUTE FUNCTION fail_{operation}();"), fx.Ct);
}
private async Task HealSequencesAsync(ArchiveFixture fx, string operation)
{
await using var session = await fx.Db.Database.OpenAsync(fx.Ct);
await session.ExecuteScriptAsync(ForDialect($"DROP TRIGGER fail_{operation};", $"DROP TRIGGER fail_{operation} ON sequences;"), fx.Ct);
}
/// <summary>Reports on the calling thread, so a test can act between two sequences.</summary>
private sealed class Inline(Action<int> report) : IProgress<int>
{
public void Report(int value) => report(value);
}
[Test]
public async Task TheDryRunCountsWhatMovesAndChangesNothing()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id);
var folder = fx.Paths.Sequence(sequences[0].Folder).Folder;
var plan = await fx.Service.PlanDeleteAsync([sequences[0].Id, sequences[1].Id], null, fx.Ct);
Assert.Empty(plan.Blocked);
Assert.Count(2, plan.Steps);
var (files, bytes) = OnDisk(folder);
Assert.Equal(files, plan.Steps[0].Files);
Assert.Equal(bytes, plan.Steps[0].Bytes);
Assert.Equal($".titano/trash/{sequences[0].Id:N}", plan.Steps[0].TrashFolder);
Assert.Equal(6, plan.Frames);
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Assert.True(Directory.Exists(folder), "a dry run moves nothing");
Assert.False(Directory.Exists(SequenceTrash.TrashDirectory(fx.Paths)));
}
[Test]
public async Task DeletingMovesTheWholeFolderToTheTrashAndDropsTheRows()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var victim = sequences[1];
await RenderAsync(fx, victim);
var folder = fx.Paths.Sequence(victim.Folder).Folder;
var (files, bytes) = OnDisk(folder);
var plan = await fx.Service.PlanDeleteAsync([victim.Id], null, fx.Ct);
var entries = await fx.Service.DeleteAsync(plan, "alberto", null, fx.Ct);
var entry = Assert.Contains(entries, e => e.SequenceId == victim.Id);
Assert.False(Directory.Exists(folder));
var trashed = Path.Combine(SequenceTrash.TrashDirectory(fx.Paths), entry.Name);
Assert.Equal((files, bytes), OnDisk(trashed));
Assert.Equal(victim.Id, ManifestStore.ReadSequence(fx.Paths.Sequence(fx.Paths.ToRelative(trashed)).ManifestPath).Id);
Assert.Null(await fx.Db.Sequences.GetAsync(victim.Id));
Assert.Empty(await fx.Db.Frames.ListBySequenceAsync(victim.Id));
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(victim.Id));
Assert.NotNull(await fx.Db.Sequences.GetAsync(sequences[0].Id));
var listed = Assert.Contains(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct), e => e.SequenceId == victim.Id);
Assert.Equal("inbox/b", listed.Folder);
Assert.Equal(3, listed.Frames);
Assert.Equal("alberto", listed.DeletedBy);
// The trash is hidden from scans: nothing comes back on its own.
var scan = await fx.ScanAsync(ScanMode.Full);
Assert.Equal(2, scan.Folders);
Assert.Null(await fx.Db.Sequences.GetAsync(victim.Id));
}
[Test]
public async Task RestoringBringsBackTheSameIndexRowsAndRenders()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var victim = sequences[0];
await fx.Db.Sequences.EditAsync(victim.Id, new Titano.Data.Repositories.SequenceEdit { SettingsJson = """{"exposure":{"deflickerWindow":{"isAuto":false,"manual":41}}}""" }, null);
var render = await RenderAsync(fx, victim);
var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id);
var settings = (await fx.Db.Sequences.GetAsync(victim.Id))!.SettingsJson;
var entry = (await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([victim.Id], null, fx.Ct), null, null, fx.Ct)).Single();
var restored = await fx.Service.RestoreAsync(fx.Archive.Id, entry.Name, fx.Ct);
Assert.Equal(victim.Folder, restored.Folder);
Assert.Equal(settings, restored.SettingsJson);
Assert.Equal(1, restored.RenderedCount);
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Assert.Equal(render.OutputPath, (await fx.Db.Renders.ListBySequenceAsync(victim.Id)).Single().OutputPath);
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
Assert.Empty(Directory.EnumerateFileSystemEntries(SequenceTrash.TrashDirectory(fx.Paths)));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
// Deleted again: the trash takes it again under the same name.
var again = (await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([victim.Id], null, fx.Ct), null, null, fx.Ct)).Single();
Assert.Equal(entry.Name, again.Name);
}
[Test]
public async Task ARestoreIntoATakenFolderUsesAFreeOneAndKeepsRendersReachable()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var victim = sequences[2];
await RenderAsync(fx, victim);
var entry = (await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([victim.Id], null, fx.Ct), null, null, fx.Ct)).Single();
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "c"), Start.AddDays(5), 2, firstSeed: 40);
await fx.ScanAsync();
var restored = await fx.Service.RestoreAsync(fx.Archive.Id, entry.Name, fx.Ct);
Assert.Equal("inbox/c (2)", restored.Folder);
var output = (await fx.Db.Renders.ListBySequenceAsync(victim.Id)).Single().OutputPath;
Assert.Equal("inbox/c (2)/exports/preview.mp4", output);
Assert.FileExists(fx.Paths.FromRelative(output));
foreach (var frame in await fx.Db.Frames.ListBySequenceAsync(victim.Id)) Assert.FileExists(fx.Paths.FromRelative(frame.RelativePath));
Assert.Count(4, await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id));
}
[Test]
public async Task AFolderThatLostItsSidecarComesBackUnderItsId()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var victim = await fx.Service.SetSequenceInfoAsync(sequences[1].Id, "Ridge", ["fog"], 4, "Tripod", fx.Ct);
var hero = (await fx.Db.Frames.ListBySequenceAsync(victim.Id)).Last().Id;
await fx.Db.Sequences.UpsertAsync(victim with { HeroFrameId = hero }, fx.Ct);
var entry = (await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([victim.Id], null, fx.Ct), null, null, fx.Ct)).Single();
var trashed = fx.Paths.Sequence(fx.Paths.ToRelative(Path.Combine(SequenceTrash.TrashDirectory(fx.Paths), entry.Name)));
File.Delete(trashed.ManifestPath);
var restored = await fx.Service.RestoreAsync(fx.Archive.Id, entry.Name, fx.Ct);
Assert.Equal(victim.Id, restored.Id);
Assert.Null(restored.HeroFrameId, "the frames were adopted with new ids");
var sidecar = ManifestStore.ReadSequence(fx.Paths.Sequence(victim.Folder).ManifestPath);
Assert.Equal(("Ridge", "fog", 4, "Tripod"), (sidecar.Title, sidecar.Tags.Single(), sidecar.Rating, sidecar.Notes));
Assert.Equal(("Ridge", 4), (restored.Title, restored.Rating));
Assert.Equal(victim.Folder, restored.Folder);
Assert.Equal(3, restored.FrameCount);
Assert.Count(3, await fx.Db.Frames.ListBySequenceAsync(victim.Id));
Assert.Equal(victim.Id, ManifestStore.ReadSequence(fx.Paths.Sequence(victim.Folder).ManifestPath).Id);
Assert.Equal(0, (await fx.ScanAsync()).Indexed, "the index and the new sidecar agree");
}
[Test]
public async Task SequencesThatCannotMoveAreBlockedAndUntouched()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
Photos.WriteSeries(Path.Combine(fx.Paths.Root, "inbox", "a", "night"), Start.AddDays(3), 2, firstSeed: 30);
await fx.ScanAsync();
await fx.Db.Jobs.EnqueueAsync(Running(JobKind.Proxies, [sequences[1].Id]));
// The folder of the third sequence now holds the sidecar of another sequence (copied over by hand).
File.Copy(fx.Paths.Sequence(sequences[0].Folder).ManifestPath, fx.Paths.Sequence(sequences[2].Folder).ManifestPath, overwrite: true);
var plan = await fx.Service.PlanDeleteAsync([.. sequences.Select(s => s.Id)], null, fx.Ct);
Assert.Empty(plan.Steps);
Assert.SequenceEqual([DeleteBlock.ContainsSequences, DeleteBlock.Busy, DeleteBlock.ForeignSidecar],
plan.Blocked.OrderBy(b => b.Sequence.Folder, StringComparer.Ordinal).Select(b => b.Reason));
}
[Test]
public async Task APhotoFolderAdoptedAtTheRootNeverMoves()
{
var root = Context.CreateTempDirectory("adopted");
Photos.WriteSeries(root, Start, 2);
var fx = Own(await CreateAsync(Context, root, await NewOptionsAsync(multiConnection: true)));
await fx.ScanAsync();
var location = (await fx.Db.Sequences.ListLocationsAsync(fx.Archive.Id)).Single();
Assert.Equal(string.Empty, location.Folder);
var plan = await fx.Service.PlanDeleteAsync([location.Id], null, fx.Ct);
Assert.Equal(DeleteBlock.ArchiveRoot, plan.Blocked.Single().Reason);
}
[Test]
public async Task AStalePlanIsRefusedBeforeAnythingMoves()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var plan = await fx.Service.PlanDeleteAsync([sequences[0].Id, sequences[1].Id], null, fx.Ct);
await fx.Service.ApplyRenameAsync(await fx.Service.PlanRenameAsync(fx.Archive.Id, [sequences[1].Id], "moved/{date}", null, fx.Ct), null, fx.Ct);
var stale = await Assert.ThrowsAsync<StaleDeletePlanException>(() => fx.Service.DeleteAsync(plan, null, null, fx.Ct));
Assert.Equal(sequences[1].Id, stale.SequenceId);
Assert.True(Directory.Exists(fx.Paths.Sequence(sequences[0].Folder).Folder));
Assert.NotNull(await fx.Db.Sequences.GetAsync(sequences[0].Id));
}
[Test]
public async Task ARowWhoseFolderIsMissingStaysForTheOrphansCheck()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
Directory.Delete(fx.Paths.Sequence(sequences[0].Folder).Folder, recursive: true);
var plan = await fx.Service.PlanDeleteAsync([sequences[0].Id], null, fx.Ct);
Assert.Empty(plan.Steps);
Assert.Equal(DeleteBlock.FolderMissing, plan.Blocked.Single().Reason);
Assert.NotNull(await fx.Db.Sequences.GetAsync(sequences[0].Id));
}
[Test]
public async Task ASequenceWithoutAFolderYetLosesOnlyItsRows()
{
var fx = await FixtureAsync();
var empty = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = fx.Archive.Id,
Title = "Waiting for photos",
Folder = string.Empty,
Origin = SequenceOrigin.Server,
SyncState = SyncState.InSync,
UpdatedAt = DateTimeOffset.UtcNow,
};
await fx.Db.Sequences.UpsertAsync(empty, fx.Ct);
var plan = await fx.Service.PlanDeleteAsync([empty.Id], null, fx.Ct);
Assert.Null(plan.Steps.Single().TrashFolder);
Assert.Empty(await fx.Service.DeleteAsync(plan, null, null, fx.Ct));
Assert.Null(await fx.Db.Sequences.GetAsync(empty.Id));
}
[Test]
public async Task JobsOnTheWholeArchiveHoldEverySequenceOfIt()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var ids = sequences.Select(s => s.Id).ToList();
// A verify of one named sequence holds only that one.
var verifyOne = Running(JobKind.Verify, [fx.Archive.Id], ArchiveJobs.Verify(fx.Archive, [sequences[2].Id]).ParametersJson);
await fx.Db.Jobs.EnqueueAsync(verifyOne);
var plan = await fx.Service.PlanDeleteAsync(ids, null, fx.Ct);
Assert.Equal(sequences[2].Id, plan.Blocked.Single(b => b.Reason == DeleteBlock.Busy).Sequence.Id);
Assert.Count(2, plan.Steps);
// An import (whose folders only its plan knows) holds the whole archive, and so does a paused one.
var import = Running(JobKind.Import, [fx.Archive.Id]) with { State = JobState.Paused };
await fx.Db.Jobs.EnqueueAsync(import);
plan = await fx.Service.PlanDeleteAsync(ids, null, fx.Ct);
Assert.Empty(plan.Steps);
Assert.True(plan.Blocked.All(b => b.Reason == DeleteBlock.Busy));
// A plan made before the job started is refused when it runs.
await fx.Db.Jobs.SetStateAsync(import.Id, JobState.Done, null, fx.Ct);
var before = await fx.Service.PlanDeleteAsync([sequences[0].Id], null, fx.Ct);
await fx.Db.Jobs.EnqueueAsync(Running(JobKind.Scan, [fx.Archive.Id]));
await Assert.ThrowsAsync<StaleDeletePlanException>(() => fx.Service.DeleteAsync(before, null, null, fx.Ct));
Assert.True(Directory.Exists(fx.Paths.Sequence(sequences[0].Folder).Folder));
}
[Test]
public async Task WhenTheIndexCannotLetGoTheFolderComesBack()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var victim = sequences[0];
var folder = fx.Paths.Sequence(victim.Folder).Folder;
var before = await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id);
var plan = await fx.Service.PlanDeleteAsync([victim.Id], null, fx.Ct);
await FailSequencesAsync(fx, "DELETE");
await Assert.ThrowsAsync<DatabaseException>(() => fx.Service.DeleteAsync(plan, null, null, fx.Ct));
Assert.True(Directory.Exists(folder), "the folder is back where it was");
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Assert.Empty(Directory.EnumerateFileSystemEntries(SequenceTrash.TrashDirectory(fx.Paths)));
await HealSequencesAsync(fx, "DELETE");
Assert.Count(1, await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([victim.Id], null, fx.Ct), null, null, fx.Ct));
}
[Test]
public async Task ARestoreThatCannotBeIndexedLeavesTheEntryInTheTrash()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var victim = sequences[1];
var entry = (await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([victim.Id], null, fx.Ct), null, null, fx.Ct)).Single();
await FailSequencesAsync(fx, "INSERT");
await Assert.ThrowsAsync<DatabaseException>(() => fx.Service.RestoreAsync(fx.Archive.Id, entry.Name, fx.Ct));
Assert.False(Directory.Exists(fx.Paths.Sequence(victim.Folder).Folder));
Assert.Null(await fx.Db.Sequences.GetAsync(victim.Id));
Assert.Equal(entry.Name, (await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct)).Single().Name);
await HealSequencesAsync(fx, "INSERT");
Assert.Equal(victim.Folder, (await fx.Service.RestoreAsync(fx.Archive.Id, entry.Name, fx.Ct)).Folder);
}
[Test]
public async Task CancellingStopsBetweenTwoWholeSequences()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var plan = await fx.Service.PlanDeleteAsync([sequences[0].Id, sequences[1].Id], null, fx.Ct);
using var cancel = CancellationTokenSource.CreateLinkedTokenSource(fx.Ct);
await Assert.ThrowsAsync<OperationCanceledException>(() => fx.Service.DeleteAsync(plan, null, new Inline(_ => cancel.Cancel()), cancel.Token));
Assert.Null(await fx.Db.Sequences.GetAsync(sequences[0].Id));
Assert.Count(1, await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
Assert.NotNull(await fx.Db.Sequences.GetAsync(sequences[1].Id));
Assert.True(Directory.Exists(fx.Paths.Sequence(sequences[1].Folder).Folder));
}
[Test]
public async Task ACancelledDryRunStopsAndReportsWhatItChecked()
{
var fx = await FixtureAsync();
var sequences = await PopulateAsync(fx);
var checkedCounts = new List<int>();
var plan = await fx.Service.PlanDeleteAsync([.. sequences.Select(s => s.Id)], new Inline(checkedCounts.Add), fx.Ct);
Assert.SequenceEqual([1, 2, 3], checkedCounts);
Assert.Count(3, plan.Steps);
using var cancel = CancellationTokenSource.CreateLinkedTokenSource(fx.Ct);
await Assert.ThrowsAsync<OperationCanceledException>(() =>
fx.Service.PlanDeleteAsync([.. sequences.Select(s => s.Id)], new Inline(_ => cancel.Cancel()), cancel.Token));
}
}
public sealed class SqliteSequenceTrashTests(TestContext context) : SequenceTrashTests(context)
{
protected override Backend Backend => Backend.SqliteFile;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresSequenceTrashTests(TestContext context) : SequenceTrashTests(context)
{
protected override Backend Backend => Backend.Postgres;
}