fix(server): key kept Reorganize plans on what they read, plan apart from the request

A kept dry run was keyed on a stamp of every sequence row of the archive,
updated_at and verified_at included, so any upload, ingest status write,
verify or tag edit anywhere invalidated it and the confirm planned the whole
selection again. The plan was also bound to the request, so a proxy cutting
the request off cancelled it and a retry started over.

- The stamp (SequenceRepository.GetStampAsync) now hashes only what the
  planner reads from the index: every row's id and folder (collisions and
  what a moving folder carries), the planned rows' title, first capture,
  camera, lens, photo count and frames version, and the titles of the rows
  inside a planned folder. With all, every row is planned.
- ReorganizePlanCache makes a plan on the thread pool with the host's
  stopping token, once per key for concurrent requests; a request cut off
  only stops waiting, and the same request again waits for the plan or
  takes it. Refusals and failures are still not kept.
- A kept plan is dropped by its own timer five minutes after it was made
  (and never used past that), instead of staying until the next request.
- The protocol and endpoint docs say that plan_changed answers changes the
  index has; one made on disk alone is found by the job, which fails and
  changes nothing. The Capacity doc no longer claims a step per sequence.
- Tests: what the stamp follows and ignores, a kept plan surviving an upload
  elsewhere and a verify, one plan for concurrent requests and after a
  cut-off, the timer, an all:true apply carrying a nested sequence beside a
  blocked-only one, the first sequence told before a pause. The
  no-archive-module job_unavailable test expected a folder the planner no
  longer plans without a sidecar; it now expects the unreadable step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 7e01a4f85fe4b880ddd98a481fc8591649cec254)
This commit is contained in:
Alby96 committed 2026-10-27 18:09:46 +01:00
1 parent 6e99a4b269
commit 37800b28ef
7 files changed
+328 -80

No files matched your search

@@ -428,21 +428,40 @@ public sealed class SequenceRepository
}
/// <summary>
/// A digest of the index rows of <paramref name="archiveId"/> (owner review 2, R7): another value once a sequence is
/// added or removed, or once a row changes in what a Reorganize plans from (folder, title, first capture, camera, lens,
/// frame count) or in what every write of it moves (its versions, verify time and time of change). A change made on
/// disk alone, which the index does not have yet, leaves it as it was.
/// A digest of what a Reorganize of <paramref name="sequenceIds"/> (null: every sequence) plans from in the index of
/// <paramref name="archiveId"/> (owner review 2, R7): every sequence of the archive and its folder, which decide the
/// folders that get " (2)" and what a moving folder carries; of the sequences planned, their title, first capture,
/// camera, lens, photo count and frames version; of the others inside their folders, the title. Another value once one
/// of these changes. Any other write (an upload into a sequence not planned, a verify, a status, tag or note change)
/// leaves it as it was, and so does a change made on disk alone, which the index does not have.
/// </summary>
public async Task<string> GetStampAsync(Guid archiveId, CancellationToken cancellationToken = default)
public async Task<string> GetStampAsync(Guid archiveId, IReadOnlyCollection<Guid>? sequenceIds, CancellationToken cancellationToken = default)
{
var rows = await _db.ListAsync(
"SELECT id, folder, title, first_capture, camera_make, camera_model, lens, frame_count, frames_version, settings_version, verified_at, updated_at " +
"FROM sequences WHERE archive_id = $1 ORDER BY id", [archiveId],
r => string.Create(CultureInfo.InvariantCulture,
$"{r.GetGuid(0):N}\u001f{r.GetString(1)}\u001f{r.GetStringOrNull(2)}\u001f{r.GetDateTimeOrNull(3):O}\u001f{r.GetStringOrNull(4)}\u001f" +
$"{r.GetStringOrNull(5)}\u001f{r.GetStringOrNull(6)}\u001f{r.GetInt32(7)}\u001f{r.GetInt32(8)}\u001f{r.GetInt32(9)}\u001f" +
$"{r.GetDateTimeOffsetOrNull(10):O}\u001f{r.GetDateTimeOffset(11):O}"), cancellationToken).ConfigureAwait(false);
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join('\n', rows))));
"SELECT id, folder, title, first_capture, camera_make, camera_model, lens, frame_count, frames_version FROM sequences WHERE archive_id = $1 ORDER BY id",
[archiveId], r => (Id: r.GetGuid(0), Folder: r.GetString(1), Title: r.GetStringOrNull(2), Read: string.Create(CultureInfo.InvariantCulture,
$"{r.GetStringOrNull(2)}\u001f{r.GetDateTimeOrNull(3):O}\u001f{r.GetStringOrNull(4)}\u001f{r.GetStringOrNull(5)}\u001f{r.GetStringOrNull(6)}\u001f" +
$"{r.GetInt32(7)}\u001f{r.GetInt32(8)}")), cancellationToken).ConfigureAwait(false);
var selected = sequenceIds?.ToHashSet();
var planned = new HashSet<string>(rows.Where(r => selected?.Contains(r.Id) != false && r.Folder.Length > 0).Select(r => r.Folder),
StringComparer.OrdinalIgnoreCase);
using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
foreach (var row in rows)
{
var read = selected?.Contains(row.Id) != false ? row.Read : Inside(row.Folder) ? row.Title : null;
hash.AppendData(Encoding.UTF8.GetBytes(string.Create(CultureInfo.InvariantCulture, $"{row.Id:N}\u001f{row.Folder}\u001e{read}\n")));
}
return Convert.ToHexStringLower(hash.GetHashAndReset());
// Whether a folder lies inside a planned sequence's folder (RenamePlanner.IsInside), checking each folder around it.
bool Inside(string folder)
{
for (var slash = folder.LastIndexOf('/'); slash > 0; slash = folder.LastIndexOf('/', slash - 1))
{
if (planned.Contains(folder[..slash])) return true;
}
return false;
}
}
/// <summary>
+5 -3
View File
@@ -86,9 +86,11 @@ public sealed record LibraryFacetsDto(IReadOnlyList<FacetDto> Years, IReadOnlyLi
/// <c>POST /api/v1/archive/reorganize</c> (owner review 2, R7; administrators of the archive): new folder, file and title
/// templates applied to sequences already in the archive, <see cref="SequenceIds"/> or every one with <see cref="All"/>
/// (exactly one of the two). A null template keeps that part; at least one is given, each valid as the archive settings'
/// templates are. <see cref="DryRun"/> answers the plan (<see cref="ReorganizePlanDto"/>) and changes nothing; the change
/// itself sends that plan's <see cref="Fingerprint"/> back (409 <c>plan_changed</c> when the archive changed since) and runs
/// as a <c>move</c> job (202).
/// templates are. <see cref="DryRun"/> answers the plan (<see cref="ReorganizePlanDto"/>) and changes nothing; the server
/// keeps it a few minutes, so the same dry run again (also after one cut off) is answered from it. The change itself sends
/// that plan's <see cref="Fingerprint"/> back and runs as a <c>move</c> job (202): 409 <c>plan_changed</c> when the index
/// changed since in what the plan reads; a change made on disk alone, which the index does not have yet, is found by the
/// job, which then fails and changes nothing.
/// </summary>
public sealed record ReorganizeRequest(IReadOnlyList<Guid>? SequenceIds, bool All, string? FolderTemplate, string? FileTemplate, string? TitleTemplate,
bool DryRun, string? Fingerprint = null);
+11 -6
View File
@@ -143,12 +143,15 @@ public static class ArchiveEndpoints
/// <c>archive_offline</c>. Audited; the job tells each sequence it changes as <c>sequenceChanged</c> (<c>reorganized</c>)
/// once that sequence's step is journaled (a step that failed half-way, when its retry completes it; a plan the server
/// completes as it starts, no one: no client is connected yet). Photos a sequence receives between the dry run and the
/// confirmation under the names the plan leaves them keep the fingerprint as it was. A dry run's plan is kept a few
/// minutes while the index stays as it was (<see cref="ReorganizePlanCache"/>): the same dry run again, and its
/// confirmation, take it instead of planning again.
/// confirmation under the names the plan leaves them keep the fingerprint as it was. A dry run's plan is made apart from
/// the request, until the server stops, and kept a few minutes while what it reads from the index stays as it was
/// (<see cref="ReorganizePlanCache"/>): the same dry run again (also after the first was cut off), and its confirmation,
/// take it instead of planning again. So <c>plan_changed</c> answers a change the index has; one made on disk alone since
/// the dry run (a folder made by hand, a desktop writing to a shared archive before a scan) is found by the job, which
/// then fails and changes nothing.
/// </summary>
private static async Task<IResult> ReorganizeAsync(HttpContext context, Caller caller, ReorganizeRequest request, ChronosDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, ReorganizePlanCache plans)
[FromServices] ArchiveService? archives, JobEngineHost host, AuditLog audit, ReorganizePlanCache plans, IHostApplicationLifetime lifetime)
{
var ct = context.RequestAborted;
if (request.All == (request.SequenceIds is not null) || request.SequenceIds is { Count: 0 or > LibraryEndpoints.MaxBulkIds })
@@ -161,11 +164,13 @@ public static class ArchiveEndpoints
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
var sequences = request.All ? null : request.SequenceIds;
// Stamped before planning: a change committed while the plan is made gives the next request another key.
var key = ReorganizePlanCache.Key.Of(archive.Id, await db.Sequences.GetStampAsync(archive.Id, ct), sequences, templates);
var key = ReorganizePlanCache.Key.Of(archive.Id, await db.Sequences.GetStampAsync(archive.Id, sequences, ct), sequences, templates);
RenamePlan plan;
try
{
plan = await plans.GetOrPlanAsync(key, () => LibraryEndpoints.Engine(archives, db).PlanReorganizeAsync(archive.Id, sequences, templates, ct));
// Made until the server stops, whatever becomes of this request: the same request again takes it.
var stopping = lifetime.ApplicationStopping;
plan = await plans.GetOrPlanAsync(key, () => LibraryEndpoints.Engine(archives, db).PlanReorganizeAsync(archive.Id, sequences, templates, stopping), ct);
}
catch (NestedRenameException ex)
{
+104 -27
View File
@@ -6,25 +6,31 @@ namespace Chronos.Server.Api;
/// <summary>
/// Reorganize's dry runs kept a short while (owner review 2, R7): the same dry run asked again, and the confirmation that
/// follows it, take the plan made then instead of reading every sidecar and photo folder of the selection again (with
/// <c>all</c>, of the whole archive), while the archive's index is as it was then
/// (<see cref="SequenceRepository.GetStampAsync"/>) and for at most <see cref="Lifetime"/>. A change made on disk alone,
/// which the index does not have, is not seen by a kept plan: the <c>move</c> job plans again and refuses a plan that no
/// longer matches the archive, so nothing changes that the dry run did not show.
/// <c>all</c>, of the whole archive), while what the plan reads from the index is as it was then
/// (<see cref="SequenceRepository.GetStampAsync"/>) and for at most <see cref="Lifetime"/> once made. A plan is made apart
/// from the request that asked for it (until the server stops), once for every request of the same key: a request cut off
/// meanwhile (a proxy's timeout) leaves it to be made, and the same request again waits for it or takes it. A change made
/// on disk alone, which the index does not have, is not seen by a kept plan: the <c>move</c> job plans again and refuses a
/// plan that no longer matches the archive, so nothing changes that the dry run did not show.
/// </summary>
public sealed class ReorganizePlanCache(TimeProvider time)
public sealed class ReorganizePlanCache(TimeProvider time) : IDisposable
{
/// <summary>How long a plan is kept, from when its planning started.</summary>
/// <summary>How long a plan is kept once made; then its timer lets it go.</summary>
public static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(5);
/// <summary>Plans kept at most (a plan of every sequence holds one step per sequence); the oldest goes first.</summary>
/// <summary>
/// Plans kept or being made at most (each holds a step for every sequence it changes or carries, or whose photos keep
/// their names); the oldest made goes first, then the oldest being made, which is still answered but not kept.
/// </summary>
public const int Capacity = 8;
private readonly Lock _gate = new();
private readonly Dictionary<Key, (RenamePlan Plan, DateTimeOffset Started)> _plans = [];
private readonly Dictionary<Key, Entry> _plans = [];
private long _order;
/// <summary>
/// What a plan is kept by: the archive, the stamp of its index, the sequences (all of them, or the ids in the order
/// given, which decides the folder that gets " (2)") and the templates.
/// What a plan is kept by: the archive, the stamp of what it reads from the index, the sequences (all of them, or the ids
/// in the order given, which decides the folder that gets " (2)") and the templates.
/// </summary>
public readonly record struct Key(Guid ArchiveId, string Stamp, string Sequences, RenameTemplates Templates)
{
@@ -33,37 +39,108 @@ public sealed class ReorganizePlanCache(TimeProvider time)
new(archiveId, stamp, sequenceIds is null ? "*" : string.Join(',', sequenceIds.Select(id => id.ToString("N"))), templates);
}
/// <summary>Plans kept or being made now.</summary>
internal int Count
{
get
{
lock (_gate) return _plans.Count;
}
}
/// <summary>
/// The plan kept for <paramref name="key"/>, or the one <paramref name="plan"/> makes now, then kept; a refusal
/// (<paramref name="plan"/> throws) is not kept.
/// The plan kept for <paramref name="key"/>, the one being made for it, or the one <paramref name="plan"/> starts making
/// now, apart from the caller, then kept. A refusal (<paramref name="plan"/> throws) is passed to every caller waiting for
/// it and not kept. <paramref name="cancellationToken"/> stops the wait only: the plan is still made, and kept.
/// </summary>
public async Task<RenamePlan> GetOrPlanAsync(Key key, Func<Task<RenamePlan>> plan)
public Task<RenamePlan> GetOrPlanAsync(Key key, Func<Task<RenamePlan>> plan, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
DateTimeOffset started;
Entry? entry;
bool start;
lock (_gate)
{
started = time.GetUtcNow();
Expire(started);
if (_plans.TryGetValue(key, out var kept)) return kept.Plan;
// Never past its lifetime, whatever its timer.
if (_plans.TryGetValue(key, out entry) && entry.Made is { } made && time.GetUtcNow() - made >= Lifetime) Remove(key);
start = !_plans.TryGetValue(key, out entry);
if (start)
{
if (_plans.Count >= Capacity) Remove(_plans.MinBy(p => (p.Value.Made is null, p.Value.Order)).Key);
entry = new Entry(++_order);
_plans[key] = entry;
}
}
var made = await plan().ConfigureAwait(false);
lock (_gate)
{
if (!_plans.ContainsKey(key) && _plans.Count >= Capacity) _plans.Remove(_plans.MinBy(p => p.Value.Started).Key);
_plans[key] = (made, started);
}
return made;
if (start) _ = MakeAsync(key, entry!, plan);
return entry!.Plan.Task.WaitAsync(cancellationToken);
}
/// <summary>Forgets the plan kept for <paramref name="key"/>: its job is queued, and what the job changes gives the index another stamp.</summary>
public void Forget(Key key)
{
lock (_gate) _plans.Remove(key);
lock (_gate) Remove(key);
}
private void Expire(DateTimeOffset now)
public void Dispose()
{
foreach (var key in _plans.Where(p => now - p.Value.Started >= Lifetime).Select(p => p.Key).ToList()) _plans.Remove(key);
lock (_gate)
{
foreach (var key in _plans.Keys.ToList()) Remove(key);
}
}
private async Task MakeAsync(Key key, Entry entry, Func<Task<RenamePlan>> plan)
{
RenamePlan made;
try
{
made = await Task.Run(plan).ConfigureAwait(false);
}
catch (Exception ex)
{
// A refusal, a failure, or the server stopping: the next request plans again.
lock (_gate)
{
if (_plans.GetValueOrDefault(key) == entry) Remove(key);
}
if (ex is OperationCanceledException canceled) entry.Plan.SetCanceled(canceled.CancellationToken);
else entry.Plan.SetException(ex);
// Observed here: a request cut off before it ended no longer waits for it.
_ = entry.Plan.Task.Exception;
return;
}
lock (_gate)
{
if (_plans.GetValueOrDefault(key) == entry)
{
entry.Made = time.GetUtcNow();
entry.Expiry = time.CreateTimer(_ => Expire(key, entry), null, Lifetime, Timeout.InfiniteTimeSpan);
}
}
entry.Plan.SetResult(made);
}
private void Expire(Key key, Entry entry)
{
lock (_gate)
{
if (_plans.GetValueOrDefault(key) == entry) Remove(key);
}
}
private void Remove(Key key)
{
if (_plans.Remove(key, out var entry)) entry.Expiry?.Dispose();
}
/// <summary>A plan being made (<see cref="Made"/> null) or kept, and the order it was asked in.</summary>
private sealed class Entry(long order)
{
public long Order { get; } = order;
public TaskCompletionSource<RenamePlan> Plan { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public DateTimeOffset? Made { get; set; }
public ITimer? Expiry { get; set; }
}
}