Files
Chronos/tests/Titano.Core.Tests/Archiving/ArchiveFolderTests.cs
T
Claude 0085765a12 fix(archive,analysis): an unreadable photo changes nothing; a report stale by proxies never replaces a current one
The orphans fix and scans treated a folder whose only new photo could not be
read yet (held open, no permission, an offline placeholder) as changed: the
sidecar was rewritten, the covering flags cleared and analyses queued again at
every click. SequenceAdopter.Reconcile now returns null when it indexed nothing
and changed no flag, as its contract says.

A deep pass counted as current by frames version alone, so a pass whose verdict
a proxy made stale overwrote the report a later pass made from the proxies,
then dropped the deep status. It now counts as current only when its report
describes the frames as they are, and otherwise replaces only a saved report
that does not describe them either.

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

202 lines
10 KiB
C#

using Titano.Core.Archiving;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Imaging;
using Titano.Core.Metadata;
using Titano.Core.Model;
using Titano.Testing;
namespace Titano.Core.Tests.Archiving;
[Category("archive")]
public sealed class ArchiveFolderTests(TestContext context)
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
private ArchivePaths NewArchive() => new(context.CreateTempDirectory("archive"));
[Test]
public void SequenceFoldersAreFoundInLayoutAndAdoptedForms()
{
var archive = NewArchive();
TestPhotos.WriteSeries(Path.Combine(archive.Root, "2026", "2026-09-28 Canon EOS R5", "originals"), Start, 3, TimeSpan.FromSeconds(10));
TestPhotos.WriteSeries(Path.Combine(archive.Root, "Trips", "Harbour"), Start, 2, TimeSpan.FromSeconds(10));
TestPhotos.WriteSeries(Path.Combine(archive.Root, "Trips", "Harbour", "selects"), Start, 1, TimeSpan.FromSeconds(10));
TestPhotos.WriteSeries(Path.Combine(archive.Root, ".hidden"), Start, 1, TimeSpan.FromSeconds(10));
File.WriteAllBytes(Path.Combine(archive.Root, "Trips", "._IMG_0001.JPG"), [1]);
Directory.CreateDirectory(Path.Combine(archive.Root, "empty"));
var folders = ArchiveScanner.FindSequenceFolders(archive);
Assert.SequenceEqual(["2026/2026-09-28 Canon EOS R5", "Trips/Harbour", "Trips/Harbour/selects"], folders.Select(f => f.RelativeFolder));
Assert.True(folders.All(f => f.Sidecar is null && f.Photos is not null));
Assert.SequenceEqual(["originals/IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0003.JPG"],
ArchiveScanner.ListPhotos(archive.Sequence("2026/2026-09-28 Canon EOS R5")));
}
[Test]
public void AdoptionBuildsASidecarInCaptureOrderWithoutTouchingPhotos()
{
var archive = NewArchive();
var folder = Path.Combine(archive.Root, "Harbour sunset");
// File names run against capture order: the sidecar follows capture time.
TestPhotos.Write(Path.Combine(folder, "a.jpg"), Start.AddSeconds(20), 1);
TestPhotos.Write(Path.Combine(folder, "b.jpg"), Start, 2);
TestPhotos.Write(Path.Combine(folder, "c.jpg"), Start.AddSeconds(10), 3);
var before = Directory.GetFiles(folder).ToDictionary(f => f, File.ReadAllBytes);
var manifest = SequenceAdopter.Build(Guid.CreateVersion7(), archive.Sequence("Harbour sunset"), "test");
Assert.SequenceEqual(["b.jpg", "c.jpg", "a.jpg"], manifest.Frames.Select(f => f.File));
Assert.SequenceEqual([0, 1, 2], manifest.Frames.Select(f => f.I));
Assert.Equal("Harbour sunset", manifest.Title);
Assert.Equal("Canon EOS R5", manifest.Camera!.Model);
Assert.True(manifest.Frames.All(f => f.Sha256 is null && f.Size > 0 && f.Format == ImageFileFormat.Jpeg && f.W == 48));
foreach (var (path, bytes) in before) Assert.BytesEqual(bytes, File.ReadAllBytes(path));
}
[Test]
public void ReconcileIndexesNewPhotosAndFlagsMissingOnes()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
var files = TestPhotos.WriteSeries(sequence.Originals, Start, 4, TimeSpan.FromSeconds(10));
var manifest = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null);
Assert.Null(SequenceAdopter.Reconcile(sequence, manifest));
File.Delete(files[1]);
TestPhotos.Write(Path.Combine(sequence.Originals, "IMG_0000.JPG"), Start.AddSeconds(-10), 9);
var orphans = SequenceAdopter.FindOrphans(sequence, manifest);
Assert.SequenceEqual(["originals/IMG_0000.JPG"], orphans.UnindexedFiles);
Assert.SequenceEqual(["originals/IMG_0002.JPG"], orphans.MissingFiles.Select(f => f.File));
var reconciled = SequenceAdopter.Reconcile(sequence, manifest)!;
Assert.SequenceEqual(["originals/IMG_0000.JPG", "originals/IMG_0001.JPG", "originals/IMG_0002.JPG", "originals/IMG_0003.JPG", "originals/IMG_0004.JPG"],
reconciled.Frames.Select(f => f.File));
Assert.Equal(FrameFlags.Missing, reconciled.Frames[2].Flags);
Assert.Equal(manifest.Frames[0].Id, reconciled.Frames[1].Id);
TestPhotos.Write(files[1], Start.AddSeconds(10), 2);
var restored = SequenceAdopter.Reconcile(sequence, reconciled)!;
Assert.Equal(FrameFlags.None, restored.Frames[2].Flags);
}
[Test]
public void APhotoThatCannotBeReadYetChangesNothing()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
TestPhotos.WriteSeries(sequence.Originals, Start, 3, TimeSpan.FromSeconds(10));
var manifest = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null);
var added = Path.Combine(sequence.Originals, "IMG_0009.JPG");
TestPhotos.Write(added, Start.AddSeconds(60), 9);
// Held open by another program (or without read permission): it stays unindexed, and the sidecar is as it was.
using (new FileStream(added, FileMode.Open, FileAccess.Read, FileShare.None))
{
Assert.SequenceEqual(["originals/IMG_0009.JPG"], SequenceAdopter.FindOrphans(sequence, manifest).UnindexedFiles);
Assert.Null(SequenceAdopter.Reconcile(sequence, manifest));
}
Assert.Equal(4, SequenceAdopter.Reconcile(sequence, manifest)!.Frames.Count);
}
[Test]
public async Task VerifyDetectsAFlippedByteAMissingFileAndAChangedFile()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
var files = TestPhotos.WriteSeries(sequence.Originals, Start, 4, TimeSpan.FromSeconds(10));
var adopted = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null);
var hashed = new List<SidecarFrame>();
foreach (var frame in adopted.Frames)
{
var check = await FrameVerifier.CheckAsync(sequence, frame);
Assert.Equal(FrameHealth.Hashed, check.Health);
hashed.Add(check.Updated);
}
var bytes = File.ReadAllBytes(files[0]);
bytes[bytes.Length / 2] ^= 0x01;
File.WriteAllBytes(files[0], bytes);
File.Delete(files[1]);
File.AppendAllText(files[2], "edit");
var health = new List<FrameHealth>();
foreach (var frame in hashed) health.Add((await FrameVerifier.CheckAsync(sequence, frame)).Health);
Assert.SequenceEqual([FrameHealth.Corrupt, FrameHealth.Missing, FrameHealth.Changed, FrameHealth.Ok], health);
var corrupt = await FrameVerifier.CheckAsync(sequence, hashed[0]);
Assert.Equal(FrameFlags.Corrupt, corrupt.Flags);
Assert.Equal(hashed[0].Sha256, corrupt.Updated.Sha256);
}
[Test]
public void TheIndexSnapshotIsUsedOnlyForUnchangedSidecars()
{
var archive = NewArchive();
Directory.CreateDirectory(archive.MetaDirectory);
var stampA = new FileStamp(10, new DateTime(2026, 9, 1, 0, 0, 0, DateTimeKind.Utc));
using (var writer = new IndexSnapshot.Writer(archive.SnapshotPath))
{
writer.Add("a", stampA, "{\"a\":1}"u8);
writer.Add("b/ç", new FileStamp(20, stampA.ModifiedUtc), "{\"b\":2}"u8);
writer.Commit();
}
var snapshot = IndexSnapshot.TryLoad(archive.SnapshotPath)!;
Assert.Equal(2, snapshot.Count);
Assert.BytesEqual("{\"a\":1}"u8, snapshot.TryGet("a", stampA));
Assert.Null(snapshot.TryGet("a", stampA with { Size = 11 }));
Assert.NotNull(snapshot.TryGet("b/ç", new FileStamp(20, stampA.ModifiedUtc)));
var bytes = File.ReadAllBytes(archive.SnapshotPath);
bytes[12] ^= 0x40;
File.WriteAllBytes(archive.SnapshotPath, bytes);
Assert.Null(IndexSnapshot.TryLoad(archive.SnapshotPath));
}
[Test]
public void RenamePlansAvoidTakenFoldersAndMoveIdempotently()
{
var archive = NewArchive();
Directory.CreateDirectory(Path.Combine(archive.Root, "2026", "old a"));
Directory.CreateDirectory(Path.Combine(archive.Root, "2026", "old b"));
Directory.CreateDirectory(Path.Combine(archive.Root, "2026", "2026-09-28 Sunset"));
var a = new RenameSubject(Guid.NewGuid(), "2026/old a", null, Start, "Canon", "Canon EOS R5", null);
var b = new RenameSubject(Guid.NewGuid(), "2026/old b", "Dawn", Start, "Canon", "Canon EOS R5", null);
var plan = RenamePlanner.Plan(Guid.NewGuid(), [a, b], "{year}/{date} {title}", "Sunset",
["2026/old a", "2026/old b"], f => Directory.Exists(archive.FromRelative(f)));
Assert.SequenceEqual(["2026/2026-09-28 Sunset (2)", "2026/2026-09-28 Sunset (3)"], plan.Steps.Select(s => s.ToFolder));
Assert.True(plan.Steps.All(s => s.ToTitle == "Sunset"));
Assert.Equal("Dawn", plan.Steps[1].FromTitle);
RenamePlanner.MoveFolder(archive, plan.Steps[0]);
RenamePlanner.MoveFolder(archive, plan.Steps[0]);
Assert.False(Directory.Exists(archive.FromRelative("2026/old a")));
Assert.True(Directory.Exists(archive.FromRelative("2026/2026-09-28 Sunset (2)")));
var titleOnly = RenamePlanner.Plan(Guid.NewGuid(), [b], null, "{title} morning", ["2026/old b"], _ => false);
Assert.Equal("2026/old b", titleOnly.Steps.Single().ToFolder);
Assert.Equal("Dawn morning", titleOnly.Steps.Single().ToTitle);
Assert.Empty(RenamePlanner.Plan(Guid.NewGuid(), [b], "2026/old b", null, ["2026/old b"], _ => true).Steps);
}
[Test]
public void ThumbnailsAndProxiesAreRenderedFromTheFrame()
{
var archive = NewArchive();
var sequence = archive.Sequence("s");
Directory.CreateDirectory(sequence.Originals);
File.WriteAllBytes(Path.Combine(sequence.Originals, "big.jpg"), TestPhotos.Jpeg(Start, 7, width: 640, height: 480, orientation: 6));
var frame = SequenceAdopter.Build(Guid.CreateVersion7(), sequence, null).Frames.Single();
var renderer = new FrameImageRenderer(new ImageDecoder([]));
var thumb = renderer.Thumbnail(sequence, frame)!;
Assert.Equal((240, 320), (thumb.Width, thumb.Height));
Assert.Equal(DecodeTier.Native, thumb.Tier);
Assert.Equal(240, JpegDecoder.ReadInfo(thumb.Jpeg).Width);
var proxy = renderer.Proxy(sequence, frame, new SidecarCamera { Make = "Canon", Model = "Canon EOS R5" }, new ProxyPolicy { LongEdge = 400 })!;
Assert.Equal((300, 400), (proxy.Width, proxy.Height));
var exif = MetadataReader.Read(new MemoryStream(proxy.Jpeg), "p.jpg");
Assert.Equal(Start, exif.CapturedAt);
Assert.Equal("Canon EOS R5", exif.Model);
Assert.Equal(1, exif.Orientation);
}
}