Files
Chronos/src/Titano.Core/Archiving/IndexSnapshot.cs
T
Alby96andClaude Opus 5.5 43b6871cdc feat: jobs run one at a time, parallelism per photo and a priority queue
Owner review 1, phase 2 (docs/requests/2026-10-15-owner-review-1.md, R2).

Jobs now run one at a time on the desktop and on the server. Parallelism
(Settings > Rendering, TITANO_PARALLELISM) is how many photos the running
job processes at once: thumbnail and proxy passes draw that many photos
together and still write the pack and checkpoints in frame order, decode
tiers are probed that many at a time, the deep analysis measures that many
frames and a render decodes that many ahead. Wherever originals are
developed whole (TIFF, PNG, RAW without a usable preview), fewer run at
once within the memory budget, which the running job now has whole; the
server's frame window is sized to the host instead of 1 GiB.

A new job waits its turn and pausing the running job starts the next one.
An optional priority queue gives each job kind a level (renders, imports
and downloads high, verifies and proxies low by default): a queued job of
a higher level pauses the running one without asking, and that job goes
back to the queue with its checkpoint and resumes by itself afterwards.
Jobs of the same level, and a job's own follow-ups, never interrupt it.
The Jobs screen and the admin panel show the parallelism and the queue;
Settings > Rendering and the admin panel's Settings set them, at once.

TITANO_WORKERS and the Workers key of server.json still set the
parallelism (1 to 64, with a warning at start for the variable).
Titano.Tools gains i18n prune, which removed the renamed keys from the 36
machine-translated languages; the new strings are translated in all 38.

Found while testing: uploads and imports failed when a pass read the
sidecar while they wrote it (atomic writes now retry the rename while a
reader holds the file, and never for a read-only one), and taking a lease
just released while another process read it failed on Windows (the create
now waits for the reader). Five adversarial review rounds checked the
phase before this commit.

Also updates BRIEF (12.8, 14.6, 14.8, 14.9, 24), DECISIONS, CHANGELOG,
ARCHITECTURE, STATUS, the request file and the compose/Unraid templates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 14:56:24 +02:00

128 lines
5.3 KiB
C#

using System.Buffers.Binary;
using System.Security.Cryptography;
using System.Text;
using Titano.Core.IO;
namespace Titano.Core.Archiving;
/// <summary>
/// <c>.titano/index-snapshot.bin</c> (BRIEF §7): every sidecar of the archive in one file, so a rebuild reads one file
/// sequentially instead of thousands of small ones over a share. Optional and never authoritative: an entry is used
/// only when its sidecar still has the recorded size and time, and a file whose trailing SHA-256 does not match is
/// ignored entirely.
/// </summary>
/// <remarks>Layout: "TISN", version (u16), reserved (u16), then per sidecar: folder length (u16), UTF-8 folder,
/// size (i64), modified UTC ticks (i64), length (i32), sidecar bytes; finally the SHA-256 of everything before it.</remarks>
public sealed class IndexSnapshot
{
private const ushort Version = 1;
private static ReadOnlySpan<byte> Magic => "TISN"u8;
private readonly Dictionary<string, (FileStamp Stamp, byte[] Bytes)> _entries;
private IndexSnapshot(Dictionary<string, (FileStamp, byte[])> entries) => _entries = entries;
public int Count => _entries.Count;
/// <summary>The snapshot at <paramref name="path"/>, or null when it is absent, damaged or of another version.</summary>
public static IndexSnapshot? TryLoad(string path)
{
byte[] data;
try
{
if (!File.Exists(path)) return null;
data = AtomicFile.ReadAllBytes(path);
}
catch (IOException)
{
return null;
}
if (data.Length < 8 + 32 || !data.AsSpan(0, 4).SequenceEqual(Magic) || BinaryPrimitives.ReadUInt16LittleEndian(data.AsSpan(4)) != Version)
return null;
var body = data.AsSpan(0, data.Length - 32);
if (!SHA256.HashData(body).AsSpan().SequenceEqual(data.AsSpan(data.Length - 32))) return null;
var entries = new Dictionary<string, (FileStamp, byte[])>(StringComparer.Ordinal);
var position = 8;
while (position < body.Length)
{
if (position + 2 > body.Length) return null;
var folderLength = BinaryPrimitives.ReadUInt16LittleEndian(body[position..]);
position += 2;
if (position + folderLength + 20 > body.Length) return null;
var folder = Encoding.UTF8.GetString(body.Slice(position, folderLength));
position += folderLength;
var size = BinaryPrimitives.ReadInt64LittleEndian(body[position..]);
var ticks = BinaryPrimitives.ReadInt64LittleEndian(body[(position + 8)..]);
var length = BinaryPrimitives.ReadInt32LittleEndian(body[(position + 16)..]);
position += 20;
if (length < 0 || ticks < 0 || ticks > DateTime.MaxValue.Ticks || position + length > body.Length) return null;
entries[folder] = (new FileStamp(size, new DateTime(ticks, DateTimeKind.Utc)), body.Slice(position, length).ToArray());
position += length;
}
return new IndexSnapshot(entries);
}
/// <summary>The recorded sidecar bytes of <paramref name="folder"/> when its current stamp still matches.</summary>
public byte[]? TryGet(string folder, FileStamp current) =>
_entries.TryGetValue(folder, out var entry) && entry.Stamp == current ? entry.Bytes : null;
/// <summary>Streams a new snapshot to a temporary file; <see cref="Commit"/> replaces the old one atomically.</summary>
public sealed class Writer : IDisposable
{
private readonly string _path;
private readonly string _temp;
private readonly FileStream _stream;
private readonly IncrementalHash _hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
private bool _committed;
public Writer(string path)
{
_path = path;
_temp = AtomicFile.TempPathFor(path);
_stream = new FileStream(_temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16);
Span<byte> header = stackalloc byte[8];
header.Clear();
Magic.CopyTo(header);
BinaryPrimitives.WriteUInt16LittleEndian(header[4..], Version);
Write(header);
}
public void Add(string folder, FileStamp stamp, ReadOnlySpan<byte> sidecar)
{
var name = Encoding.UTF8.GetBytes(folder);
Span<byte> head = stackalloc byte[2];
BinaryPrimitives.WriteUInt16LittleEndian(head, checked((ushort)name.Length));
Write(head);
Write(name);
Span<byte> fields = stackalloc byte[20];
BinaryPrimitives.WriteInt64LittleEndian(fields, stamp.Size);
BinaryPrimitives.WriteInt64LittleEndian(fields[8..], stamp.ModifiedUtc.Ticks);
BinaryPrimitives.WriteInt32LittleEndian(fields[16..], sidecar.Length);
Write(fields);
Write(sidecar);
}
public void Commit()
{
_stream.Write(_hash.GetHashAndReset());
_stream.Dispose();
AtomicFile.Commit(_temp, _path);
_committed = true;
}
public void Dispose()
{
_stream.Dispose();
_hash.Dispose();
if (!_committed && File.Exists(_temp)) File.Delete(_temp);
}
private void Write(ReadOnlySpan<byte> data)
{
_hash.AppendData(data);
_stream.Write(data);
}
}
}