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

@@ -43,7 +43,7 @@ public sealed class JobRepository
var claim = $"UPDATE jobs SET state = {(int)JobState.Running}, node_id = $1, started = $2, finished = NULL, error = NULL, attempts = attempts + 1";
DbParam[] args = [workerId, DateTimeOffset.UtcNow];
if (_db.Sql.IsPostgres)
return _db.SingleAsync($"{claim} WHERE id = ({pick} FOR UPDATE SKIP LOCKED) RETURNING {Columns}", args, Map, cancellationToken);
return _db.SingleAsync($"{claim} WHERE id = ({pick}{_db.Sql.ForUpdateSkipLocked}) RETURNING {Columns}", args, Map, cancellationToken);
return _db.InTransactionAsync(async session =>
{
@@ -18,6 +18,7 @@ public sealed class RenderRepository
public Task InsertAsync(Render render, CancellationToken cancellationToken = default) =>
_db.InTransactionAsync(async session =>
{
await LockSequenceAsync(session, render.SequenceId, cancellationToken).ConfigureAwait(false);
await session.ExecuteAsync($"INSERT INTO renders ({Columns}) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)",
[
render.Id, render.SequenceId, render.PresetName, DbParam.Json(render.SettingsJson), render.OutputPath, render.Codec,
@@ -38,11 +39,21 @@ public sealed class RenderRepository
{
var sequenceId = await session.ScalarAsync<Guid?>("SELECT sequence_id FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false);
if (sequenceId is null) return false;
await session.ExecuteAsync("DELETE FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false);
await LockSequenceAsync(session, sequenceId.Value, cancellationToken).ConfigureAwait(false);
if (await session.ExecuteAsync("DELETE FROM renders WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) == 0) return false;
await session.ExecuteAsync(RecountSql, [sequenceId], cancellationToken).ConfigureAwait(false);
return true;
}, cancellationToken);
/// <summary>
/// Serialises render changes per sequence on PostgreSQL, so the recount (a new statement, hence a new snapshot)
/// sees every committed render; SQLite's write lock already does this.
/// </summary>
private async Task LockSequenceAsync(IDbSession session, Guid sequenceId, CancellationToken cancellationToken)
{
if (_db.Sql.IsPostgres) await SequenceRepository.LockAsync(session, sequenceId, cancellationToken).ConfigureAwait(false);
}
private static Render Map(DbRow r) => new()
{
Id = r.GetGuid(0),
@@ -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);
}
}
+20 -2
View File
@@ -36,9 +36,27 @@ public sealed class TagRepository
public async Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default) =>
await _db.ExecuteAsync("DELETE FROM tags WHERE id = $1", [id], cancellationToken).ConfigureAwait(false) > 0;
/// <summary>Deletes tags no sequence uses any more; returns how many.</summary>
/// <summary>
/// Deletes tags no sequence uses any more; returns how many. Candidates are locked first (skipping tags a
/// concurrent tagger holds) and re-checked by a later statement, whose fresh snapshot sees every link committed
/// before the lock, so a tag being attached at the same moment survives.
/// </summary>
public Task<int> DeleteUnusedAsync(CancellationToken cancellationToken = default) =>
_db.ExecuteAsync("DELETE FROM tags WHERE NOT EXISTS (SELECT 1 FROM sequence_tags st WHERE st.tag_id = tags.id)", [], cancellationToken);
_db.InTransactionAsync(async session =>
{
const string unused = "NOT EXISTS (SELECT 1 FROM sequence_tags st WHERE st.tag_id = tags.id)";
var candidates = await session.QueryListAsync($"SELECT id FROM tags WHERE {unused}{_db.Sql.ForUpdateSkipLocked}", [],
r => r.GetGuid(0), cancellationToken).ConfigureAwait(false);
var deleted = 0;
foreach (var chunk in candidates.Chunk(500))
{
var p = new SqlParameters();
var ids = string.Join(", ", chunk.Select(id => p.Add(id)));
deleted += await session.ExecuteAsync($"DELETE FROM tags WHERE id IN ({ids}) AND {unused}", p.ToArray(), cancellationToken)
.ConfigureAwait(false);
}
return deleted;
}, cancellationToken);
/// <summary>Trims, collapses inner whitespace and validates a tag name.</summary>
public static string Normalize(string name)