fix(data): close concurrency and cleanup gaps found in review

- SQLite restore holds every pool slot instead of the write lock first,
  removing a lock-order deadlock with sessions that begin to write.
- PostgreSQL sessions always return their connection on dispose, a
  rollback while disposing never masks the original exception, and a
  busy session keeps its transaction until it is discarded.
- The pool disposes a connection whose health check the caller cancels.
- Listener commands keep their lock until the server answers and never
  tear a write with the caller's token; closing and pending no longer race.
- Tag replacement locks the sequence and the tag row; unused-tag cleanup
  locks candidates and re-checks them with a fresh snapshot; render
  counts and stats refreshes lock the sequence row on PostgreSQL.
- Sequence upserts keep rendered_count, which renders maintain.
- AuthenticationOk after an unfinished SCRAM exchange is rejected.
- Oversized read buffers are released; failed backups leave no .tmp;
  a zero idle lifetime is rejected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 10:27:19 +00:00
1 parent 8d9b04c713
commit fb42423346
17 files changed
+240 -61

No files matched your search

@@ -87,13 +87,14 @@ public sealed class SequenceRepository
"s.frame_count, s.median_interval, s.total_bytes, s.status, s.rendered_count, s.verified_at, s.hero_frame_id, s.rating, s.notes, " +
"s.settings_json, s.analysis_json, s.origin, s.sync_state, s.settings_version, s.frames_version, s.owner_user_id, s.warning_count, s.updated_at";
/// <summary>rendered_count is owned by <see cref="RenderRepository"/> once the row exists.</summary>
private static readonly string UpsertSql = SqlDialect.Upsert("sequences",
[
"id", "archive_id", "title", "title_key", "search_text", "folder", "camera_make", "camera_model", "camera_serial", "lens",
"first_capture", "last_capture", "frame_count", "median_interval", "total_bytes", "status", "rendered_count", "verified_at",
"hero_frame_id", "rating", "notes", "settings_json", "analysis_json", "origin", "sync_state", "settings_version",
"frames_version", "owner_user_id", "warning_count", "updated_at",
], 1);
], 1, ["rendered_count"]);
/// <summary>Ordinal of the tag list after <see cref="Columns"/>, and of the sort key a listing appends after it.</summary>
private const int TagsOrdinal = 28;
@@ -112,7 +113,11 @@ public sealed class SequenceRepository
$"SELECT {Columns}, (SELECT {_db.Sql.StringAgg("t.name")} FROM sequence_tags st JOIN tags t ON t.id = st.tag_id " +
$"WHERE st.sequence_id = s.id) AS tags{extraColumns} FROM sequences s";
/// <summary>Inserts or replaces the sequence row and its tag set.</summary>
/// <summary>
/// Inserts the sequence, or replaces every stored field and the tag set with the record's (last writer wins);
/// only <see cref="Sequence.RenderedCount"/> of an existing row is kept, as renders maintain it. For concurrent
/// partial changes use <see cref="SetTagsAsync"/>, <see cref="UpdateStatusAsync"/> or <see cref="RefreshStatsAsync"/>.
/// </summary>
public Task UpsertAsync(Sequence sequence, CancellationToken cancellationToken = default) =>
_db.InTransactionAsync(async session =>
{
@@ -132,8 +137,7 @@ public sealed class SequenceRepository
public async Task<bool> SetTagsAsync(Guid id, IEnumerable<string> tags, CancellationToken cancellationToken = default) =>
await _db.InTransactionAsync(async session =>
{
if (await session.ScalarAsync<Guid?>("SELECT id FROM sequences WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) is null)
return false;
if (!await LockAsync(session, id, cancellationToken).ConfigureAwait(false)) return false;
await ReplaceTagsAsync(session, id, tags, cancellationToken).ConfigureAwait(false);
await session.ExecuteAsync("UPDATE sequences SET settings_version = settings_version + 1, updated_at = $2 WHERE id = $1",
[id, DateTimeOffset.UtcNow], cancellationToken).ConfigureAwait(false);
@@ -149,7 +153,8 @@ public sealed class SequenceRepository
public Task<Sequence?> RefreshStatsAsync(Guid id, CancellationToken cancellationToken = default) =>
_db.InTransactionAsync(async session =>
{
var current = await session.QuerySingleOrDefaultAsync($"{_select} WHERE s.id = $1", [id], Map, cancellationToken).ConfigureAwait(false);
var current = await session.QuerySingleOrDefaultAsync($"{_select} WHERE s.id = $1{_db.Sql.ForUpdate}", [id], Map, cancellationToken)
.ConfigureAwait(false);
if (current is null) return null;
var stats = await session.QuerySingleAsync(
"SELECT count(*), COALESCE(SUM(size), 0), MIN(captured_at), MAX(captured_at) FROM frames WHERE sequence_id = $1",
@@ -312,16 +317,37 @@ public sealed class SequenceRepository
], cancellationToken);
}
private static async Task ReplaceTagsAsync(IDbSession session, Guid sequenceId, IEnumerable<string> tags, CancellationToken cancellationToken)
/// <summary>
/// Row-locks a sequence for a read-modify-write (PostgreSQL; SQLite's write lock already serialises writers).
/// False when it does not exist.
/// </summary>
internal static async Task<bool> LockAsync(IDbSession session, Guid id, CancellationToken cancellationToken) =>
await session.ScalarAsync<Guid?>($"SELECT id FROM sequences WHERE id = $1{SqlDialect.For(session.Dialect).ForUpdate}", [id], cancellationToken)
.ConfigureAwait(false) is not null;
/// <summary>Replaces the tag links of a sequence whose row the caller has locked (or just upserted).</summary>
private async Task ReplaceTagsAsync(IDbSession session, Guid sequenceId, IEnumerable<string> tags, CancellationToken cancellationToken)
{
await session.ExecuteAsync("DELETE FROM sequence_tags WHERE sequence_id = $1", [sequenceId], cancellationToken).ConfigureAwait(false);
foreach (var tag in TagRepository.NormalizeSet(tags))
{
var key = TagRepository.Key(tag);
await session.ExecuteAsync("INSERT INTO tags (id, name, name_key) VALUES ($1, $2, $3) ON CONFLICT (name_key) DO NOTHING",
[Guid.CreateVersion7(), tag, key], cancellationToken).ConfigureAwait(false);
await session.ExecuteAsync("INSERT INTO sequence_tags (sequence_id, tag_id) SELECT $1, id FROM tags WHERE name_key = $2",
[sequenceId, key], cancellationToken).ConfigureAwait(false);
DbParam[] args = [Guid.CreateVersion7(), tag, TagRepository.Key(tag)];
Guid tagId;
if (_db.Sql.IsPostgres)
{
// The no-op update locks an existing tag, so a concurrent DeleteUnusedAsync cannot remove it before the link exists.
tagId = (await session.ScalarAsync<Guid?>(
"INSERT INTO tags (id, name, name_key) VALUES ($1, $2, $3) ON CONFLICT (name_key) DO UPDATE SET name_key = excluded.name_key RETURNING id",
args, cancellationToken).ConfigureAwait(false))!.Value;
}
else
{
await session.ExecuteAsync("INSERT INTO tags (id, name, name_key) VALUES ($1, $2, $3) ON CONFLICT (name_key) DO NOTHING",
args, cancellationToken).ConfigureAwait(false);
tagId = (await session.ScalarAsync<Guid?>("SELECT id FROM tags WHERE name_key = $1", [args[2]], cancellationToken).ConfigureAwait(false))!.Value;
}
await session.ExecuteAsync("INSERT INTO sequence_tags (sequence_id, tag_id) VALUES ($1, $2)", [sequenceId, tagId], cancellationToken)
.ConfigureAwait(false);
}
}