fix(data): write a sequence's tags in one order on PostgreSQL

Each tag upsert locks its row until commit, and tags were written in the
order the caller listed them. A PATCH listing them in another order than
an upload, a scan or another edit of a sequence sharing two of them could
lock the rows in opposite orders, and PostgreSQL aborted one writer with a
deadlock that nothing retries. Tags are now written in the order of their
keys, and a set the sequence already carries is not written again.

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-12 23:28:40 +00:00
1 parent e6129d2a11
commit 2cdc44abe4
2 files changed
+58 -2

No files matched your search

@@ -500,11 +500,22 @@ public sealed class SequenceRepository
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>
/// <summary>
/// Replaces the tag links of a sequence whose row the caller has locked (or just upserted); a set the sequence already
/// carries (names compared case-insensitively) is left as it is. On PostgreSQL every tag written is locked until
/// commit, and the tags are written in the order of their keys whatever order the caller listed them in (a PATCH sends
/// them in any order): writers of two sequences that share tags then take those rows in one order, and never wait for
/// each other's (PostgreSQL would abort one with a deadlock, and nothing retries it).
/// </summary>
private async Task ReplaceTagsAsync(IDbSession session, Guid sequenceId, IEnumerable<string> tags, CancellationToken cancellationToken)
{
var wanted = TagRepository.NormalizeSet(tags);
var keys = wanted.Select(TagRepository.Key).ToList();
var stored = await session.QueryListAsync("SELECT t.name_key FROM sequence_tags st JOIN tags t ON t.id = st.tag_id WHERE st.sequence_id = $1",
[sequenceId], r => r.GetString(0), cancellationToken).ConfigureAwait(false);
if (stored.Count == keys.Count && stored.ToHashSet(StringComparer.Ordinal).SetEquals(keys)) return;
await session.ExecuteAsync("DELETE FROM sequence_tags WHERE sequence_id = $1", [sequenceId], cancellationToken).ConfigureAwait(false);
foreach (var tag in TagRepository.NormalizeSet(tags))
foreach (var tag in wanted.OrderBy(TagRepository.Key, StringComparer.Ordinal))
{
DbParam[] args = [Guid.CreateVersion7(), tag, TagRepository.Key(tag)];
Guid tagId;